arkenv

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ArkEnv

ArkEnv

ArkEnv is a typesafe environment variable validator for modern JavaScript runtimes. It uses
ArkType
by default for schema definition but supports any
Standard Schema
validator (like
Zod
or
Valibot
).
ArkEnv 是面向现代 JavaScript 运行时的类型安全环境变量验证工具。它默认使用
ArkType
进行模式定义,但支持任何标准 Schema 验证器(如
Zod
Valibot
)。

Capabilities

功能特性

Core Usage

核心用法

  • Define typesafe schemas using
    ArkType
    notation or any
    Standard Schema
    validator.
  • Implement complex types, arrays, and unions.
  • Configure automatic coercion and default values.
  • Follow best practices for schema organization.
  • 使用
    ArkType
    语法或任何标准 Schema 验证器定义类型安全的模式。
  • 实现复杂类型、数组和联合类型。
  • 配置自动类型转换和默认值。
  • 遵循模式组织的最佳实践。

Framework Integration

框架集成

  • Vite: Build-time validation and
    import.meta.env
    type augmentation via
    @arkenv/vite-plugin
    .
  • Bun: Build-time/Runtime validation and
    process.env
    type augmentation via
    @arkenv/bun-plugin
    .
  • Node.js: Standard
    process.env
    validation and coercion.
  • Vite:通过
    @arkenv/vite-plugin
    实现构建时验证和
    import.meta.env
    类型增强。
  • Bun:通过
    @arkenv/bun-plugin
    实现构建时/运行时验证和
    process.env
    类型增强。
  • Node.js:标准
    process.env
    验证与类型转换。

CLI (Setup & DevOps)

CLI(搭建与DevOps)

  • Initialize ArkEnv in new or existing projects using
    pnpm dlx @arkenv/cli@latest init
    .
  • Scaffold schema files and detect framework-specific configurations (
    Vite
    ,
    Bun
    , etc.).
  • Automatically configure
    tsconfig.json
    and environment types for optimal typesafety.
  • 使用
    pnpm dlx @arkenv/cli@latest init
    在新项目或现有项目中初始化ArkEnv。
  • 生成模式文件并检测框架特定配置(如
    Vite
    Bun
    等)。
  • 自动配置
    tsconfig.json
    和环境类型以实现最佳类型安全。

Agent Setup (Machine-Readable)

Agent 配置(机器可读)

AI agents SHOULD always use the CLI for project initialization to ensure consistency and reliability. Use the
--agent
flag for a fully automated, machine-readable experience.
  • Command:
    pnpm dlx @arkenv/cli@latest init --agent
  • Behavior: The
    --agent
    flag automatically enables the following behaviors:
    • --yes
      : Bypasses all interactive prompts and uses recommended defaults.
    • --quiet
      : Suppresses spinners and ANSI formatting for cleaner terminal logs.
    • --json
      : Emits a structured JSON summary to
      stdout
      upon completion (all other output is sent to
      stderr
      ).
  • Success Verification: Parse the JSON output to verify
    status: "success"
    and retrieve details like the scaffolded file path.
AI Agent 应始终使用CLI进行项目初始化,以确保一致性和可靠性。使用
--agent
标志获得完全自动化的机器可读体验。
  • 命令
    pnpm dlx @arkenv/cli@latest init --agent
  • 行为
    --agent
    标志会自动启用以下行为:
    • --yes
      :跳过所有交互式提示,使用推荐的默认值。
    • --quiet
      :抑制加载动画和ANSI格式,生成更简洁的终端日志。
    • --json
      :完成后向标准输出(stdout)发送结构化JSON摘要(所有其他输出发送到标准错误stderr)。
  • 成功验证:解析JSON输出以验证
    status: "success"
    ,并获取生成文件路径等详细信息。

Operational Logic

操作逻辑

  1. Detection:
    • Look for
      env.ts
      or
      arkenv
      imports to understand existing schema.
    • Check for framework config files (
      vite.config.ts
      ,
      bunfig.toml
      ,
      package.json
      scripts) to recommend appropriate plugins.
  2. Setup:
    • If ArkEnv is not present or a fresh setup is requested, trigger the Setup Workflow.
    • Prefer using the CLI for initialization:
      pnpm dlx @arkenv/cli@latest init
      .
    • If the CLI cannot be used or fails, fall back to manual configuration.
  1. 检测
    • 查找
      env.ts
      arkenv
      导入以了解现有模式。
    • 检查框架配置文件(
      vite.config.ts
      bunfig.toml
      package.json
      脚本)以推荐合适的插件。
  2. 搭建
    • 如果项目中未安装ArkEnv或需要全新搭建,触发搭建流程
    • 优先使用CLI进行初始化:
      pnpm dlx @arkenv/cli@latest init
    • 如果CLI无法使用或执行失败,回退到手动配置。

