From 4f2f0931cc125173bbffe51af73e77f52cc0c751 Mon Sep 17 00:00:00 2001 From: "MK (fengmk2)" Date: Wed, 28 Oct 2026 13:37:42 +0900 Subject: [PATCH 01/28] docs: propose varlock integration for schema-validated env files Add an RFC for first-class `.env` support through varlock: a bundled `vp dotenv` command family (init, check, print, explain, scan, exec), automatic Vite/Vitest plugin injection when `.env.schema` exists, create/migrate scaffolding, and opt-in `vp run` task injection. Add the user guide and config reference that describe the intended end-user experience, with sidebar entries and cross-links. Co-Authored-By: Claude Opus 5.5 --- docs/.vitepress/config.mts | 2 + docs/config/dotenv.md | 86 +++++++++++++ docs/config/index.md | 2 + docs/config/run.md | 22 ++++ docs/guide/cache.md | 2 + docs/guide/dotenv.md | 250 ++++++++++++++++++++++++++++++++++++ docs/guide/env.md | 2 + rfcs/varlock-integration.md | 244 +++++++++++++++++++++++++++++++++++ 8 files changed, 610 insertions(+) create mode 100644 docs/config/dotenv.md create mode 100644 docs/guide/dotenv.md create mode 100644 rfcs/varlock-integration.md diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 43937fd07a..dd3a52dbf9 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -91,6 +91,7 @@ const guideSidebar = [ ], }, { text: 'Commit Hooks', link: '/guide/commit-hooks' }, + { text: 'Env Files', link: '/guide/dotenv' }, { text: 'Monorepo Guide', link: '/guide/monorepo' }, ], }, @@ -307,6 +308,7 @@ export default extendConfig( { text: 'Build', link: '/config/build' }, { text: 'Pack', link: '/config/pack' }, { text: 'Staged', link: '/config/staged' }, + { text: 'Dotenv', link: '/config/dotenv' }, ], }, ], diff --git a/docs/config/dotenv.md b/docs/config/dotenv.md new file mode 100644 index 0000000000..eb80f08391 --- /dev/null +++ b/docs/config/dotenv.md @@ -0,0 +1,86 @@ +# Dotenv Config + +`vp dev`, `vp build`, `vp preview`, and `vp test` load and validate `.env` files against `.env.schema` when the file exists. The `dotenv` block in `vite.config.ts` controls that loading. See [Env Files](/guide/dotenv). + +Every option has a default that works for a project with a `.env.schema` file at the root. Most projects do not need this block. + +## Example + +```ts [vite.config.ts] +import { defineConfig } from 'vite-plus'; + +export default defineConfig({ + dotenv: { + // Load and validate `.env.schema`. Defaults to `'auto'`: on when the + // file exists at the project root, off otherwise. + schema: 'auto', + // Redact sensitive values from console output in dev and server code. + // Defaults to true, except under `vp test` where it defaults to false. + redact: true, + // Fail `vp build` when a sensitive value appears in the output. + // Defaults to true. + scanBuildOutput: true, + }, +}); +``` + +## `schema` + +- **Type:** `'auto' | boolean | string` +- **Default:** `'auto'` + +Controls whether and where the schema loads: + +- `'auto'`: load `.env.schema` from the project root when it exists. +- `true`: require a schema. Fail when `.env.schema` is missing. Use this in a project that must never run without validation. +- `false`: never load a schema, even when the file exists. Vite's own `.env` handling applies. +- A path: load the schema from that file or directory instead of the root, for example `'./config/env'`. Relative paths resolve from the config file. When a directory is given, `.env.schema`, `.env`, `.env.local`, and the environment files in that directory are loaded in the [usual order](/guide/dotenv#file-loading-order). + +Vite's `envDir` option is ignored while a schema is active. Vite+ prints a `note:` line when both are set. + +## `redact` + +- **Type:** `boolean | { console?: boolean; stdout?: boolean }` +- **Default:** `true` for `vp dev`, `vp build`, and `vp preview`; `false` for `vp test` + +Redaction replaces sensitive values with `▒` characters before they reach the terminal. + +- `console`: patch `console.log`, `console.error`, and the other console methods. This is what most projects want. +- `stdout`: also patch `process.stdout.write` and `process.stderr.write` for non-TTY output. Values split across two writes can be partly exposed, so Vite+ prints a one-time warning when this layer is on. +- `true` is `{ console: true, stdout: false }`. `false` disables both. + +Under `vp test`, redaction is off by default because patched console methods interfere with reporters and snapshot output. Set `redact: true` to turn it on there too. + +The build-output scan and the HTTP response guard are not affected by this option. Use the schema decorators `@preventLeaks=false` or `@sensitive={redact=false}` to exempt one variable. + +## `scanBuildOutput` + +- **Type:** `boolean` +- **Default:** `true` + +After `vp build` writes its output, scan every emitted file for a plaintext copy of a sensitive value. On a hit, the build fails and the error names the variable and the file. Set to `false` for a server-only build where every value is allowed in the output, or run [`vp dotenv scan dist/`](/guide/dotenv#vp-dotenv-scan) yourself at another point in the pipeline. + +## Task option: `run.tasks..dotenv` + +- **Type:** `boolean | string[]` +- **Default:** `false` + +Set on a [task](/config/run#tasks) to inject schema variables into the task process and track them in its cache key: + +```ts [vite.config.ts] +export default defineConfig({ + run: { + tasks: { + seed: { command: 'node scripts/seed.ts', dotenv: true }, + deploy: { command: 'node deploy.ts', dotenv: ['DEPLOY_*', '!DEPLOY_TOKEN'] }, + }, + }, +}); +``` + +- `true`: every variable in the schema. +- An array of patterns: the same syntax as [`cache.env`](/config/run#cache-env), with `*` wildcards and `!` exclusions. + +Selected variables behave as if listed in `cache.env`. Public values are fingerprinted by value. Sensitive values are fingerprinted through a salted hash, so the plaintext never enters the cache store and a rotated secret still invalidates the cache. A variable matched by both `dotenv` and [`cache.untrackedEnv`](/config/run#cache-untrackedenv) is passed through but not fingerprinted. + +Resolution runs once per `vp run` invocation and is shared by every task that opts in. diff --git a/docs/config/index.md b/docs/config/index.md index bfab9ef6c5..f2803c013a 100644 --- a/docs/config/index.md +++ b/docs/config/index.md @@ -18,6 +18,7 @@ export default defineConfig({ test: {}, pack: {}, staged: {}, + dotenv: {}, }); ``` @@ -33,6 +34,7 @@ Vite+ extends the basic Vite configuration with these additions: - [`test`](/config/test) for Vitest - [`pack`](/config/pack) for tsdown - [`staged`](/config/staged) for staged-file checks +- [`dotenv`](/config/dotenv) for `.env` schema loading and secret redaction - [`defaultPackage`](#defaultpackage) for the default target of bare app commands at a workspace root ## defaultPackage diff --git a/docs/config/run.md b/docs/config/run.md index b4a0c50a66..06d98247ac 100644 --- a/docs/config/run.md +++ b/docs/config/run.md @@ -469,6 +469,28 @@ tasks: { } ``` +### `dotenv` + +- **Type:** `boolean | string[]` +- **Default:** `false` + +Inject variables from `.env.schema` and the local `.env` files into the task, and track them in its cache key. `true` selects every variable in the schema. An array uses the same pattern syntax as [`cache.env`](#cache-env). + +```ts [vite.config.ts] +tasks: { + seed: { + command: 'node scripts/seed.ts', + dotenv: true, + }, + deploy: { + command: 'node deploy.ts', + dotenv: ['DEPLOY_*', '!DEPLOY_TOKEN'], + }, +} +``` + +Public values are fingerprinted by value. Sensitive values are fingerprinted through a salted hash, so the plaintext never enters the cache store. See [Dotenv Config](/config/dotenv#task-option-run-tasks-name-dotenv) and [Env Files](/guide/dotenv#using-env-files-in-tasks). + ### `cwd` - **Type:** `string` diff --git a/docs/guide/cache.md b/docs/guide/cache.md index 0e0d241077..129aae7963 100644 --- a/docs/guide/cache.md +++ b/docs/guide/cache.md @@ -83,6 +83,8 @@ tasks: { To pass a variable to the task **without** affecting cache behavior, use [`cache.untrackedEnv`](/config/run#cache-untrackedenv). This is useful for variables like `CI` or `GITHUB_ACTIONS` that should be available in the task, but do not affect caching behavior. +Values from `.env` files are not passed through either. When the project has a `.env.schema` file, set [`dotenv`](/config/run#dotenv) on the task to inject and track them. See [Env Files](/guide/dotenv#using-env-files-in-tasks). + See [Run Config](/config/run#cache-env) for details on wildcard patterns and the full list of automatically passed-through variables. ## Cache Sharing diff --git a/docs/guide/dotenv.md b/docs/guide/dotenv.md new file mode 100644 index 0000000000..322bda4ce3 --- /dev/null +++ b/docs/guide/dotenv.md @@ -0,0 +1,250 @@ +# Env Files + +Use `vp dotenv` to manage `.env` files with a committed schema. Vite+ validates environment variables, generates types, keeps secrets out of bundles and logs, and gives coding agents the structure of your config without the values. + +## Overview + +A plain `.env.example` goes stale the moment someone adds a variable. Vite+ replaces it with `.env.schema`, a `.env` file that also declares what each variable is: + +```env-spec [.env.schema] +# @defaultSensitive=false +# @generateTsTypes(path='env.d.ts') +# --- + +# @type=enum(development, preview, production, test) +APP_ENV=development + +# @required @type=url +API_URL=http://localhost:3000 + +# @required @sensitive @type=string(startsWith=sk_) +STRIPE_SECRET_KEY= +``` + +`.env.schema` is committed to git. Your real values stay in `.env.local`, which is git-ignored. Every time you run `vp dev`, `vp build`, or `vp test`, Vite+ loads the schema, layers your local values on top, and validates the result before any code runs. + +The schema format is [@env-spec](https://varlock.dev/env-spec/), and `vp dotenv` is powered by [varlock](https://varlock.dev). Vite+ bundles it, so there is nothing to install. If you use [`vp create`](/guide/create) or [`vp migrate`](/guide/migrate), Vite+ prompts you to set this up for your project automatically. + +::: tip `vp env` vs `vp dotenv` +[`vp env`](/guide/env) manages Node.js and package-manager versions. `vp dotenv` manages `.env` files. They are unrelated. +::: + +## Quick start + +Run `vp dotenv init` in a project that already has `.env` files: + +```bash +$ vp dotenv init +info: Found .env.example, .env.local +✓ Wrote .env.schema (6 items, 1 sensitive) +✓ Added !.env.schema to .gitignore +✓ Enabled TypeScript types (env.d.ts) +note: Review .env.schema and mark secrets with @sensitive, then delete .env.example. +``` + +`init` reads your existing files, infers a type for each variable where it can, and marks anything that looks like a secret as `@sensitive` for you to confirm. From now on, `vp dev` validates before it starts: + +```bash +$ vp dev +error: STRIPE_SECRET_KEY is required but has no value +note: Set it in .env.local, or run `vp dotenv explain` to see every item +``` + +Add the value to `.env.local` and the server starts. In application code, use the typed `ENV` object: + +```ts [src/api.ts] +import { ENV } from 'vite-plus/env'; + +fetch(`${ENV.API_URL}/items`); // string, inlined at build time +ENV.API_PORT; // number, not string +ENV.STRIPE_SECRET_KEY; // only available server-side, see below +``` + +`import.meta.env.VITE_*` keeps working for variables with the `VITE_` prefix. `ENV` is the recommended API: it is typed, it coerces numbers and booleans, and it does not need a prefix. + +## The `.env.schema` file + +A schema is a `.env` file with JSDoc-style comments. Lines above `# ---` are root decorators and apply to the whole file. A comment directly above a variable attaches decorators to that variable. + +### Root decorators + +| Decorator | Meaning | +| -------------------------------------------- | -------------------------------------------------------------------------------------- | +| `@defaultSensitive=false` | Variables are public unless marked `@sensitive`. Use `true` to flip the default. | +| `@defaultSensitive=inferFromPrefix('VITE_')` | Vite compatibility: `VITE_*` is public, everything else is sensitive. | +| `@defaultRequired=infer` | A variable with a non-empty value in the schema is optional, an empty one is required. | +| `@currentEnv=$APP_ENV` | Which variable selects the environment and so which `.env.` files load. | +| `@generateTsTypes(path='env.d.ts')` | Write a type declaration for `ENV` on every load. | + +### Item decorators + +| Decorator | Meaning | +| -------------- | ----------------------------------------------------------------- | +| `@required` | Fail validation when the value is empty. | +| `@optional` | Allow an empty value even when the root default is required. | +| `@sensitive` | Treat as a secret: never inline into client code, redact in logs. | +| `@type=` | Validate and coerce. See the types below. | +| `@example=...` | A sample value shown in `vp dotenv explain` and in editor hovers. | +| `@docs(url)` | Link to documentation for the variable. | + +### Types + +`string`, `number`, `boolean`, `url`, `port`, `email`, `enum(a, b, c)`, `string(startsWith=...)`, `number(min=..., max=...)`, and more. Any variable without `@type` is a `string`. See the [varlock type reference](https://varlock.dev/reference/item-decorators/) for the full list. + +### Value expansion + +A value can reference another variable: `API_URL=http://localhost:${API_PORT}`. Expansion happens after all files load, so a value in `.env.local` can refer to one in `.env.schema`. + +## File loading order + +Vite+ loads these files from the project root, later files override earlier ones: + +1. `.env.schema`: the committed schema and default values +2. `.env`: shared local defaults, usually git-ignored +3. `.env.`: values for one environment, for example `.env.production` +4. `.env.local`: your machine-only values, git-ignored +5. `.env..local`: machine-only values for one environment +6. The shell environment: a variable already set in the process always wins + +`` comes from the `@currentEnv` root decorator. If the schema declares `@currentEnv=$APP_ENV` and `APP_ENV` is not set in the shell, Vite+ derives it from the command: `development` for `vp dev`, `production` for `vp build` and `vp preview`, `test` for `vp test`. Pass `--mode staging` or set `APP_ENV=staging` to pick another one. An explicit `APP_ENV` always wins over `--mode`. + +Vite's `envDir` option is not supported when a schema is active. Set [`dotenv.schema`](/config/dotenv#schema) to a path instead. + +## Sensitive values + +Mark a secret with `@sensitive`, or flip the default with `@defaultSensitive=true` and mark public values with `@sensitive=false`. A sensitive value is protected in three places: + +- **Client bundles.** `vp build` inlines only public values. If a sensitive value still ends up in the output, for example through `import.meta.env` or a hard-coded copy, the build fails and names the variable and the chunk. +- **Logs.** In `vp dev` and in server-side code, `console.log` and friends print `STRIPE_SECRET_KEY=sk_▒▒▒▒▒▒▒▒` instead of the value. Redaction is off under `vp test` by default so reporters and snapshots are not affected. See [`dotenv.redact`](/config/dotenv#redact). +- **HTTP responses.** Server-side code that would send a sensitive value in a response body throws instead. + +These are guardrails against accidental exposure, not a sandbox. The running process still holds the plaintext. To print a value on purpose, use `revealSensitiveConfig()` from `vite-plus/env`. + +## Commands + +### `vp dotenv init` + +Scaffold `.env.schema` from existing `.env`, `.env.example`, and `.env.local` files. Adds `!.env.schema` to `.gitignore`, and offers to enable type generation. Safe to re-run: it never overwrites an existing schema. + +### `vp dotenv check` + +Validate the schema and the resolved values for the current environment. Prints nothing on success and exits non-zero on the first error. It never prints values, so it is safe in CI logs: + +```bash +vp dotenv check +vp dotenv check --env production +``` + +[`vp check`](/guide/check) runs `vp dotenv check` as one of its steps when the project has a `.env.schema` file. + +### `vp dotenv print` + +Print the resolved values for other tools. Sensitive values are masked unless you pass `--reveal`: + +```bash +vp dotenv print # KEY=value lines, secrets masked +vp dotenv print --format json # a JSON object +vp dotenv print --format shell # export KEY=value lines for `eval` +vp dotenv print --reveal --format env # plaintext, for a deploy step that needs it +``` + +Without `--reveal`, a masked value looks like `STRIPE_SECRET_KEY=sk_▒▒▒▒▒▒▒▒`. Treat `--reveal` output like the contents of `.env.local`: do not pipe it into a log. + +### `vp dotenv explain` + +Print every variable with its type, where its value came from, and whether it is sensitive. Sensitive values are masked: + +```bash +$ vp dotenv explain +APP_ENV development enum .env.schema +API_URL http://localh… url .env.local +API_PORT 3000 port .env.schema (default) +STRIPE_SECRET_KEY sk_▒▒▒▒▒▒▒▒▒▒ string .env.local sensitive +``` + +### `vp dotenv scan` + +Search files for plaintext copies of sensitive values. Reports file, line, and variable name, and exits non-zero on any hit: + +```bash +vp dotenv scan # the whole project, respecting .gitignore +vp dotenv scan --staged # only files staged in git, for a pre-commit hook +vp dotenv scan dist/ # a build output directory +``` + +### `vp dotenv exec` + +Run any command with the resolved environment injected, for scripts and tools that are not Vite: + +```bash +vp dotenv exec -- node scripts/seed.ts +vp dotenv exec --env production -- prisma migrate deploy +``` + +When output is piped or redirected, sensitive values are redacted from stdout and stderr. Output to a terminal is not redacted. + +`vp dotenv exec` runs one command in the schema environment. [`vp run`](/guide/run) runs a task from `vite.config.ts`. To give a task the schema environment, see the next section. + +## Using env files in tasks + +A [`vp run`](/guide/run) task starts in a clean environment, so `.env` values do not reach it by default. Two options: + +Wrap the command when a single task needs the values: + +```ts [vite.config.ts] +export default defineConfig({ + run: { + tasks: { + seed: { command: 'vp dotenv exec -- node scripts/seed.ts' }, + }, + }, +}); +``` + +Or let Vite+ inject them and track them for the [task cache](/guide/cache): + +```ts [vite.config.ts] +export default defineConfig({ + run: { + tasks: { + seed: { command: 'node scripts/seed.ts', dotenv: true }, + deploy: { command: 'node deploy.ts', dotenv: ['DEPLOY_*', '!DEPLOY_TOKEN'] }, + }, + }, +}); +``` + +With `dotenv: true`, every schema variable is visible to the task and part of its cache key. Public values are hashed by value. Sensitive values are hashed through a salt, so rotating a secret invalidates the cache without the plaintext entering the cache store. Cache-miss messages print only the variable name. See [`dotenv`](/config/run#dotenv) in the run config. + +Tasks that run `vp dev`, `vp build`, or `vp test` need neither option: those commands load the schema themselves. + +## Commit hooks and CI + +Add a scan to the project-owned pre-commit hook so a secret pasted into source never reaches a commit: + +```sh [.vite-hooks/pre-commit] +vp staged +vp dotenv scan --staged +``` + +When you opt into hooks during `vp create` and the project has a schema, Vite+ adds this line for you. In CI, `vp check` already covers validation. Add `vp dotenv scan dist/` after the build step if you deploy a client bundle. See [Commit Hooks](/guide/commit-hooks) and [CI](/guide/ci). + +## Migrating from `.env.example` or dotenv + +[`vp migrate`](/guide/migrate) detects `.env.example`, `dotenv`, and `dotenvx` and offers to generate a schema. The generated schema starts with `@defaultSensitive=inferFromPrefix('VITE_')`, so `VITE_*` stays public and everything else is treated as a secret. Behavior does not change until you edit the schema. + +Scripts that use `dotenv -e .env.test -- ` are listed in the migration summary with the `vp dotenv exec --env test -- ` equivalent. They are not rewritten automatically. + +If you want to change the default so sensitivity is explicit per variable, replace the root decorator with `@defaultSensitive=false` and mark each secret with `@sensitive`. `vp dotenv check` warns while both `.env.example` and `.env.schema` exist. + +## Coding agents + +The schema holds names, types, and descriptions. The values live in git-ignored files. When `vp create` or `vp config` writes agent instructions, it adds one rule: read `.env.schema` to learn the configuration, never read `.env`, `.env.local`, or other value files. An agent can then add a variable, write its type, and wire it into code without ever seeing a secret. + +## Requirements + +`vp dotenv` and schema loading require Node.js 22.3 or later. When the project pins an older runtime, the command exits with a message that names the pinned version, and `vp dev`, `vp build`, and `vp test` skip schema loading with a warning. + +## Disabling + +Delete `.env.schema` and Vite+ returns to plain Vite `.env` behavior. To keep the file but skip loading, set [`dotenv.schema: false`](/config/dotenv#schema) in `vite.config.ts`. diff --git a/docs/guide/env.md b/docs/guide/env.md index 69c1f0d5da..83cc0a10b7 100644 --- a/docs/guide/env.md +++ b/docs/guide/env.md @@ -2,6 +2,8 @@ `vp env` manages the complete JavaScript environment: one Node.js runtime and one selected package manager. npm, pnpm, Yarn, and Bun are peer package-manager families. It belongs to the [global CLI](/guide/global-cli) and is not included in the project-local `vite-plus` package. +Looking for `.env` files and environment variables? See [Env Files](/guide/dotenv). + ## Overview Think of the project environment as two independently selected components: diff --git a/rfcs/varlock-integration.md b/rfcs/varlock-integration.md new file mode 100644 index 0000000000..2c9345b5a0 --- /dev/null +++ b/rfcs/varlock-integration.md @@ -0,0 +1,244 @@ +# RFC: Varlock Integration - Schema-Validated `.env` Files for Vite+ + +## Summary + +This RFC proposes first-class `.env` support for Vite+ through [varlock](https://github.com/dmno-dev/varlock). Varlock replaces plain dotenv loading with a git-committed `.env.schema` file, validation, type generation, secret redaction, and leak prevention. Vite+ bundles varlock the same way it bundles Oxlint or Vitest, exposes it as a new `vp dotenv` command family, and injects its Vite plugin automatically when a project has a `.env.schema` file. + +The integration ships in three phases. Phase 1 bundles the tool and wires the Vite/Vitest plugin. Phase 2 adds scaffolding in `vp create` and `vp migrate`, plus secret scanning in the git-hooks flow. Phase 3 connects varlock-resolved env to `vp run` task caching. + +## Background + +### What varlock provides + +Varlock (MIT, TypeScript, built with tsdown, zero runtime dependencies) is built on **@env-spec**, a DSL that attaches schema metadata to `.env` files through JSDoc-style comments: + +```env-spec +# @defaultSensitive=false @generateTsTypes(path='env.d.ts') +# @currentEnv=$APP_ENV +# --- + +APP_ENV=enum(development, preview, production, test) + +# @required @sensitive @type=string(startsWith=sk-) +STRIPE_SECRET_KEY= + +# @type=port +API_PORT=3000 + +API_URL=http://localhost:${API_PORT} +``` + +The committed `.env.schema` replaces `.env.example` and stays authoritative: every load validates against it. Local `.env` / `.env.local` / `.env.` files layer values on top. + +Relevant capabilities: + +- **CLI**: `init` (scaffold a schema from existing `.env` files), `load` (validate and print, with `--format json|env|shell`), `run -- ` (inject resolved env into a subprocess, with stdout redaction), `scan` (find plaintext secrets in files and build output, with `--staged` and git-hook install), `explain`, plus encryption and secret-manager plugin commands. +- **`@varlock/vite-integration`**: a Vite plugin that replaces Vite's own dotenv loading, inlines non-sensitive values as `ENV.xxx` at build time (no `VITE_` prefix needed), supports `%ENV.X%` in HTML, scans build output for leaked sensitive values, and patches `console` for redaction in dev/SSR. +- **Runtime API**: `import { ENV } from 'varlock/env'` with generated TypeScript types via `@generateTsTypes`. +- **Sensitivity is declared, not inferred from prefixes** (`@sensitive`, `@defaultSensitive`, or `@defaultSensitive=inferFromPrefix('VITE_')` for compatibility). + +Constraints that shape this design: + +- The parser (`@env-spec/parser`) and resolver are **JavaScript only**. No Rust implementation exists. +- The varlock package requires **Node >= 22.3**. +- The Vite plugin **ignores Vite's `envDir`** and uses its own `loadPath` convention. +- Varlock selects environments through `@currentEnv` (e.g. `$APP_ENV`), not through Vite's `mode`. + +### Current state in Vite+ + +Vite+ has no `.env` handling of its own today. The relevant facts: + +- **The `vp env` name is taken.** It manages Node.js runtimes and package managers (`crates/vp_global_cli/src/cli.rs:228`, `rfcs/env-command.md`). A dotenv feature needs another name. +- **Upstream tools do all dotenv work.** Vite's `loadEnv` runs inside `resolveConfig`, tsdown has `--env-file` (forwarded by `vp pack`), and `vpx` forwards Node's `--env-file` flags (`crates/vp_global_cli/src/commands/vpx_script.rs:58`). +- **`vp run` tasks get a filtered environment.** Only `cache.env` / `cache.untrackedEnv` patterns pass through, `cache.env` values are hashed into the cache fingerprint, and cache-miss messages print variable names only (`docs/config/run.md`, `docs/guide/cache.md`). fspy tracks file reads automatically, so `.env` files a task reads already become cache inputs. Env-var reads are not tracked. +- **Plugin injection precedent exists.** `defineConfig` injects built-in plugins through `injectPluginIntoInlineConfig` (`packages/cli/src/define-config.ts:865`), and `lazyPlugins` skips user plugin factories during config-metadata resolution (`VP_RESOLVING_CONFIG_METADATA`). +- **JS command precedent exists.** `vp staged` is a JS command that inlines `lint-staged` as a devDependency, with a lazy tsdown entry and a thin Rust delegate (`packages/cli/src/bin.ts:115`, `packages/cli/tsdown.config.ts:68`). +- **`vp create` writes a conflicting `.gitignore`.** `DOTENV_GITIGNORE_LINES` ignores `.env.*` and un-ignores only `.env.example` (`packages/cli/src/create/utils.ts:222`). This would git-ignore `.env.schema`. +- **`vp migrate` knows dotenv wrappers.** `KNOWN_RUNNER_WRAPPERS` includes `dotenv` and `dotenvx` but not `varlock` (`crates/vp_migration/src/script_rewrite.rs:301`). +- **No secret redaction or scanning exists** anywhere in product code. + +## Goals + +1. A Vite+ project with a `.env.schema` file gets validated, typed env in `vp dev`, `vp build`, and `vp test` with zero configuration. +2. One command family covers schema scaffolding, validation, inspection, secret scanning, and subprocess injection. +3. Secrets stay out of client bundles, logs, and git history by default. +4. `vp create` and `vp migrate` make `.env.schema` the default path for new and migrated projects. +5. Agents that work in a Vite+ project can read env structure from the schema without reading secret values. This matches the agent-guidance direction of `packages/cli/src/utils/agent.ts`. + +## Non-goals + +- A Rust implementation of the env-spec parser. All resolution runs in the JS layer (see "Rust/JS boundary"). +- Replacing `vp env`. Runtime management keeps its name and scope. +- Bundling varlock's secret-manager plugins (1Password, AWS, Vault, ...). Projects install those themselves, and the bundled varlock loads them as it does upstream. +- A Vite+ credential proxy or any security boundary stronger than varlock's own guardrails. + +## Design + +### 1. Bundling and distribution + +Ship `varlock` and `@varlock/vite-integration` as **runtime dependencies** of `@voidzero-dev/vite-plus` (not inlined devDependencies), for three reasons: + +1. User code imports `varlock/env` at runtime, and generated `env.d.ts` types reference the package. +2. The package carries platform-specific `optionalDependencies` (native helpers), which inlining would break. +3. The Vite plugin and the runtime `ENV` object must resolve to the **same copy** of varlock. + +Mechanics: + +- Add both packages to `packages/cli/package.json` dependencies and declare varlock in `packages/cli/toolchain.config.json`, so `vp --version` reports the bundled version and the upstream-bump automation covers it. +- Re-export the runtime entry as **`vite-plus/env`** (and `vite-plus/env/auto-load`), mirroring the `vite-plus/test*` pattern. User code imports `import { ENV } from 'vite-plus/env'`. The injected Vite plugin aliases `varlock/env` to the bundled copy, so varlock's generated types and docs examples also work unchanged. +- The CLI command (section 2) executes the bundled JS package through the managed Node runtime. The standalone Bun-compiled varlock binary is not used: it would add a second distribution channel and bypass the runtime that `vp` already manages. +- Disable varlock's upstream telemetry when Vite+ invokes it, consistent with how Vite+ treats other bundled tools. +- Node floor: varlock requires Node >= 22.3. `vp` manages Node per project. The dotenv feature must fail with a clear message ("requires Node 22.3+, current project pins X") instead of a module crash when the pinned runtime is older. + +### 2. CLI surface: `vp dotenv` + +A new command family named **`vp dotenv`**. Naming rationale: `vp env` is taken by runtime management, `vp secrets` undersells the feature (schema and validation apply to non-secret config too), and `dotenv` names exactly the file family the command manages. Subcommand names follow the Vite+ vocabulary rather than varlock's: `check` validates like `vp check`, `exec` runs a command in an environment like `vp exec`, and `print` is separate from `check` so plaintext secrets only ever leave one command, behind an explicit `--reveal` flag. + +| Command | Wraps | Behavior | +| ------------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | +| `vp dotenv init` | `varlock init` | Scaffold `.env.schema` from existing `.env` files, add the `.gitignore` exception, offer type generation. | +| `vp dotenv check` | `varlock load` | Validate schema plus local values. No output on success, exit non-zero on errors. Never prints values. This is the CI entry point. | +| `vp dotenv print` | `varlock printenv` | Print resolved values as `env`, `json`, or `shell`. Sensitive values are masked unless `--reveal` is passed. | +| `vp dotenv explain` | `varlock explain` | Pretty-print every item with type, source, and sensitivity, values masked. | +| `vp dotenv scan` | `varlock scan` | Find plaintext secrets in files, staged changes, or build output. | +| `vp dotenv exec -- ` | `varlock run` | Inject resolved env into a subprocess with stdout redaction. | + +Implementation follows the `staged` template exactly: + +- A branch in `packages/cli/src/bin.ts` that lazy-imports `./dotenv/bin.js`. +- A tsdown entry `'dotenv/bin': './src/dotenv/bin.ts'` in `packages/cli/tsdown.config.ts`. +- A `Commands::Dotenv` variant in `crates/vp_global_cli/src/cli.rs` delegating through `commands/delegate.rs`, with `disable_help_flag` and trailing var args. +- Help rows in both `help.rs` files (section "Develop" or a new "Config" row), plus `skip_clap_unified_help`. +- Output through `packages/cli/src/utils/terminal.ts`, prompts through `@voidzero-dev/vite-plus-prompts`. + +The wrapper stays thin: it resolves the bundled varlock, maps Vite+ conventions (project root, managed Node, telemetry off), and forwards everything else. `vp help dotenv` documents the mapping. Power users can always run `vpx varlock ` for upstream commands Vite+ does not surface (encryption, plugins, proxy). + +### 3. Vite and Vitest integration + +**Activation**: `defineConfig` injects `@varlock/vite-integration` through the existing `injectPluginIntoInlineConfig` path when both hold: + +1. A `.env.schema` file exists at the project root (or at the configured path). +2. The project config does not disable it. + +Config key, grouped under one Vite+ extension to keep the surface small: + +```ts +export default defineConfig({ + dotenv: { + schema: true, // default: auto (true when .env.schema exists) + scanBuildOutput: true, // default: true when schema is active + }, +}); +``` + +Rules: + +- **Metadata-resolution guard**: the injection is skipped when `VP_RESOLVING_CONFIG_METADATA` is set, like every other built-in plugin. Schema errors must not break `vp run` config extraction. +- **Static extractor**: `crates/vp_static_config` is unchanged. It never reads `.env` files today and continues not to. The `dotenv` key is a plain literal in most configs, so the extractor can report it statically, which Phase 3 uses. +- **Mode mapping**: when the schema declares `@currentEnv` (e.g. `$APP_ENV`) and that variable is unset in the ambient environment, the integration derives it from Vite's `mode` (`development` for dev, `production` for build, `test` under Vitest). An explicit ambient value always wins. This gives upstream varlock semantics while keeping `vp build --mode staging` meaningful. +- **`envDir`**: the varlock plugin ignores Vite's `envDir` and warns. Vite+ surfaces that warning through its own output helper and documents `dotenv.schema: ''` as the replacement. +- **Vitest**: the same injection applies to `vp test`, via the existing test-side plugin injection. Two test-specific defaults: console-patch redaction is **disabled under Vitest** by default (patched console methods would interfere with test reporters and snapshot output), and validation failures fail fast before the run starts. A `dotenv.redactInTests: true` escape hatch re-enables redaction. +- **`vp pack` (tsdown)**: out of scope for Phase 1. tsdown keeps its `--env-file` flags. A later phase can add an equivalent tsdown integration, tracked as an open question. + +What users get with zero config beyond the schema file: validated env on every dev/build/test, `ENV.xxx` build-time inlining without the `VITE_` prefix, build-output leak scanning, and generated types. + +### 4. Secret scanning and git hooks + +- `vp dotenv scan` wraps `varlock scan` (section 2). +- **`vp staged` / git hooks**: when a project has `.env.schema`, the hook flow installed by `vp create` (`installGitHooks`) adds `varlock scan --staged` as a pre-commit step. Existing projects opt in through the same hooks configuration. +- **`vp check`**: add `dotenv` as a check step that runs `vp dotenv check` plus `vp dotenv scan`, active only when `.env.schema` exists. This keeps "the one command CI runs" accurate. +- Build-output scanning is already part of the Vite plugin (section 3), so bundled client secrets are caught at `vp build` time even without hooks. + +### 5. `vp create` and `vp migrate` + +**`vp create`**: + +- Fix `DOTENV_GITIGNORE_LINES` to add `!.env.schema` (`packages/cli/src/create/utils.ts:222`). This change ships unconditionally and first: without it, a scaffolded schema silently disappears from git. +- Add an opt-in prompt ("Set up a typed .env schema?") alongside the existing agents/editors/hooks prompts. On yes: write a starter `.env.schema` with `@generateTsTypes` enabled, add `env.d.ts` to `tsconfig.json` include, and extend the generated agent instructions (`writeAgentInstructions`) with one rule: _read `.env.schema` for env structure, never read `.env` or `.env.local`_. This is the "AI-safe" half of the feature and a genuine differentiator for Vite+ projects. + +**`vp migrate`**: + +- Add `varlock` to `KNOWN_RUNNER_WRAPPERS` so existing `varlock run --` wrappers in scripts are recognized and preserved (inner command rewritten, wrapper kept). +- New migrator module `env-schema.ts` in `packages/cli/src/migration/migrator/`: detect `.env.example`, `dotenv`/`dotenvx` dependencies, or `VITE_`-prefixed usage, and offer to generate `.env.schema` through varlock's init logic, with `@defaultSensitive=inferFromPrefix('VITE_')` as the compatibility default so behavior does not change silently. `dotenv -e` script wrappers are reported in the migration summary with a suggested `vp dotenv exec --` replacement, but are not rewritten automatically in the first release. +- A corresponding entry in `docs/guide/migrate-rules.md` and the migration report. + +### 6. `vp run` task integration (Phase 3) + +Tasks today run in a filtered, fingerprinted environment, which is the right default. Varlock integration extends it in two steps: + +**Step A - no engine changes (works from Phase 1):** + +- A task that itself runs Vite/Vitest gets validation through the injected plugin. +- Any other task can be wrapped: `command: 'vp dotenv exec -- node script.js'`. fspy already records the `.env*` file reads as cache inputs, so edits to `.env` or `.env.schema` correctly invalidate the cache. + +**Step B - first-class injection (opt-in):** + +```ts +run: { + tasks: { + deploy: { + command: 'node deploy.js', + dotenv: true, // or a filter: { dotenv: ['STRIPE_*', '!*_SECRET'] } + }, + }, +} +``` + +- Resolution runs once per `vp run` invocation in the JS layer and reaches the Rust runner through the existing resolver env merge (`merge_resolved_envs`, `packages/cli/binding/src/cli/resolver.rs:311`), before the child env is assembled. +- **Fingerprinting**: non-sensitive resolved values are fingerprinted by value, like `cache.env` today. Sensitive values are fingerprinted as a salted hash so a rotated secret invalidates the cache without the plaintext entering fingerprint storage or logs. Cache-miss output keeps printing names only (already the behavior). +- Keys selected by `dotenv` behave as if listed in `cache.env`: visible to the task and tracked. `untrackedEnv` semantics are unchanged. +- Resolution cost is paid once per invocation, not per task, and varlock's own disk cache (`@cache=disk`) applies. + +Step B is the largest engineering item in this RFC (it crosses the NAPI boundary and the fingerprint format) and is deliberately last. + +### 7. Rust/JS boundary + +All env-spec parsing and resolution stays in the JS layer: + +- `vp dotenv` is a delegated JS command (like `staged`), so the global Rust CLI never parses schemas. +- The Vite/Vitest plugin runs inside Node anyway. +- Phase 3 injection resolves in JS and hands Rust a resolved map through the existing resolver-env channel. + +**Rejected alternative**: a Rust env-spec parser (a `vp_env_spec` crate) for the static-config fast path. The grammar is young and still moving (varlock is at 1.x with an open RFC), a second implementation would drift, and no hot path needs it: config extraction does not depend on env values, and `vp run` resolution happens once per invocation where Node startup is already paid. Revisit only if a future feature needs schema data before any JS runs. + +### 8. Documentation + +- New guide `docs/guide/dotenv.md` (schema workflow, sensitivity model, environments, agents) and reference `docs/config/dotenv.md` (the `dotenv` config key, task `dotenv` option). +- `docs/guide/run.md` and `docs/guide/cache.md` gain a short "env schemas" cross-reference. +- The bundled varlock version joins the version table maintained by the upstream-dependency docs sync. + +## Rollout + +| Phase | Scope | Risk | +| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | +| 1 | Bundle varlock + plugin, `vite-plus/env` re-export, `vp dotenv init/check/explain/scan/run`, auto plugin injection for dev/build/test, `.gitignore` fix, docs | Low: additive, inert without `.env.schema` | +| 2 | `vp create` prompt + agent guidance, `vp migrate` module + wrapper recognition, git-hook scan step, `vp check` step | Low-medium: touches scaffolding flows | +| 3 | `vp run` task injection + sensitive-value fingerprinting, tsdown/`vp pack` integration decision | Medium: cache format and NAPI surface | + +Every phase is inert for projects without a `.env.schema` file. Existing dotenv behavior (Vite's `loadEnv`, `VITE_` prefix) is untouched until a project adopts the schema, and `@defaultSensitive=inferFromPrefix('VITE_')` gives a no-behavior-change adoption path. + +## Risks and mitigations + +- **Upstream velocity.** Varlock is pre-2.0 and the env-spec RFC is open. Mitigation: pin the version in `toolchain.config.json`, cover the `vp dotenv` surface and plugin injection with CLI snapshot fixtures, and route upgrades through the existing upstream-bump flow. +- **Node >= 22.3 floor.** Projects pinned to older Node get a clear actionable error from `vp dotenv` and from plugin injection, not a crash (section 1). +- **Console/stream patching side effects.** Redaction patches global `console` and can patch `process.stdout.write`. Mitigation: disabled under Vitest by default, and the `dotenv` config key can disable redaction while keeping validation. +- **Two sources of truth during adoption.** A project with both `.env.example` and `.env.schema` is confusing. `vp dotenv init` and the migrator offer to delete `.env.example` after generating the schema, and `vp dotenv check` warns when both exist. +- **`envDir` users.** The varlock plugin ignores `envDir`. The injection detects a configured `envDir` and surfaces a migration hint before the upstream warning fires. +- **Snapshot-test flakiness.** `vp dotenv` fixtures must avoid network (no plugin installs) and keep caches isolated per case, per the snapshot-runner rules. + +## Open questions + +1. **`vp pack` / tsdown**: should library builds get the same schema loading (replacing `--env-file`)? Depends on an upstream tsdown integration or a small Vite+-owned shim. +2. **`vp check` default**: should the dotenv step be on by default when a schema exists, or opt-in for one release first? +3. **Mode mapping details**: exact precedence between `--mode`, `APP_ENV`, and `@currentEnv` for preview environments (e.g. `vite preview`). +4. **`vpx --env-file`**: deprecate in favor of `vp dotenv exec --` once Phase 1 lands, or keep both indefinitely? +5. **Monorepos**: varlock's `loadPath` is cwd-based. How schema files compose across workspace packages (one root schema with `@import` vs per-package schemas) needs a worked example before the docs ship. +6. **Reclaiming the `env` name**: `env` is the most accurate name for this feature, and users will ask why `vp env` does not manage `.env` files. A future major release could rename runtime management to `vp runtime` (or fold it into `vp toolchain`, which has its own RFC) and make `vp env` the dotenv family, with `vp dotenv` kept as an alias. This is a breaking change and is out of scope here, but the `vp dotenv` surface should avoid any design that would make such a rename harder. + +## Rejected alternatives + +- **`vp env` subcommands** (`vp env check`): collides with runtime management, both in dispatch and in user mental model. +- **Inline varlock as a devDependency** (the `lint-staged` pattern): breaks the shared-copy requirement between plugin and runtime `ENV`, and breaks native optional dependencies. +- **Ship the standalone varlock binary**: duplicates distribution and bypasses the managed Node runtime for no capability gain. +- **Vite+-owned schema format**: env-spec is tool-agnostic, has editor support (VS Code extension), an ecosystem of secret-manager plugins, and an upstream community. Owning a format would buy control and cost compatibility. +- **Rust parser port**: see section 7. From 59377ce545af789df10f4c7f91833807952948fb Mon Sep 17 00:00:00 2001 From: "MK (fengmk2)" Date: Wed, 28 Oct 2026 14:22:29 +0900 Subject: [PATCH 02/28] wip: add vp dotenv and the varlock Vite integration Phase 1 of rfcs/varlock-integration.md: - `vp dotenv init|check|print|explain|scan|exec`, parsed by clap in the native binding and run through the bundled varlock CLI script. - Load `@varlock/vite-integration` from `defineConfig` when the project root has `.env.schema`, with a resolve plugin for `varlock/*` imports and a client build-output scan. The new `dotenv` config key controls it. - `vite-plus/env` re-exports `varlock/env`. - Pin varlock and its Vite integration, and report varlock in the toolchain and version output. - Keep `.env.schema` tracked in the `vp create` .gitignore default. - Align the RFC and docs with varlock's actual CLI and plugin behavior. Not done yet: pnpm-lock.yaml does not include varlock, the native binding and global CLI are not compiled, the hand-edited binding index files are unchecked against napi output, and the affected CLI snapshots are not re-recorded. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + crates/vp_global_cli/src/cli.rs | 9 + crates/vp_global_cli/src/commands/dotenv.rs | 16 + crates/vp_global_cli/src/commands/mod.rs | 1 + crates/vp_global_cli/src/help.rs | 2 + docs/config/dotenv.md | 62 +--- docs/config/run.md | 22 -- docs/guide/cache.md | 2 +- docs/guide/dotenv.md | 161 ++++----- packages/cli/binding/index.cjs | 1 + packages/cli/binding/index.d.cts | 19 ++ packages/cli/binding/src/cli/help.rs | 4 +- .../src/js_command_args/commands/dotenv.rs | 321 ++++++++++++++++++ .../src/js_command_args/commands/mod.rs | 1 + packages/cli/package.json | 6 + .../cli/src/__tests__/js-command-args.spec.ts | 21 ++ packages/cli/src/__tests__/toolchain.spec.ts | 1 + packages/cli/src/__tests__/versions.spec.ts | 1 + packages/cli/src/bin.ts | 4 +- .../cli/src/create/__tests__/utils.spec.ts | 13 +- packages/cli/src/create/utils.ts | 1 + packages/cli/src/define-config.ts | 26 +- .../cli/src/dotenv/__tests__/varlock.spec.ts | 185 ++++++++++ .../src/dotenv/__tests__/vite-plugin.spec.ts | 128 +++++++ packages/cli/src/dotenv/bin.ts | 72 ++++ packages/cli/src/dotenv/varlock.ts | 196 +++++++++++ packages/cli/src/dotenv/vite-plugin.ts | 187 ++++++++++ packages/cli/src/env.ts | 8 + packages/cli/src/utils/command.ts | 26 ++ packages/cli/src/utils/terminal.ts | 6 +- packages/cli/src/version.ts | 1 + packages/cli/toolchain.config.json | 27 +- packages/cli/tsdown.config.ts | 2 + pnpm-workspace.yaml | 5 + rfcs/varlock-integration.md | 107 +++--- 35 files changed, 1417 insertions(+), 228 deletions(-) create mode 100644 crates/vp_global_cli/src/commands/dotenv.rs create mode 100644 packages/cli/binding/src/js_command_args/commands/dotenv.rs create mode 100644 packages/cli/src/dotenv/__tests__/varlock.spec.ts create mode 100644 packages/cli/src/dotenv/__tests__/vite-plugin.spec.ts create mode 100644 packages/cli/src/dotenv/bin.ts create mode 100644 packages/cli/src/dotenv/varlock.ts create mode 100644 packages/cli/src/dotenv/vite-plugin.ts create mode 100644 packages/cli/src/env.ts diff --git a/README.md b/README.md index 2d1fabcb08..ebf265f21e 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,7 @@ Use `vp migrate` to migrate to Vite+. It merges tool-specific config files such - **lint** - Lint code - **fmt** - Format code - **test** - Run tests +- **dotenv** - Manage `.env` files with a validated schema #### Execute diff --git a/crates/vp_global_cli/src/cli.rs b/crates/vp_global_cli/src/cli.rs index 610c50dddd..217554d4fd 100644 --- a/crates/vp_global_cli/src/cli.rs +++ b/crates/vp_global_cli/src/cli.rs @@ -118,6 +118,13 @@ pub enum Commands { args: Vec, }, + /// Manage .env files with a validated .env.schema + #[command(disable_help_flag = true)] + Dotenv { + #[arg(trailing_var_arg = true, allow_hyphen_values = true)] + args: Vec, + }, + // ========================================================================= // Category C: Local CLI Delegation (forwarded to the local vite-plus CLI) // ========================================================================= @@ -1180,6 +1187,8 @@ pub async fn run_command_with_options( Commands::Staged { args } => commands::staged::execute(cwd, &args, raw_subcommand).await, + Commands::Dotenv { args } => commands::dotenv::execute(cwd, &args, raw_subcommand).await, + // Category C: Local CLI Delegation (forwarded to the local vite-plus CLI) Commands::Dev { args } => { maybe_print_runtime_header("dev", &args, render_options.show_header); diff --git a/crates/vp_global_cli/src/commands/dotenv.rs b/crates/vp_global_cli/src/commands/dotenv.rs new file mode 100644 index 0000000000..5695ee1133 --- /dev/null +++ b/crates/vp_global_cli/src/commands/dotenv.rs @@ -0,0 +1,16 @@ +//! Dotenv command (Category B: JavaScript Command). + +use std::process::ExitStatus; + +use vt_path::AbsolutePathBuf; + +use crate::error::Error; + +/// Execute the `dotenv` command by delegating to local or global vite-plus. +pub async fn execute( + cwd: AbsolutePathBuf, + args: &[String], + raw_subcommand: Option<&str>, +) -> Result { + super::delegate::execute(cwd, "dotenv", args, raw_subcommand).await +} diff --git a/crates/vp_global_cli/src/commands/mod.rs b/crates/vp_global_cli/src/commands/mod.rs index 1474c1bcfb..b8147945ff 100644 --- a/crates/vp_global_cli/src/commands/mod.rs +++ b/crates/vp_global_cli/src/commands/mod.rs @@ -202,6 +202,7 @@ pub mod global; // Category B: JS Script Commands pub mod config; pub mod create; +pub mod dotenv; pub mod hooks; pub mod migrate; pub mod staged; diff --git a/crates/vp_global_cli/src/help.rs b/crates/vp_global_cli/src/help.rs index 915fe4af75..fb4ff9d68d 100644 --- a/crates/vp_global_cli/src/help.rs +++ b/crates/vp_global_cli/src/help.rs @@ -277,6 +277,7 @@ pub fn top_level_help_doc() -> HelpDoc { row("lint", "Lint code"), row("fmt, format", "Format code"), row("test", "Run tests"), + row("dotenv", "Manage .env files with a validated schema"), ], ), section_rows( @@ -432,6 +433,7 @@ fn skip_clap_unified_help(command: &str) -> bool { | "config" | "hooks" | "staged" + | "dotenv" | "dev" | "build" | "preview" diff --git a/docs/config/dotenv.md b/docs/config/dotenv.md index eb80f08391..dba5e77064 100644 --- a/docs/config/dotenv.md +++ b/docs/config/dotenv.md @@ -2,7 +2,7 @@ `vp dev`, `vp build`, `vp preview`, and `vp test` load and validate `.env` files against `.env.schema` when the file exists. The `dotenv` block in `vite.config.ts` controls that loading. See [Env Files](/guide/dotenv). -Every option has a default that works for a project with a `.env.schema` file at the root. Most projects do not need this block. +Both options have defaults that suit a project with `.env.schema` at its root. Most projects do not need this block. ## Example @@ -12,12 +12,9 @@ import { defineConfig } from 'vite-plus'; export default defineConfig({ dotenv: { // Load and validate `.env.schema`. Defaults to `'auto'`: on when the - // file exists at the project root, off otherwise. + // project root has `.env.schema`, off otherwise. schema: 'auto', - // Redact sensitive values from console output in dev and server code. - // Defaults to true, except under `vp test` where it defaults to false. - redact: true, - // Fail `vp build` when a sensitive value appears in the output. + // Fail `vp build` when a sensitive value appears in the client output. // Defaults to true. scanBuildOutput: true, }, @@ -26,61 +23,24 @@ export default defineConfig({ ## `schema` -- **Type:** `'auto' | boolean | string` +- **Type:** `'auto' | boolean` - **Default:** `'auto'` -Controls whether and where the schema loads: +Controls whether the schema loads: -- `'auto'`: load `.env.schema` from the project root when it exists. -- `true`: require a schema. Fail when `.env.schema` is missing. Use this in a project that must never run without validation. +- `'auto'`: load the schema when the project root has `.env.schema`, or when its `package.json` sets `varlock.loadPath`. +- `true`: require a schema. The command fails when neither exists. Use this in a project that must never run without validation. - `false`: never load a schema, even when the file exists. Vite's own `.env` handling applies. -- A path: load the schema from that file or directory instead of the root, for example `'./config/env'`. Relative paths resolve from the config file. When a directory is given, `.env.schema`, `.env`, `.env.local`, and the environment files in that directory are loaded in the [usual order](/guide/dotenv#file-loading-order). -Vite's `envDir` option is ignored while a schema is active. Vite+ prints a `note:` line when both are set. - -## `redact` - -- **Type:** `boolean | { console?: boolean; stdout?: boolean }` -- **Default:** `true` for `vp dev`, `vp build`, and `vp preview`; `false` for `vp test` - -Redaction replaces sensitive values with `▒` characters before they reach the terminal. - -- `console`: patch `console.log`, `console.error`, and the other console methods. This is what most projects want. -- `stdout`: also patch `process.stdout.write` and `process.stderr.write` for non-TTY output. Values split across two writes can be partly exposed, so Vite+ prints a one-time warning when this layer is on. -- `true` is `{ console: true, stdout: false }`. `false` disables both. - -Under `vp test`, redaction is off by default because patched console methods interfere with reporters and snapshot output. Set `redact: true` to turn it on there too. - -The build-output scan and the HTTP response guard are not affected by this option. Use the schema decorators `@preventLeaks=false` or `@sensitive={redact=false}` to exempt one variable. +The project root is the `root` option of the config, or the working directory. To keep the schema files in another directory, set [`varlock.loadPath`](https://varlock.dev/reference/cli-commands/) in `package.json`. `vp dotenv` and the build use the same setting. Vite's `envDir` option is not supported while a schema is active. ## `scanBuildOutput` - **Type:** `boolean` - **Default:** `true` -After `vp build` writes its output, scan every emitted file for a plaintext copy of a sensitive value. On a hit, the build fails and the error names the variable and the file. Set to `false` for a server-only build where every value is allowed in the output, or run [`vp dotenv scan dist/`](/guide/dotenv#vp-dotenv-scan) yourself at another point in the pipeline. - -## Task option: `run.tasks..dotenv` - -- **Type:** `boolean | string[]` -- **Default:** `false` - -Set on a [task](/config/run#tasks) to inject schema variables into the task process and track them in its cache key: - -```ts [vite.config.ts] -export default defineConfig({ - run: { - tasks: { - seed: { command: 'node scripts/seed.ts', dotenv: true }, - deploy: { command: 'node deploy.ts', dotenv: ['DEPLOY_*', '!DEPLOY_TOKEN'] }, - }, - }, -}); -``` - -- `true`: every variable in the schema. -- An array of patterns: the same syntax as [`cache.env`](/config/run#cache-env), with `*` wildcards and `!` exclusions. +After `vp build` writes the client output, scan every emitted file for a plaintext copy of a sensitive value. On a match, the build fails and the scan output lists each match. Server output is not scanned. Set the option to `false` when every value is allowed in the output, or run [`vp dotenv scan`](/guide/dotenv#vp-dotenv-scan) yourself at another point in the pipeline. -Selected variables behave as if listed in `cache.env`. Public values are fingerprinted by value. Sensitive values are fingerprinted through a salted hash, so the plaintext never enters the cache store and a rotated secret still invalidates the cache. A variable matched by both `dotenv` and [`cache.untrackedEnv`](/config/run#cache-untrackedenv) is passed through but not fingerprinted. +## Redaction -Resolution runs once per `vp run` invocation and is shared by every task that opts in. +Log redaction and the HTTP response guard are configured in the schema, not in `vite.config.ts`. Use the `@redact` root decorator, or `@sensitive={redact=false}` on one variable. See the [varlock documentation](https://varlock.dev). diff --git a/docs/config/run.md b/docs/config/run.md index 06d98247ac..b4a0c50a66 100644 --- a/docs/config/run.md +++ b/docs/config/run.md @@ -469,28 +469,6 @@ tasks: { } ``` -### `dotenv` - -- **Type:** `boolean | string[]` -- **Default:** `false` - -Inject variables from `.env.schema` and the local `.env` files into the task, and track them in its cache key. `true` selects every variable in the schema. An array uses the same pattern syntax as [`cache.env`](#cache-env). - -```ts [vite.config.ts] -tasks: { - seed: { - command: 'node scripts/seed.ts', - dotenv: true, - }, - deploy: { - command: 'node deploy.ts', - dotenv: ['DEPLOY_*', '!DEPLOY_TOKEN'], - }, -} -``` - -Public values are fingerprinted by value. Sensitive values are fingerprinted through a salted hash, so the plaintext never enters the cache store. See [Dotenv Config](/config/dotenv#task-option-run-tasks-name-dotenv) and [Env Files](/guide/dotenv#using-env-files-in-tasks). - ### `cwd` - **Type:** `string` diff --git a/docs/guide/cache.md b/docs/guide/cache.md index 129aae7963..dd3fc3f1bb 100644 --- a/docs/guide/cache.md +++ b/docs/guide/cache.md @@ -83,7 +83,7 @@ tasks: { To pass a variable to the task **without** affecting cache behavior, use [`cache.untrackedEnv`](/config/run#cache-untrackedenv). This is useful for variables like `CI` or `GITHUB_ACTIONS` that should be available in the task, but do not affect caching behavior. -Values from `.env` files are not passed through either. When the project has a `.env.schema` file, set [`dotenv`](/config/run#dotenv) on the task to inject and track them. See [Env Files](/guide/dotenv#using-env-files-in-tasks). +Values from `.env` files are not passed through either. When the project has a `.env.schema` file, run the task's command through `vp dotenv exec --` to give it the resolved values. See [Env Files](/guide/dotenv#using-env-files-in-tasks). See [Run Config](/config/run#cache-env) for details on wildcard patterns and the full list of automatically passed-through variables. diff --git a/docs/guide/dotenv.md b/docs/guide/dotenv.md index 322bda4ce3..8141c3b461 100644 --- a/docs/guide/dotenv.md +++ b/docs/guide/dotenv.md @@ -1,6 +1,6 @@ # Env Files -Use `vp dotenv` to manage `.env` files with a committed schema. Vite+ validates environment variables, generates types, keeps secrets out of bundles and logs, and gives coding agents the structure of your config without the values. +Use `vp dotenv` to manage `.env` files with a committed schema. Vite+ validates environment variables, generates types, keeps secrets out of client bundles and logs, and gives coding agents the structure of your config without the values. ## Overview @@ -8,6 +8,7 @@ A plain `.env.example` goes stale the moment someone adds a variable. Vite+ repl ```env-spec [.env.schema] # @defaultSensitive=false +# @currentEnv=$APP_ENV # @generateTsTypes(path='env.d.ts') # --- @@ -17,13 +18,16 @@ APP_ENV=development # @required @type=url API_URL=http://localhost:3000 +# @type=port +API_PORT=3000 + # @required @sensitive @type=string(startsWith=sk_) STRIPE_SECRET_KEY= ``` -`.env.schema` is committed to git. Your real values stay in `.env.local`, which is git-ignored. Every time you run `vp dev`, `vp build`, or `vp test`, Vite+ loads the schema, layers your local values on top, and validates the result before any code runs. +`.env.schema` is committed to git. Your real values stay in `.env.local`, which is git-ignored. When the project root has a `.env.schema` file, `vp dev`, `vp build`, `vp preview`, and `vp test` load the schema, layer your local values on top, and validate the result before any code runs. -The schema format is [@env-spec](https://varlock.dev/env-spec/), and `vp dotenv` is powered by [varlock](https://varlock.dev). Vite+ bundles it, so there is nothing to install. If you use [`vp create`](/guide/create) or [`vp migrate`](/guide/migrate), Vite+ prompts you to set this up for your project automatically. +The schema format is [@env-spec](https://varlock.dev/env-spec/), and `vp dotenv` is powered by [varlock](https://varlock.dev). Vite+ bundles varlock and its Vite integration, so there is nothing to install or register. ::: tip `vp env` vs `vp dotenv` [`vp env`](/guide/env) manages Node.js and package-manager versions. `vp dotenv` manages `.env` files. They are unrelated. @@ -34,89 +38,77 @@ The schema format is [@env-spec](https://varlock.dev/env-spec/), and `vp dotenv` Run `vp dotenv init` in a project that already has `.env` files: ```bash -$ vp dotenv init -info: Found .env.example, .env.local -✓ Wrote .env.schema (6 items, 1 sensitive) -✓ Added !.env.schema to .gitignore -✓ Enabled TypeScript types (env.d.ts) -note: Review .env.schema and mark secrets with @sensitive, then delete .env.example. +vp dotenv init ``` -`init` reads your existing files, infers a type for each variable where it can, and marks anything that looks like a secret as `@sensitive` for you to confirm. From now on, `vp dev` validates before it starts: +`init` scans your `.env` files and your code, writes `.env.schema` with decorators inferred for each variable, and adds `!.env.schema` to `.gitignore` when the file would otherwise be ignored. Review the schema and mark each secret with `@sensitive`. -```bash -$ vp dev -error: STRIPE_SECRET_KEY is required but has no value -note: Set it in .env.local, or run `vp dotenv explain` to see every item -``` +`varlock init` also adds `varlock` to the `dependencies` in `package.json`. Vite+ already bundles varlock, so `vp dotenv init` prints a warning when this happens. Remove the extra copy with `vp remove varlock`. -Add the value to `.env.local` and the server starts. In application code, use the typed `ENV` object: +From now on, `vp dev` validates before it serves the app. When a required value is missing or has the wrong type, the terminal and the browser show varlock's error, and `vp build` stops with exit code 1. Add the value to `.env.local` and try again. In application code, use the typed `ENV` object: ```ts [src/api.ts] import { ENV } from 'vite-plus/env'; fetch(`${ENV.API_URL}/items`); // string, inlined at build time ENV.API_PORT; // number, not string -ENV.STRIPE_SECRET_KEY; // only available server-side, see below +ENV.STRIPE_SECRET_KEY; // sensitive: never inlined into client code ``` -`import.meta.env.VITE_*` keeps working for variables with the `VITE_` prefix. `ENV` is the recommended API: it is typed, it coerces numbers and booleans, and it does not need a prefix. +`import.meta.env.VITE_*` keeps working for variables with the `VITE_` prefix. `ENV` is the recommended API: it is typed, it coerces numbers and booleans, and it does not need a prefix. Code that imports `ENV` from `varlock/env`, as in the varlock documentation, gets the same object. ## The `.env.schema` file -A schema is a `.env` file with JSDoc-style comments. Lines above `# ---` are root decorators and apply to the whole file. A comment directly above a variable attaches decorators to that variable. +A schema is a `.env` file with JSDoc-style comments. Lines above `# ---` hold root decorators, which apply to the whole file. A comment directly above a variable attaches decorators to that variable. -### Root decorators +Common root decorators: -| Decorator | Meaning | -| -------------------------------------------- | -------------------------------------------------------------------------------------- | -| `@defaultSensitive=false` | Variables are public unless marked `@sensitive`. Use `true` to flip the default. | -| `@defaultSensitive=inferFromPrefix('VITE_')` | Vite compatibility: `VITE_*` is public, everything else is sensitive. | -| `@defaultRequired=infer` | A variable with a non-empty value in the schema is optional, an empty one is required. | -| `@currentEnv=$APP_ENV` | Which variable selects the environment and so which `.env.` files load. | -| `@generateTsTypes(path='env.d.ts')` | Write a type declaration for `ENV` on every load. | +| Decorator | Meaning | +| -------------------------------------------- | ---------------------------------------------------------------------------------- | +| `@defaultSensitive=false` | Variables are public unless marked `@sensitive`. Use `true` to flip the default. | +| `@defaultSensitive=inferFromPrefix('VITE_')` | Vite compatibility: `VITE_*` is public, everything else is sensitive. | +| `@currentEnv=$APP_ENV` | The variable that selects the environment, and so which `.env.[env]` files load. | +| `@generateTsTypes(path='env.d.ts')` | Write a type declaration for `ENV` on every load. Add the file to `tsconfig.json`. | -### Item decorators +Common item decorators: | Decorator | Meaning | | -------------- | ----------------------------------------------------------------- | | `@required` | Fail validation when the value is empty. | -| `@optional` | Allow an empty value even when the root default is required. | | `@sensitive` | Treat as a secret: never inline into client code, redact in logs. | -| `@type=` | Validate and coerce. See the types below. | -| `@example=...` | A sample value shown in `vp dotenv explain` and in editor hovers. | +| `@type=` | Validate and coerce, for example `url`, `port`, or `enum(a, b)`. | | `@docs(url)` | Link to documentation for the variable. | -### Types - -`string`, `number`, `boolean`, `url`, `port`, `email`, `enum(a, b, c)`, `string(startsWith=...)`, `number(min=..., max=...)`, and more. Any variable without `@type` is a `string`. See the [varlock type reference](https://varlock.dev/reference/item-decorators/) for the full list. - -### Value expansion - -A value can reference another variable: `API_URL=http://localhost:${API_PORT}`. Expansion happens after all files load, so a value in `.env.local` can refer to one in `.env.schema`. +A value can reference another variable: `API_URL=http://localhost:${API_PORT}`. See the [varlock documentation](https://varlock.dev) for every decorator, type, and value function, including loaders for secret managers such as 1Password. ## File loading order -Vite+ loads these files from the project root, later files override earlier ones: +Vite+ loads these files from the project root. Later entries override earlier ones: 1. `.env.schema`: the committed schema and default values -2. `.env`: shared local defaults, usually git-ignored -3. `.env.`: values for one environment, for example `.env.production` -4. `.env.local`: your machine-only values, git-ignored -5. `.env..local`: machine-only values for one environment -6. The shell environment: a variable already set in the process always wins +2. `.env`: loaded, but prefer the files below +3. `.env.local`: your machine-only values, git-ignored +4. `.env.[env]`: values for one environment, for example `.env.production` +5. `.env.[env].local`: machine-only values for one environment, git-ignored +6. The process environment: a variable already set in the shell always wins -`` comes from the `@currentEnv` root decorator. If the schema declares `@currentEnv=$APP_ENV` and `APP_ENV` is not set in the shell, Vite+ derives it from the command: `development` for `vp dev`, `production` for `vp build` and `vp preview`, `test` for `vp test`. Pass `--mode staging` or set `APP_ENV=staging` to pick another one. An explicit `APP_ENV` always wins over `--mode`. +`[env]` is the value of the variable that `@currentEnv` names. To build for staging with the schema above, set that variable: -Vite's `envDir` option is not supported when a schema is active. Set [`dotenv.schema`](/config/dotenv#schema) to a path instead. +```bash +APP_ENV=staging vp build +``` + +Vite's `--mode` flag does not change the varlock environment. + +To keep the schema somewhere other than the project root, set `varlock.loadPath` in `package.json`. Vite's `envDir` option is not supported while a schema is active. ## Sensitive values -Mark a secret with `@sensitive`, or flip the default with `@defaultSensitive=true` and mark public values with `@sensitive=false`. A sensitive value is protected in three places: +Mark a secret with `@sensitive`, or flip the default with `@defaultSensitive=true`. A sensitive value is protected in three places: -- **Client bundles.** `vp build` inlines only public values. If a sensitive value still ends up in the output, for example through `import.meta.env` or a hard-coded copy, the build fails and names the variable and the chunk. -- **Logs.** In `vp dev` and in server-side code, `console.log` and friends print `STRIPE_SECRET_KEY=sk_▒▒▒▒▒▒▒▒` instead of the value. Redaction is off under `vp test` by default so reporters and snapshots are not affected. See [`dotenv.redact`](/config/dotenv#redact). -- **HTTP responses.** Server-side code that would send a sensitive value in a response body throws instead. +- **Client bundles.** `vp build` inlines only public values. After the build writes the client output, Vite+ runs [`vp dotenv scan`](#vp-dotenv-scan) on it. If a sensitive value appears there, for example through a hard-coded copy, the scan lists each match and the build fails. See [`dotenv.scanBuildOutput`](/config/dotenv#scanbuildoutput). +- **Logs.** In `vp dev` and in server-side code, `console.log` and the other console methods print a masked value instead of the secret. Use the `@redact` root decorator in the schema to change this. +- **HTTP responses.** Server-side code that would send a sensitive value in a response body throws an error instead. These are guardrails against accidental exposure, not a sandbox. The running process still holds the plaintext. To print a value on purpose, use `revealSensitiveConfig()` from `vite-plus/env`. @@ -124,18 +116,17 @@ These are guardrails against accidental exposure, not a sandbox. The running pro ### `vp dotenv init` -Scaffold `.env.schema` from existing `.env`, `.env.example`, and `.env.local` files. Adds `!.env.schema` to `.gitignore`, and offers to enable type generation. Safe to re-run: it never overwrites an existing schema. +Create `.env.schema` from the existing `.env` files. See [Quick start](#quick-start). ### `vp dotenv check` -Validate the schema and the resolved values for the current environment. Prints nothing on success and exits non-zero on the first error. It never prints values, so it is safe in CI logs: +Validate the resolved values against the schema without printing them, which makes it safe in CI logs. On success it prints a `pass:` line. On failure varlock prints the errors and the command exits with a non-zero code: ```bash vp dotenv check -vp dotenv check --env production ``` -[`vp check`](/guide/check) runs `vp dotenv check` as one of its steps when the project has a `.env.schema` file. +`--env ` selects an environment when the schema does not use `@currentEnv`. With `@currentEnv`, set its variable instead, for example `APP_ENV=production vp dotenv check`. ### `vp dotenv print` @@ -148,48 +139,43 @@ vp dotenv print --format shell # export KEY=value lines for `eval` vp dotenv print --reveal --format env # plaintext, for a deploy step that needs it ``` -Without `--reveal`, a masked value looks like `STRIPE_SECRET_KEY=sk_▒▒▒▒▒▒▒▒`. Treat `--reveal` output like the contents of `.env.local`: do not pipe it into a log. +Treat `--reveal` output like the contents of `.env.local`: do not send it to a log. ### `vp dotenv explain` -Print every variable with its type, where its value came from, and whether it is sensitive. Sensitive values are masked: +Without an argument, list every item with its value, and mark which ones are sensitive. Sensitive values are masked. With a key, show the definitions, sources, and overrides that produce that one value: ```bash -$ vp dotenv explain -APP_ENV development enum .env.schema -API_URL http://localh… url .env.local -API_PORT 3000 port .env.schema (default) -STRIPE_SECRET_KEY sk_▒▒▒▒▒▒▒▒▒▒ string .env.local sensitive +vp dotenv explain +vp dotenv explain API_URL ``` ### `vp dotenv scan` -Search files for plaintext copies of sensitive values. Reports file, line, and variable name, and exits non-zero on any hit: +Search files for plaintext copies of sensitive values. It reports each match with its file and line, and exits with a non-zero code on any match: ```bash -vp dotenv scan # the whole project, respecting .gitignore -vp dotenv scan --staged # only files staged in git, for a pre-commit hook -vp dotenv scan dist/ # a build output directory +vp dotenv scan # the project, respecting .gitignore +vp dotenv scan --staged # only files staged in Git, for a pre-commit hook +vp dotenv scan --include-ignored dist/ # a build output directory ``` ### `vp dotenv exec` -Run any command with the resolved environment injected, for scripts and tools that are not Vite: +Run any command with the resolved environment, for scripts and tools that are not Vite: ```bash vp dotenv exec -- node scripts/seed.ts -vp dotenv exec --env production -- prisma migrate deploy +APP_ENV=production vp dotenv exec -- prisma migrate deploy ``` When output is piped or redirected, sensitive values are redacted from stdout and stderr. Output to a terminal is not redacted. -`vp dotenv exec` runs one command in the schema environment. [`vp run`](/guide/run) runs a task from `vite.config.ts`. To give a task the schema environment, see the next section. +`vp dotenv exec` runs one command in the schema environment. [`vp run`](/guide/run) runs a task from `vite.config.ts`. ## Using env files in tasks -A [`vp run`](/guide/run) task starts in a clean environment, so `.env` values do not reach it by default. Two options: - -Wrap the command when a single task needs the values: +A [`vp run`](/guide/run) task starts in a clean environment, so `.env` values do not reach it by default. To give a task the schema environment, run its command through `vp dotenv exec`: ```ts [vite.config.ts] export default defineConfig({ @@ -201,22 +187,7 @@ export default defineConfig({ }); ``` -Or let Vite+ inject them and track them for the [task cache](/guide/cache): - -```ts [vite.config.ts] -export default defineConfig({ - run: { - tasks: { - seed: { command: 'node scripts/seed.ts', dotenv: true }, - deploy: { command: 'node deploy.ts', dotenv: ['DEPLOY_*', '!DEPLOY_TOKEN'] }, - }, - }, -}); -``` - -With `dotenv: true`, every schema variable is visible to the task and part of its cache key. Public values are hashed by value. Sensitive values are hashed through a salt, so rotating a secret invalidates the cache without the plaintext entering the cache store. Cache-miss messages print only the variable name. See [`dotenv`](/config/run#dotenv) in the run config. - -Tasks that run `vp dev`, `vp build`, or `vp test` need neither option: those commands load the schema themselves. +The task cache already tracks the `.env` files that the command reads, so a changed value runs the task again. Tasks that run `vp dev`, `vp build`, or `vp test` need no wrapper: those commands load the schema themselves. ## Commit hooks and CI @@ -227,23 +198,15 @@ vp staged vp dotenv scan --staged ``` -When you opt into hooks during `vp create` and the project has a schema, Vite+ adds this line for you. In CI, `vp check` already covers validation. Add `vp dotenv scan dist/` after the build step if you deploy a client bundle. See [Commit Hooks](/guide/commit-hooks) and [CI](/guide/ci). - -## Migrating from `.env.example` or dotenv +In CI, run `vp dotenv check` before the build. See [Commit Hooks](/guide/commit-hooks) and [CI](/guide/ci). -[`vp migrate`](/guide/migrate) detects `.env.example`, `dotenv`, and `dotenvx` and offers to generate a schema. The generated schema starts with `@defaultSensitive=inferFromPrefix('VITE_')`, so `VITE_*` stays public and everything else is treated as a secret. Behavior does not change until you edit the schema. +## Server-side rendering -Scripts that use `dotenv -e .env.test -- ` are listed in the migration summary with the `vp dotenv exec --env test -- ` equivalent. They are not rewritten automatically. - -If you want to change the default so sensitivity is explicit per variable, replace the root decorator with `@defaultSensitive=false` and mark each secret with `@sensitive`. `vp dotenv check` warns while both `.env.example` and `.env.schema` exist. +The varlock integration adds startup code to server entry points, and that code imports varlock at runtime. When you deploy a server build, install `varlock` as a dependency of the server package, and start the server with `vp dotenv exec --` so that the resolved environment is present. ## Coding agents -The schema holds names, types, and descriptions. The values live in git-ignored files. When `vp create` or `vp config` writes agent instructions, it adds one rule: read `.env.schema` to learn the configuration, never read `.env`, `.env.local`, or other value files. An agent can then add a variable, write its type, and wire it into code without ever seeing a secret. - -## Requirements - -`vp dotenv` and schema loading require Node.js 22.3 or later. When the project pins an older runtime, the command exits with a message that names the pinned version, and `vp dev`, `vp build`, and `vp test` skip schema loading with a warning. +The schema holds names, types, and descriptions. The values live in git-ignored files. Tell your coding agent to read `.env.schema` to learn the configuration, and never to read `.env`, `.env.local`, or other value files. The agent can then add a variable, write its type, and use it in code without seeing a secret. ## Disabling diff --git a/packages/cli/binding/index.cjs b/packages/cli/binding/index.cjs index d049e7dee4..a339c4bc86 100644 --- a/packages/cli/binding/index.cjs +++ b/packages/cli/binding/index.cjs @@ -1119,6 +1119,7 @@ module.exports.mergeTsdownConfig = nativeBinding.mergeTsdownConfig; module.exports.migrateTaskCacheConfig = nativeBinding.migrateTaskCacheConfig; module.exports.parseConfigArgs = nativeBinding.parseConfigArgs; module.exports.parseCreateArgs = nativeBinding.parseCreateArgs; +module.exports.parseDotenvArgs = nativeBinding.parseDotenvArgs; module.exports.parseHooksArgs = nativeBinding.parseHooksArgs; module.exports.parseLiteralCommands = nativeBinding.parseLiteralCommands; module.exports.parseMigrateArgs = nativeBinding.parseMigrateArgs; diff --git a/packages/cli/binding/index.d.cts b/packages/cli/binding/index.d.cts index 65f53b067c..d972821192 100644 --- a/packages/cli/binding/index.d.cts +++ b/packages/cli/binding/index.d.cts @@ -3905,6 +3905,18 @@ export interface DevCommand { /** Build documentation links with the same compiled origin as the native CLI. */ export declare function documentationUrl(path: string): string; +export interface DotenvArgs { + command: 'init' | 'check' | 'print' | 'explain' | 'scan' | 'exec'; + env?: string; + format: 'env' | 'json' | 'shell'; + reveal: boolean; + key?: string; + targets: Array; + staged: boolean; + includeIgnored: boolean; + execCommand: Array; +} + /** * Download a package manager, or use the one on PATH when no global install manages it. * @@ -4145,6 +4157,13 @@ export type ParseCreateArgsOutcome = | { status: 'exit'; code: number } | { status: 'error'; error: CliParseError }; +export declare function parseDotenvArgs(argv: Array): ParseDotenvArgsOutcome; + +export type ParseDotenvArgsOutcome = + | { status: 'ok'; value: DotenvArgs } + | { status: 'exit'; code: number } + | { status: 'error'; error: CliParseError }; + export declare function parseHooksArgs(argv: Array): ParseHooksArgsOutcome; export type ParseHooksArgsOutcome = diff --git a/packages/cli/binding/src/cli/help.rs b/packages/cli/binding/src/cli/help.rs index a586d974b3..480d387a82 100644 --- a/packages/cli/binding/src/cli/help.rs +++ b/packages/cli/binding/src/cli/help.rs @@ -360,7 +360,9 @@ mod tests { fn global_subcommands_produce_invalid_subcommand_error() { use clap::error::ErrorKind; - for subcommand in ["config", "create", "env", "hooks", "implode", "migrate", "upgrade"] { + for subcommand in + ["config", "create", "dotenv", "env", "hooks", "implode", "migrate", "upgrade"] + { let error = CLIArgs::try_parse_from(["vp", subcommand]) .expect_err(&format!("expected error for global subcommand '{subcommand}'")); assert_eq!( diff --git a/packages/cli/binding/src/js_command_args/commands/dotenv.rs b/packages/cli/binding/src/js_command_args/commands/dotenv.rs new file mode 100644 index 0000000000..96314e05e2 --- /dev/null +++ b/packages/cli/binding/src/js_command_args/commands/dotenv.rs @@ -0,0 +1,321 @@ +use clap::{ArgAction, Args, Command, Subcommand, builder::NonEmptyStringValueParser}; +use napi_derive::napi; +use vp_cli_help::{HelpSection, help_doc_from_command, print_help_doc}; + +use crate::js_command_args::parser::{CliParseError, ParseResult, help_arg, parse_args}; + +const ENV_HELP: &str = "Environment to load, such as production (@currentEnv takes priority)"; + +#[derive(Debug, Args)] +struct DotenvCliArgs { + #[command(subcommand)] + command: DotenvSubcommand, +} + +#[derive(Debug, Subcommand)] +enum DotenvSubcommand { + /// Create .env.schema from the existing .env files + #[command(disable_help_flag = true)] + Init(InitArgs), + /// Validate the .env files against .env.schema without printing values + #[command(disable_help_flag = true)] + Check(CheckArgs), + /// Print the resolved values, with sensitive values masked + #[command(disable_help_flag = true)] + Print(PrintArgs), + /// Show how config items resolve, with sensitive values masked + #[command(disable_help_flag = true)] + Explain(ExplainArgs), + /// Find plaintext copies of sensitive values in files + #[command(disable_help_flag = true)] + Scan(ScanArgs), + /// Run a command with the resolved environment + #[command(disable_help_flag = true)] + Exec(ExecArgs), +} + +#[derive(Debug, Args)] +struct InitArgs { + #[arg(short = 'h', long, action = ArgAction::Help, help = "Show this help message")] + help: Option, +} + +#[derive(Debug, Args)] +struct CheckArgs { + #[arg(long, value_name = "name", value_parser = NonEmptyStringValueParser::new(), help = ENV_HELP)] + env: Option, + + #[arg(short = 'h', long, action = ArgAction::Help, help = "Show this help message")] + help: Option, +} + +#[derive(Debug, Args)] +struct PrintArgs { + #[arg(long, value_name = "name", value_parser = NonEmptyStringValueParser::new(), help = ENV_HELP)] + env: Option, + + #[arg( + long, + value_name = "format", + value_parser = ["env", "json", "shell"], + default_value = "env", + help = "Output format" + )] + format: String, + + #[arg(long, action = ArgAction::SetTrue, help = "Print sensitive values in plaintext")] + reveal: bool, + + #[arg(short = 'h', long, action = ArgAction::Help, help = "Show this help message")] + help: Option, +} + +#[derive(Debug, Args)] +struct ExplainArgs { + #[arg(value_name = "KEY", help = "Config item to explain (default: every item)")] + key: Option, + + #[arg(long, value_name = "name", value_parser = NonEmptyStringValueParser::new(), help = ENV_HELP)] + env: Option, + + #[arg(short = 'h', long, action = ArgAction::Help, help = "Show this help message")] + help: Option, +} + +#[derive(Debug, Args)] +struct ScanArgs { + #[arg( + value_name = "PATH", + help = "Files, directories, or globs to scan (default: the current directory)" + )] + targets: Vec, + + #[arg(long, action = ArgAction::SetTrue, help = "Scan only the files staged in Git")] + staged: bool, + + #[arg(long, action = ArgAction::SetTrue, help = "Also scan Git-ignored files")] + include_ignored: bool, + + #[arg(short = 'h', long, action = ArgAction::Help, help = "Show this help message")] + help: Option, +} + +#[derive(Debug, Args)] +struct ExecArgs { + #[arg(short = 'h', long, action = ArgAction::Help, help = "Show this help message")] + help: Option, + + #[arg( + value_name = "COMMAND", + required = true, + num_args = 1.., + trailing_var_arg = true, + allow_hyphen_values = true, + help = "Command and arguments to run" + )] + command: Vec, +} + +fn dotenv_command() -> Command { + DotenvCliArgs::augment_args( + Command::new("vp dotenv") + .about("Manage .env files with a validated .env.schema.") + .disable_help_flag(true) + .disable_help_subcommand(true) + .override_usage("vp dotenv [OPTIONS]") + .arg_required_else_help(true), + ) + .arg(help_arg()) +} + +#[napi(object, object_from_js = false)] +pub struct DotenvArgs { + #[napi(ts_type = "'init' | 'check' | 'print' | 'explain' | 'scan' | 'exec'")] + pub command: String, + pub env: Option, + #[napi(ts_type = "'env' | 'json' | 'shell'")] + pub format: String, + pub reveal: bool, + pub key: Option, + pub targets: Vec, + pub staged: bool, + pub include_ignored: bool, + pub exec_command: Vec, +} + +impl DotenvArgs { + fn new(command: &str) -> Self { + Self { + command: command.into(), + env: None, + format: "env".into(), + reveal: false, + key: None, + targets: Vec::new(), + staged: false, + include_ignored: false, + exec_command: Vec::new(), + } + } +} + +impl From for DotenvArgs { + fn from(value: DotenvCliArgs) -> Self { + match value.command { + DotenvSubcommand::Init(_) => Self::new("init"), + DotenvSubcommand::Check(args) => Self { env: args.env, ..Self::new("check") }, + DotenvSubcommand::Print(args) => Self { + env: args.env, + format: args.format, + reveal: args.reveal, + ..Self::new("print") + }, + DotenvSubcommand::Explain(args) => { + Self { env: args.env, key: args.key, ..Self::new("explain") } + } + DotenvSubcommand::Scan(args) => Self { + targets: args.targets, + staged: args.staged, + include_ignored: args.include_ignored, + ..Self::new("scan") + }, + DotenvSubcommand::Exec(args) => { + Self { exec_command: args.command, ..Self::new("exec") } + } + } + } +} + +#[napi(discriminant = "status", discriminant_case = "camelCase", object_from_js = false)] +pub enum ParseDotenvArgsOutcome { + Ok { value: DotenvArgs }, + Exit { code: u32 }, + Error { error: CliParseError }, +} + +fn command_for_help(mut command: Command, argv: &[String]) -> Command { + command.build(); + if let Some(name) = argv.first() + && let Some(subcommand) = command.find_subcommand(name) + { + return subcommand.clone(); + } + command +} + +#[napi] +pub fn parse_dotenv_args(argv: Vec) -> ParseDotenvArgsOutcome { + let help_argv = argv.clone(); + match parse_args::(dotenv_command(), argv) { + ParseResult::Ok(value) => ParseDotenvArgsOutcome::Ok { value: value.into() }, + ParseResult::Help(command) => { + let command = command_for_help(*command, &help_argv); + let is_top_level = command.get_name() == "vp dotenv"; + let mut doc = help_doc_from_command( + command, + Some(vp_shared::documentation_url("/guide/dotenv").into()), + ); + if is_top_level { + doc.sections.push(HelpSection::Lines { + title: "Examples".into(), + lines: vec![ + " vp dotenv init".into(), + " vp dotenv check".into(), + " vp dotenv print --format json".into(), + " vp dotenv scan --staged".into(), + " vp dotenv exec -- node scripts/seed.ts".into(), + ], + }); + } + print_help_doc(&doc); + ParseDotenvArgsOutcome::Exit { code: 0 } + } + ParseResult::Error(error) => ParseDotenvArgsOutcome::Error { error }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(argv: &[&str]) -> ParseResult { + parse_args(dotenv_command(), argv.iter().map(|value| (*value).to_owned()).collect()) + } + + fn parsed(argv: &[&str]) -> DotenvArgs { + parse(argv).expect_ok().into() + } + + fn parse_error(argv: &[&str]) -> CliParseError { + parse(argv).expect_error() + } + + #[test] + fn parses_init_and_check() { + assert_eq!(parsed(&["init"]).command, "init"); + + let args = parsed(&["check", "--env", "production"]); + assert_eq!(args.command, "check"); + assert_eq!(args.env.as_deref(), Some("production")); + } + + #[test] + fn print_masks_by_default_and_accepts_formats() { + let args = parsed(&["print"]); + assert_eq!(args.command, "print"); + assert_eq!(args.format, "env"); + assert!(!args.reveal); + + for format in ["env", "json", "shell"] { + let args = parsed(&["print", "--format", format, "--reveal"]); + assert_eq!(args.format, format); + assert!(args.reveal); + } + } + + #[test] + fn explain_key_is_optional() { + assert_eq!(parsed(&["explain"]).key, None); + let args = parsed(&["explain", "API_URL", "--env", "test"]); + assert_eq!(args.key.as_deref(), Some("API_URL")); + assert_eq!(args.env.as_deref(), Some("test")); + } + + #[test] + fn scan_collects_targets_and_flags() { + let args = parsed(&["scan", "dist", "public", "--staged", "--include-ignored"]); + assert_eq!(args.targets, ["dist", "public"]); + assert!(args.staged); + assert!(args.include_ignored); + assert!(parsed(&["scan"]).targets.is_empty()); + } + + #[test] + fn exec_forwards_the_command_verbatim() { + let args = parsed(&["exec", "--", "node", "--inspect", "seed.ts", "-h"]); + assert_eq!(args.exec_command, ["node", "--inspect", "seed.ts", "-h"]); + + let args = parsed(&["exec", "node", "--watch", "seed.ts"]); + assert_eq!(args.exec_command, ["node", "--watch", "seed.ts"]); + } + + #[test] + fn top_level_and_subcommand_help_return_help() { + for argv in + [&[][..], &["-h"][..], &["--help"][..], &["print", "--help"][..], &["exec", "-h"][..]] + { + assert!(matches!(parse(argv), ParseResult::Help(_)), "argv: {argv:?}"); + } + } + + #[test] + fn rejects_invalid_arguments() { + assert_eq!(parse_error(&["unknown"]).kind, "unknown-argument"); + assert_eq!(parse_error(&["help"]).kind, "unknown-argument"); + assert_eq!(parse_error(&["init", "extra"]).kind, "unknown-argument"); + assert_eq!(parse_error(&["check", "--env"]).kind, "invalid-value"); + assert_eq!(parse_error(&["check", "--env", ""]).kind, "invalid-value"); + assert_eq!(parse_error(&["print", "--format", "yaml"]).kind, "invalid-value"); + assert_eq!(parse_error(&["exec"]).kind, "missing-argument"); + } +} diff --git a/packages/cli/binding/src/js_command_args/commands/mod.rs b/packages/cli/binding/src/js_command_args/commands/mod.rs index d2b359c875..4a5cecd59a 100644 --- a/packages/cli/binding/src/js_command_args/commands/mod.rs +++ b/packages/cli/binding/src/js_command_args/commands/mod.rs @@ -1,6 +1,7 @@ mod common; mod config; mod create; +mod dotenv; mod hooks; mod migrate; mod staged; diff --git a/packages/cli/package.json b/packages/cli/package.json index 1b1af34278..1539d99b55 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -62,6 +62,10 @@ "./bin": { "import": "./dist/bin.js" }, + "./env": { + "types": "./dist/env.d.ts", + "default": "./dist/env.js" + }, "./fmt": { "types": "./dist/fmt.d.ts", "import": "./dist/fmt.js" @@ -355,6 +359,7 @@ "@oxc-project/runtime": "catalog:", "@oxc-project/types": "catalog:", "@oxlint/plugins": "catalog:", + "@varlock/vite-integration": "catalog:", "@vitest/browser": "catalog:", "@vitest/browser-preview": "catalog:", "@vitest/mocker": "catalog:", @@ -365,6 +370,7 @@ "oxfmt": "catalog:", "oxlint": "catalog:", "tsrs": "catalog:", + "varlock": "catalog:", "vite": "workspace:@voidzero-dev/vite-plus-core@*", "vitest": "catalog:" }, diff --git a/packages/cli/src/__tests__/js-command-args.spec.ts b/packages/cli/src/__tests__/js-command-args.spec.ts index 6a08c13082..bbbefda08c 100644 --- a/packages/cli/src/__tests__/js-command-args.spec.ts +++ b/packages/cli/src/__tests__/js-command-args.spec.ts @@ -4,6 +4,7 @@ import type { CliParseError } from '../../binding/index.js'; import { parseConfigArgs, parseCreateArgs, + parseDotenvArgs, parseHooksArgs, parseMigrateArgs, parseStagedArgs, @@ -68,6 +69,23 @@ describe('JavaScript command NAPI arguments', () => { }); }); + it('returns dotenv subcommands with defaults for every field', () => { + expect(expectParsed(parseDotenvArgs(['print', '--format', 'json', '--env', 'test']))).toEqual({ + command: 'print', + env: 'test', + format: 'json', + reveal: false, + targets: [], + staged: false, + includeIgnored: false, + execCommand: [], + }); + expect(expectParsed(parseDotenvArgs(['exec', '--', 'node', '-h'])).execCommand).toEqual([ + 'node', + '-h', + ]); + }); + it('keeps migrate runtime defaults out of Rust', () => { expect(expectParsed(parseMigrateArgs(['project', '--no-interactive', '--no-hooks']))).toEqual({ path: 'project', @@ -102,6 +120,7 @@ describe('JavaScript command NAPI arguments', () => { it.each([ ['config', () => parseConfigArgs(['--no-hooks-dir'])], ['hooks', () => parseHooksArgs(['enable', '--no-hooks-dir'])], + ['dotenv', () => parseDotenvArgs(['check', '--reveal'])], ['migrate', () => parseMigrateArgs(['--no-full'])], ['create', () => parseCreateArgs(['--all'])], ])('returns strict errors for %s', (_command, parse) => { @@ -113,6 +132,8 @@ describe('JavaScript command NAPI arguments', () => { ['config', () => parseConfigArgs(['-h'])], ['hooks', () => parseHooksArgs(['-h'])], ['hooks without a subcommand', () => parseHooksArgs([])], + ['dotenv', () => parseDotenvArgs(['-h'])], + ['dotenv without a subcommand', () => parseDotenvArgs([])], ['migrate', () => parseMigrateArgs(['-h'])], ['create', () => parseCreateArgs(['-h'])], ])('returns a successful help exit for %s', (_command, parse) => { diff --git a/packages/cli/src/__tests__/toolchain.spec.ts b/packages/cli/src/__tests__/toolchain.spec.ts index c99b467cc0..64a38c26e0 100644 --- a/packages/cli/src/__tests__/toolchain.spec.ts +++ b/packages/cli/src/__tests__/toolchain.spec.ts @@ -28,6 +28,7 @@ describe('toolchain export', () => { 'oxlint', 'oxfmt', 'tsrs', + 'varlock', 'tsdown', 'vite-task', 'oxc', diff --git a/packages/cli/src/__tests__/versions.spec.ts b/packages/cli/src/__tests__/versions.spec.ts index bc18a542a3..8b0cde830d 100644 --- a/packages/cli/src/__tests__/versions.spec.ts +++ b/packages/cli/src/__tests__/versions.spec.ts @@ -118,6 +118,7 @@ describe('versions export', () => { expect(versions.oxlint).toBeTypeOf('string'); expect(versions.oxfmt).toBeTypeOf('string'); expect(versions.tsrs).toBeTypeOf('string'); + expect(versions.varlock).toBeTypeOf('string'); }); }); }); diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.ts index 08b0152a1b..8b90490d25 100644 --- a/packages/cli/src/bin.ts +++ b/packages/cli/src/bin.ts @@ -1,7 +1,7 @@ /** * Unified entry point for both the local CLI (via bin/vp) and the global CLI (via Rust vp binary). * - * Global commands (create, migrate, sync-versions, config, hooks, staged, --version) are handled by tsdown-bundled modules. + * Global commands (create, migrate, sync-versions, config, dotenv, hooks, staged, --version) are handled by tsdown-bundled modules. * All other commands are delegated to the Rust core through NAPI bindings, which * uses JavaScript tool resolver functions to locate tool binaries. * @@ -150,6 +150,8 @@ if (maybePrintCommandHelp(args)) { await import('./sync-versions/bin.js'); } else if (command === 'config') { await import('./config/bin.js'); +} else if (command === 'dotenv') { + await import('./dotenv/bin.js'); } else if (command === 'hooks') { await import('./hooks/bin.js'); } else if (command === '--version' || command === '-V') { diff --git a/packages/cli/src/create/__tests__/utils.spec.ts b/packages/cli/src/create/__tests__/utils.spec.ts index 5ba9fa4170..c530db0850 100644 --- a/packages/cli/src/create/__tests__/utils.spec.ts +++ b/packages/cli/src/create/__tests__/utils.spec.ts @@ -168,7 +168,8 @@ describe('ensureDefaultGitignoreEntries', () => { return fs.readFileSync(path.join(projectDir, '.gitignore'), 'utf8'); } - const dotenvBlock = '# dotenv environment variable files\n.env\n.env.*\n!.env.example\n'; + const dotenvBlock = + '# dotenv environment variable files\n.env\n.env.*\n!.env.example\n!.env.schema\n'; it('creates a fresh `.gitignore` with default entries when none exists', () => { ensureDefaultGitignoreEntries(projectDir); @@ -227,7 +228,15 @@ describe('ensureDefaultGitignoreEntries', () => { ); ensureDefaultGitignoreEntries(projectDir); expect(gitignore()).toBe( - '# dotenv environment variable files\n.env\nnode_modules\n.env.*\n!.env.example\n', + '# dotenv environment variable files\n.env\nnode_modules\n.env.*\n!.env.example\n!.env.schema\n', + ); + }); + + it('keeps `.env.schema` tracked when `.env.*` is already ignored', () => { + fs.writeFileSync(path.join(projectDir, '.gitignore'), 'node_modules\n.env\n.env.*\n'); + ensureDefaultGitignoreEntries(projectDir); + expect(gitignore()).toBe( + 'node_modules\n.env\n.env.*\n\n# dotenv environment variable files\n!.env.example\n!.env.schema\n', ); }); }); diff --git a/packages/cli/src/create/utils.ts b/packages/cli/src/create/utils.ts index ca9b996576..49eeb2edc6 100644 --- a/packages/cli/src/create/utils.ts +++ b/packages/cli/src/create/utils.ts @@ -272,6 +272,7 @@ const DOTENV_GITIGNORE_LINES = [ '.env', '.env.*', '!.env.example', + '!.env.schema', ] as const; /** diff --git a/packages/cli/src/define-config.ts b/packages/cli/src/define-config.ts index f001e543c4..45d369a692 100644 --- a/packages/cli/src/define-config.ts +++ b/packages/cli/src/define-config.ts @@ -31,6 +31,7 @@ import type { InlineConfig as VitestInlineConfig } from 'vitest/node'; import { withConfigMetadataResolution } from './config-metadata.ts'; import type { CreateTemplateEntry } from './create/org-manifest.ts'; +import { dotenvPlugins, type DotenvOptions } from './dotenv/vite-plugin.ts'; import type { PackUserConfig } from './pack.ts'; import type { RunConfig } from './run-config.ts'; import type { StagedConfig } from './staged-config.ts'; @@ -86,6 +87,11 @@ declare module 'vite' { staged?: StagedConfig; + /** + * Load and validate `.env` files against `.env.schema`. + */ + dotenv?: DotenvOptions; + /** * Options for `vp create`. * @@ -975,20 +981,32 @@ function injectPlugin(config: T): T { }; } +/** + * A root config also loads `.env.schema`. Projects and nested test projects + * share the root's env, so they do not load it again. + */ +function injectRootPlugins(config: T): T { + const injected = injectPlugin(config); + const dotenv = dotenvPlugins(injected); + return dotenv.length === 0 + ? injected + : { ...injected, plugins: [...(injected.plugins ?? []), ...dotenv] }; +} + function injectPluginIntoConfig(config: ViteUserConfigExport): ViteUserConfigExport { if (typeof config === 'function') { return (env: ConfigEnv) => { const result = config(env); if (types.isPromise(result)) { - return result.then(injectPlugin); + return result.then(injectRootPlugins); } - return injectPlugin(result); + return injectRootPlugins(result); }; } if (types.isPromise(config)) { - return config.then(injectPlugin); + return config.then(injectRootPlugins); } - return injectPlugin(config); + return injectRootPlugins(config); } /** diff --git a/packages/cli/src/dotenv/__tests__/varlock.spec.ts b/packages/cli/src/dotenv/__tests__/varlock.spec.ts new file mode 100644 index 0000000000..6d4327ebbd --- /dev/null +++ b/packages/cli/src/dotenv/__tests__/varlock.spec.ts @@ -0,0 +1,185 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import type { DotenvArgs } from '../../../binding/index.js'; +import { + buildVarlockInvocation, + findPackageRoot, + formatCheckPassMessage, + hasVarlockDependency, + parseLoadOutput, + renderMaskedValues, + withVarlockDefaults, +} from '../varlock.ts'; + +function dotenvArgs(overrides: Partial & Pick): DotenvArgs { + return { + format: 'env', + reveal: false, + targets: [], + staged: false, + includeIgnored: false, + execCommand: [], + ...overrides, + }; +} + +describe('buildVarlockInvocation', () => { + it('maps init to varlock init', () => { + expect(buildVarlockInvocation(dotenvArgs({ command: 'init' }))).toEqual({ + argv: ['init'], + output: 'inherit', + }); + }); + + it('validates with redacted JSON so check never prints values', () => { + expect(buildVarlockInvocation(dotenvArgs({ command: 'check', env: 'production' }))).toEqual({ + argv: ['load', '--format', 'json', '--agent', '--env', 'production'], + output: 'check', + }); + }); + + it('masks print output unless --reveal is passed', () => { + for (const format of ['env', 'json', 'shell'] as const) { + expect(buildVarlockInvocation(dotenvArgs({ command: 'print', format }))).toEqual({ + argv: ['load', '--format', 'json', '--agent'], + output: 'masked', + }); + expect( + buildVarlockInvocation(dotenvArgs({ command: 'print', format, reveal: true })), + ).toEqual({ argv: ['load', '--format', format], output: 'inherit' }); + } + }); + + it('explains one key, or lists every item through the pretty load output', () => { + expect( + buildVarlockInvocation(dotenvArgs({ command: 'explain', key: 'API_URL', env: 'test' })), + ).toEqual({ argv: ['explain', 'API_URL', '--env', 'test'], output: 'inherit' }); + expect(buildVarlockInvocation(dotenvArgs({ command: 'explain' }))).toEqual({ + argv: ['load'], + output: 'inherit', + }); + }); + + it('passes scan flags before the targets', () => { + expect( + buildVarlockInvocation( + dotenvArgs({ command: 'scan', targets: ['dist'], staged: true, includeIgnored: true }), + ), + ).toEqual({ argv: ['scan', '--staged', '--include-ignored', 'dist'], output: 'inherit' }); + }); + + it('maps exec to varlock run and keeps the command after --', () => { + expect( + buildVarlockInvocation( + dotenvArgs({ command: 'exec', execCommand: ['node', '--inspect', 'a.ts'] }), + ), + ).toEqual({ argv: ['run', '--', 'node', '--inspect', 'a.ts'], output: 'inherit' }); + }); +}); + +describe('renderMaskedValues', () => { + const values = { + API_URL: 'http://localhost:3000', + API_PORT: 3000, + DEBUG: false, + GREETING: 'hello "world"', + STRIPE_SECRET_KEY: 'sk▒▒▒▒▒', + EMPTY: null, + }; + + it('renders dotenv lines and quotes values that need it', () => { + expect(renderMaskedValues(values, 'env')).toBe( + [ + 'API_URL=http://localhost:3000', + 'API_PORT=3000', + 'DEBUG=false', + 'GREETING="hello \\"world\\""', + 'STRIPE_SECRET_KEY="sk▒▒▒▒▒"', + 'EMPTY=', + '', + ].join('\n'), + ); + }); + + it('renders shell exports with single quotes', () => { + expect(renderMaskedValues({ A: "it's", B: 'plain' }, 'shell')).toBe( + "export A='it'\\''s'\nexport B=plain\n", + ); + }); + + it('renders JSON as is', () => { + expect(renderMaskedValues({ A: 1 }, 'json')).toBe('{\n "A": 1\n}\n'); + }); + + it('prints nothing for an empty config', () => { + expect(renderMaskedValues({}, 'env')).toBe(''); + }); +}); + +describe('parseLoadOutput', () => { + it('accepts a JSON object only', () => { + expect(parseLoadOutput('{"A":"1"}')).toEqual({ A: '1' }); + expect(parseLoadOutput('[1]')).toBeUndefined(); + expect(parseLoadOutput('not json')).toBeUndefined(); + }); +}); + +describe('formatCheckPassMessage', () => { + it('counts config items', () => { + expect(formatCheckPassMessage({ A: 1, B: 2 })).toBe('Found no errors in 2 config items'); + expect(formatCheckPassMessage({ A: 1 })).toBe('Found no errors in 1 config item'); + expect(formatCheckPassMessage(undefined)).toBe('Found no errors in the env config'); + }); +}); + +describe('withVarlockDefaults', () => { + it('turns telemetry off unless the user set the variable', () => { + expect(withVarlockDefaults({ PATH: '/bin' })).toEqual({ + PATH: '/bin', + VARLOCK_TELEMETRY_DISABLED: '1', + }); + const env = { VARLOCK_TELEMETRY_DISABLED: '0' }; + expect(withVarlockDefaults(env)).toBe(env); + }); +}); + +describe('package lookups', () => { + let dir: string; + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-dotenv-')); + }); + + afterEach(() => { + fs.rmSync(dir, { recursive: true, force: true }); + }); + + it('finds the package root by name', () => { + const pkg = path.join(dir, 'node_modules', 'varlock'); + fs.mkdirSync(path.join(pkg, 'dist', 'runtime'), { recursive: true }); + fs.writeFileSync(path.join(pkg, 'package.json'), '{"name":"varlock"}'); + fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"app"}'); + + expect(findPackageRoot(path.join(pkg, 'dist', 'runtime', 'env.cjs'), 'varlock')).toBe(pkg); + expect(findPackageRoot(path.join(pkg, 'dist', 'runtime', 'env.cjs'), 'app')).toBe(dir); + expect(findPackageRoot(path.join(dir, 'file.js'), 'missing')).toBeUndefined(); + }); + + it('detects varlock only in dependencies, like varlock init', () => { + expect(hasVarlockDependency(dir)).toBe(false); + fs.writeFileSync( + path.join(dir, 'package.json'), + JSON.stringify({ devDependencies: { varlock: '^1.0.0' } }), + ); + expect(hasVarlockDependency(dir)).toBe(false); + fs.writeFileSync( + path.join(dir, 'package.json'), + JSON.stringify({ dependencies: { varlock: '^1.0.0' } }), + ); + expect(hasVarlockDependency(dir)).toBe(true); + }); +}); diff --git a/packages/cli/src/dotenv/__tests__/vite-plugin.spec.ts b/packages/cli/src/dotenv/__tests__/vite-plugin.spec.ts new file mode 100644 index 0000000000..b7406697e9 --- /dev/null +++ b/packages/cli/src/dotenv/__tests__/vite-plugin.spec.ts @@ -0,0 +1,128 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { CONFIG_METADATA_ENV } from '../../utils/constants.ts'; +import { + dotenvPlugins, + findDependencyBinDir, + hasDotenvSchema, + prependPathEntry, +} from '../vite-plugin.ts'; + +vi.mock('@varlock/vite-integration', () => ({ + varlockVitePlugin: () => ({ name: 'varlock-vite-plugin' }), +})); + +function pluginNames(plugins: unknown[]): string[] { + return plugins.flat().map((plugin) => (plugin as { name: string }).name); +} + +describe('dotenv Vite plugins', () => { + let root: string; + let savedEnv: NodeJS.ProcessEnv; + + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-dotenv-plugin-')); + savedEnv = { ...process.env }; + delete process.env[CONFIG_METADATA_ENV]; + }); + + afterEach(() => { + process.env = savedEnv; + fs.rmSync(root, { recursive: true, force: true }); + }); + + it('detects .env.schema or a varlock.loadPath in package.json', () => { + expect(hasDotenvSchema(root)).toBe(false); + fs.writeFileSync( + path.join(root, 'package.json'), + JSON.stringify({ varlock: { loadPath: './env/' } }), + ); + expect(hasDotenvSchema(root)).toBe(true); + fs.rmSync(path.join(root, 'package.json')); + fs.writeFileSync(path.join(root, '.env.schema'), '# @defaultSensitive=false\n# ---\n'); + expect(hasDotenvSchema(root)).toBe(true); + }); + + it('adds nothing without a schema', () => { + expect(dotenvPlugins({ root })).toEqual([]); + }); + + it('adds nothing while a config is read only for metadata', () => { + fs.writeFileSync(path.join(root, '.env.schema'), ''); + process.env[CONFIG_METADATA_ENV] = '1'; + expect(dotenvPlugins({ root })).toEqual([]); + }); + + it('adds nothing when dotenv.schema is false', () => { + fs.writeFileSync(path.join(root, '.env.schema'), ''); + expect(dotenvPlugins({ root, dotenv: { schema: false } })).toEqual([]); + }); + + it('loads the varlock integration with the resolve and scan plugins', async () => { + fs.writeFileSync(path.join(root, '.env.schema'), ''); + const plugins = dotenvPlugins({ root }); + expect(plugins).toHaveLength(1); + expect(pluginNames(await Promise.all(plugins))).toEqual([ + 'vite-plus:dotenv-resolve', + 'varlock-vite-plugin', + 'vite-plus:dotenv-scan-build-output', + ]); + expect(process.env.VARLOCK_TELEMETRY_DISABLED).toBe('1'); + }); + + it('leaves out the build output scan when it is disabled', async () => { + fs.writeFileSync(path.join(root, '.env.schema'), ''); + const plugins = dotenvPlugins({ root, dotenv: { scanBuildOutput: false } }); + expect(pluginNames(await Promise.all(plugins))).toEqual([ + 'vite-plus:dotenv-resolve', + 'varlock-vite-plugin', + ]); + }); + + it('fails when dotenv.schema is true and no schema exists', async () => { + const [plugins] = dotenvPlugins({ root, dotenv: { schema: true } }); + await expect(plugins).rejects.toThrow('`dotenv.schema` is true'); + }); +}); + +describe('findDependencyBinDir', () => { + let packageRoot: string; + + beforeEach(() => { + packageRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-dotenv-bin-')); + fs.mkdirSync(path.join(packageRoot, 'node_modules', '.bin'), { recursive: true }); + }); + + afterEach(() => { + fs.rmSync(packageRoot, { recursive: true, force: true }); + }); + + it('finds the package-local bin link that pnpm creates', () => { + const binDir = path.join(packageRoot, 'node_modules', '.bin'); + expect(findDependencyBinDir(packageRoot, 'varlock', 'linux')).toBeUndefined(); + fs.writeFileSync(path.join(binDir, 'varlock'), ''); + expect(findDependencyBinDir(packageRoot, 'varlock', 'linux')).toBe(binDir); + expect(findDependencyBinDir(packageRoot, 'varlock', 'win32')).toBeUndefined(); + fs.writeFileSync(path.join(binDir, 'varlock.cmd'), ''); + expect(findDependencyBinDir(packageRoot, 'varlock', 'win32')).toBe(binDir); + }); +}); + +describe('prependPathEntry', () => { + it('prepends once and keeps the existing key casing', () => { + const env: NodeJS.ProcessEnv = { Path: 'C:\\bin;C:\\tools' }; + prependPathEntry(env, 'C:\\vp\\.bin', ';'); + prependPathEntry(env, 'C:\\vp\\.bin', ';'); + expect(env).toEqual({ Path: 'C:\\vp\\.bin;C:\\bin;C:\\tools' }); + }); + + it('creates PATH when it is missing', () => { + const env: NodeJS.ProcessEnv = {}; + prependPathEntry(env, '/vp/.bin', ':'); + expect(env).toEqual({ PATH: '/vp/.bin' }); + }); +}); diff --git a/packages/cli/src/dotenv/bin.ts b/packages/cli/src/dotenv/bin.ts new file mode 100644 index 0000000000..abca66b380 --- /dev/null +++ b/packages/cli/src/dotenv/bin.ts @@ -0,0 +1,72 @@ +// `vp dotenv`: manage `.env` files with a schema through the bundled varlock CLI. +// +// Arguments are parsed by clap in the native binding. This module maps them to +// a varlock invocation and runs varlock's own CLI script with the current Node +// runtime, so no `varlock` bin has to be on PATH. + +import { parseDotenvArgs } from '../../binding/index.js'; +import { unwrapCliParseOutcome } from '../utils/cli-parse.ts'; +import { runCommand, runCommandCapturingStdout } from '../utils/command.ts'; +import { errorMsg, passMsg, warnMsg } from '../utils/terminal.ts'; +import { + buildVarlockInvocation, + formatCheckPassMessage, + hasVarlockDependency, + parseLoadOutput, + renderMaskedValues, + resolveVarlockCli, + withVarlockDefaults, +} from './varlock.ts'; + +async function main(): Promise { + const args = unwrapCliParseOutcome(parseDotenvArgs(process.argv.slice(3))); + const invocation = buildVarlockInvocation(args); + const cwd = process.cwd(); + + let cli: string; + try { + cli = resolveVarlockCli(); + } catch (err) { + errorMsg( + `Could not find the varlock package bundled with Vite+. Run \`vp install\` to restore dependencies.\n${err instanceof Error ? err.message : String(err)}`, + ); + return 1; + } + + const options = { + command: process.execPath, + args: [cli, ...invocation.argv], + cwd, + envs: withVarlockDefaults(process.env), + }; + + if (invocation.output === 'inherit') { + const hadDependency = args.command === 'init' && hasVarlockDependency(cwd); + const { exitCode } = await runCommand(options); + if (args.command === 'init' && exitCode === 0 && !hadDependency && hasVarlockDependency(cwd)) { + warnMsg( + '`varlock init` added `varlock` to dependencies, but Vite+ already bundles it. Run `vp remove varlock` to keep a single copy.', + ); + } + return exitCode; + } + + const { exitCode, stdout } = await runCommandCapturingStdout(options); + if (exitCode !== 0) { + return exitCode; + } + const values = parseLoadOutput(stdout.toString('utf-8')); + if (invocation.output === 'check') { + passMsg(formatCheckPassMessage(values)); + return 0; + } + if (!values) { + errorMsg('Could not read the resolved values from varlock.'); + return 1; + } + process.stdout.write(renderMaskedValues(values, args.format)); + return 0; +} + +// Let piped stdout drain before exit; `process.exit()` can cut off `print` output. +process.exitCode = await main(); diff --git a/packages/cli/src/dotenv/varlock.ts b/packages/cli/src/dotenv/varlock.ts new file mode 100644 index 0000000000..48bc736bb9 --- /dev/null +++ b/packages/cli/src/dotenv/varlock.ts @@ -0,0 +1,196 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +import type { DotenvArgs } from '../../binding/index.js'; +import { resolveBundled } from '../utils/constants.ts'; + +export type DotenvFormat = 'env' | 'json' | 'shell'; + +/** + * How `vp dotenv` runs the varlock CLI and handles its stdout. + * + * - `inherit`: varlock writes to the terminal directly. + * - `check`: stdout is discarded and replaced by a pass line. varlock reports + * validation errors on stderr, which stays attached. + * - `masked`: stdout is redacted JSON (`load --agent`), which Vite+ renders in + * the requested format. varlock rejects `--agent` for `env` and `shell`. + */ +export type VarlockOutputMode = 'inherit' | 'check' | 'masked'; + +export interface VarlockInvocation { + argv: string[]; + output: VarlockOutputMode; +} + +function envArgs(env: string | undefined | null): string[] { + return env ? ['--env', env] : []; +} + +export function buildVarlockInvocation(args: DotenvArgs): VarlockInvocation { + switch (args.command) { + case 'init': + return { argv: ['init'], output: 'inherit' }; + case 'check': + return { + argv: ['load', '--format', 'json', '--agent', ...envArgs(args.env)], + output: 'check', + }; + case 'print': + if (args.reveal) { + return { + argv: ['load', '--format', args.format, ...envArgs(args.env)], + output: 'inherit', + }; + } + return { + argv: ['load', '--format', 'json', '--agent', ...envArgs(args.env)], + output: 'masked', + }; + case 'explain': + // `varlock explain` requires a key. The pretty `load` output is the + // all-items view, and it masks sensitive values the same way. + return { + argv: args.key + ? ['explain', args.key, ...envArgs(args.env)] + : ['load', ...envArgs(args.env)], + output: 'inherit', + }; + case 'scan': + return { + argv: [ + 'scan', + ...(args.staged ? ['--staged'] : []), + ...(args.includeIgnored ? ['--include-ignored'] : []), + ...args.targets, + ], + output: 'inherit', + }; + case 'exec': + return { argv: ['run', '--', ...args.execCommand], output: 'inherit' }; + } +} + +const SAFE_VALUE = /^[\w@%+=:,./-]*$/; + +function stringifyValue(value: unknown): string { + if (typeof value === 'string') { + return value; + } + if (value === null || value === undefined) { + return ''; + } + return typeof value === 'object' ? JSON.stringify(value) : String(value); +} + +function quoteEnvValue(value: string): string { + if (SAFE_VALUE.test(value)) { + return value; + } + const escaped = value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('\n', '\\n'); + return `"${escaped}"`; +} + +function quoteShellValue(value: string): string { + if (SAFE_VALUE.test(value)) { + return value; + } + return `'${value.replaceAll("'", `'\\''`)}'`; +} + +/** Render the redacted values from `varlock load --format json --agent`. */ +export function renderMaskedValues(values: Record, format: DotenvFormat): string { + if (format === 'json') { + return `${JSON.stringify(values, null, 2)}\n`; + } + const lines = Object.entries(values).map(([key, value]) => { + const text = stringifyValue(value); + return format === 'shell' + ? `export ${key}=${quoteShellValue(text)}` + : `${key}=${quoteEnvValue(text)}`; + }); + return lines.length > 0 ? `${lines.join('\n')}\n` : ''; +} + +/** Parse the JSON object that `varlock load --format json` prints. */ +export function parseLoadOutput(stdout: string): Record | undefined { + try { + const parsed: unknown = JSON.parse(stdout); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) + ? (parsed as Record) + : undefined; + } catch { + return undefined; + } +} + +export function formatCheckPassMessage(values: Record | undefined): string { + if (!values) { + return 'Found no errors in the env config'; + } + const count = Object.keys(values).length; + return `Found no errors in ${count} config ${count === 1 ? 'item' : 'items'}`; +} + +/** Walk up from `start` to the directory whose `package.json` has `name`. */ +export function findPackageRoot(start: string, name: string): string | undefined { + let dir = path.dirname(start); + while (true) { + const manifest = path.join(dir, 'package.json'); + if (fs.existsSync(manifest)) { + try { + if (JSON.parse(fs.readFileSync(manifest, 'utf-8')).name === name) { + return dir; + } + } catch { + // Not a readable manifest; keep walking. + } + } + const parent = path.dirname(dir); + if (parent === dir) { + return undefined; + } + dir = parent; + } +} + +/** + * Absolute path of the bundled varlock CLI script. + * + * varlock does not export `./package.json`, so resolve a public entry and walk + * up to the package root. + */ +export function resolveVarlockCli(): string { + const entry = resolveBundled('varlock/env'); + const root = findPackageRoot(entry, 'varlock'); + if (!root) { + throw new Error(`Could not find the varlock package root from ${entry}`); + } + const manifest = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf-8')) as { + bin?: string | Record; + }; + const bin = typeof manifest.bin === 'string' ? manifest.bin : manifest.bin?.varlock; + if (!bin) { + throw new Error(`Could not find the 'varlock' bin entry in ${root}/package.json`); + } + return path.join(root, bin); +} + +/** varlock telemetry is opt-out. Vite+ turns it off unless the user set the variable. */ +export function withVarlockDefaults(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { + return env.VARLOCK_TELEMETRY_DISABLED === undefined + ? { ...env, VARLOCK_TELEMETRY_DISABLED: '1' } + : env; +} + +/** + * `varlock init` installs varlock unless `dependencies.varlock` already exists. + * Vite+ bundles varlock, so the caller warns when init adds the dependency. + */ +export function hasVarlockDependency(projectDir: string): boolean { + try { + const manifest = JSON.parse(fs.readFileSync(path.join(projectDir, 'package.json'), 'utf-8')); + return Boolean(manifest?.dependencies?.varlock); + } catch { + return false; + } +} diff --git a/packages/cli/src/dotenv/vite-plugin.ts b/packages/cli/src/dotenv/vite-plugin.ts new file mode 100644 index 0000000000..a6ea4cccac --- /dev/null +++ b/packages/cli/src/dotenv/vite-plugin.ts @@ -0,0 +1,187 @@ +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import type { Plugin, PluginOption, UserConfig } from 'vite'; + +import { CONFIG_METADATA_ENV } from '../utils/constants.ts'; +import { findPackageRoot, resolveVarlockCli, withVarlockDefaults } from './varlock.ts'; + +export interface DotenvOptions { + /** + * Load and validate `.env.schema` in `vp dev`, `vp build`, `vp preview`, and + * `vp test`. `'auto'` loads it when the project root has `.env.schema` or + * its `package.json` sets `varlock.loadPath`. + * @default 'auto' + */ + schema?: boolean | 'auto'; + + /** + * Fail `vp build` when a sensitive value appears in the client output. + * @default true + */ + scanBuildOutput?: boolean; +} + +export const DOTENV_SCHEMA_FILE = '.env.schema'; + +const VARLOCK_IMPORT = /^varlock(?:\/|$)/; + +export function hasDotenvSchema(root: string): boolean { + if (fs.existsSync(path.join(root, DOTENV_SCHEMA_FILE))) { + return true; + } + try { + const manifest = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf-8')); + return Boolean(manifest?.varlock?.loadPath); + } catch { + return false; + } +} + +/** + * The bin directory that the package manager links for the dependencies of + * `packageRoot`. pnpm creates it inside the package; hoisting installs (npm, + * Bun) put the bin in the project's `node_modules/.bin` instead. + */ +export function findDependencyBinDir( + packageRoot: string, + bin: string, + platform: NodeJS.Platform = process.platform, +): string | undefined { + const dir = path.join(packageRoot, 'node_modules', '.bin'); + return fs.existsSync(path.join(dir, platform === 'win32' ? `${bin}.cmd` : bin)) ? dir : undefined; +} + +export function prependPathEntry( + env: NodeJS.ProcessEnv, + dir: string, + delimiter: string = path.delimiter, +): void { + const key = Object.keys(env).find((name) => name.toUpperCase() === 'PATH') ?? 'PATH'; + const entries = (env[key] ?? '').split(delimiter).filter(Boolean); + if (!entries.includes(dir)) { + env[key] = [dir, ...entries].join(delimiter); + } +} + +/** + * The varlock Vite integration runs the varlock CLI that it finds in + * `node_modules/.bin` above the project root, then on PATH. Under pnpm, a + * dependency of vite-plus has no link there, so put vite-plus's own bin + * directory on PATH before the integration loads. + */ +function prepareVarlockProcessEnv(modulePath: string): void { + process.env.VARLOCK_TELEMETRY_DISABLED ??= '1'; + const vitePlusRoot = findPackageRoot(modulePath, 'vite-plus'); + const binDir = vitePlusRoot && findDependencyBinDir(vitePlusRoot, 'varlock'); + if (binDir) { + prependPathEntry(process.env, binDir); + } +} + +/** + * Resolve `varlock` and `varlock/*` from vite-plus, not from the importer. + * The integration's SSR init code and user code that follows the varlock docs + * import `varlock/env`, which a pnpm project cannot resolve when only + * vite-plus depends on varlock. One copy also keeps `ENV` and the plugin state + * together. + */ +function varlockResolvePlugin(anchor: string): Plugin { + return { + name: 'vite-plus:dotenv-resolve', + enforce: 'pre', + resolveId: { + filter: { id: VARLOCK_IMPORT }, + handler(source, importer, options) { + if (importer === anchor) { + return null; + } + return this.resolve(source, anchor, { ...options, skipSelf: true }); + }, + }, + }; +} + +function scanBuildOutputPlugin(): Plugin { + let root = process.cwd(); + return { + name: 'vite-plus:dotenv-scan-build-output', + apply: 'build', + // Server bundles may legitimately embed resolved env (varlock's + // `resolved-env` SSR mode), so only client output is scanned. + applyToEnvironment: (environment) => environment.config.consumer === 'client', + configResolved(config) { + root = config.root; + }, + writeBundle: { + order: 'post', + sequential: true, + handler(outputOptions) { + const outDir = + outputOptions.dir ?? (outputOptions.file ? path.dirname(outputOptions.file) : undefined); + if (!outDir) { + return; + } + const target = path.relative(root, outDir) || '.'; + // Build output is usually git-ignored, which `varlock scan` skips by default. + const result = spawnSync( + process.execPath, + [resolveVarlockCli(), 'scan', '--include-ignored', target], + { cwd: root, env: withVarlockDefaults(process.env), stdio: 'inherit' }, + ); + if (result.status !== 0) { + this.error( + `Sensitive values from the env config were found in ${target}. Remove them from client code, or set \`dotenv.scanBuildOutput: false\` in vite.config.ts.`, + ); + } + }, + }, + }; +} + +async function loadDotenvPlugins( + root: string, + schemaFound: boolean, + options: DotenvOptions, +): Promise { + if (!schemaFound) { + throw new Error( + `\`dotenv.schema\` is true, but ${root} has no ${DOTENV_SCHEMA_FILE} and its package.json sets no \`varlock.loadPath\`. Run \`vp dotenv init\` to create one.`, + ); + } + const modulePath = fileURLToPath(import.meta.url); + prepareVarlockProcessEnv(modulePath); + // Importing the integration runs `varlock load` at once, so import it only + // when a schema is present. + const { varlockVitePlugin } = await import('@varlock/vite-integration'); + return [ + varlockResolvePlugin(modulePath), + varlockVitePlugin(), + ...(options.scanBuildOutput === false ? [] : [scanBuildOutputPlugin()]), + ]; +} + +/** + * The plugins that load `.env.schema` for a root Vite config, or none. + * + * `vp dev ./app` sets the root on the command line, which a config file cannot + * see. Detection then uses the config's `root` or the working directory. + */ +export function dotenvPlugins(config: UserConfig): PluginOption[] { + if (process.env[CONFIG_METADATA_ENV] === '1') { + return []; + } + const options = config.dotenv ?? {}; + const schema = options.schema ?? 'auto'; + if (schema === false) { + return []; + } + const root = path.resolve(config.root ?? process.cwd()); + const schemaFound = hasDotenvSchema(root); + if (!schemaFound && schema === 'auto') { + return []; + } + return [loadDotenvPlugins(root, schemaFound, options)]; +} diff --git a/packages/cli/src/env.ts b/packages/cli/src/env.ts new file mode 100644 index 0000000000..7d98858201 --- /dev/null +++ b/packages/cli/src/env.ts @@ -0,0 +1,8 @@ +/** + * Typed access to the env values that `.env.schema` declares. + * + * Re-exports the varlock runtime that the injected Vite integration + * initializes, so `ENV` here and the plugin's build-time replacements read the + * same copy of varlock. + */ +export * from 'varlock/env'; diff --git a/packages/cli/src/utils/command.ts b/packages/cli/src/utils/command.ts index d9edc5d8e6..57a2b4e57a 100644 --- a/packages/cli/src/utils/command.ts +++ b/packages/cli/src/utils/command.ts @@ -117,3 +117,29 @@ export async function runCommand(options: RunCommandOptions): Promise { + const child = spawn(options.command, options.args, { + stdio: ['inherit', 'pipe', 'inherit'], + cwd: options.cwd, + env: options.envs, + }); + return new Promise((resolve, reject) => { + const stdout: Buffer[] = []; + child.stdout?.on('data', (data) => { + stdout.push(data); + }); + child.on('close', (code, signal) => { + resolve({ exitCode: exitCodeFromClose(code, signal), stdout: Buffer.concat(stdout) }); + }); + child.on('error', (err) => { + reject(err); + }); + }); +} diff --git a/packages/cli/src/utils/terminal.ts b/packages/cli/src/utils/terminal.ts index 1a6265d32a..ba57f73739 100644 --- a/packages/cli/src/utils/terminal.ts +++ b/packages/cli/src/utils/terminal.ts @@ -48,7 +48,11 @@ export function formatDuration(durationMs: number) { } // Standard message prefix functions matching the Rust CLI convention. -// warn/error go to stderr (diagnostics). +// pass goes to stdout (results); warn/error go to stderr (diagnostics). + +export function passMsg(msg: string) { + log(`${styleText(['blueBright', 'bold'], 'pass:')} ${msg}`); +} export function warnMsg(msg: string) { console.error(styleText(['yellow', 'bold'], 'warn:'), msg); diff --git a/packages/cli/src/version.ts b/packages/cli/src/version.ts index 86d10d5f73..f865b2895d 100644 --- a/packages/cli/src/version.ts +++ b/packages/cli/src/version.ts @@ -18,6 +18,7 @@ const TOOL_DISPLAY_ORDER = [ 'oxlint', 'tsrs', 'tsdown', + 'varlock', ] as const; interface LocalPackageMetadata { diff --git a/packages/cli/toolchain.config.json b/packages/cli/toolchain.config.json index 3c1a2a3cc9..ee974fa80a 100644 --- a/packages/cli/toolchain.config.json +++ b/packages/cli/toolchain.config.json @@ -1,6 +1,15 @@ { "schemaVersion": 1, - "versionExportIds": ["vite", "rolldown", "vitest", "oxfmt", "oxlint", "tsrs", "tsdown"], + "versionExportIds": [ + "vite", + "rolldown", + "vitest", + "oxfmt", + "oxlint", + "tsrs", + "tsdown", + "varlock" + ], "nodes": [ { "id": "vite-plus", @@ -88,6 +97,17 @@ "package": "tsrs" } }, + { + "id": "varlock", + "name": "varlock", + "kind": "tool", + "delivery": ["dependency"], + "aliases": [], + "versionSource": { + "type": "npm-dependency", + "package": "varlock" + } + }, { "id": "tsdown", "name": "tsdown", @@ -203,6 +223,11 @@ "to": "oxfmt", "relationship": "depends-on" }, + { + "from": "vite-plus", + "to": "varlock", + "relationship": "depends-on" + }, { "from": "vite-plus", "to": "vite-task", diff --git a/packages/cli/tsdown.config.ts b/packages/cli/tsdown.config.ts index 5577b38a05..d5d8772e3d 100644 --- a/packages/cli/tsdown.config.ts +++ b/packages/cli/tsdown.config.ts @@ -70,6 +70,7 @@ export default defineConfig([ bin: './src/bin.ts', index: './src/index.ts', 'define-config': './src/define-config.ts', + env: './src/env.ts', fmt: './src/fmt.ts', lint: './src/lint.ts', 'lint-plugins': './src/lint-plugins.ts', @@ -85,6 +86,7 @@ export default defineConfig([ 'sync-versions/bin': './src/sync-versions/bin.ts', version: './src/version.ts', 'config/bin': './src/config/bin.ts', + 'dotenv/bin': './src/dotenv/bin.ts', 'hooks/bin': './src/hooks/bin.ts', 'staged/bin': './src/staged/bin.ts', // `vpx \n"); + const report = createMigrationReport(); + + migrateVarlockToVitePlus(dir, undefined, report); + + expect(report.warnings).toEqual([ + expect.stringContaining( + 'Kept the varlock dependency in package.json: src/App.vue still uses it.', + ), + ]); + }); + + it('keeps varlock for scripts that run its CLI and for varlock plugins', () => { + packageJson({ scripts: { start: 'varlock run -- node server.js' } }); + const report = createMigrationReport(); + migrateVarlockToVitePlus(dir, undefined, report); + expect(report.warnings).toEqual([ + expect.stringContaining( + 'Kept the varlock dependency in package.json: `scripts` in package.json still uses it.', + ), + ]); + + packageJson(); + write('.husky/pre-commit', 'npx varlock load\n'); + const hook = createMigrationReport(); + migrateVarlockToVitePlus(dir, undefined, hook); + expect(hook.warnings).toEqual([ + expect.stringContaining( + 'Kept the varlock dependency in package.json: .husky/pre-commit still uses it.', + ), + ]); + fs.rmSync(path.join(dir, '.husky'), { recursive: true }); + + packageJson({ dependencies: { varlock: '^1.20.0', '@varlock/1password-plugin': '^1.0.0' } }); + const second = createMigrationReport(); + migrateVarlockToVitePlus(dir, undefined, second); + expect(second.warnings).toEqual([ + expect.stringContaining( + 'Kept the varlock dependency in package.json: @varlock/1password-plugin needs it.', + ), + ]); + }); + + it('warns about a plugin call with options and keeps the integration', () => { + write( + 'vite.config.ts', + VITE_CONFIG.replace( + 'varlockVitePlugin()', + "varlockVitePlugin({ ssrInjectMode: 'resolved-env' })", + ), + ); + const report = createMigrationReport(); + + migrateVarlockToVitePlus(dir, undefined, report); + + expect(read('vite.config.ts')).toContain( + "varlockVitePlugin({ ssrInjectMode: 'resolved-env' })", + ); + expect(readJsonFile(path.join(dir, 'package.json'))).toMatchObject({ + devDependencies: { '@varlock/vite-integration': '^1.5.0' }, + }); + expect(report.warnings).toEqual([ + 'Kept varlockVitePlugin(...) in vite.config.ts: Vite+ adds the varlock integration without options, so both would run. Remove the call, or set `dotenv: { schema: false }` to keep only yours.', + 'Kept the @varlock/vite-integration dependency in package.json: vite.config.ts still uses it.', + ]); + }); +}); diff --git a/packages/cli/src/migration/bin.ts b/packages/cli/src/migration/bin.ts index 19ee6ccfd3..92b7b916a0 100644 --- a/packages/cli/src/migration/bin.ts +++ b/packages/cli/src/migration/bin.ts @@ -61,6 +61,7 @@ import { collectToolchainVersionChanges, confirmPrettierMigration, confirmTsxMigration, + confirmVarlockMigration, confirmOxnodeMigration, confirmTsNodeMigration, detectEslintProject, @@ -70,6 +71,7 @@ import { detectPrettierProject, detectTsupProject, detectTsxProject, + detectVarlockProject, detectOxnodeProject, detectTsNodeProject, detectVitePlusBootstrapPending, @@ -93,6 +95,7 @@ import { migrateSetupVpVersion, migrateTsupToTsdown, migrateTsxToVpx, + migrateVarlockToVitePlus, migrateOxnodeToVpx, migrateTsNodeToVpx, configureYarnNodeModulesMode, @@ -319,6 +322,7 @@ interface MigrationPlan extends MigrationSetupPlan { migrateTsx: boolean; migrateOxnode: boolean; migrateTsNode: boolean; + migrateVarlock: boolean; fixBaseUrl: boolean; migrateNodeVersionFile: boolean; nodeVersionDetection?: NodeVersionManagerDetection; @@ -421,6 +425,7 @@ function hasExistingVitePlusMigrationCandidates( detectTsxProject(workspaceInfo.rootDir, workspaceInfo.packages) || detectOxnodeProject(workspaceInfo.rootDir, workspaceInfo.packages) || detectTsNodeProject(workspaceInfo.rootDir, workspaceInfo.packages) || + detectVarlockProject(workspaceInfo.rootDir, workspaceInfo.packages) || detectNodeVersionManagerFile(workspaceInfo.rootDir) !== undefined || getFrameworkShimCandidates(workspaceInfo.rootDir, workspaceInfo.packages).length > 0 ); @@ -486,6 +491,9 @@ async function collectMigrationPlan( detectOxnodeProject(rootDir, packages) && (await confirmOxnodeMigration(options.interactive)); const migrateTsNode = detectTsNodeProject(rootDir, packages) && (await confirmTsNodeMigration(options.interactive)); + // 3d. varlock Vite integration detection + prompt + const migrateVarlock = + detectVarlockProject(rootDir, packages) && (await confirmVarlockMigration(options.interactive)); // 9. tsconfig baseUrl prompt const fixBaseUrl = hasBaseUrlInWorkspace({ rootDir, packages }) @@ -520,6 +528,7 @@ async function collectMigrationPlan( migrateTsx, migrateOxnode, migrateTsNode, + migrateVarlock, fixBaseUrl, migrateNodeVersionFile, nodeVersionDetection, @@ -636,6 +645,9 @@ function showMigrationSummary(options: { if (report.tsNodeMigrated) { log(`${styleText('gray', '•')} ts-node scripts migrated to Vite+`); } + if (report.varlockMigrated) { + log(`${styleText('gray', '•')} varlock setup migrated to Vite+ (\`vp dotenv\`)`); + } if (report.nodeVersionFileMigrated) { log(`${styleText('gray', '•')} Node version manager file migrated to .node-version`); } @@ -939,6 +951,11 @@ async function executeMigrationPlan( updateMigrationProgress('Migrating ts-node scripts'); migrateTsNodeToVpx(workspaceInfo.rootDir, workspaceInfo.packages, report); } + // 6d. varlock Vite integration → the integration that Vite+ adds + if (plan.migrateVarlock) { + updateMigrationProgress('Migrating varlock'); + migrateVarlockToVitePlus(workspaceInfo.rootDir, workspaceInfo.packages, report); + } // Earlier setup and tool migrations can abort or change the preflight inputs. // Only now apply Vitest compatibility edits, using the original runner version. @@ -1564,6 +1581,25 @@ async function main() { } } + if ( + fullSetup && + detectVarlockProject(workspaceInfoOptional.rootDir, workspaceInfoOptional.packages) + ) { + if (options.interactive) { + clearMigrationProgress(); + } + if (await confirmVarlockMigration(options.interactive)) { + updateMigrationProgress('Migrating varlock'); + const varlockResult = migrateVarlockToVitePlus( + workspaceInfoOptional.rootDir, + workspaceInfoOptional.packages, + report, + ); + didMigrate ||= varlockResult.changed; + needsInstall ||= varlockResult.dependencyRemoved; + } + } + // Check if node version manager file migration is needed (full setup only) if (fullSetup) { const nodeVersionDetection = detectNodeVersionManagerFile(workspaceInfoOptional.rootDir); diff --git a/packages/cli/src/migration/migrator.ts b/packages/cli/src/migration/migrator.ts index faefebdf73..f51b54ad1f 100644 --- a/packages/cli/src/migration/migrator.ts +++ b/packages/cli/src/migration/migrator.ts @@ -8,6 +8,7 @@ export * from './migrator/script-runner.ts'; export * from './migrator/oxnode.ts'; export * from './migrator/ts-node.ts'; export * from './migrator/ts-node-config.ts'; +export * from './migrator/varlock.ts'; export * from './migrator/tsconfig.ts'; export * from './migrator/framework-shim.ts'; export * from './migrator/vitest-ecosystem.ts'; diff --git a/packages/cli/src/migration/migrator/README.md b/packages/cli/src/migration/migrator/README.md index a24381e0c0..948aa105a7 100644 --- a/packages/cli/src/migration/migrator/README.md +++ b/packages/cli/src/migration/migrator/README.md @@ -40,6 +40,7 @@ Pick the file by what a function _does_, not by where it happens to be called. | `ts-node-config.ts` | Conservative ts-node option translation and config/env preflight before script migration. | | `oxnode.ts` | oxnode → `vpx` command rules, loader compatibility, and its prompt/warnings. | | `script-runner.ts` | Shared script-runner command parsing, shebang rewrites, project detection, and conservative dependency retention. | +| `varlock.ts` | varlock Vite setup → the varlock support that Vite+ bundles: `varlockVitePlugin()` removal, schema type generator, unused varlock dependencies, and its prompt. | | `tsconfig.ts` | `tsconfig.json` cleanup and `types` rewriting. | | `framework-shim.ts` | Framework (Vue/Astro) shim detection and injection. | | `git-hooks.ts` | Vite+ hook defaults, project-owned hook preservation, and conservative detection of existing hook tools. | diff --git a/packages/cli/src/migration/migrator/varlock.ts b/packages/cli/src/migration/migrator/varlock.ts new file mode 100644 index 0000000000..3b3a652f23 --- /dev/null +++ b/packages/cli/src/migration/migrator/varlock.ts @@ -0,0 +1,518 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { styleText } from 'node:util'; + +import type { ArrayExpression, ImportDeclaration, Node, Span } from '@oxc-project/types'; +import { + confirm as promptConfirm, + isCancel, + log as promptLog, +} from '@voidzero-dev/vite-plus-prompts'; + +import { adoptVitePlusTypeGenerator } from '../../dotenv/schema-header.ts'; +import { DOTENV_SCHEMA_FILE, resolveVarlockPackage } from '../../dotenv/varlock.ts'; +import type { WorkspacePackage } from '../../types/index.ts'; +import { VITE_CONFIG_FILES } from '../../utils/constants.ts'; +import { editJsonFile } from '../../utils/json.ts'; +import { displayRelative } from '../../utils/path.ts'; +import { cancelAndExit } from '../../utils/prompts.ts'; +import { parseSource, propertyName } from '../ast-utils.ts'; +import { getWorkspaceProjectPaths, sourceTreeMatches } from '../migrator.ts'; +import type { MigrationReport } from '../report.ts'; +import { addMigrationWarning } from '../report.ts'; +import type { DependencyBag } from './shared.ts'; +import { readPackageJsonIfExists } from './shared.ts'; + +const VITE_INTEGRATION = '@varlock/vite-integration'; +const VITE_PLUGIN_EXPORT = 'varlockVitePlugin'; +const VARLOCK = 'varlock'; +/** The dependency fields from which the migration removes a package; a peer stays a contract. */ +const INSTALL_FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies'] as const; + +// An import, require, or resolve of `varlock` or a subpath, as in `from 'varlock/env'`. +// Not `@varlock/*` packages, whose specifier does not start with `varlock`. +const VARLOCK_MODULE_REFERENCE = + /(?:\bfrom|\bimport|\bimport\.meta\.resolve|\brequire(?:\.resolve)?)\s*\(?\s*(?:\/\*[\s\S]*?\*\/\s*)*['"`]varlock(?:\/[^'"`]*)?['"`]/; +// The varlock CLI in command position, as in `varlock run --` or `npx varlock load`. +const VARLOCK_COMMAND = + /(?:^|[\s;&|("'=/\\`])varlock(?:\.(?:cmd|exe|ps1))?(?=[ \t]+\S|[ \t]*$|["'`;&|)])/m; +const VITE_INTEGRATION_REFERENCE = /['"`]@varlock\/vite-integration(?:\/[^'"`]*)?['"`]/; +// Framework components import modules in their script blocks. +const CODE_EXTENSIONS = new Set([ + '.ts', + '.mts', + '.cts', + '.tsx', + '.js', + '.mjs', + '.cjs', + '.jsx', + '.vue', + '.svelte', + '.astro', +]); +// Shell scripts, CI workflows, and other text that can run the CLI. +const TEXT_FILES = /\.(?:sh|bash|zsh|ya?ml|toml)$/; +const TYPE_GENERATOR = /@generate(?:Ts|VitePlus)Types\(([^()]*)\)/; +const OTHER_PLUGIN = /@plugin\(\s*(?!vite-plus\s*\))[^)]/; + +interface Edit { + start: number; + end: number; +} + +function installedPackages(pkg: DependencyBag | undefined): Set { + const names = new Set(); + for (const field of INSTALL_FIELDS) { + for (const name of Object.keys(pkg?.[field] ?? {})) { + names.add(name); + } + } + return names; +} + +function viteConfigFiles(dir: string): Array { + return VITE_CONFIG_FILES.map((file) => path.join(dir, file)).filter((file) => + fs.existsSync(file), + ); +} + +function importsViteIntegration(file: string): boolean { + try { + return VITE_INTEGRATION_REFERENCE.test(fs.readFileSync(file, 'utf8')); + } catch { + return false; + } +} + +/** The project directories with a varlock Vite setup: the integration in package.json or vite.config. */ +function varlockProjectDirs( + rootDir: string, + packages?: ReadonlyArray, +): Array { + return getWorkspaceProjectPaths({ + rootDir, + packages: packages ? [...packages] : undefined, + }).filter( + (dir) => + installedPackages(readPackageJsonIfExists(path.join(dir, 'package.json'))).has( + VITE_INTEGRATION, + ) || viteConfigFiles(dir).some(importsViteIntegration), + ); +} + +/** + * Whether a project uses varlock through its Vite integration, which Vite+ + * bundles and adds for `.env.schema` itself. + */ +export function detectVarlockProject( + rootDir: string, + packages?: ReadonlyArray, +): boolean { + return varlockProjectDirs(rootDir, packages).length > 0; +} + +function isNode(value: unknown): value is Node { + return typeof value === 'object' && value !== null && 'type' in value && 'start' in value; +} + +function walk(node: Node, enter: (node: Node, parent: Node | undefined) => void, parent?: Node) { + enter(node, parent); + for (const value of Object.values(node)) { + const children: Array = Array.isArray(value) ? value : [value]; + for (const child of children) { + if (isNode(child)) { + walk(child, enter, node); + } + } + } +} + +/** + * The span that removes `item`, at `index` in `items`, from a comma-separated + * list, with one comma next to it. `open` and `close` are the positions just + * inside the brackets. A list item alone on its line takes the whole line + * with it. + */ +function listItemRemoval( + source: string, + item: Span, + items: ReadonlyArray, + index: number, + bounds: { open: number; close: number }, + comments: ReadonlyArray, +): Edit { + const { open, close } = bounds; + const commaBetween = (from: number, to: number) => { + for (let at = from; at < to; at++) { + const comment = comments.find((span) => span.start <= at && at < span.end); + if (comment) { + at = comment.end - 1; + } else if (source[at] === ',') { + return at; + } + } + return undefined; + }; + const following = commaBetween(item.end, items[index + 1]?.start ?? close); + const preceding = + following === undefined ? commaBetween(items[index - 1]?.end ?? open, item.start) : undefined; + let start = preceding ?? item.start; + let end = following === undefined ? item.end : following + 1; + if (following !== undefined) { + while (source[end] === ' ' || source[end] === '\t') { + end++; + } + } + const lineStart = source.lastIndexOf('\n', start - 1) + 1; + const newline = source.indexOf('\n', end); + const lineEnd = newline === -1 ? source.length : newline; + if (source.slice(lineStart, start).trim() === '' && source.slice(end, lineEnd).trim() === '') { + start = lineStart; + end = newline === -1 ? lineEnd : newline + 1; + } + return { start, end }; +} + +function wholeStatement(source: string, node: Span): Edit { + const newline = source.indexOf('\n', node.end); + const lineStart = source.lastIndexOf('\n', node.start - 1) + 1; + const end = newline === -1 ? source.length : newline + 1; + return source.slice(lineStart, node.start).trim() === '' && + source.slice(node.end, end).trim() === '' + ? { start: lineStart, end } + : { start: node.start, end: node.end }; +} + +/** + * The edits that remove `calls` from `array`. When no plugin is left, the + * `plugins` property goes too, so that the config does not keep an empty list. + */ +function pluginRemovals( + source: string, + array: ArrayExpression, + calls: ReadonlySet, + parents: ReadonlyMap, + comments: ReadonlyArray, +): Array { + const property = parents.get(array); + const object = property ? parents.get(property) : undefined; + if ( + array.elements.every((element) => element === null || calls.has(element)) && + property?.type === 'Property' && + propertyName(property.key) === 'plugins' && + object?.type === 'ObjectExpression' + ) { + if (object.properties.length === 1) { + return [{ start: object.start + 1, end: object.end - 1 }]; + } + return [ + listItemRemoval( + source, + property, + object.properties, + object.properties.findIndex((other) => other.start === property.start), + { open: object.start + 1, close: object.end - 1 }, + comments, + ), + ]; + } + return Array.from(calls, (call) => + listItemRemoval( + source, + call, + array.elements, + array.elements.findIndex((element) => element?.start === call.start), + { open: array.start + 1, close: array.end - 1 }, + comments, + ), + ); +} + +export interface VarlockPluginRemoval { + /** The rewritten source, or the original when nothing changed. */ + source: string; + removed: number; + /** Calls that stay, because they pass options or are not plugin array items. */ + kept: number; +} + +/** + * Remove `varlockVitePlugin()` calls without arguments from plugin arrays in a + * Vite config, and their import when nothing else uses it. Vite+ adds the + * integration for `.env.schema` itself, and two integrations would both load + * the schema and transform `ENV`. + */ +export function removeVarlockVitePlugin(file: string, source: string): VarlockPluginRemoval { + const { program, bindings, comments } = parseSource(file, source); + const edits: Array = []; + let removed = 0; + let kept = 0; + for (const statement of program.body) { + if (statement.type !== 'ImportDeclaration' || statement.source.value !== VITE_INTEGRATION) { + continue; + } + const declaration: ImportDeclaration = statement; + declaration.specifiers.forEach((specifier, index) => { + if ( + specifier.type !== 'ImportSpecifier' || + specifier.imported.type !== 'Identifier' || + specifier.imported.name !== VITE_PLUGIN_EXPORT + ) { + return; + } + const references = new Set( + bindings.find((binding) => binding.start === specifier.local.start)?.references ?? [], + ); + const removedCalls = new Set(); + const parents = new Map(); + const removable = new Map>(); + walk(program, (node, parent) => { + if (parent) { + parents.set(node, parent); + } + if ( + node.type !== 'CallExpression' || + node.callee.type !== 'Identifier' || + !references.has(node.callee.start) + ) { + return; + } + if (node.arguments.length > 0 || parent?.type !== 'ArrayExpression') { + kept++; + return; + } + removable.set(parent, (removable.get(parent) ?? new Set()).add(node)); + removedCalls.add(node.callee.start); + removed++; + }); + for (const [array, calls] of removable) { + edits.push(...pluginRemovals(source, array, calls, parents, comments)); + } + if ([...references].some((reference) => !removedCalls.has(reference))) { + return; + } + if (declaration.specifiers.length === 1) { + edits.push(wholeStatement(source, declaration)); + } else if (declaration.specifiers.every((other) => other.type === 'ImportSpecifier')) { + edits.push( + listItemRemoval( + source, + specifier, + declaration.specifiers, + index, + { + open: source.indexOf('{', declaration.start) + 1, + close: source.lastIndexOf('}', declaration.source.start), + }, + comments, + ), + ); + } + }); + } + let rewritten = source; + for (const edit of edits.toSorted((left, right) => right.start - left.start)) { + rewritten = rewritten.slice(0, edit.start) + rewritten.slice(edit.end); + } + return { source: rewritten, removed, kept }; +} + +/** The types file that the schema generates, which a migration must not count as a use. */ +function generatedTypesFile(dir: string, schema: string | undefined): string | undefined { + const args = schema === undefined ? undefined : TYPE_GENERATOR.exec(schema)?.[1]; + if (args === undefined) { + return undefined; + } + const file = /\bpath\s*=\s*(['"]?)([^,'"\s)]+)\1/.exec(args)?.[2] ?? 'env.d.ts'; + return path.resolve(dir, file); +} + +/** The first file in `dir` whose content matches, as a reason to keep a dependency. */ +function findUse( + dir: string, + isRoot: boolean, + matches: (content: string, file: string) => boolean, + skipFile?: string, +): string | undefined { + let found: string | undefined; + sourceTreeMatches( + dir, + (content, file) => { + if (file === skipFile || !matches(content, file)) { + return false; + } + found = file; + return true; + }, + { + // The root can serve any package, so its scan covers the whole workspace. + crossPackageBoundaries: isRoot, + extensions: CODE_EXTENSIONS, + fileNamePattern: TEXT_FILES, + // Git hooks and files such as `Dockerfile` can run the CLI. + includeExtensionless: true, + includePackageReferences: true, + }, + ); + if (found === undefined) { + return undefined; + } + return path.basename(found) === 'package.json' + ? `\`scripts\` in ${displayRelative(found)}` + : displayRelative(found); +} + +function varlockUse(dir: string, isRoot: boolean, schema: string | undefined): string | undefined { + const plugins = [...installedPackages(readPackageJsonIfExists(path.join(dir, 'package.json')))] + .filter((name) => name.startsWith('@varlock/') && name !== VITE_INTEGRATION) + .toSorted(); + if (plugins.length > 0) { + return `${plugins.join(', ')} ${plugins.length === 1 ? 'needs' : 'need'} it`; + } + if (schema !== undefined && OTHER_PLUGIN.test(schema)) { + return `${DOTENV_SCHEMA_FILE} loads another varlock plugin`; + } + const file = findUse( + dir, + isRoot, + (content, filePath) => + CODE_EXTENSIONS.has(path.extname(filePath)) + ? VARLOCK_MODULE_REFERENCE.test(content) + : VARLOCK_COMMAND.test(content), + generatedTypesFile(dir, schema), + ); + return file === undefined ? undefined : `${file} still uses it`; +} + +function bundledVarlockVersion(): string | undefined { + try { + return resolveVarlockPackage().version; + } catch { + return undefined; + } +} + +function removeDependency(packageJsonPath: string, name: string): boolean { + let removed = false; + editJsonFile(packageJsonPath, (json) => { + for (const field of INSTALL_FIELDS) { + const dependencies = json[field]; + if (dependencies?.[name] !== undefined) { + delete dependencies[name]; + removed = true; + if (Object.keys(dependencies).length === 0) { + delete json[field]; + } + } + } + return removed ? json : undefined; + }); + return removed; +} + +/** + * Move a varlock Vite setup to the varlock support that Vite+ bundles: + * + * - Remove `varlockVitePlugin()` without options from the Vite config. + * - Switch `@generateTsTypes(...)` in `.env.schema` to `@plugin(vite-plus) + * @generateVitePlusTypes(...)` with the same options, so that the types + * also apply to `ENV` from `vite-plus/dotenv`. + * - Remove `@varlock/vite-integration`, and `varlock` when nothing else uses + * them. + * + * The schema keeps its sensitivity and environment settings, so the project + * loads the same values as before. + */ +export function migrateVarlockToVitePlus( + rootDir: string, + packages?: ReadonlyArray, + report?: MigrationReport, +) { + let changed = false; + let dependencyRemoved = false; + const version = bundledVarlockVersion(); + for (const dir of varlockProjectDirs(rootDir, packages)) { + const isRoot = dir === rootDir; + for (const file of viteConfigFiles(dir)) { + const source = fs.readFileSync(file, 'utf8'); + const result = removeVarlockVitePlugin(file, source); + if (result.source !== source) { + fs.writeFileSync(file, result.source); + changed = true; + } + if (result.kept > 0) { + addMigrationWarning( + report, + `Kept ${VITE_PLUGIN_EXPORT}(...) in ${displayRelative(file)}: Vite+ adds the varlock integration without options, so both would run. Remove the call, or set \`dotenv: { schema: false }\` to keep only yours.`, + ); + } + } + + const schemaFile = path.join(dir, DOTENV_SCHEMA_FILE); + let schema = fs.existsSync(schemaFile) ? fs.readFileSync(schemaFile, 'utf8') : undefined; + if (schema !== undefined) { + const adopted = adoptVitePlusTypeGenerator(schema); + if (adopted !== schema) { + fs.writeFileSync(schemaFile, adopted); + schema = adopted; + changed = true; + } + } + + const packageJsonPath = path.join(dir, 'package.json'); + const installed = installedPackages(readPackageJsonIfExists(packageJsonPath)); + if (installed.has(VITE_INTEGRATION)) { + const use = findUse(dir, isRoot, (content, file) => + CODE_EXTENSIONS.has(path.extname(file)) ? VITE_INTEGRATION_REFERENCE.test(content) : false, + ); + if (use === undefined) { + dependencyRemoved = + removeDependency(packageJsonPath, VITE_INTEGRATION) || dependencyRemoved; + } else { + addMigrationWarning( + report, + `Kept the ${VITE_INTEGRATION} dependency in ${displayRelative(packageJsonPath)}: ${use} still uses it.`, + ); + } + } + if (installed.has(VARLOCK)) { + const use = varlockUse(dir, isRoot, schema); + if (use === undefined) { + dependencyRemoved = removeDependency(packageJsonPath, VARLOCK) || dependencyRemoved; + } else { + const versionAdvice = + version === undefined ? '' : ` Keep it at ${version}, the version that Vite+ bundles.`; + addMigrationWarning( + report, + `Kept the ${VARLOCK} dependency in ${displayRelative(packageJsonPath)}: ${use}.${versionAdvice}`, + ); + } + } + } + changed ||= dependencyRemoved; + if (report && changed) { + report.varlockMigrated = true; + } + return { changed, dependencyRemoved }; +} + +export async function confirmVarlockMigration(interactive: boolean): Promise { + if (interactive) { + const confirmed = await promptConfirm({ + message: + 'Migrate the varlock setup to Vite+?\n ' + + styleText( + 'gray', + 'Vite+ bundles varlock and its Vite integration, and loads `.env.schema` itself. `varlockVitePlugin()` leaves the Vite config, the schema types also cover `ENV` from `vite-plus/dotenv`, and the varlock dependencies are removed once nothing uses them.', + ), + initialValue: true, + }); + if (isCancel(confirmed)) { + cancelAndExit(); + } + return confirmed; + } + promptLog.info('varlock Vite integration detected. Auto-migrating to Vite+...'); + return true; +} diff --git a/packages/cli/src/migration/report.ts b/packages/cli/src/migration/report.ts index 44813bd7c5..352a138c1a 100644 --- a/packages/cli/src/migration/report.ts +++ b/packages/cli/src/migration/report.ts @@ -28,6 +28,7 @@ export interface MigrationReport { tsxMigrated: boolean; oxnodeMigrated: boolean; tsNodeMigrated: boolean; + varlockMigrated: boolean; nodeVersionFileMigrated: boolean; setupVpVersionUpdatedFileCount: number; gitHooksConfigured: boolean; @@ -57,6 +58,7 @@ export function createMigrationReport(): MigrationReport { tsxMigrated: false, oxnodeMigrated: false, tsNodeMigrated: false, + varlockMigrated: false, prettierMigrated: false, nodeVersionFileMigrated: false, setupVpVersionUpdatedFileCount: 0, diff --git a/rfcs/varlock-integration.md b/rfcs/varlock-integration.md index 73b7ec47ea..c5ee4042cc 100644 --- a/rfcs/varlock-integration.md +++ b/rfcs/varlock-integration.md @@ -181,6 +181,7 @@ What users get with zero config beyond the schema file: validated env on every d **`vp migrate`**: - Add `varlock` to `KNOWN_RUNNER_WRAPPERS` so existing `varlock run --` wrappers in scripts are recognized and preserved (inner command rewritten, wrapper kept). +- Migrator module `varlock.ts` in `packages/cli/src/migration/migrator/` moves an existing varlock Vite setup to Vite+: it removes `varlockVitePlugin()` without options from the Vite config (and an emptied `plugins` property), switches `@generateTsTypes(...)` to `@plugin(vite-plus) @generateVitePlusTypes(...)` with the same options, and removes `@varlock/vite-integration` and `varlock` when nothing else uses them. It keeps `@defaultSensitive` and `@currentEnv`, so the project loads the same values. It asks in interactive mode (default yes), migrates in non-interactive mode, and runs with `--full` on a project that already uses Vite+. Imports from `varlock/env` stay, because server code that Vite does not bundle would then need `vite-plus` at run time. - New migrator module `env-schema.ts` in `packages/cli/src/migration/migrator/`: detect `.env.example`, `dotenv`/`dotenvx` dependencies, or `VITE_`-prefixed usage, and offer to generate `.env.schema` through varlock's init logic, with `@defaultSensitive=inferFromPrefix('VITE_')` as the compatibility default so behavior does not change silently. `dotenv -e` script wrappers are reported in the migration summary with a suggested `vp dotenv exec --` replacement, but are not rewritten automatically in the first release. - A corresponding entry in `docs/guide/migrate-rules.md` and the migration report. @@ -249,7 +250,7 @@ Every phase is inert for projects without a `.env.schema` file. Existing dotenv - **Two sources of truth during adoption.** A project with both `.env.example` and `.env.schema` is confusing. `varlock init` offers to delete `.env.example` in interactive mode; the Phase 2 migrator does the same. - **`envDir` users.** The integration ignores `envDir` and prints its own warning, which points to `varlock.loadPath`. - **Snapshot-test flakiness.** `vp dotenv` fixtures must avoid network (no plugin installs) and keep caches isolated per case, per the snapshot-runner rules. -- **Agent skill shipped by varlock.** The `varlock` package publishes a `skills/` directory. pnpm 12 reports it after install ("Agent skills awaiting approval: varlock") and asks the user to run `pnpm approve`, so every pnpm 12 user of vite-plus may see this prompt. This needs a decision before release: accept the prompt, ask upstream for a package without the skill, or document it. +- **Agent skill shipped by varlock.** The `varlock` package publishes a `skills/` directory. pnpm 12 (checked with 12.11.2) asks for approval of agent skills from direct dependencies only: an install that resolves dependencies prints "Agent skills awaiting approval: varlock" and points to `pnpm approve`, and an install with an unchanged lockfile prints nothing. A project that depends only on `vite-plus` gets `varlock` as a transitive dependency and sees no prompt. A project that adds `varlock` itself, and this repository (`packages/cli` depends on it), see the prompt until they approve or deny the skill. `pnpm approve '!varlock'` writes `permissions: { varlock: { skills: false } }` to `pnpm-workspace.yaml`. The varlock migration in `vp migrate` removes a direct `varlock` dependency that the project no longer needs, which also removes the prompt. ## Open questions From 2e7fe905f1383231cdef083cb69bb0985369ef2f Mon Sep 17 00:00:00 2001 From: "MK (fengmk2)" Date: Fri, 4 Dec 2026 15:59:35 +0800 Subject: [PATCH 24/28] feat(dotenv): add vp dotenv encrypt and lock, mark vp dotenv experimental varlock encrypts secrets with a key stored on the device (Secure Enclave, TPM, or a key file) as `varlock("local:...")`, and every command that loads the schema already decrypts them. Projects without a direct `varlock` dependency had no command to create those values, though. `vp dotenv encrypt` runs `varlock encrypt` with the terminal attached: it reads a value from stdin or a prompt, or encrypts the sensitive plaintext values of a file with `--file`. `vp dotenv lock` runs `varlock lock`, which ends the biometric session. Neither needs a schema, except `encrypt --file`. The guide gets a local encryption section: which commands decrypt, where varlock keeps the key, that only the encrypting device can decrypt, and that `varlock(prompt)` asks only through `vp dotenv exec`. The guide, the `dotenv` config reference, the varlock migration rules, and the README command lists now say that `vp dotenv` and the `.env.schema` support are experimental. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- .../snapshots/command_dotenv_help.global.md | 6 ++ .../snapshots/command_dotenv_help.local.md | 6 ++ docs/config/dotenv.md | 4 ++ docs/guide/dotenv.md | 44 ++++++++++++- docs/guide/migrate-rules.md | 2 +- packages/cli/README.md | 2 +- packages/cli/binding/index.d.cts | 3 +- .../src/js_command_args/commands/dotenv.rs | 53 +++++++++++++++- .../cli/src/dotenv/__tests__/encrypt.spec.ts | 63 +++++++++++++++++++ .../cli/src/dotenv/__tests__/varlock.spec.ts | 15 +++++ packages/cli/src/dotenv/bin.ts | 7 ++- packages/cli/src/dotenv/varlock.ts | 8 +++ rfcs/varlock-integration.md | 32 +++++----- 14 files changed, 226 insertions(+), 21 deletions(-) create mode 100644 packages/cli/src/dotenv/__tests__/encrypt.spec.ts diff --git a/README.md b/README.md index fc7964261f..5fd6e661bf 100644 --- a/README.md +++ b/README.md @@ -115,7 +115,7 @@ Use `vp migrate` to migrate to Vite+. It merges tool-specific config files such - **lint** - Lint code - **fmt** - Format code - **test** - Run tests -- **dotenv** - Validate and inspect project environment variables using `.env.schema` +- **dotenv** - Validate and inspect project environment variables using `.env.schema` (experimental) #### Execute diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.global.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.global.md index 95c8a87648..c8d0d311d0 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.global.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.global.md @@ -19,6 +19,8 @@ Commands: explain Show how config items resolve, with sensitive values masked scan Find plaintext copies of sensitive values in files exec Run a command with the resolved environment + encrypt Encrypt a value with a key stored on this device + lock Require biometric authentication for the next decryption Examples: vp dotenv init @@ -26,6 +28,7 @@ Examples: vp dotenv print --format json vp dotenv scan --staged vp dotenv exec -- node scripts/seed.ts + vp dotenv encrypt --file .env.local Documentation: https://viteplus.dev/guide/dotenv ``` @@ -68,6 +71,8 @@ Commands: explain Show how config items resolve, with sensitive values masked scan Find plaintext copies of sensitive values in files exec Run a command with the resolved environment + encrypt Encrypt a value with a key stored on this device + lock Require biometric authentication for the next decryption Examples: vp dotenv init @@ -75,6 +80,7 @@ Examples: vp dotenv print --format json vp dotenv scan --staged vp dotenv exec -- node scripts/seed.ts + vp dotenv encrypt --file .env.local Documentation: https://viteplus.dev/guide/dotenv ``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.local.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.local.md index 95c8a87648..c8d0d311d0 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.local.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.local.md @@ -19,6 +19,8 @@ Commands: explain Show how config items resolve, with sensitive values masked scan Find plaintext copies of sensitive values in files exec Run a command with the resolved environment + encrypt Encrypt a value with a key stored on this device + lock Require biometric authentication for the next decryption Examples: vp dotenv init @@ -26,6 +28,7 @@ Examples: vp dotenv print --format json vp dotenv scan --staged vp dotenv exec -- node scripts/seed.ts + vp dotenv encrypt --file .env.local Documentation: https://viteplus.dev/guide/dotenv ``` @@ -68,6 +71,8 @@ Commands: explain Show how config items resolve, with sensitive values masked scan Find plaintext copies of sensitive values in files exec Run a command with the resolved environment + encrypt Encrypt a value with a key stored on this device + lock Require biometric authentication for the next decryption Examples: vp dotenv init @@ -75,6 +80,7 @@ Examples: vp dotenv print --format json vp dotenv scan --staged vp dotenv exec -- node scripts/seed.ts + vp dotenv encrypt --file .env.local Documentation: https://viteplus.dev/guide/dotenv ``` diff --git a/docs/config/dotenv.md b/docs/config/dotenv.md index dba5e77064..7721cd640a 100644 --- a/docs/config/dotenv.md +++ b/docs/config/dotenv.md @@ -1,5 +1,9 @@ # Dotenv Config +::: warning Experimental +The `dotenv` config and the `.env.schema` support are experimental and may change. See [Env Files](/guide/dotenv). +::: + `vp dev`, `vp build`, `vp preview`, and `vp test` load and validate `.env` files against `.env.schema` when the file exists. The `dotenv` block in `vite.config.ts` controls that loading. See [Env Files](/guide/dotenv). Both options have defaults that suit a project with `.env.schema` at its root. Most projects do not need this block. diff --git a/docs/guide/dotenv.md b/docs/guide/dotenv.md index b99e854a2e..f862fb7c4e 100644 --- a/docs/guide/dotenv.md +++ b/docs/guide/dotenv.md @@ -1,5 +1,9 @@ # Env Files +::: warning Experimental +`vp dotenv` and the `.env.schema` support in `vp dev`, `vp build`, `vp preview`, and `vp test` are experimental. Commands, options, the `dotenv` config, and the schema setup that `vp dotenv init` writes may change. +::: + Use `vp dotenv` to manage `.env` files with a committed schema. Vite+ validates environment variables, generates types, keeps secrets out of client bundles and logs, and gives coding agents the structure of your config without the values. ## Overview @@ -175,6 +179,29 @@ A variable is sensitive when the schema marks it `@sensitive`, or when `@default These are guardrails against accidental exposure, not a sandbox. The running process still holds the plaintext. To print a value on purpose, use `revealSensitiveConfig()` from `vite-plus/dotenv`. +## Local encryption + +varlock can encrypt a secret with a key that stays on your device. The env file then holds a reference instead of the plaintext: + +```env [.env.local] +STRIPE_SECRET_KEY=varlock("local:AQQG...") +``` + +Every command that loads the schema decrypts the value: `vp dev`, `vp build`, `vp preview`, `vp test`, the `vp dotenv` commands, and `ENV` in `vite.config.ts`. varlock keeps the key in the most secure store that the device has: + +- macOS: the Secure Enclave, with Touch ID or the login password. +- Windows: the TPM, with Windows Hello. +- Linux: TPM2 or the Secret Service, with a polkit or PAM prompt. +- Otherwise: a key file in your user config directory (`~/.config/varlock`). + +Vite+ installs varlock's native helper for these stores, so the project needs no extra package. + +Only the device that encrypted a value can decrypt it. Keep encrypted values in git-ignored files such as `.env.local`, and give CI and other machines their values another way, for example as CI secrets in the process environment. + +To set a value, use [`vp dotenv encrypt`](#vp-dotenv-encrypt), or write `KEY=varlock(prompt)` and run a command through `vp dotenv exec`. varlock then asks for the value, encrypts it, and writes the reference back to the file. Commands that do not give varlock a terminal do not ask: `vp dev`, `vp build`, `vp preview`, `vp test`, `vp dotenv check`, and `vp dotenv print` without `--reveal` fail with "No encrypted value found" instead. On macOS with Touch ID, varlock asks in a system dialog instead of the terminal. + +See the [varlock local encryption guide](https://varlock.dev/guides/local-encryption/) for the setup on each platform. + ## Commands ### `vp dotenv init` @@ -191,7 +218,7 @@ vp dotenv check `--mode ` sets `viteMode()`, so that the command checks the values that `vp build --mode ` uses. `vp dotenv check --mode production` checks the values of `vp build`. `--env ` selects an environment when the schema does not use `@currentEnv`. With `@currentEnv`, set its variable instead, for example `APP_ENV=production vp dotenv check`. -Every `vp dotenv` command except `init` fails when the directory has no `.env.schema` and no `varlock.loadPath`, so a check that runs in the wrong directory cannot pass without checking anything. +Every `vp dotenv` command that loads the config fails when the directory has no `.env.schema` and no `varlock.loadPath`, so a check that runs in the wrong directory cannot pass without checking anything. `init`, `lock`, and `encrypt` without `--file` do not load it. ### `vp dotenv print` @@ -238,6 +265,21 @@ When output is piped or redirected, sensitive values are redacted from stdout an `vp dotenv exec` runs one command in the schema environment. [`vp run`](/guide/run) runs a task from `vite.config.ts`. +### `vp dotenv encrypt` + +Encrypt a secret with a key that stays on this device, so that an env file can hold the encrypted value. Pipe the value on stdin, or run the command in a terminal to type it: + +```bash +echo "$STRIPE_SECRET_KEY" | vp dotenv encrypt # prints varlock("local:...") +vp dotenv encrypt --file .env.local # encrypts sensitive plaintext values in place +``` + +With `--file`, varlock lists the sensitive plaintext values of the file and encrypts the ones that you confirm. See [Local encryption](#local-encryption). + +### `vp dotenv lock` + +End the biometric session of local encryption, so that the next decryption asks for Touch ID, Windows Hello, or another biometric check again. Run it before you leave the computer. A key without biometric support has no session to end, and the command says so. + ## Using env files in tasks A [`vp run`](/guide/run) task starts in a clean environment, so `.env` values do not reach it by default. To give a task the schema environment, run its command through `vp dotenv exec`: diff --git a/docs/guide/migrate-rules.md b/docs/guide/migrate-rules.md index f467f32d1f..1d7180e2ec 100644 --- a/docs/guide/migrate-rules.md +++ b/docs/guide/migrate-rules.md @@ -413,7 +413,7 @@ As with oxnode, migration rewrites package scripts, JSON lint-staged tasks, and ## varlock Rules -When a package uses [varlock](https://varlock.dev) through its Vite integration (`@varlock/vite-integration` in `package.json`, or an import of it in `vite.config.*`), migration offers to move the setup to the varlock support that Vite+ bundles (see [Env Files](/guide/dotenv)). The prompt defaults to yes, and `--no-interactive` migrates without asking. Vite+ loads `.env.schema` and adds the integration itself, so migration: +The varlock support in Vite+ is experimental (see [Env Files](/guide/dotenv)). When a package uses [varlock](https://varlock.dev) through its Vite integration (`@varlock/vite-integration` in `package.json`, or an import of it in `vite.config.*`), migration offers to move the setup to the varlock support that Vite+ bundles (see [Env Files](/guide/dotenv)). The prompt defaults to yes, and `--no-interactive` migrates without asking. Vite+ loads `.env.schema` and adds the integration itself, so migration: - Removes `varlockVitePlugin()` calls without arguments from plugin arrays in `vite.config.*`, and their import when nothing else uses it. A `plugins` property with no plugin left goes too. A call with options stays, with a warning: Vite+ adds the integration without options, so both would run. Remove the call, or set `dotenv: { schema: false }` to keep only yours. - Replaces `@generateTsTypes(...)` in `.env.schema` with `@plugin(vite-plus) @generateVitePlusTypes(...)` and the same options, so that the generated types also apply to `ENV` from `vite-plus/dotenv`. Other root decorators, such as `@defaultSensitive` and `@currentEnv`, stay unchanged, so the project loads the same values as before. diff --git a/packages/cli/README.md b/packages/cli/README.md index 3b6f988890..a567184474 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -110,7 +110,7 @@ Use `vp migrate` to migrate to Vite+. It merges tool-specific config files such - **lint** - Lint code - **fmt** - Format code - **test** - Run tests -- **dotenv** - Validate and inspect project environment variables using `.env.schema` +- **dotenv** - Validate and inspect project environment variables using `.env.schema` (experimental) #### Execute diff --git a/packages/cli/binding/index.d.cts b/packages/cli/binding/index.d.cts index 6904c5d0d7..e5e9b24ef9 100644 --- a/packages/cli/binding/index.d.cts +++ b/packages/cli/binding/index.d.cts @@ -3906,7 +3906,7 @@ export interface DevCommand { export declare function documentationUrl(path: string): string; export interface DotenvArgs { - command: 'init' | 'check' | 'print' | 'explain' | 'scan' | 'exec'; + command: 'init' | 'check' | 'print' | 'explain' | 'scan' | 'exec' | 'encrypt' | 'lock'; env?: string; mode?: string; format: 'env' | 'json' | 'shell'; @@ -3917,6 +3917,7 @@ export interface DotenvArgs { includeIgnored: boolean; interactive: boolean; execCommand: Array; + file?: string; } /** diff --git a/packages/cli/binding/src/js_command_args/commands/dotenv.rs b/packages/cli/binding/src/js_command_args/commands/dotenv.rs index 7fa4394029..2dfe0d87cb 100644 --- a/packages/cli/binding/src/js_command_args/commands/dotenv.rs +++ b/packages/cli/binding/src/js_command_args/commands/dotenv.rs @@ -33,6 +33,12 @@ enum DotenvSubcommand { /// Run a command with the resolved environment #[command(disable_help_flag = true)] Exec(ExecArgs), + /// Encrypt a value with a key stored on this device + #[command(disable_help_flag = true)] + Encrypt(EncryptArgs), + /// Require biometric authentication for the next decryption + #[command(disable_help_flag = true)] + Lock(LockArgs), } #[derive(Debug, Args)] @@ -138,6 +144,29 @@ struct ExecArgs { command: Vec, } +#[derive(Debug, Args)] +struct EncryptArgs { + #[arg( + long, + value_name = "file", + value_parser = NonEmptyStringValueParser::new(), + help = "Encrypt the sensitive plaintext values in this env file in place" + )] + file: Option, + + #[arg(long, value_name = "name", value_parser = NonEmptyStringValueParser::new(), help = MODE_HELP)] + mode: Option, + + #[arg(short = 'h', long, action = ArgAction::Help, help = "Show this help message")] + help: Option, +} + +#[derive(Debug, Args)] +struct LockArgs { + #[arg(short = 'h', long, action = ArgAction::Help, help = "Show this help message")] + help: Option, +} + fn dotenv_command() -> Command { DotenvCliArgs::augment_args( Command::new("vp dotenv") @@ -154,7 +183,9 @@ fn dotenv_command() -> Command { #[napi(object, object_from_js = false)] pub struct DotenvArgs { - #[napi(ts_type = "'init' | 'check' | 'print' | 'explain' | 'scan' | 'exec'")] + #[napi( + ts_type = "'init' | 'check' | 'print' | 'explain' | 'scan' | 'exec' | 'encrypt' | 'lock'" + )] pub command: String, pub env: Option, pub mode: Option, @@ -167,6 +198,7 @@ pub struct DotenvArgs { pub include_ignored: bool, pub interactive: bool, pub exec_command: Vec, + pub file: Option, } impl DotenvArgs { @@ -183,6 +215,7 @@ impl DotenvArgs { include_ignored: false, interactive: true, exec_command: Vec::new(), + file: None, } } } @@ -216,6 +249,10 @@ impl From for DotenvArgs { DotenvSubcommand::Exec(args) => { Self { mode: args.mode, exec_command: args.command, ..Self::new("exec") } } + DotenvSubcommand::Encrypt(args) => { + Self { mode: args.mode, file: args.file, ..Self::new("encrypt") } + } + DotenvSubcommand::Lock(_) => Self::new("lock"), } } } @@ -258,6 +295,7 @@ pub fn parse_dotenv_args(argv: Vec) -> ParseDotenvArgsOutcome { " vp dotenv print --format json".into(), " vp dotenv scan --staged".into(), " vp dotenv exec -- node scripts/seed.ts".into(), + " vp dotenv encrypt --file .env.local".into(), ], }); } @@ -352,6 +390,19 @@ mod tests { assert_eq!(args.exec_command, ["node", "--watch", "seed.ts"]); } + #[test] + fn encrypt_takes_a_file_and_lock_takes_nothing() { + let args = parsed(&["encrypt"]); + assert_eq!(args.command, "encrypt"); + assert_eq!(args.file, None); + let args = parsed(&["encrypt", "--file", ".env.local", "--mode", "production"]); + assert_eq!(args.file.as_deref(), Some(".env.local")); + assert_eq!(args.mode.as_deref(), Some("production")); + assert_eq!(parsed(&["lock"]).command, "lock"); + assert_eq!(parse_error(&["encrypt", "--file", ""]).kind, "invalid-value"); + assert_eq!(parse_error(&["lock", "extra"]).kind, "unknown-argument"); + } + #[test] fn top_level_and_subcommand_help_return_help() { for argv in diff --git a/packages/cli/src/dotenv/__tests__/encrypt.spec.ts b/packages/cli/src/dotenv/__tests__/encrypt.spec.ts new file mode 100644 index 0000000000..40007ec288 --- /dev/null +++ b/packages/cli/src/dotenv/__tests__/encrypt.spec.ts @@ -0,0 +1,63 @@ +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { pkgRoot } from '../../utils/path.ts'; + +// Runs the built CLI with varlock's file-based key, which lives under +// XDG_CONFIG_HOME, so the test neither prompts for Touch ID nor touches the +// user's keys. +describe('vp dotenv encrypt and lock', () => { + let dir: string; + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-dotenv-encrypt-')); + fs.writeFileSync(path.join(dir, 'package.json'), '{ "name": "app", "private": true }\n'); + fs.writeFileSync( + path.join(dir, '.env.schema'), + '# @defaultSensitive=false\n# ---\n# @required @sensitive\nSECRET=\n', + ); + }); + + afterEach(() => { + fs.rmSync(dir, { recursive: true, force: true }); + }); + + function vp(args: Array, input?: string) { + return spawnSync(process.execPath, [path.join(pkgRoot, 'bin', 'vp'), 'dotenv', ...args], { + cwd: dir, + input, + encoding: 'utf8', + env: { + ...process.env, + XDG_CONFIG_HOME: path.join(dir, 'xdg'), + _VARLOCK_FORCE_FILE_ENCRYPTION_FALLBACK: '1', + VARLOCK_TELEMETRY_DISABLED: '1', + }, + }); + } + + it('encrypts a value from stdin into a reference that loads back', () => { + const encrypted = vp(['encrypt'], 'sk_live_123\n'); + const reference = /varlock\("local:[^"]+"\)/.exec(encrypted.stdout)?.[0]; + expect(encrypted.status).toBe(0); + expect(reference).toBeDefined(); + + fs.writeFileSync(path.join(dir, '.env.local'), `SECRET=${reference}\n`); + const revealed = vp(['print', '--reveal']); + expect(revealed.status).toBe(0); + expect(revealed.stdout).toContain('sk_live_123'); + }); + + it('needs no schema to encrypt one value or to lock the session', () => { + fs.rmSync(path.join(dir, '.env.schema')); + + expect(vp(['encrypt'], 'value\n').stdout).toMatch(/varlock\("local:[^"]+"\)/); + const locked = vp(['lock']); + expect(locked.status).toBe(0); + expect(locked.stdout).toContain('The file backend does not support biometric lock.'); + }); +}); diff --git a/packages/cli/src/dotenv/__tests__/varlock.spec.ts b/packages/cli/src/dotenv/__tests__/varlock.spec.ts index a7d9c3a79b..edbaf0b90b 100644 --- a/packages/cli/src/dotenv/__tests__/varlock.spec.ts +++ b/packages/cli/src/dotenv/__tests__/varlock.spec.ts @@ -85,6 +85,21 @@ describe('buildVarlockInvocation', () => { ), ).toEqual({ argv: ['run', '--', 'node', '--inspect', 'a.ts'], output: 'inherit' }); }); + + it('maps encrypt and lock to the varlock commands with the terminal attached', () => { + expect(buildVarlockInvocation(dotenvArgs({ command: 'encrypt' }))).toEqual({ + argv: ['encrypt'], + output: 'inherit', + }); + expect(buildVarlockInvocation(dotenvArgs({ command: 'encrypt', file: '.env.local' }))).toEqual({ + argv: ['encrypt', '--file', '.env.local'], + output: 'inherit', + }); + expect(buildVarlockInvocation(dotenvArgs({ command: 'lock' }))).toEqual({ + argv: ['lock'], + output: 'inherit', + }); + }); }); describe('renderMaskedValues', () => { diff --git a/packages/cli/src/dotenv/bin.ts b/packages/cli/src/dotenv/bin.ts index 4983778e99..393530f315 100644 --- a/packages/cli/src/dotenv/bin.ts +++ b/packages/cli/src/dotenv/bin.ts @@ -100,7 +100,12 @@ async function main(): Promise { // Without a schema, varlock loads an empty config and every command // succeeds, so a misplaced `check` or `scan` would pass without checking. - if (args.command !== 'init' && !hasDotenvSchema(cwd)) { + // Encrypting one value and locking the session do not load the config. + const loadsConfig = + args.command !== 'init' && + args.command !== 'lock' && + !(args.command === 'encrypt' && !args.file); + if (loadsConfig && !hasDotenvSchema(cwd)) { errorMsg( `No ${DOTENV_SCHEMA_FILE} in ${cwd}, and its package.json sets no \`varlock.loadPath\`. Run this command from the project root, or run \`vp dotenv init\` to create a schema.`, ); diff --git a/packages/cli/src/dotenv/varlock.ts b/packages/cli/src/dotenv/varlock.ts index 4246fa45b8..18039e2576 100644 --- a/packages/cli/src/dotenv/varlock.ts +++ b/packages/cli/src/dotenv/varlock.ts @@ -95,6 +95,14 @@ export function buildVarlockInvocation(args: DotenvArgs): VarlockInvocation { }; case 'exec': return { argv: ['run', '--', ...args.execCommand], output: 'inherit' }; + case 'encrypt': + // Without `--file`, varlock reads the value from stdin or prompts for it. + return { + argv: ['encrypt', ...(args.file ? ['--file', args.file] : [])], + output: 'inherit', + }; + case 'lock': + return { argv: ['lock'], output: 'inherit' }; default: { const command: never = args.command; throw new Error(`Unknown dotenv command: ${String(command)}`); diff --git a/rfcs/varlock-integration.md b/rfcs/varlock-integration.md index c5ee4042cc..602e89e5ad 100644 --- a/rfcs/varlock-integration.md +++ b/rfcs/varlock-integration.md @@ -95,15 +95,17 @@ Mechanics: A new command family named **`vp dotenv`**. Naming rationale: `vp env` is taken by runtime management, `vp secrets` undersells the feature (schema and validation apply to non-secret config too), and `dotenv` names exactly the file family the command manages. Subcommand names follow the Vite+ vocabulary rather than varlock's: `check` validates like `vp check`, `exec` runs a command in an environment like `vp exec`, and `print` is separate from `check` so plaintext secrets only ever leave one command, behind an explicit `--reveal` flag. -| Command | Runs | Behavior | -| -------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `vp dotenv init` | `varlock init`, or `varlock init --agent` with `--no-interactive` | Scaffold `.env.schema` from existing `.env` files and code, add the `.gitignore` exception when needed, pick a type-generation decorator. | -| `vp dotenv check` | `varlock load --format json --agent` | Validate schema plus local values. Discard stdout and print a `pass:` line. varlock reports errors on stderr. This is the CI entry point. Fails, like every subcommand except `init`, when the directory has no schema. | -| `vp dotenv print` | `varlock load --format json --agent` | Vite+ renders the redacted JSON as `env`, `json`, or `shell`. varlock rejects `--agent` with `env` and `shell`, so Vite+ does the rendering. | -| `vp dotenv print --reveal` | `varlock load --format ` | Plaintext output in varlock's own format. | -| `vp dotenv explain [KEY]` | `varlock explain KEY`, or `varlock load` without a key | `varlock explain` requires a key. The pretty `load` output is the all-items view, and it masks sensitive values. | -| `vp dotenv scan` | `varlock scan` | Find plaintext secrets in files, staged changes, or build output. `--install-hook` is not exposed: Vite+ owns hooks. | -| `vp dotenv exec -- ` | `varlock run -- ` | Inject resolved env into a subprocess with stdout redaction. `varlock run` has no `--env` option, so the environment comes from `@currentEnv`. | +| Command | Runs | Behavior | +| -------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `vp dotenv init` | `varlock init`, or `varlock init --agent` with `--no-interactive` | Scaffold `.env.schema` from existing `.env` files and code, add the `.gitignore` exception when needed, pick a type-generation decorator. | +| `vp dotenv check` | `varlock load --format json --agent` | Validate schema plus local values. Discard stdout and print a `pass:` line. varlock reports errors on stderr. This is the CI entry point. Fails, like every subcommand that loads the config, when the directory has no schema. | +| `vp dotenv print` | `varlock load --format json --agent` | Vite+ renders the redacted JSON as `env`, `json`, or `shell`. varlock rejects `--agent` with `env` and `shell`, so Vite+ does the rendering. | +| `vp dotenv print --reveal` | `varlock load --format ` | Plaintext output in varlock's own format. | +| `vp dotenv explain [KEY]` | `varlock explain KEY`, or `varlock load` without a key | `varlock explain` requires a key. The pretty `load` output is the all-items view, and it masks sensitive values. | +| `vp dotenv scan` | `varlock scan` | Find plaintext secrets in files, staged changes, or build output. `--install-hook` is not exposed: Vite+ owns hooks. | +| `vp dotenv exec -- ` | `varlock run -- ` | Inject resolved env into a subprocess with stdout redaction. `varlock run` has no `--env` option, so the environment comes from `@currentEnv`. | +| `vp dotenv encrypt` | `varlock encrypt [--file ]` | Encrypt a value from stdin or a prompt into `varlock("local:...")`, or the sensitive plaintext values of a file, with a key stored on the device. It needs no schema without `--file`. The terminal stays attached for the prompts. | +| `vp dotenv lock` | `varlock lock` | End the biometric session of local encryption. It needs no schema, and reports when the key has no biometric support. | `vp dotenv check`, `print`, `explain`, `scan`, and `exec` take `--mode `, which sets `VP_VITE_MODE` for the varlock process, so `viteMode()` in the schema returns the same mode as in `vp build --mode ` (see "Environment selection" in section 3). @@ -233,11 +235,13 @@ All env-spec parsing and resolution stays in the JS layer: ## Rollout -| Phase | Scope | Risk | -| ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | -| 1 | Bundle varlock + plugin, `vite-plus/dotenv` re-export, `vp dotenv init/check/print/explain/scan/exec`, auto plugin injection for dev/build/preview/test, client build-output scan, `.gitignore` fix, docs | Low: additive, inert without `.env.schema` | -| 2 | `vp create` prompt + agent guidance, `vp migrate` module + wrapper recognition, git-hook scan step, `vp check` step | Low-medium: touches scaffolding flows | -| 3 | `vp run` task injection + sensitive-value fingerprinting, tsdown/`vp pack` integration decision | Medium: cache format and NAPI surface | +| Phase | Scope | Risk | +| ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | +| 1 | Bundle varlock + plugin, `vite-plus/dotenv` re-export, `vp dotenv init/check/print/explain/scan/exec/encrypt/lock`, auto plugin injection for dev/build/preview/test, client build-output scan, `.gitignore` fix, docs | Low: additive, inert without `.env.schema` | +| 2 | `vp create` prompt + agent guidance, `vp migrate` module + wrapper recognition, git-hook scan step, `vp check` step | Low-medium: touches scaffolding flows | +| 3 | `vp run` task injection + sensitive-value fingerprinting, tsdown/`vp pack` integration decision | Medium: cache format and NAPI surface | + +Phase 1 ships as an experimental feature: the user docs (the Env Files guide, the `dotenv` config reference, the varlock migration rules, and the README command lists) say so, and commands, options, and the schema setup that `vp dotenv init` writes may change before it is stable. Every phase is inert for projects without a `.env.schema` file. Existing dotenv behavior (Vite's `loadEnv`, `VITE_` prefix) is untouched until a project adopts the schema, and `@defaultSensitive=inferFromPrefix('VITE_')` gives a no-behavior-change adoption path. From a82db6d743fa458af8136cacda88afb848aff88c Mon Sep 17 00:00:00 2001 From: "MK (fengmk2)" Date: Fri, 4 Dec 2026 20:41:31 +0800 Subject: [PATCH 25/28] feat(dotenv): add vp dotenv keychain for macOS Keychain items `keychain()` already reads secrets from the macOS Keychain in every command that loads the schema, but projects without a direct `varlock` dependency had no command to store or manage those items. `vp dotenv keychain` passes every argument, `--help` included, to `varlock keychain` (`set`, `import`, `fix-access`, or `list`) with the terminal attached. Vite+ does not declare the subcommands and options again, so it does not have to follow their changes. varlock reports the platform error outside macOS, and `keychain import` checks for its schema itself. Co-Authored-By: Claude Opus 5.5 --- .../snapshots/command_dotenv_help.global.md | 34 ++++++++-------- .../snapshots/command_dotenv_help.local.md | 34 ++++++++-------- docs/guide/dotenv.md | 17 +++++++- packages/cli/binding/index.d.cts | 12 +++++- .../src/js_command_args/commands/dotenv.rs | 39 ++++++++++++++++++- .../cli/src/dotenv/__tests__/encrypt.spec.ts | 15 +++++++ .../cli/src/dotenv/__tests__/varlock.spec.ts | 9 +++++ packages/cli/src/dotenv/bin.ts | 4 +- packages/cli/src/dotenv/varlock.ts | 3 ++ rfcs/varlock-integration.md | 33 ++++++++-------- 10 files changed, 148 insertions(+), 52 deletions(-) diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.global.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.global.md index c8d0d311d0..1aa030c79f 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.global.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.global.md @@ -13,14 +13,15 @@ Options: -h, --help Show this help message Commands: - init Create .env.schema from the existing .env files - check Validate the .env files against .env.schema without printing values - print Print the resolved values, with sensitive values masked - explain Show how config items resolve, with sensitive values masked - scan Find plaintext copies of sensitive values in files - exec Run a command with the resolved environment - encrypt Encrypt a value with a key stored on this device - lock Require biometric authentication for the next decryption + init Create .env.schema from the existing .env files + check Validate the .env files against .env.schema without printing values + print Print the resolved values, with sensitive values masked + explain Show how config items resolve, with sensitive values masked + scan Find plaintext copies of sensitive values in files + exec Run a command with the resolved environment + encrypt Encrypt a value with a key stored on this device + lock Require biometric authentication for the next decryption + keychain Manage the macOS Keychain items that keychain() reads (macOS only) Examples: vp dotenv init @@ -65,14 +66,15 @@ Options: -h, --help Show this help message Commands: - init Create .env.schema from the existing .env files - check Validate the .env files against .env.schema without printing values - print Print the resolved values, with sensitive values masked - explain Show how config items resolve, with sensitive values masked - scan Find plaintext copies of sensitive values in files - exec Run a command with the resolved environment - encrypt Encrypt a value with a key stored on this device - lock Require biometric authentication for the next decryption + init Create .env.schema from the existing .env files + check Validate the .env files against .env.schema without printing values + print Print the resolved values, with sensitive values masked + explain Show how config items resolve, with sensitive values masked + scan Find plaintext copies of sensitive values in files + exec Run a command with the resolved environment + encrypt Encrypt a value with a key stored on this device + lock Require biometric authentication for the next decryption + keychain Manage the macOS Keychain items that keychain() reads (macOS only) Examples: vp dotenv init diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.local.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.local.md index c8d0d311d0..1aa030c79f 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.local.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.local.md @@ -13,14 +13,15 @@ Options: -h, --help Show this help message Commands: - init Create .env.schema from the existing .env files - check Validate the .env files against .env.schema without printing values - print Print the resolved values, with sensitive values masked - explain Show how config items resolve, with sensitive values masked - scan Find plaintext copies of sensitive values in files - exec Run a command with the resolved environment - encrypt Encrypt a value with a key stored on this device - lock Require biometric authentication for the next decryption + init Create .env.schema from the existing .env files + check Validate the .env files against .env.schema without printing values + print Print the resolved values, with sensitive values masked + explain Show how config items resolve, with sensitive values masked + scan Find plaintext copies of sensitive values in files + exec Run a command with the resolved environment + encrypt Encrypt a value with a key stored on this device + lock Require biometric authentication for the next decryption + keychain Manage the macOS Keychain items that keychain() reads (macOS only) Examples: vp dotenv init @@ -65,14 +66,15 @@ Options: -h, --help Show this help message Commands: - init Create .env.schema from the existing .env files - check Validate the .env files against .env.schema without printing values - print Print the resolved values, with sensitive values masked - explain Show how config items resolve, with sensitive values masked - scan Find plaintext copies of sensitive values in files - exec Run a command with the resolved environment - encrypt Encrypt a value with a key stored on this device - lock Require biometric authentication for the next decryption + init Create .env.schema from the existing .env files + check Validate the .env files against .env.schema without printing values + print Print the resolved values, with sensitive values masked + explain Show how config items resolve, with sensitive values masked + scan Find plaintext copies of sensitive values in files + exec Run a command with the resolved environment + encrypt Encrypt a value with a key stored on this device + lock Require biometric authentication for the next decryption + keychain Manage the macOS Keychain items that keychain() reads (macOS only) Examples: vp dotenv init diff --git a/docs/guide/dotenv.md b/docs/guide/dotenv.md index f862fb7c4e..400e5acd7e 100644 --- a/docs/guide/dotenv.md +++ b/docs/guide/dotenv.md @@ -202,6 +202,8 @@ To set a value, use [`vp dotenv encrypt`](#vp-dotenv-encrypt), or write `KEY=var See the [varlock local encryption guide](https://varlock.dev/guides/local-encryption/) for the setup on each platform. +On macOS, a secret can also stay in the macOS Keychain. The env file then holds a reference such as `keychain(service="varlock", account="app:local:STRIPE_SECRET_KEY")`, which every command that loads the schema reads through the same helper. Store and manage these items with [`vp dotenv keychain`](#vp-dotenv-keychain), or pick an existing item with `KEY=keychain(prompt)`. See the [varlock macOS Keychain page](https://varlock.dev/plugins/macos-keychain/). + ## Commands ### `vp dotenv init` @@ -218,7 +220,7 @@ vp dotenv check `--mode ` sets `viteMode()`, so that the command checks the values that `vp build --mode ` uses. `vp dotenv check --mode production` checks the values of `vp build`. `--env ` selects an environment when the schema does not use `@currentEnv`. With `@currentEnv`, set its variable instead, for example `APP_ENV=production vp dotenv check`. -Every `vp dotenv` command that loads the config fails when the directory has no `.env.schema` and no `varlock.loadPath`, so a check that runs in the wrong directory cannot pass without checking anything. `init`, `lock`, and `encrypt` without `--file` do not load it. +Every `vp dotenv` command that loads the config fails when the directory has no `.env.schema` and no `varlock.loadPath`, so a check that runs in the wrong directory cannot pass without checking anything. `init`, `lock`, `keychain`, and `encrypt` without `--file` do not load it. ### `vp dotenv print` @@ -280,6 +282,19 @@ With `--file`, varlock lists the sensitive plaintext values of the file and encr End the biometric session of local encryption, so that the next decryption asks for Touch ID, Windows Hello, or another biometric check again. Run it before you leave the computer. A key without biometric support has no session to end, and the command says so. +### `vp dotenv keychain` + +Manage the macOS Keychain items that `keychain()` reads (see [Local encryption](#local-encryption)). It passes every argument to `varlock keychain`, so the subcommands and options are varlock's own. It works on macOS only. + +```bash +vp dotenv keychain set STRIPE_SECRET_KEY --write-to .env.local # store a secret, write keychain(...) +vp dotenv keychain import .env.local # move sensitive plaintext values in place +vp dotenv keychain list # item metadata, never values +vp dotenv keychain fix-access --path .env.local # give varlock's helper access +``` + +Run `vp dotenv keychain --help` for every option. + ## Using env files in tasks A [`vp run`](/guide/run) task starts in a clean environment, so `.env` values do not reach it by default. To give a task the schema environment, run its command through `vp dotenv exec`: diff --git a/packages/cli/binding/index.d.cts b/packages/cli/binding/index.d.cts index e5e9b24ef9..df0c623c60 100644 --- a/packages/cli/binding/index.d.cts +++ b/packages/cli/binding/index.d.cts @@ -3906,7 +3906,16 @@ export interface DevCommand { export declare function documentationUrl(path: string): string; export interface DotenvArgs { - command: 'init' | 'check' | 'print' | 'explain' | 'scan' | 'exec' | 'encrypt' | 'lock'; + command: + | 'init' + | 'check' + | 'print' + | 'explain' + | 'scan' + | 'exec' + | 'encrypt' + | 'lock' + | 'keychain'; env?: string; mode?: string; format: 'env' | 'json' | 'shell'; @@ -3918,6 +3927,7 @@ export interface DotenvArgs { interactive: boolean; execCommand: Array; file?: string; + keychainArgs: Array; } /** diff --git a/packages/cli/binding/src/js_command_args/commands/dotenv.rs b/packages/cli/binding/src/js_command_args/commands/dotenv.rs index 2dfe0d87cb..7f7b6d69d8 100644 --- a/packages/cli/binding/src/js_command_args/commands/dotenv.rs +++ b/packages/cli/binding/src/js_command_args/commands/dotenv.rs @@ -39,6 +39,9 @@ enum DotenvSubcommand { /// Require biometric authentication for the next decryption #[command(disable_help_flag = true)] Lock(LockArgs), + /// Manage the macOS Keychain items that keychain() reads (macOS only) + #[command(disable_help_flag = true)] + Keychain(KeychainArgs), } #[derive(Debug, Args)] @@ -167,6 +170,20 @@ struct LockArgs { help: Option, } +/// Every argument, `--help` included, goes to `varlock keychain`, whose +/// subcommands and options Vite+ does not declare again. +#[derive(Debug, Args)] +struct KeychainArgs { + #[arg( + value_name = "ARGS", + num_args = 0.., + trailing_var_arg = true, + allow_hyphen_values = true, + help = "Arguments for varlock keychain: set, import, fix-access, or list (default), and their options" + )] + args: Vec, +} + fn dotenv_command() -> Command { DotenvCliArgs::augment_args( Command::new("vp dotenv") @@ -184,7 +201,7 @@ fn dotenv_command() -> Command { #[napi(object, object_from_js = false)] pub struct DotenvArgs { #[napi( - ts_type = "'init' | 'check' | 'print' | 'explain' | 'scan' | 'exec' | 'encrypt' | 'lock'" + ts_type = "'init' | 'check' | 'print' | 'explain' | 'scan' | 'exec' | 'encrypt' | 'lock' | 'keychain'" )] pub command: String, pub env: Option, @@ -199,6 +216,7 @@ pub struct DotenvArgs { pub interactive: bool, pub exec_command: Vec, pub file: Option, + pub keychain_args: Vec, } impl DotenvArgs { @@ -216,6 +234,7 @@ impl DotenvArgs { interactive: true, exec_command: Vec::new(), file: None, + keychain_args: Vec::new(), } } } @@ -253,6 +272,9 @@ impl From for DotenvArgs { Self { mode: args.mode, file: args.file, ..Self::new("encrypt") } } DotenvSubcommand::Lock(_) => Self::new("lock"), + DotenvSubcommand::Keychain(args) => { + Self { keychain_args: args.args, ..Self::new("keychain") } + } } } } @@ -403,6 +425,21 @@ mod tests { assert_eq!(parse_error(&["lock", "extra"]).kind, "unknown-argument"); } + #[test] + fn keychain_forwards_every_argument() { + assert!(parsed(&["keychain"]).keychain_args.is_empty()); + for argv in [ + &["keychain", "--help"][..], + &["keychain", "-h"][..], + &["keychain", "set", "API_KEY", "--write-to", ".env.local", "--force"][..], + &["keychain", "list", "--keychain", "System"][..], + ] { + let args = parsed(argv); + assert_eq!(args.command, "keychain"); + assert_eq!(args.keychain_args, argv[1..], "argv: {argv:?}"); + } + } + #[test] fn top_level_and_subcommand_help_return_help() { for argv in diff --git a/packages/cli/src/dotenv/__tests__/encrypt.spec.ts b/packages/cli/src/dotenv/__tests__/encrypt.spec.ts index 40007ec288..f1fe005a05 100644 --- a/packages/cli/src/dotenv/__tests__/encrypt.spec.ts +++ b/packages/cli/src/dotenv/__tests__/encrypt.spec.ts @@ -52,6 +52,21 @@ describe('vp dotenv encrypt and lock', () => { expect(revealed.stdout).toContain('sk_live_123'); }); + it('passes keychain arguments, --help included, to varlock keychain', () => { + fs.rmSync(path.join(dir, '.env.schema')); + + const help = vp(['keychain', '--help']); + expect(help.status).toBe(0); + expect(help.stdout).toContain('Manage macOS Keychain items used by keychain()'); + }); + + // On macOS the command would read the real Keychain. + it.skipIf(process.platform === 'darwin')('reports that keychain needs macOS', () => { + const result = vp(['keychain', 'list']); + expect(result.status).not.toBe(0); + expect(result.stdout + result.stderr).toContain('varlock keychain is only supported on macOS'); + }); + it('needs no schema to encrypt one value or to lock the session', () => { fs.rmSync(path.join(dir, '.env.schema')); diff --git a/packages/cli/src/dotenv/__tests__/varlock.spec.ts b/packages/cli/src/dotenv/__tests__/varlock.spec.ts index edbaf0b90b..921938d9e4 100644 --- a/packages/cli/src/dotenv/__tests__/varlock.spec.ts +++ b/packages/cli/src/dotenv/__tests__/varlock.spec.ts @@ -25,6 +25,7 @@ function dotenvArgs(overrides: Partial & Pick includeIgnored: false, interactive: true, execCommand: [], + keychainArgs: [], ...overrides, }; } @@ -100,6 +101,14 @@ describe('buildVarlockInvocation', () => { output: 'inherit', }); }); + + it('forwards keychain arguments to varlock keychain unchanged', () => { + expect( + buildVarlockInvocation( + dotenvArgs({ command: 'keychain', keychainArgs: ['set', 'API_KEY', '--force'] }), + ), + ).toEqual({ argv: ['keychain', 'set', 'API_KEY', '--force'], output: 'inherit' }); + }); }); describe('renderMaskedValues', () => { diff --git a/packages/cli/src/dotenv/bin.ts b/packages/cli/src/dotenv/bin.ts index 393530f315..37502078dd 100644 --- a/packages/cli/src/dotenv/bin.ts +++ b/packages/cli/src/dotenv/bin.ts @@ -100,10 +100,12 @@ async function main(): Promise { // Without a schema, varlock loads an empty config and every command // succeeds, so a misplaced `check` or `scan` would pass without checking. - // Encrypting one value and locking the session do not load the config. + // Encrypting one value and locking the session do not load the config, and + // `varlock keychain import` checks for its schema itself. const loadsConfig = args.command !== 'init' && args.command !== 'lock' && + args.command !== 'keychain' && !(args.command === 'encrypt' && !args.file); if (loadsConfig && !hasDotenvSchema(cwd)) { errorMsg( diff --git a/packages/cli/src/dotenv/varlock.ts b/packages/cli/src/dotenv/varlock.ts index 18039e2576..38e3e2dbce 100644 --- a/packages/cli/src/dotenv/varlock.ts +++ b/packages/cli/src/dotenv/varlock.ts @@ -103,6 +103,9 @@ export function buildVarlockInvocation(args: DotenvArgs): VarlockInvocation { }; case 'lock': return { argv: ['lock'], output: 'inherit' }; + case 'keychain': + // macOS only. varlock parses the subcommands and options itself. + return { argv: ['keychain', ...args.keychainArgs], output: 'inherit' }; default: { const command: never = args.command; throw new Error(`Unknown dotenv command: ${String(command)}`); diff --git a/rfcs/varlock-integration.md b/rfcs/varlock-integration.md index 602e89e5ad..288997bf16 100644 --- a/rfcs/varlock-integration.md +++ b/rfcs/varlock-integration.md @@ -95,17 +95,18 @@ Mechanics: A new command family named **`vp dotenv`**. Naming rationale: `vp env` is taken by runtime management, `vp secrets` undersells the feature (schema and validation apply to non-secret config too), and `dotenv` names exactly the file family the command manages. Subcommand names follow the Vite+ vocabulary rather than varlock's: `check` validates like `vp check`, `exec` runs a command in an environment like `vp exec`, and `print` is separate from `check` so plaintext secrets only ever leave one command, behind an explicit `--reveal` flag. -| Command | Runs | Behavior | -| -------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `vp dotenv init` | `varlock init`, or `varlock init --agent` with `--no-interactive` | Scaffold `.env.schema` from existing `.env` files and code, add the `.gitignore` exception when needed, pick a type-generation decorator. | -| `vp dotenv check` | `varlock load --format json --agent` | Validate schema plus local values. Discard stdout and print a `pass:` line. varlock reports errors on stderr. This is the CI entry point. Fails, like every subcommand that loads the config, when the directory has no schema. | -| `vp dotenv print` | `varlock load --format json --agent` | Vite+ renders the redacted JSON as `env`, `json`, or `shell`. varlock rejects `--agent` with `env` and `shell`, so Vite+ does the rendering. | -| `vp dotenv print --reveal` | `varlock load --format ` | Plaintext output in varlock's own format. | -| `vp dotenv explain [KEY]` | `varlock explain KEY`, or `varlock load` without a key | `varlock explain` requires a key. The pretty `load` output is the all-items view, and it masks sensitive values. | -| `vp dotenv scan` | `varlock scan` | Find plaintext secrets in files, staged changes, or build output. `--install-hook` is not exposed: Vite+ owns hooks. | -| `vp dotenv exec -- ` | `varlock run -- ` | Inject resolved env into a subprocess with stdout redaction. `varlock run` has no `--env` option, so the environment comes from `@currentEnv`. | -| `vp dotenv encrypt` | `varlock encrypt [--file ]` | Encrypt a value from stdin or a prompt into `varlock("local:...")`, or the sensitive plaintext values of a file, with a key stored on the device. It needs no schema without `--file`. The terminal stays attached for the prompts. | -| `vp dotenv lock` | `varlock lock` | End the biometric session of local encryption. It needs no schema, and reports when the key has no biometric support. | +| Command | Runs | Behavior | +| ------------------------------ | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `vp dotenv init` | `varlock init`, or `varlock init --agent` with `--no-interactive` | Scaffold `.env.schema` from existing `.env` files and code, add the `.gitignore` exception when needed, pick a type-generation decorator. | +| `vp dotenv check` | `varlock load --format json --agent` | Validate schema plus local values. Discard stdout and print a `pass:` line. varlock reports errors on stderr. This is the CI entry point. Fails, like every subcommand that loads the config, when the directory has no schema. | +| `vp dotenv print` | `varlock load --format json --agent` | Vite+ renders the redacted JSON as `env`, `json`, or `shell`. varlock rejects `--agent` with `env` and `shell`, so Vite+ does the rendering. | +| `vp dotenv print --reveal` | `varlock load --format ` | Plaintext output in varlock's own format. | +| `vp dotenv explain [KEY]` | `varlock explain KEY`, or `varlock load` without a key | `varlock explain` requires a key. The pretty `load` output is the all-items view, and it masks sensitive values. | +| `vp dotenv scan` | `varlock scan` | Find plaintext secrets in files, staged changes, or build output. `--install-hook` is not exposed: Vite+ owns hooks. | +| `vp dotenv exec -- ` | `varlock run -- ` | Inject resolved env into a subprocess with stdout redaction. `varlock run` has no `--env` option, so the environment comes from `@currentEnv`. | +| `vp dotenv encrypt` | `varlock encrypt [--file ]` | Encrypt a value from stdin or a prompt into `varlock("local:...")`, or the sensitive plaintext values of a file, with a key stored on the device. It needs no schema without `--file`. The terminal stays attached for the prompts. | +| `vp dotenv lock` | `varlock lock` | End the biometric session of local encryption. It needs no schema, and reports when the key has no biometric support. | +| `vp dotenv keychain [args...]` | `varlock keychain [args...]` | Manage the macOS Keychain items that `keychain()` reads (`set`, `import`, `fix-access`, `list`). macOS only. Every argument, `--help` included, goes to varlock unchanged, so Vite+ does not declare the subcommands and options again and does not follow their changes. | `vp dotenv check`, `print`, `explain`, `scan`, and `exec` take `--mode `, which sets `VP_VITE_MODE` for the varlock process, so `viteMode()` in the schema returns the same mode as in `vp build --mode ` (see "Environment selection" in section 3). @@ -235,11 +236,11 @@ All env-spec parsing and resolution stays in the JS layer: ## Rollout -| Phase | Scope | Risk | -| ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | -| 1 | Bundle varlock + plugin, `vite-plus/dotenv` re-export, `vp dotenv init/check/print/explain/scan/exec/encrypt/lock`, auto plugin injection for dev/build/preview/test, client build-output scan, `.gitignore` fix, docs | Low: additive, inert without `.env.schema` | -| 2 | `vp create` prompt + agent guidance, `vp migrate` module + wrapper recognition, git-hook scan step, `vp check` step | Low-medium: touches scaffolding flows | -| 3 | `vp run` task injection + sensitive-value fingerprinting, tsdown/`vp pack` integration decision | Medium: cache format and NAPI surface | +| Phase | Scope | Risk | +| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | +| 1 | Bundle varlock + plugin, `vite-plus/dotenv` re-export, `vp dotenv init/check/print/explain/scan/exec/encrypt/lock/keychain`, auto plugin injection for dev/build/preview/test, client build-output scan, `.gitignore` fix, docs | Low: additive, inert without `.env.schema` | +| 2 | `vp create` prompt + agent guidance, `vp migrate` module + wrapper recognition, git-hook scan step, `vp check` step | Low-medium: touches scaffolding flows | +| 3 | `vp run` task injection + sensitive-value fingerprinting, tsdown/`vp pack` integration decision | Medium: cache format and NAPI surface | Phase 1 ships as an experimental feature: the user docs (the Env Files guide, the `dotenv` config reference, the varlock migration rules, and the README command lists) say so, and commands, options, and the schema setup that `vp dotenv init` writes may change before it is stable. From 3a56a2cb1bd096a20f9e2aacdc28f654cc76e414 Mon Sep 17 00:00:00 2001 From: "MK (fengmk2)" Date: Fri, 4 Dec 2026 23:15:19 +0800 Subject: [PATCH 26/28] fix(dotenv): count every item in check, adapt init to servers On cnpmcore, a server with about 80 optional variables and none set, `vp dotenv check` printed `Found no errors in 0 config items`, because it counted only the values in `load --format json`. It now reads the full graph (`json-full --agent`, so sensitive values stay redacted) and prints both numbers: `Found no errors in 80 config items (0 have a value)`. `vp dotenv init` also assumed a Vite app. `inferFromPrefix('VITE_')` made every variable of a server sensitive, and the `viteMode()` item had no Vite command to follow. init now reads the package.json scripts and `index.html`: only a project that serves or builds a client app with Vite gets the prefix rule, and only one whose scripts run Vite or Vitest gets the `APP_ENV` item. A server keeps `@defaultSensitive=false`. The guide also notes that output redaction in `vp dotenv exec` masks every occurrence of a sensitive value, so a short value such as `postgres` masks the same word in unrelated output. Co-Authored-By: Claude Opus 5.5 --- .../snapshots/command_dotenv_schema.md | 4 +- docs/guide/dotenv.md | 8 ++-- .../dotenv/__tests__/schema-header.spec.ts | 47 +++++++++++++++++++ .../cli/src/dotenv/__tests__/varlock.spec.ts | 15 ++++-- packages/cli/src/dotenv/bin.ts | 29 ++++++++++-- packages/cli/src/dotenv/schema-header.ts | 41 +++++++++++++++- packages/cli/src/dotenv/varlock.ts | 19 ++++++-- rfcs/varlock-integration.md | 2 +- 8 files changed, 145 insertions(+), 20 deletions(-) diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_schema.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_schema.md index 6b20e74d68..3826e0e89f 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_schema.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_schema.md @@ -24,8 +24,6 @@ the required secret has no value ❓ STRIPE_SECRET_KEY* 🔐sensitive └ undefined - Value is required but is currently empty - -💥 [varlock] Invalid env vars: STRIPE_SECRET_KEY 💥 ``` ## `vpt write-file .env.local 'STRIPE_SECRET_KEY=sk_test_1234567890abcdef @@ -35,7 +33,7 @@ the required secret has no value ## `vp dotenv check` ``` -pass: Found no errors in 2 config items +pass: Found no errors in 2 config items (2 have a value) ``` ## `vp dotenv print` diff --git a/docs/guide/dotenv.md b/docs/guide/dotenv.md index 400e5acd7e..ff79b627c4 100644 --- a/docs/guide/dotenv.md +++ b/docs/guide/dotenv.md @@ -53,8 +53,10 @@ vp dotenv init `vp dotenv init` then adapts the schema that `varlock init` writes: - `@generateTsTypes(path=env.d.ts)` becomes `@plugin(vite-plus)` and `@generateVitePlusTypes(path=env.d.ts, importMetaEnv=none)`. The Vite+ generator writes the same types, and also makes them apply to `ENV` from `vite-plus/dotenv`. `importMetaEnv=none` leaves `import.meta.env` to Vite's own types, because Vite exposes only `VITE_*` variables there. -- `@defaultSensitive=false` becomes `@defaultSensitive=inferFromPrefix('VITE_')`, so that only `VITE_*` variables are public by default, as in Vite. -- A schema without `@currentEnv` gets `@currentEnv=$APP_ENV` and an `APP_ENV` item with `fallback(viteMode(), development)`, so that the environment follows the Vite mode. Its enum lists `development`, `production`, `test`, and the environments of your `.env.[env]` files. +- In a project that serves or builds a client app with Vite (a `vp dev`, `vp build`, `vp preview`, or `vite` script, or an `index.html`), `@defaultSensitive=false` becomes `@defaultSensitive=inferFromPrefix('VITE_')`, so that only `VITE_*` variables are public by default, as in Vite. +- In a project whose scripts run Vite or Vitest, a schema without `@currentEnv` gets `@currentEnv=$APP_ENV` and an `APP_ENV` item with `fallback(viteMode(), development)`, so that the environment follows the Vite mode. Its enum lists `development`, `production`, `test`, and the environments of your `.env.[env]` files. + +A server without a client bundle, such as an Express or egg app, keeps `@defaultSensitive=false`, so only the variables that you mark `@sensitive` are secrets. Run its commands through [`vp dotenv exec`](#vp-dotenv-exec). Your project needs no `varlock` dependency. Vite+ bundles the CLI and the runtime, and the generated types reach `ENV` through `vite-plus/dotenv`. `varlock init` adds `varlock` to `package.json` by default, but `vp dotenv init` prevents that and leaves `package.json` unchanged. Add `varlock` yourself only in these cases: @@ -263,7 +265,7 @@ vp dotenv exec -- node scripts/seed.ts vp dotenv exec --mode production -- prisma migrate deploy ``` -When output is piped or redirected, sensitive values are redacted from stdout and stderr. Output to a terminal is not redacted. +When output is piped or redirected, sensitive values are redacted from stdout and stderr. Output to a terminal is not redacted. Redaction replaces every occurrence of a sensitive value, so a short or common value, such as a database password `postgres`, also masks the same word elsewhere in the output, as in `"dialect":"po▒▒▒▒▒"`. Use values that do not occur in normal output. `vp dotenv exec` runs one command in the schema environment. [`vp run`](/guide/run) runs a task from `vite.config.ts`. diff --git a/packages/cli/src/dotenv/__tests__/schema-header.spec.ts b/packages/cli/src/dotenv/__tests__/schema-header.spec.ts index cf8b0f1958..f5e2df39c2 100644 --- a/packages/cli/src/dotenv/__tests__/schema-header.spec.ts +++ b/packages/cli/src/dotenv/__tests__/schema-header.spec.ts @@ -5,6 +5,7 @@ import { addModeEnvironment, adoptVitePlusSchemaHeader, currentEnvVariable, + detectViteUsage, environmentNames, followsViteMode, modeMismatchWarning, @@ -34,6 +35,15 @@ describe('adoptVitePlusSchemaHeader', () => { ); }); + it('keeps @defaultSensitive=false for a project without a client bundle', () => { + expect(adoptVitePlusSchemaHeader(INIT_SCHEMA, { inferVitePrefix: false })).toBe( + INIT_SCHEMA.replace( + '# @generateTsTypes(path=env.d.ts)', + '# @plugin(vite-plus) @generateVitePlusTypes(path=env.d.ts, importMetaEnv=none)', + ), + ); + }); + it('keeps an importMetaEnv option and an existing plugin decorator', () => { const schema = '# @plugin(vite-plus)\n# @generateTsTypes(path=env.d.ts, importMetaEnv=loose)\n# ---\n'; @@ -96,6 +106,43 @@ describe('addModeEnvironment', () => { }); }); +describe('detectViteUsage', () => { + it('finds a client app in Vite commands or an index.html', () => { + for (const command of [ + 'vp dev', + 'vp build && vp preview', + 'vite build', + 'vite', + 'vite --port 3000', + ]) { + expect(detectViteUsage({ script: command }, false), command).toEqual({ + clientApp: true, + runsVite: true, + }); + } + expect(detectViteUsage({}, true)).toEqual({ clientApp: true, runsVite: true }); + }); + + it('tells a server or a library from a client app', () => { + const server = { dev: 'egg-bin dev', test: 'egg-bin test', lint: 'vp lint', fmt: 'vp fmt' }; + expect(detectViteUsage(server, false)).toEqual({ clientApp: false, runsVite: false }); + expect(detectViteUsage({ test: 'vp test' }, false)).toEqual({ + clientApp: false, + runsVite: true, + }); + expect(detectViteUsage({ test: 'vitest run' }, false)).toEqual({ + clientApp: false, + runsVite: true, + }); + for (const command of ['vp run build', 'vitepress dev', 'vite-node a.ts']) { + expect(detectViteUsage({ script: command }, false), command).toEqual({ + clientApp: false, + runsVite: false, + }); + } + }); +}); + describe('environmentNames', () => { it('lists the default modes, then the environments of .env files', () => { expect( diff --git a/packages/cli/src/dotenv/__tests__/varlock.spec.ts b/packages/cli/src/dotenv/__tests__/varlock.spec.ts index 921938d9e4..9c8bfec60e 100644 --- a/packages/cli/src/dotenv/__tests__/varlock.spec.ts +++ b/packages/cli/src/dotenv/__tests__/varlock.spec.ts @@ -5,6 +5,7 @@ import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import type { DotenvArgs } from '../../../binding/index.js'; +import type { JsonObject } from '../../utils/json-value.ts'; import { hasVitePlusInstalled, preseedVarlockDependency } from '../dependency.ts'; import { buildVarlockInvocation, @@ -44,7 +45,7 @@ describe('buildVarlockInvocation', () => { it('validates with redacted JSON so check never prints values', () => { expect(buildVarlockInvocation(dotenvArgs({ command: 'check', env: 'production' }))).toEqual({ - argv: ['load', '--format', 'json', '--agent', '--env', 'production'], + argv: ['load', '--format', 'json-full', '--compact', '--agent', '--env', 'production'], output: 'check', }); }); @@ -173,10 +174,18 @@ describe('parseLoadOutput', () => { }); }); +function graph(config: JsonObject): JsonObject { + return { config }; +} + describe('formatCheckPassMessage', () => { it('counts config items', () => { - expect(formatCheckPassMessage({ A: 1, B: 2 })).toBe('Found no errors in 2 config items'); - expect(formatCheckPassMessage({ A: 1 })).toBe('Found no errors in 1 config item'); + expect(formatCheckPassMessage(graph({ A: { value: 1 }, B: { isSensitive: false } }))).toBe( + 'Found no errors in 2 config items (1 has a value)', + ); + expect(formatCheckPassMessage(graph({ A: { isSensitive: false } }))).toBe( + 'Found no errors in 1 config item (0 have a value)', + ); expect(formatCheckPassMessage(undefined)).toBe('Found no errors in the env config'); }); }); diff --git a/packages/cli/src/dotenv/bin.ts b/packages/cli/src/dotenv/bin.ts index 37502078dd..8fa92d0fbd 100644 --- a/packages/cli/src/dotenv/bin.ts +++ b/packages/cli/src/dotenv/bin.ts @@ -12,11 +12,13 @@ import { parseDotenvArgs } from '../../binding/index.js'; import { unwrapCliParseOutcome } from '../utils/cli-parse.ts'; import type { RunCommandOptions } from '../utils/command.ts'; import { runCommand, runCommandCapturingStdout } from '../utils/command.ts'; +import { isObjectValue, parseJsonObject } from '../utils/json-value.ts'; import { errorMsg, log, passMsg } from '../utils/terminal.ts'; import { hasVitePlusInstalled, preseedVarlockDependency } from './dependency.ts'; import { addModeEnvironment, adoptVitePlusSchemaHeader, + detectViteUsage, environmentNames, followsViteMode, VITE_MODE_ENV, @@ -33,6 +35,23 @@ import { withVarlockDefaults, } from './varlock.ts'; +/** The `scripts` of a `package.json`, or none when it cannot be read. */ +function readScripts(packageJsonPath: string): Record { + try { + const scripts = parseJsonObject(fs.readFileSync(packageJsonPath, 'utf8')).scripts; + if (!isObjectValue(scripts)) { + return {}; + } + return Object.fromEntries( + Object.entries(scripts).filter( + (entry): entry is [string, string] => typeof entry[1] === 'string', + ), + ); + } catch { + return {}; + } +} + /** * Run `varlock init` with the Vite+ setup. The bundled varlock provides the * CLI, the runtime, and the types, so the project needs no `varlock` @@ -66,10 +85,14 @@ async function runInit(options: RunCommandOptions, varlock: VarlockPackage): Pro return exitCode; } const schema = fs.readFileSync(schemaFile, 'utf8'); - const adopted = addModeEnvironment( - adoptVitePlusSchemaHeader(schema), - environmentNames(fs.readdirSync(cwd)), + const usage = detectViteUsage( + readScripts(path.join(cwd, 'package.json')), + fs.existsSync(path.join(cwd, 'index.html')), ); + const header = adoptVitePlusSchemaHeader(schema, { inferVitePrefix: usage.clientApp }); + const adopted = usage.runsVite + ? addModeEnvironment(header, environmentNames(fs.readdirSync(cwd))) + : header; if (adopted !== schema) { fs.writeFileSync(schemaFile, adopted); // Write the types now, so that the editor has them before the first `vp dev`. diff --git a/packages/cli/src/dotenv/schema-header.ts b/packages/cli/src/dotenv/schema-header.ts index a6bc828924..a5da965e57 100644 --- a/packages/cli/src/dotenv/schema-header.ts +++ b/packages/cli/src/dotenv/schema-header.ts @@ -57,13 +57,18 @@ export function adoptVitePlusTypeGenerator(schema: string, defaultImportMetaEnv? * `import.meta.env`. * - `@defaultSensitive=false` becomes `@defaultSensitive=inferFromPrefix('VITE_')`, * so that, like in Vite, only `VITE_*` variables are public by default. + * `inferVitePrefix: false` keeps it for a project without a client bundle, + * where every variable would become sensitive. * * A schema without a header stays unchanged. */ -export function adoptVitePlusSchemaHeader(schema: string): string { +export function adoptVitePlusSchemaHeader( + schema: string, + options: { inferVitePrefix?: boolean } = {}, +): string { const adopted = adoptVitePlusTypeGenerator(schema, 'none'); const header = schemaHeader(adopted); - if (header === undefined) { + if (header === undefined || options.inferVitePrefix === false) { return adopted; } return ( @@ -128,6 +133,38 @@ export function environmentNames(fileNames: ReadonlyArray): Array !defaults.includes(name)).toSorted()]; } +// A Vite command that serves or builds a client app, as in `vp build`, +// `vite build`, or `vite` with options or a root. Not `vp run build`, which +// names a task, or `vite-node` and `vitepress`. +const CLIENT_APP_COMMAND = + /(?:^|[\s;&|(])(?:vp|vite-plus)\s+(?:dev|build|preview)\b|(?:^|[\s;&|(])vite(?=\s*$|\s*[;&|)]|\s+(?:dev|serve|build|preview)\b|\s+[-./])/; +// A command that runs Vitest, which also uses the Vite mode. +const TEST_COMMAND = /(?:^|[\s;&|(])(?:(?:vp|vite-plus)\s+test|vitest)\b/; + +export interface ViteUsage { + /** The project serves or builds a client app with Vite, so `VITE_*` reaches the browser. */ + clientApp: boolean; + /** The project runs a command whose Vite mode `viteMode()` can follow. */ + runsVite: boolean; +} + +/** + * How a project uses Vite, from its `package.json` scripts and whether it has + * an `index.html`. `vp dotenv init` adapts the schema only to the parts that + * apply: a server such as an Express or egg app has no client bundle. + */ +export function detectViteUsage( + scripts: Readonly>, + hasIndexHtml: boolean, +): ViteUsage { + const commands = Object.values(scripts); + const clientApp = hasIndexHtml || commands.some((command) => CLIENT_APP_COMMAND.test(command)); + return { + clientApp, + runsVite: clientApp || commands.some((command) => TEST_COMMAND.test(command)), + }; +} + /** Whether the schema uses `viteMode()`, so that its environment can follow the Vite mode. */ export function followsViteMode(schema: string): boolean { return VITE_MODE_CALL.test(schema); diff --git a/packages/cli/src/dotenv/varlock.ts b/packages/cli/src/dotenv/varlock.ts index 38e3e2dbce..bb6094fc8d 100644 --- a/packages/cli/src/dotenv/varlock.ts +++ b/packages/cli/src/dotenv/varlock.ts @@ -59,8 +59,9 @@ export function buildVarlockInvocation(args: DotenvArgs): VarlockInvocation { // `--agent` is varlock's non-interactive mode: default answers, no prompts. return { argv: args.interactive ? ['init'] : ['init', '--agent'], output: 'inherit' }; case 'check': + // The full graph lists every item, also the ones without a value. return { - argv: ['load', '--format', 'json', '--agent', ...envArgs(args.env)], + argv: ['load', '--format', 'json-full', '--compact', '--agent', ...envArgs(args.env)], output: 'check', }; case 'print': @@ -197,12 +198,20 @@ export function parseLoadOutput(stdout: string): JsonObject | undefined { return undefined; } -export function formatCheckPassMessage(values: JsonObject | undefined): string { - if (!values) { +/** + * The pass line of `vp dotenv check`, from the `json-full` graph: the number + * of config items, and how many of them have a value. A schema can declare + * optional items that no file sets, so the two numbers can differ. + */ +export function formatCheckPassMessage(graph: JsonObject | undefined): string { + const config = graph?.config; + if (!isObjectValue(config)) { return 'Found no errors in the env config'; } - const count = Object.keys(values).length; - return `Found no errors in ${count} config ${count === 1 ? 'item' : 'items'}`; + const items = Object.values(config); + const withValue = items.filter((item) => isObjectValue(item) && item.value !== undefined).length; + const count = `${items.length} config ${items.length === 1 ? 'item' : 'items'}`; + return `Found no errors in ${count} (${withValue} ${withValue === 1 ? 'has' : 'have'} a value)`; } /** Walk up from `start` to the directory whose `package.json` has `name`. */ diff --git a/rfcs/varlock-integration.md b/rfcs/varlock-integration.md index 288997bf16..10820a13bd 100644 --- a/rfcs/varlock-integration.md +++ b/rfcs/varlock-integration.md @@ -280,7 +280,7 @@ Every phase is inert for projects without a `.env.schema` file. Existing dotenv - Vite+ ships a varlock plugin in `vite-plus` (the `./plugin` export, which varlock requires) that registers `@generateVitePlusTypes` through the plugin API (`plugin.registerCodeGenerator`). The generator runs varlock's own `generateTsTypes` generator from `ctx.graph.codeGeneratorsRegistry` and adds the same augmentation for `vite-plus/dotenv`, or imports `ENV` from `vite-plus/dotenv` with `exposeEnv=local`. varlock writes the final file itself on every load, and leaves it alone when the text is the same. - TypeScript merges an augmentation of a module that only does `export * from 'varlock/env'` into varlock's own interfaces (checked with TypeScript 7.0.2 in a pnpm-like layout), so `vite-plus/dotenv` needs no change. The `varlock/env` block stays for code that imports from there. - The plugin is one CommonJS file. varlock runs `.cjs` plugins with its own `varlock/plugin-lib`, so the plugin works with whichever varlock copy loads it (checked with 1.24.0 and 1.25.0). - - `vp dotenv init` writes `dependencies.varlock` before `varlock init` runs, so that `varlock init` skips its own ` add varlock`, then restores `package.json`. It then replaces the `@generateTsTypes(...)` that `varlock init` wrote with `@plugin(vite-plus) @generateVitePlusTypes(..., importMetaEnv=none)` and `@defaultSensitive=false` with `@defaultSensitive=inferFromPrefix('VITE_')`, adds `@currentEnv=$APP_ENV` with `APP_ENV=fallback(viteMode(), development)` when the schema has no `@currentEnv`, and runs one load to write the types. It keeps the setup of a project that already depends on `varlock`, and runs `varlock init` unchanged in a project without `vite-plus` in `node_modules`. + - `vp dotenv init` writes `dependencies.varlock` before `varlock init` runs, so that `varlock init` skips its own ` add varlock`, then restores `package.json`. It then replaces the `@generateTsTypes(...)` that `varlock init` wrote with `@plugin(vite-plus) @generateVitePlusTypes(..., importMetaEnv=none)` and, in a project that serves or builds a client app with Vite (a `vp dev`, `vp build`, `vp preview`, or `vite` script, or an `index.html`), `@defaultSensitive=false` with `@defaultSensitive=inferFromPrefix('VITE_')`. In a project whose scripts run Vite or Vitest, it adds `@currentEnv=$APP_ENV` with `APP_ENV=fallback(viteMode(), development)` when the schema has no `@currentEnv`. A server without a client bundle keeps `@defaultSensitive=false`, because the prefix rule would make every variable sensitive. It then runs one load to write the types. It keeps the setup of a project that already depends on `varlock`, and runs `varlock init` unchanged in a project without `vite-plus` in `node_modules`. - The generator depends on the text of the built-in output (the `declare module 'varlock/env'` block). Without that block, it returns the output unchanged. A test runs the bundled varlock with the built plugin. - Rejected for this: post-processing the generated file after each load (varlock rewrites it on the next load, so every load writes twice, and a direct `varlock` command removes the change), and an ambient `declare module 'varlock/env'` bridge file (TypeScript prefers the ambient module over `node_modules`, also inside `vite-plus`, so the re-export becomes a cycle). From cb8429485c92a3e81c6cbe98220976f80b4e1c68 Mon Sep 17 00:00:00 2001 From: "MK (fengmk2)" Date: Fri, 4 Dec 2026 23:23:09 +0800 Subject: [PATCH 27/28] docs(rfc): explain why the dotenv command is exec, not run Co-Authored-By: Claude Opus 5.5 --- rfcs/varlock-integration.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/rfcs/varlock-integration.md b/rfcs/varlock-integration.md index 10820a13bd..ef582b3dc9 100644 --- a/rfcs/varlock-integration.md +++ b/rfcs/varlock-integration.md @@ -95,6 +95,8 @@ Mechanics: A new command family named **`vp dotenv`**. Naming rationale: `vp env` is taken by runtime management, `vp secrets` undersells the feature (schema and validation apply to non-secret config too), and `dotenv` names exactly the file family the command manages. Subcommand names follow the Vite+ vocabulary rather than varlock's: `check` validates like `vp check`, `exec` runs a command in an environment like `vp exec`, and `print` is separate from `check` so plaintext secrets only ever leave one command, behind an explicit `--reveal` flag. +The command that runs another command is `vp dotenv exec`, not `vp dotenv run` after varlock's `varlock run`. `vp run` is the task runner, and a task command often contains this command (`command: 'vp dotenv exec -- node seed.ts'`), so a second `run` with another meaning would appear next to it. Vite+ already uses `exec` for one command in a prepared environment: `vp exec` runs a binary from `node_modules/.bin`, and `vp env exec` runs a command with a chosen Node.js or package manager. The cost is a name that differs from `varlock run`, which Vite+ accepts because it names commands by what they do, not by the upstream tool. + | Command | Runs | Behavior | | ------------------------------ | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `vp dotenv init` | `varlock init`, or `varlock init --agent` with `--no-interactive` | Scaffold `.env.schema` from existing `.env` files and code, add the `.gitignore` exception when needed, pick a type-generation decorator. | From 74cb68680819bf3842356f0b927dc5bb3e8929ba Mon Sep 17 00:00:00 2001 From: "MK (fengmk2)" Date: Sat, 5 Dec 2026 00:07:11 +0800 Subject: [PATCH 28/28] fix(dotenv): find a schema header without a divider varlock reads the header as the comment blocks before the first item. A blank line, a divider, or the end of the file ends a block. `varlock init` writes no divider when `.env.example` starts with a comment block, so `vp dotenv init` and `vp migrate` left such a schema unchanged. A section divider below the items also counted as the end of the header. Co-Authored-By: Claude Opus 5.5 --- docs/guide/dotenv.md | 2 +- .../dotenv/__tests__/schema-header.spec.ts | 63 +++++++++++++++ packages/cli/src/dotenv/schema-header.ts | 79 +++++++++++++++---- 3 files changed, 129 insertions(+), 15 deletions(-) diff --git a/docs/guide/dotenv.md b/docs/guide/dotenv.md index ff79b627c4..7c82f804f8 100644 --- a/docs/guide/dotenv.md +++ b/docs/guide/dotenv.md @@ -83,7 +83,7 @@ ENV.STRIPE_SECRET_KEY; // sensitive: never inlined into client code ## The `.env.schema` file -A schema is a `.env` file with JSDoc-style comments. Lines above `# ---` hold root decorators, which apply to the whole file. A comment directly above a variable attaches decorators to that variable. +A schema is a `.env` file with JSDoc-style comments. The comment blocks at the top of the file hold root decorators, which apply to the whole file. A blank line or a `# ---` divider ends such a block. A comment directly above a variable attaches decorators to that variable. Common root decorators: diff --git a/packages/cli/src/dotenv/__tests__/schema-header.spec.ts b/packages/cli/src/dotenv/__tests__/schema-header.spec.ts index f5e2df39c2..5a73e1c6b6 100644 --- a/packages/cli/src/dotenv/__tests__/schema-header.spec.ts +++ b/packages/cli/src/dotenv/__tests__/schema-header.spec.ts @@ -22,6 +22,26 @@ const INIT_SCHEMA = `# This env file uses @env-spec - see https://varlock.dev/en API_URL= `; +// The schema that `varlock init` writes from a `.env.example` that starts with +// a comment block: the header ends with a blank line and has no divider. +const INIT_SCHEMA_FROM_EXAMPLE = `# Put local values in .env.local. +# @defaultRequired=infer @defaultSensitive=false +# @generateTsTypes(path=env.d.ts) + +# example env variable injected by \`varlock init\` ⚠️ DELETE THIS ITEM! ⚠️ +# @required @sensitive @example="example value" +EXAMPLE_ITEM="delete me!" +# @sensitive +DB_PASSWORD= +`; +// The section that `varlock init` adds for items that only other env files set. +const INIT_ADDED_SECTION = ` +# items added to schema by \`varlock init\` +# PLEASE REVIEW THESE! +# --- +REDIS_URL= +`; + describe('adoptVitePlusSchemaHeader', () => { it('switches the init schema to the Vite+ generator and the VITE_ prefix default', () => { expect(adoptVitePlusSchemaHeader(INIT_SCHEMA)).toBe( @@ -44,6 +64,18 @@ describe('adoptVitePlusSchemaHeader', () => { ); }); + it('finds a header that ends with a blank line instead of a divider', () => { + expect(adoptVitePlusSchemaHeader(INIT_SCHEMA_FROM_EXAMPLE)).toBe( + INIT_SCHEMA_FROM_EXAMPLE.replace( + '@defaultSensitive=false', + "@defaultSensitive=inferFromPrefix('VITE_')", + ).replace( + '# @generateTsTypes(path=env.d.ts)', + '# @plugin(vite-plus) @generateVitePlusTypes(path=env.d.ts, importMetaEnv=none)', + ), + ); + }); + it('keeps an importMetaEnv option and an existing plugin decorator', () => { const schema = '# @plugin(vite-plus)\n# @generateTsTypes(path=env.d.ts, importMetaEnv=loose)\n# ---\n'; @@ -61,6 +93,14 @@ describe('adoptVitePlusSchemaHeader', () => { expect(adoptVitePlusSchemaHeader('# @generateTsTypes(path=env.d.ts)\nAPI_URL=\n')).toBe( '# @generateTsTypes(path=env.d.ts)\nAPI_URL=\n', ); + // A divider after the first item starts a section, not the end of the header. + expect( + adoptVitePlusSchemaHeader( + '# @defaultSensitive=false\n\n# @generateTsTypes(path=env.d.ts)\nA=\n# ---\nB=\n', + ), + ).toBe( + "# @defaultSensitive=inferFromPrefix('VITE_')\n\n# @generateTsTypes(path=env.d.ts)\nA=\n# ---\nB=\n", + ); }); }); @@ -74,6 +114,13 @@ describe('currentEnvVariable', () => { ); }); + it('reads every comment block before the first item', () => { + expect(currentEnvVariable('# intro\n\n# @currentEnv=$APP_ENV\n\nAPP_ENV=dev\n')).toBe( + 'APP_ENV', + ); + expect(currentEnvVariable('# @currentEnv=$APP_ENV\n# ======\nAPP_ENV=dev\n')).toBe('APP_ENV'); + }); + it('finds nothing without a header, a decorator, or a plain variable', () => { expect(currentEnvVariable('# @currentEnv=$APP_ENV\nAPP_ENV=development\n')).toBeUndefined(); expect(currentEnvVariable('# @defaultSensitive=false\n# ---\n')).toBeUndefined(); @@ -97,6 +144,22 @@ describe('addModeEnvironment', () => { ); }); + it('adds them to a header without a divider and leaves later sections alone', () => { + const schema = addModeEnvironment( + adoptVitePlusSchemaHeader(INIT_SCHEMA_FROM_EXAMPLE + INIT_ADDED_SECTION), + ['development', 'production', 'test'], + ); + + expect(currentEnvVariable(schema)).toBe('APP_ENV'); + expect(schema).toContain( + '# @plugin(vite-plus) @generateVitePlusTypes(path=env.d.ts, importMetaEnv=none)\n# @currentEnv=$APP_ENV\n\n# The environment, which selects the .env.[env] files to load.', + ); + expect(schema).toContain( + 'APP_ENV=fallback(viteMode(), development)\n\n# example env variable injected by', + ); + expect(schema.endsWith(INIT_ADDED_SECTION)).toBe(true); + }); + it('keeps a schema that selects its environment or cannot call viteMode()', () => { const withCurrentEnv = adopted.replace('# ----------', '# @currentEnv=$NODE_ENV\n# ----------'); expect(addModeEnvironment(withCurrentEnv, ['development'])).toBe(withCurrentEnv); diff --git a/packages/cli/src/dotenv/schema-header.ts b/packages/cli/src/dotenv/schema-header.ts index a5da965e57..6b64912701 100644 --- a/packages/cli/src/dotenv/schema-header.ts +++ b/packages/cli/src/dotenv/schema-header.ts @@ -1,7 +1,9 @@ -// Text helpers for the `.env.schema` header: the root decorators on the lines -// before the first `# ---` divider. +// Text helpers for the `.env.schema` header: the comment blocks with the root +// decorators before the first item. -const HEADER_END = /^#\s*-{3,}\s*$/m; +// An env-spec divider, such as `# ---` or `# ======`. +const DIVIDER_LINE = /^#[ \t]*[-=*#]{3,}/; +const BLANK_LINE = /^[ \t]*\r?$/; const TS_TYPES_DECORATOR = /@generateTsTypes\(([^()]*)\)/; const VITE_PLUS_PLUGIN_DECORATOR = /@plugin\(\s*vite-plus\s*\)/; const PUBLIC_BY_DEFAULT = /@defaultSensitive=false\b/; @@ -19,9 +21,61 @@ const MODE_ENVIRONMENT_VARIABLE = 'APP_ENV'; /** `.env.` files that do not hold the values of an environment. */ const NOT_ENVIRONMENTS = new Set(['schema', 'local', 'example', 'sample', 'template', 'defaults']); +interface HeaderRange { + /** The end of the last comment line in the last header block. */ + commentsEnd: number; + /** The end of the last header block, after its divider line if it has one. */ + end: number; +} + +/** + * Find the header as env-spec does: the comment blocks before the first item. + * A blank line, a divider, or the end of the file closes a comment block. The + * comment lines directly above an item document that item, so they are not + * part of the header. Offsets point before the line break. + */ +function findHeader(schema: string): HeaderRange | undefined { + const lines = schema.split('\n'); + let header: HeaderRange | undefined; + let offset = 0; + let index = 0; + const skipLine = () => { + offset += lines[index].length + 1; + index++; + }; + while (index < lines.length) { + const line = lines[index]; + if (BLANK_LINE.test(line) || DIVIDER_LINE.test(line)) { + skipLine(); + continue; + } + if (!line.startsWith('#')) { + break; + } + let commentsEnd = offset; + while ( + index < lines.length && + lines[index].startsWith('#') && + !DIVIDER_LINE.test(lines[index]) + ) { + commentsEnd = offset + lines[index].length; + skipLine(); + } + if (index === lines.length || BLANK_LINE.test(lines[index])) { + header = { commentsEnd, end: commentsEnd }; + } else if (DIVIDER_LINE.test(lines[index])) { + header = { commentsEnd, end: offset + lines[index].length }; + skipLine(); + } else { + break; + } + } + return header; +} + function schemaHeader(schema: string): string | undefined { - const end = HEADER_END.exec(schema); - return end ? schema.slice(0, end.index) : undefined; + const header = findHeader(schema); + return header === undefined ? undefined : schema.slice(0, header.end); } /** @@ -87,19 +141,16 @@ export function adoptVitePlusSchemaHeader( * header, or with `@currentEnv` or an `APP_ENV` item already. */ export function addModeEnvironment(schema: string, environments: ReadonlyArray): string { - const end = HEADER_END.exec(schema); - const header = end === null ? '' : schema.slice(0, end.index); + const range = findHeader(schema); + const header = range === undefined ? '' : schema.slice(0, range.end); if ( - end === null || + range === undefined || !VITE_PLUS_PLUGIN_DECORATOR.test(header) || ANY_CURRENT_ENV_DECORATOR.test(header) || new RegExp(`^${MODE_ENVIRONMENT_VARIABLE}=`, 'm').test(schema) ) { return schema; } - // The end of the divider line; `HEADER_END` also matches the blank lines after it. - const lineEnd = schema.indexOf('\n', end.index); - const dividerEnd = lineEnd === -1 ? schema.length : lineEnd; const item = [ '', '', @@ -109,10 +160,10 @@ export function addModeEnvironment(schema: string, environments: ReadonlyArray