Skip to content

Commit 8293bde

Browse files
fengmk2claude
andcommitted
feat(dotenv): type ENV through a vite-plus varlock plugin, add no varlock dependency
The generated types augment `varlock/env`, which TypeScript resolves from the project, so `ENV` needed a direct `varlock` dependency. Ship a varlock plugin in `vite-plus` (the `./plugin` export that varlock requires) that registers `@generateVitePlusTypes`. It runs varlock's own TypeScript generator and adds the same augmentation for `vite-plus/dotenv`, so varlock writes the final file itself on every load. The plugin is one CommonJS file: varlock runs `.cjs` plugins with its own `varlock/plugin-lib`, so it works with the varlock copy that loads it. `vp dotenv init` now leaves `package.json` unchanged. It writes the dependency only so that `varlock init` skips its own install, restores the file, switches the new schema to `@plugin(vite-plus) @generateVitePlusTypes(..., importMetaEnv=none)`, and runs one load to write the types. A project that already depends on `varlock`, or has no `vite-plus` in node_modules, keeps the plain `varlock init` behavior. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 51e65f0 commit 8293bde

11 files changed

Lines changed: 368 additions & 50 deletions

File tree

‎docs/guide/dotenv.md‎

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ A plain `.env.example` goes stale the moment someone adds a variable. Vite+ repl
99
```env-spec [.env.schema]
1010
# @defaultSensitive=false
1111
# @currentEnv=$APP_ENV
12-
# @generateTsTypes(path='env.d.ts', importMetaEnv=none)
12+
# @plugin(vite-plus)
13+
# @generateVitePlusTypes(path='env.d.ts', importMetaEnv=none)
1314
# ---
1415
1516
# @type=enum(development, preview, production, test)
@@ -41,14 +42,16 @@ Run `vp dotenv init` in a project that already has `.env` files:
4142
vp dotenv init
4243
```
4344

44-
`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`. In a project with a `package.json`, `init` also adds `@generateTsTypes(path=env.d.ts)`. Add `importMetaEnv=none` to it. Otherwise the generated types add every variable to `import.meta.env`, sensitive ones included, but Vite exposes only `VITE_*` variables there.
45+
`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`.
4546

46-
`vp dotenv init` also adds `varlock` to the `dependencies` in `package.json`, at the version that Vite+ bundles, and runs `vp install`. Keep it if TypeScript code reads `ENV`. `ENV` gets its keys only from the types that `@generateTsTypes` writes. Those types extend the `varlock/env` module, and TypeScript must resolve that module from your project. With pnpm, the copy that Vite+ bundles is not visible from your project, so every `ENV` property is a type error. Keep the dependency at the version that Vite+ bundles (`vp --version` lists it), for two reasons:
47+
`vp dotenv init` also sets up the types for `ENV`. `varlock init` writes `@generateTsTypes(path=env.d.ts)`, and `vp dotenv init` replaces it with `@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.
4748

48-
- With the same version, the package manager installs one copy, so `ENV` from `vite-plus/dotenv` gets the generated types.
49-
- The Vite integration runs the varlock CLI that it finds in your project's `node_modules/.bin`, and it reads the output of that CLI. Another version can change that output.
49+
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:
5050

51-
If the init fails or you cancel it, `vp dotenv init` restores `package.json`. If no TypeScript code reads `ENV`, for example in a JavaScript project, you can remove the dependency. Vite+ then uses its bundled varlock everywhere.
51+
- Code imports `ENV` from `varlock/env` and you use TypeScript, which must resolve that module from your project.
52+
- A production server starts with `varlock run` (see [Server-side rendering](#server-side-rendering)).
53+
54+
If you add it, use the version that Vite+ bundles (`vp --version` lists it). The Vite integration runs the varlock CLI that it finds in your project's `node_modules/.bin`, and another version can change the output that the integration reads. In a project without `vite-plus` in `node_modules`, `vp dotenv init` runs `varlock init` unchanged.
5255

5356
In CI or for a coding agent, run `vp dotenv init --no-interactive` to use the default answers instead of prompts.
5457

@@ -62,20 +65,20 @@ ENV.API_PORT; // number, not string
6265
ENV.STRIPE_SECRET_KEY; // sensitive: never inlined into client code
6366
```
6467