Setup Workflow

搭建流程

When setting up ArkEnv, follow these steps:
  1. Initialize: Run
    pnpm dlx @arkenv/cli@latest init --agent
    . This will attempt to detect the environment, install dependencies, and scaffold a base
    env.ts
    .
  2. Review & Refine
    env.ts
    :
    • Inspect the generated
      env.ts
      . Ensure it captures the required environment variables.
    • Refine types (e.g., change
      string
      to
      number.port
      or specific union types).
  3. Manual Plugin Configuration:
    • The CLI installs plugins but might not update config files.
    • Vite: Update
      vite.config.ts
      to import and include the
      arkenv
      plugin.
    • Bun: Configure
      bunfig.toml
      or add the plugin to the runtime if necessary.
  4. Typesafety & Augmentation:
    • Vite: Add type augmentation to
      src/vite-env.d.ts
      or a new
      env.d.ts
      .
      ts
      interface ImportMetaEnv extends import("@arkenv/vite-plugin").ImportMetaEnvAugmented<typeof import("./env").Env> {}
    • Bun: Create a
      bun-env.d.ts
      file (or update an existing one) with the following pattern:
      ts
      /// <reference types="bun-types" />
      type ProcessEnvAugmented = import("@arkenv/bun-plugin").ProcessEnvAugmented<typeof import("./src/env").default>;
      declare namespace NodeJS {
        interface ProcessEnv extends ProcessEnvAugmented {}
      }
    • Ensure
      tsconfig.json
      has
      strict: true
      (the CLI tries to do this, but verify).
  5. Usage Update: Scan the codebase for existing environment variable usage (
    process.env
    or
    import.meta.env
    ) and ensure they are now typesafe via the augmentations.
  6. Validation: Run
    pnpm check
    (or equivalent) or a build to confirm everything is typesafe and valid.
搭建ArkEnv时,请遵循以下步骤:
  1. 初始化:运行
    pnpm dlx @arkenv/cli@latest init --agent
    。该命令会尝试检测环境、安装依赖并生成基础的
    env.ts
    文件。
  2. 审核与优化
    env.ts
    • 检查生成的
      env.ts
      文件,确保它包含所需的环境变量。
    • 优化类型(例如,将
      string
      改为
      number.port
      或特定的联合类型)。
  3. 手动配置插件
    • CLI会安装插件,但可能不会更新配置文件。
    • Vite:更新
      vite.config.ts
      以导入并添加
      arkenv
      插件。
    • Bun:必要时配置
      bunfig.toml
      或在运行时添加插件。
  4. 类型安全与增强
    • Vite:在
      src/vite-env.d.ts
      或新的
      env.d.ts
      文件中添加类型增强。
      ts
      interface ImportMetaEnv extends import("@arkenv/vite-plugin").ImportMetaEnvAugmented<typeof import("./env").Env> {}
    • Bun:创建
      bun-env.d.ts
      文件(或更新现有文件),使用以下格式:
      ts
      /// <reference types="bun-types" />
      type ProcessEnvAugmented = import("@arkenv/bun-plugin").ProcessEnvAugmented<typeof import("./src/env").default>;
      declare namespace NodeJS {
        interface ProcessEnv extends ProcessEnvAugmented {}
      }
    • 确保
      tsconfig.json
      中设置了
      strict: true
      (CLI会尝试配置,但请自行验证)。
  5. 更新用法:扫描代码库中现有环境变量的使用(
    process.env
    import.meta.env
    ),确保它们现在通过类型增强实现了类型安全。
  6. 验证:运行
    pnpm check
    (或等效命令)或执行构建,确认所有内容都符合类型安全且验证通过。

Core Concepts

核心概念

Defining a Schema

定义模式

The best practice is to export a schema definition using
type
.
ts
import { type } from 'arkenv';

export const Env = type({
  NODE_ENV: "'development' | 'production' | 'test' = 'development'",
  VITE_API_URL: "string",
  PORT: "number.port = 3000"
});
最佳实践是使用
type
导出模式定义。
ts
import { type } from 'arkenv';

export const Env = type({
  NODE_ENV: "'development' | 'production' | 'test' = 'development'",
  VITE_API_URL: "string",
  PORT: "number.port = 3000"
});

Usage: Node.js (Standard)

用法:Node.js(标准)

In Node.js, you validate the environment at runtime and export the result.
ts
import arkenv from 'arkenv';
import { Env } from './env';

export const env = arkenv(Env);

// Usage
const port = env.PORT; // typed as number
在Node.js中,你需要在运行时验证环境并导出结果。
ts
import arkenv from 'arkenv';
import { Env } from './env';

export const env = arkenv(Env);

// 用法示例
const port = env.PORT; // 类型为number

Usage: Vite (Frontend)

用法:Vite(前端)

Vite requires build-time injection. Use the plugin in
vite.config.ts
and augment
ImportMetaEnv
.
ts
// vite.config.ts
import arkenv from '@arkenv/vite-plugin';
import { Env } from './env';

export default defineConfig({
  plugins: [arkenv(Env)]
});
ts
// src/vite-env.d.ts
import type { ImportMetaEnvAugmented } from "@arkenv/vite-plugin";
import type { Env } from "../env";

interface ImportMetaEnv extends ImportMetaEnvAugmented<typeof Env> {}
Vite需要构建时注入。在
vite.config.ts
中使用插件并增强
ImportMetaEnv
ts
// vite.config.ts
import arkenv from '@arkenv/vite-plugin';
import { Env } from './env';

export default defineConfig({
  plugins: [arkenv(Env)]
});
ts
// src/vite-env.d.ts
import type { ImportMetaEnvAugmented } from "@arkenv/vite-plugin";
import type { Env } from "../env";

interface ImportMetaEnv extends ImportMetaEnvAugmented<typeof Env> {}

Usage: Bun

用法:Bun

Bun can use either runtime validation or a plugin for type augmentation.
ts
// src/env.d.ts
import type { ProcessEnvAugmented } from "@arkenv/bun-plugin";
import type { Env } from "./env";

declare global {
  namespace NodeJS {
    interface ProcessEnv extends ProcessEnvAugmented<typeof Env> {}
  }
}
Bun可以使用运行时验证或插件实现类型增强。
ts
// src/env.d.ts
import type { ProcessEnvAugmented } from "@arkenv/bun-plugin";
import type { Env } from "./env";

declare global {
  namespace NodeJS {
    interface ProcessEnv extends ProcessEnvAugmented<typeof Env> {}
  }
}

CLI Commands

CLI 命令

init

init

Set up ArkEnv in your project. It detects your framework and configures the appropriate plugin and type augmentations.
bash
pnpm dlx @arkenv/cli@latest init
在你的项目中搭建ArkEnv。它会检测你的框架并配置相应的插件和类型增强。
bash
pnpm dlx @arkenv/cli@latest init

Best Practices

最佳实践

  1. Prefer Native Primitives: To leverage the full power of ArkEnv plugins, you should access environment variables through the runtime's native primitives.
    • Vite: Use
      import.meta.env
      .
    • Bun: Use
      process.env
      .
    • This ensures that build-time validation, static replacement (Vite), and runtime optimizations (Bun) work as intended while remaining fully typesafe via type augmentation.
  2. Avoid
    import { env }
    in Plugin-managed Projects
    : In projects using
    @arkenv/vite-plugin
    or
    @arkenv/bun-plugin
    , you should generally avoid importing a runtime-validated
    env
    object. Using native primitives is the "cleanest" way to get typesafety and ensures consistency with framework-specific behavior.
  3. Use Type Augmentation: This is the recommended way to make
    import.meta.env
    or
    process.env
    typesafe. It connects your schema definition to the native primitives without adding runtime overhead to your application logic.
  4. Re-use Schema: Define your schema once and use it for both the plugin (build-time/config) and runtime validation if needed.
  5. Coercion: ArkEnv automatically coerces strings from
    .env
    files (e.g.,
    "3000"
    becomes
    3000
    ).
  1. 优先使用原生原语:为了充分发挥ArkEnv插件的能力,你应该通过运行时的原生原语访问环境变量。
    • Vite:使用
      import.meta.env
    • Bun:使用
      process.env
    • 这确保了构建时验证、静态替换(Vite)和运行时优化(Bun)按预期工作,同时通过类型增强保持完全的类型安全。
  2. 在插件管理的项目中避免
    import { env }
    :在使用
    @arkenv/vite-plugin
    @arkenv/bun-plugin
    的项目中,通常应避免导入运行时验证的
    env
    对象。使用原生原语是实现类型安全的“最简洁”方式,并确保与框架特定行为的一致性。
  3. 使用类型增强:这是让
    import.meta.env
    process.env
    实现类型安全的推荐方式。它将你的模式定义与原生原语关联,而不会为应用逻辑增加运行时开销。
  4. 复用模式:只需定义一次模式,即可同时用于插件(构建时/配置)和运行时验证(如果需要)。
  5. 类型转换:ArkEnv会自动转换
    .env
    文件中的字符串(例如,
    "3000"
    会转换为
    3000
    )。