65-
`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.
68+
`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. With TypeScript, that import needs a direct `varlock` dependency.
6669

6770
## The `.env.schema` file
6871

6972
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.
7073

7174
Common root decorators:
7275

73-
| Decorator | Meaning |
74-
| ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
75-
| `@defaultSensitive=false` | Variables are public unless marked `@sensitive`. Use `true` to flip the default. |
76-
| `@defaultSensitive=inferFromPrefix('VITE_')` | Vite compatibility: `VITE_*` is public, everything else is sensitive. |
77-
| `@currentEnv=$APP_ENV` | The variable that selects the environment, and so which `.env.[env]` files load. |
78-
| `@generateTsTypes(path='env.d.ts', importMetaEnv=none)` | Write a type declaration for `ENV` on every load. Add the file to `tsconfig.json`. `importMetaEnv=none` leaves `import.meta.env` to Vite's own types. |
76+
| Decorator | Meaning |
77+
| ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
78+
| `@defaultSensitive=false` | Variables are public unless marked `@sensitive`. Use `true` to flip the default. |
79+
| `@defaultSensitive=inferFromPrefix('VITE_')` | Vite compatibility: `VITE_*` is public, everything else is sensitive. |
80+
| `@currentEnv=$APP_ENV` | The variable that selects the environment, and so which `.env.[env]` files load. |
81+
| `@plugin(vite-plus)` `@generateVitePlusTypes(path='env.d.ts', importMetaEnv=none)` | Write a type declaration for `ENV` from `vite-plus/dotenv` and `varlock/env` on every load. It takes the options of `@generateTsTypes`. Add the file to `tsconfig.json`. `importMetaEnv=none` leaves `import.meta.env` to Vite's own types. |
7982

8083
Common item decorators:
8184

‎packages/cli/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@
6666
"types": "./dist/dotenv.d.ts",
6767
"default": "./dist/dotenv.js"
6868
},
69+
"./plugin": "./dist/dotenv/varlock-plugin.cjs",
6970
"./fmt": {
7071
"types": "./dist/fmt.d.ts",
7172
"import": "./dist/fmt.js"
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import { describe, expect, it } from 'vitest';
2+
3+
import { addVitePlusDotenvTypes, adoptVitePlusTypegen } from '../typegen.ts';
4+
5+
// The shape of varlock 1.25's `@generateTsTypes` output with `exposeEnv=global`.
6+
const GLOBAL_TYPES = `/* eslint-disable */
7+
// @ts-nocheck
8+
export type CoercedEnvSchema = {
9+
API_PORT: number;
10+
};
11+
12+
type _CoercedEnvSchema_3a158ead = CoercedEnvSchema;
13+
14+
declare module 'varlock/env' {
15+
export interface TypedEnvSchema extends Readonly<_CoercedEnvSchema_3a158ead> {}
16+
export interface PublicTypedEnvSchema extends Readonly<Pick<_CoercedEnvSchema_3a158ead, 'API_PORT'>> {}
17+
}
18+
19+
export type EnvSchemaAsStrings = { API_PORT: string };
20+
`;
21+
22+
describe('addVitePlusDotenvTypes', () => {
23+
it('adds the same augmentation for vite-plus/dotenv and keeps the varlock/env one', () => {
24+
const types = addVitePlusDotenvTypes(GLOBAL_TYPES);
25+
26+
expect(types).toContain(`declare module 'varlock/env' {
27+
export interface TypedEnvSchema extends Readonly<_CoercedEnvSchema_3a158ead> {}`);
28+
expect(types).toContain(`}
29+
30+
declare module 'vite-plus/dotenv' {
31+
export interface TypedEnvSchema extends Readonly<_CoercedEnvSchema_3a158ead> {}
32+
export interface PublicTypedEnvSchema extends Readonly<Pick<_CoercedEnvSchema_3a158ead, 'API_PORT'>> {}
33+
}
34+
`);
35+
expect(addVitePlusDotenvTypes(types)).toBe(types);
36+
});
37+
38+
it('imports ENV from vite-plus/dotenv with exposeEnv=local', () => {
39+
const local = "import { ENV as _ENV } from 'varlock/env';\n\nexport const ENV = _ENV;\n";
40+
41+
expect(addVitePlusDotenvTypes(local)).toBe(
42+
"import { ENV as _ENV } from 'vite-plus/dotenv';\n\nexport const ENV = _ENV;\n",
43+
);
44+
});
45+
46+
it('leaves output without varlock/env unchanged', () => {
47+
const none = 'export type CoercedEnvSchema = { API_PORT: number };\n';
48+
49+
expect(addVitePlusDotenvTypes(none)).toBe(none);
50+
});
51+
});
52+
53+
describe('adoptVitePlusTypegen', () => {
54+
// The header that `varlock init` writes in a project with a package.json.
55+
const INIT_SCHEMA = `# This env file uses @env-spec - see https://varlock.dev/env-spec for more info
56+
#
57+
# @defaultRequired=infer @defaultSensitive=false
58+
# @generateTsTypes(path=env.d.ts)
59+
# ----------
60+
61+
# @type=url
62+
API_URL=
63+
`;
64+
65+
it('switches the init schema to the Vite+ generator', () => {
66+
expect(adoptVitePlusTypegen(INIT_SCHEMA)).toBe(
67+
INIT_SCHEMA.replace(
68+
'# @generateTsTypes(path=env.d.ts)',
69+
'# @plugin(vite-plus) @generateVitePlusTypes(path=env.d.ts, importMetaEnv=none)',
70+
),
71+
);
72+
});
73+
74+
it('keeps an importMetaEnv option and an existing plugin decorator', () => {
75+
const schema =
76+
'# @plugin(vite-plus)\n# @generateTsTypes(path=env.d.ts, importMetaEnv=loose)\n# ---\n';
77+
78+
expect(adoptVitePlusTypegen(schema)).toBe(
79+
'# @plugin(vite-plus)\n# @generateVitePlusTypes(path=env.d.ts, importMetaEnv=loose)\n# ---\n',
80+
);
81+
});
82+
83+
it('changes only the header', () => {
84+
const schema =
85+
'# @defaultSensitive=false\n# ---\n# @generateTsTypes(path=env.d.ts)\nAPI_URL=\n';
86+
87+
expect(adoptVitePlusTypegen(schema)).toBe(schema);
88+
expect(adoptVitePlusTypegen('# @generateTsTypes(path=env.d.ts)\nAPI_URL=\n')).toBe(
89+
'# @generateTsTypes(path=env.d.ts)\nAPI_URL=\n',
90+
);
91+
});
92+
});
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import { spawnSync } from 'node:child_process';
2+
import fs from 'node:fs';
3+
import os from 'node:os';
4+
import path from 'node:path';
5+
6+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
7+
8+
import { pkgRoot } from '../../utils/path.ts';
9+
import { resolveVarlockPackage } from '../varlock.ts';
10+
11+
// Runs the bundled varlock CLI with the built `./plugin` export, like a
12+
// project that has `vite-plus` in node_modules and no `varlock` dependency.
13+
describe('the vite-plus varlock plugin', () => {
14+
let dir: string;
15+
16+
beforeEach(() => {
17+
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-varlock-plugin-'));
18+
fs.mkdirSync(path.join(dir, 'node_modules'));
19+
fs.symlinkSync(pkgRoot, path.join(dir, 'node_modules', 'vite-plus'), 'junction');
20+
fs.writeFileSync(path.join(dir, 'package.json'), '{ "name": "app", "private": true }\n');
21+
fs.writeFileSync(
22+
path.join(dir, '.env.schema'),
23+
[
24+
'# @defaultSensitive=false',
25+
'# @plugin(vite-plus) @generateVitePlusTypes(path=env.d.ts, importMetaEnv=none)',
26+
'# ---',
27+
'# @type=port',
28+
'API_PORT=3000',
29+
'',
30+
].join('\n'),
31+
);
32+
});
33+
34+
afterEach(() => {
35+
fs.rmSync(dir, { recursive: true, force: true });
36+
});
37+
38+
function load() {
39+
return spawnSync(
40+
process.execPath,
41+
[resolveVarlockPackage().cli, 'load', '--format', 'json', '--agent'],
42+
{
43+
cwd: dir,
44+
env: { ...process.env, VARLOCK_TELEMETRY_DISABLED: '1' },
45+
encoding: 'utf8',
46+
},
47+
);
48+
}
49+
50+
it('makes varlock write types for vite-plus/dotenv itself', () => {
51+
const first = load();
52+
expect(first.stderr).toBe('');
53+
expect(first.status).toBe(0);
54+
const file = path.join(dir, 'env.d.ts');
55+
const types = fs.readFileSync(file, 'utf8');
56+
expect(types).toContain("declare module 'varlock/env' {");
57+
expect(types).toContain("declare module 'vite-plus/dotenv' {");
58+
expect(types).toContain('API_PORT: number;');
59+
expect(types).not.toContain('interface ImportMetaEnv');
60+
61+
// The next load generates the same text, so varlock leaves the file alone.
62+
const writtenAt = fs.statSync(file).mtimeMs;
63+
expect(load().status).toBe(0);
64+
expect(fs.readFileSync(file, 'utf8')).toBe(types);
65+
expect(fs.statSync(file).mtimeMs).toBe(writtenAt);
66+
});
67+
});

‎packages/cli/src/dotenv/__tests__/varlock.spec.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import path from 'node:path';
55
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
66

77
import type { DotenvArgs } from '../../../binding/index.js';
8-
import { preseedVarlockDependency } from '../dependency.ts';
8+
import { hasVitePlusInstalled, preseedVarlockDependency } from '../dependency.ts';
99
import {
1010
buildVarlockInvocation,
1111
findPackageRoot,
@@ -223,6 +223,15 @@ describe('package lookups', () => {
223223
);
224224
});
225225

226+
it('finds vite-plus in node_modules of the directory or a parent', () => {
227+
const app = path.join(dir, 'packages', 'app');
228+
fs.mkdirSync(app, { recursive: true });
229+
expect(hasVitePlusInstalled(app)).toBe(false);
230+
fs.mkdirSync(path.join(dir, 'node_modules', 'vite-plus'), { recursive: true });
231+
fs.writeFileSync(path.join(dir, 'node_modules', 'vite-plus', 'package.json'), '{}');
232+
expect(hasVitePlusInstalled(app)).toBe(true);
233+
});
234+
226235
it('leaves an existing varlock dependency and a missing package.json alone', () => {
227236
expect(preseedVarlockDependency(dir, '1.25.0')).toBeUndefined();
228237
const content = JSON.stringify({ dependencies: { varlock: '^1.20.0' } });

‎packages/cli/src/dotenv/bin.ts‎

Lines changed: 52 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,18 @@
44
// a varlock invocation and runs varlock's own CLI script with the current Node
55
// runtime, so no `varlock` bin has to be on PATH.
66

7+
import { spawnSync } from 'node:child_process';
78
import fs from 'node:fs';
89
import path from 'node:path';
910

1011
import { parseDotenvArgs } from '../../binding/index.js';
1112
import { unwrapCliParseOutcome } from '../utils/cli-parse.ts';
12-
import { getVpCommand, runCommand, runCommandCapturingStdout } from '../utils/command.ts';
13-
import { errorMsg, log, passMsg, warnMsg } from '../utils/terminal.ts';
14-
import { preseedVarlockDependency } from './dependency.ts';
13+
import type { RunCommandOptions } from '../utils/command.ts';
14+
import { runCommand, runCommandCapturingStdout } from '../utils/command.ts';
15+
import { errorMsg, log, passMsg } from '../utils/terminal.ts';
16+
import { hasVitePlusInstalled, preseedVarlockDependency } from './dependency.ts';
17+
import { adoptVitePlusTypegen } from './typegen.ts';
18+
import type { VarlockPackage } from './varlock.ts';
1519
import {
1620
buildVarlockInvocation,
1721
DOTENV_SCHEMA_FILE,
@@ -24,30 +28,51 @@ import {
2428
} from './varlock.ts';
2529

2630
/**
27-
* Finish the dependency that `preseedVarlockDependency` added. When `varlock
28-
* init` wrote a schema, install it. When the init failed or was cancelled
29-
* (varlock exits with code 0 on a cancelled prompt), restore `package.json`.
31+
* Run `varlock init` with the Vite+ setup. The bundled varlock provides the
32+
* CLI, the runtime, and the types, so the project needs no `varlock`
33+
* dependency. The dependency written first only makes `varlock init` skip its
34+
* own `<package manager> add varlock`, and `package.json` goes back to how it
35+
* was. A new schema then uses `@generateVitePlusTypes` from
36+
* `@plugin(vite-plus)`, and one load writes its types.
37+
*
38+
* A project without `vite-plus` in `node_modules` cannot load that plugin, and
39+
* a project with its own `varlock` keeps its setup, so `varlock init` runs as
40+
* it is for them.
3041
*/
31-
async function finishVarlockDependency(
32-
cwd: string,
33-
version: string,
34-
initExitCode: number,
35-
originalManifest: string,
36-
): Promise<number> {
37-
if (initExitCode !== 0 || !hasDotenvSchema(cwd)) {
42+
async function runInit(options: RunCommandOptions, varlock: VarlockPackage): Promise<number> {
43+
const { cwd } = options;
44+
const originalManifest = hasVitePlusInstalled(cwd)
45+
? preseedVarlockDependency(cwd, varlock.version)
46+
: undefined;
47+
if (originalManifest === undefined) {
48+
return (await runCommand(options)).exitCode;
49+
}
50+
const schemaFile = path.join(cwd, DOTENV_SCHEMA_FILE);
51+
const hadSchema = fs.existsSync(schemaFile);
52+
let exitCode: number;
53+
try {
54+
({ exitCode } = await runCommand(options));
55+
} finally {
3856
fs.writeFileSync(path.join(cwd, 'package.json'), originalManifest);
39-
return initExitCode;
4057
}
41-
const { exitCode } = await runCommand({ ...getVpCommand(['install']), cwd, envs: process.env });
42-
if (exitCode !== 0) {
43-
warnMsg(
44-
`Added \`varlock\` ${version} to dependencies, but \`vp install\` failed. Run \`vp install\` again.`,
45-
);
58+
// varlock exits with code 0 on a cancelled prompt, so check for the schema too.
59+
if (exitCode !== 0 || hadSchema || !fs.existsSync(schemaFile)) {
4660
return exitCode;
4761
}
48-
passMsg(
49-
`Added \`varlock\` ${version}, the version Vite+ bundles, to dependencies. TypeScript uses it to apply the generated ENV types.`,
50-
);
62+
const schema = fs.readFileSync(schemaFile, 'utf8');
63+
const adopted = adoptVitePlusTypegen(schema);
64+
if (adopted !== schema) {
65+
fs.writeFileSync(schemaFile, adopted);
66+
// Write the types now, so that the editor has them before the first `vp dev`.
67+
spawnSync(options.command, [varlock.cli, 'load', '--format', 'json', '--agent'], {
68+
cwd,
69+
env: options.envs,
70+
stdio: 'ignore',
71+
});
72+
passMsg(
73+
'Set up `.env.schema` to type `ENV` from `vite-plus/dotenv` with `@plugin(vite-plus)` and `@generateVitePlusTypes`. The project needs no `varlock` dependency.',
74+
);
75+
}
5176
return 0;
5277
}
5378

@@ -65,7 +90,7 @@ async function main(): Promise<number> {
6590
return 1;
6691
}
6792

68-
let varlock: { cli: string; version: string };
93+
let varlock: VarlockPackage;
6994
try {
7095
varlock = resolveVarlockPackage();
7196
} catch (error) {
@@ -84,12 +109,10 @@ async function main(): Promise<number> {
84109
};
85110

86111
if (invocation.output === 'inherit') {
87-
const originalManifest =
88-
args.command === 'init' ? preseedVarlockDependency(cwd, varlock.version) : undefined;
89-
const { exitCode } = await runCommand(options);
90-
return originalManifest === undefined
91-
? exitCode
92-
: finishVarlockDependency(cwd, varlock.version, exitCode, originalManifest);
112+
if (args.command === 'init') {
113+
return runInit(options, varlock);
114+
}
115+
return (await runCommand(options)).exitCode;
93116
}
94117

95118
const { exitCode, stdout } = await runCommandCapturingStdout(options);

0 commit comments

Comments
 (0)