diff --git a/README.md b/README.md index 2d1fabcb08..5fd6e661bf 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** - Validate and inspect project environment variables using `.env.schema` (experimental) #### Execute diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/cli_helper_message/snapshots/cli_helper_message.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/cli_helper_message/snapshots/cli_helper_message.md index db73ff1f06..3c3851b8bc 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/cli_helper_message/snapshots/cli_helper_message.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/cli_helper_message/snapshots/cli_helper_message.md @@ -24,6 +24,7 @@ Develop: lint Lint code fmt, format Format code test Run tests + dotenv Validate and inspect project environment variables using .env.schema Execute: run Run tasks (also available as standalone `vpr`) @@ -84,6 +85,7 @@ Tools: oxlint tsrs tsdown + varlock Environment: Package manager Not found @@ -475,6 +477,7 @@ VITE+ - The Unified Toolchain for the Web Usage: vp env [COMMAND] Manage Node.js and package-manager environments +For project environment variables, see vp dotenv. Setup: setup Create or update shims in VP_HOME/bin diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/cli_helper_message/snapshots/cli_helper_message_local.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/cli_helper_message/snapshots/cli_helper_message_local.md index aa3ea41603..af3f17f12f 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/cli_helper_message/snapshots/cli_helper_message_local.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/cli_helper_message/snapshots/cli_helper_message_local.md @@ -26,6 +26,7 @@ Core Commands: config Configure hooks and agent integration hooks Manage the Git hook dispatcher staged Run linters on staged files + dotenv Validate and inspect project environment variables using .env.schema toolchain Show Vite+ tool versions and relationships Package Manager Commands: diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots.toml new file mode 100644 index 0000000000..df68e40951 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots.toml @@ -0,0 +1,29 @@ +[[case]] +name = "command_dotenv_help" +vp = ["local", "global"] +steps = [ + { argv = ["vp", "dotenv", "-h"], continue-on-failure = true }, + { argv = ["vp", "dotenv", "print", "--help"], continue-on-failure = true }, + { argv = ["vp", "help", "dotenv"], continue-on-failure = true }, +] + +[[case]] +name = "command_dotenv_errors" +vp = "global" +steps = [ + { argv = ["vp", "dotenv", "check"], comment = "fails without a schema instead of passing an empty config", continue-on-failure = true }, + { argv = ["vp", "dotenv", "exec", "--env", "production", "--", "node"], comment = "an option before the command is rejected, not run as the command", continue-on-failure = true }, + { argv = ["vp", "dotenv", "print", "--format", "yaml"], continue-on-failure = true }, +] + +[[case]] +name = "command_dotenv_schema" +vp = "global" +steps = [ + { argv = ["vpt", "write-file", ".env.schema", "# @defaultSensitive=false\n# ---\n\n# @type=url\nAPI_URL=http://localhost:3000\n\n# @required @sensitive\nSTRIPE_SECRET_KEY=\n"], snapshot = false }, + { argv = ["vp", "dotenv", "check"], comment = "the required secret has no value", continue-on-failure = true }, + { argv = ["vpt", "write-file", ".env.local", "STRIPE_SECRET_KEY=sk_test_1234567890abcdef\n"], snapshot = false }, + { argv = ["vp", "dotenv", "check"], continue-on-failure = true }, + { argv = ["vp", "dotenv", "print"], comment = "the secret is masked", continue-on-failure = true }, + { argv = ["vp", "dotenv", "print", "--format", "json"], continue-on-failure = true }, +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_errors.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_errors.md new file mode 100644 index 0000000000..9faf431c1a --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_errors.md @@ -0,0 +1,42 @@ +# command_dotenv_errors + +## `vp dotenv check` + +fails without a schema instead of passing an empty config + +**Exit code:** 1 + +``` +error: No .env.schema in , and its package.json sets no `varlock.loadPath`. Run this command from the project root, or run `vp dotenv init` to create a schema. +``` + +## `vp dotenv exec --env production -- node` + +an option before the command is rejected, not run as the command + +**Exit code:** 1 + +``` +VITE+ - The Unified Toolchain for the Web + +error: unexpected argument '--env' found + + tip: to pass '--env' as a value, use '-- --env' + +Usage: vp dotenv exec [OPTIONS] ... + +For more information, try '--help'. +``` + +## `vp dotenv print --format yaml` + +**Exit code:** 1 + +``` +VITE+ - The Unified Toolchain for the Web + +error: invalid value 'yaml' for '--format ' + [possible values: env, json, shell] + +For more information, try '--help'. +``` 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 new file mode 100644 index 0000000000..1aa030c79f --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.global.md @@ -0,0 +1,88 @@ +# command_dotenv_help + +## `vp dotenv -h` + +``` +VITE+ - The Unified Toolchain for the Web + +Usage: vp dotenv [OPTIONS] + +Validate project environment variables against .env.schema, including values supplied by CI. + +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 + keychain Manage the macOS Keychain items that keychain() reads (macOS only) + +Examples: + vp dotenv init + vp dotenv check + 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 +``` + +## `vp dotenv print --help` + +``` +VITE+ - The Unified Toolchain for the Web + +Usage: vp dotenv print [OPTIONS] + +Print the resolved values, with sensitive values masked + +Options: + --env Environment to load, such as production (@currentEnv takes priority) + --mode Vite mode for viteMode() in .env.schema, as in vp build --mode + --format Output format + --reveal Print sensitive values in plaintext + -h, --help Show this help message + +Documentation: https://viteplus.dev/guide/dotenv +``` + +## `vp help dotenv` + +``` +VITE+ - The Unified Toolchain for the Web + +Usage: vp dotenv [OPTIONS] + +Validate project environment variables against .env.schema, including values supplied by CI. + +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 + keychain Manage the macOS Keychain items that keychain() reads (macOS only) + +Examples: + vp dotenv init + vp dotenv check + 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 new file mode 100644 index 0000000000..1aa030c79f --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_help.local.md @@ -0,0 +1,88 @@ +# command_dotenv_help + +## `vp dotenv -h` + +``` +VITE+ - The Unified Toolchain for the Web + +Usage: vp dotenv [OPTIONS] + +Validate project environment variables against .env.schema, including values supplied by CI. + +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 + keychain Manage the macOS Keychain items that keychain() reads (macOS only) + +Examples: + vp dotenv init + vp dotenv check + 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 +``` + +## `vp dotenv print --help` + +``` +VITE+ - The Unified Toolchain for the Web + +Usage: vp dotenv print [OPTIONS] + +Print the resolved values, with sensitive values masked + +Options: + --env Environment to load, such as production (@currentEnv takes priority) + --mode Vite mode for viteMode() in .env.schema, as in vp build --mode + --format Output format + --reveal Print sensitive values in plaintext + -h, --help Show this help message + +Documentation: https://viteplus.dev/guide/dotenv +``` + +## `vp help dotenv` + +``` +VITE+ - The Unified Toolchain for the Web + +Usage: vp dotenv [OPTIONS] + +Validate project environment variables against .env.schema, including values supplied by CI. + +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 + keychain Manage the macOS Keychain items that keychain() reads (macOS only) + +Examples: + vp dotenv init + vp dotenv check + 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_schema.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_schema.md new file mode 100644 index 0000000000..3826e0e89f --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_dotenv/snapshots/command_dotenv_schema.md @@ -0,0 +1,55 @@ +# command_dotenv_schema + +## `vpt write-file .env.schema '# @defaultSensitive=false +# --- + +# @type=url +API_URL=http://localhost:3000 + +# @required @sensitive +STRIPE_SECRET_KEY= +'` + + +## `vp dotenv check` + +the required secret has no value + +**Exit code:** 1 + +``` + +🚨🚨🚨 Configuration is currently invalid 🚨🚨🚨 + +❓ STRIPE_SECRET_KEY* πŸ”sensitive + β”” undefined + - Value is required but is currently empty +``` + +## `vpt write-file .env.local 'STRIPE_SECRET_KEY=sk_test_1234567890abcdef +'` + + +## `vp dotenv check` + +``` +pass: Found no errors in 2 config items (2 have a value) +``` + +## `vp dotenv print` + +the secret is masked + +``` +API_URL=http://localhost:3000 +STRIPE_SECRET_KEY='skβ–’β–’β–’β–’β–’' +``` + +## `vp dotenv print --format json` + +``` +{ + "API_URL": "http://localhost:3000", + "STRIPE_SECRET_KEY": "skβ–’β–’β–’β–’β–’" +} +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_helper/snapshots/command_helper.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_helper/snapshots/command_helper.md index 2da460f19b..fd032f0a56 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_helper/snapshots/command_helper.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_helper/snapshots/command_helper.md @@ -26,6 +26,7 @@ Core Commands: config Configure hooks and agent integration hooks Manage the Git hook dispatcher staged Run linters on staged files + dotenv Validate and inspect project environment variables using .env.schema toolchain Show Vite+ tool versions and relationships Package Manager Commands: diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_toolchain/snapshots/toolchain_full_global.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_toolchain/snapshots/toolchain_full_global.md index 860c74f1da..0f0409d095 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_toolchain/snapshots/toolchain_full_global.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_toolchain/snapshots/toolchain_full_global.md @@ -21,6 +21,7 @@ vite-plus@ β”œβ”€β”€ depends on oxlint@ β”œβ”€β”€ depends on tsrs@ β”œβ”€β”€ depends on oxfmt@ +β”œβ”€β”€ depends on varlock@ β”œβ”€β”€ compiles vite-task (built , revision ) └── compiles oxc-node@ () β”œβ”€β”€ compiles oxc@ diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_toolchain/snapshots/toolchain_full_local.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_toolchain/snapshots/toolchain_full_local.md index e125bb8365..07adccae23 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_toolchain/snapshots/toolchain_full_local.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_toolchain/snapshots/toolchain_full_local.md @@ -21,6 +21,7 @@ vite-plus@ β”œβ”€β”€ depends on oxlint@ β”œβ”€β”€ depends on tsrs@ β”œβ”€β”€ depends on oxfmt@ +β”œβ”€β”€ depends on varlock@ β”œβ”€β”€ compiles vite-task (built , revision ) └── compiles oxc-node@ () β”œβ”€β”€ compiles oxc@ diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_toolchain/snapshots/toolchain_old_local_routing.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_toolchain/snapshots/toolchain_old_local_routing.md index 727e750ae0..cdaed87cca 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_toolchain/snapshots/toolchain_old_local_routing.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_toolchain/snapshots/toolchain_old_local_routing.md @@ -50,6 +50,7 @@ vite-plus@ β”œβ”€β”€ depends on oxlint@ β”œβ”€β”€ depends on tsrs@ β”œβ”€β”€ depends on oxfmt@ +β”œβ”€β”€ depends on varlock@ β”œβ”€β”€ compiles vite-task (built , revision ) └── compiles oxc-node@ () β”œβ”€β”€ compiles oxc@ @@ -87,6 +88,7 @@ vite-plus@ β”œβ”€β”€ depends on oxlint@ β”œβ”€β”€ depends on tsrs@ β”œβ”€β”€ depends on oxfmt@ +β”œβ”€β”€ depends on varlock@ β”œβ”€β”€ compiles vite-task (built , revision ) └── compiles oxc-node@ () β”œβ”€β”€ compiles oxc@ diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_version_local_tools/snapshots/command_version_local_tools.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_version_local_tools/snapshots/command_version_local_tools.md index bbb0a67908..e120a10cd4 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_version_local_tools/snapshots/command_version_local_tools.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_version_local_tools/snapshots/command_version_local_tools.md @@ -20,4 +20,5 @@ Tools: oxlint tsrs tsdown + varlock ``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_version_no_side_effects/snapshots/command_version_no_side_effects.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_version_no_side_effects/snapshots/command_version_no_side_effects.md index 74521cd9d4..15f8f7df7c 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_version_no_side_effects/snapshots/command_version_no_side_effects.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_version_no_side_effects/snapshots/command_version_no_side_effects.md @@ -20,6 +20,7 @@ Tools: oxlint tsrs tsdown + varlock Environment: Package manager Not found diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_version_with_env/snapshots/command_version_with_env.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_version_with_env/snapshots/command_version_with_env.md index 6794e89a27..b996cd3af4 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_version_with_env/snapshots/command_version_with_env.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_version_with_env/snapshots/command_version_with_env.md @@ -18,6 +18,7 @@ Tools: oxlint tsrs tsdown + varlock Environment: Package manager pnpm diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vp_alias/snapshots/command_vp_alias.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vp_alias/snapshots/command_vp_alias.md index cedec611c8..b1607281be 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vp_alias/snapshots/command_vp_alias.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/command_vp_alias/snapshots/command_vp_alias.md @@ -26,6 +26,7 @@ Core Commands: config Configure hooks and agent integration hooks Manage the Git hook dispatcher staged Run linters on staged files + dotenv Validate and inspect project environment variables using .env.schema toolchain Show Vite+ tool versions and relationships Package Manager Commands: diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_org_bundled_monorepo/snapshots/create_org_bundled_monorepo.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_org_bundled_monorepo/snapshots/create_org_bundled_monorepo.md index ff75554728..829acd38fb 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_org_bundled_monorepo/snapshots/create_org_bundled_monorepo.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/create_org_bundled_monorepo/snapshots/create_org_bundled_monorepo.md @@ -67,4 +67,5 @@ node_modules .env .env.* !.env.example +!.env.schema ``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/cwd_flag/snapshots/cwd_flag.global.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/cwd_flag/snapshots/cwd_flag.global.md index c26a35e919..9e2eb15546 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/cwd_flag/snapshots/cwd_flag.global.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/cwd_flag/snapshots/cwd_flag.global.md @@ -167,6 +167,7 @@ Tools: oxlint tsrs tsdown + varlock Environment: Package manager Not found diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/.env.schema b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/.env.schema new file mode 100644 index 0000000000..84a5c24365 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/.env.schema @@ -0,0 +1,9 @@ +# @defaultSensitive=false @currentEnv=$APP_ENV +# @generateTsTypes(path=env.d.ts) +# --- + +# @type=enum(development, production) +APP_ENV=development + +# @type=url +VITE_API_URL=http://localhost:3000 diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/.fixture/varlock/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/.fixture/varlock/package.json new file mode 100644 index 0000000000..c2e9357698 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/.fixture/varlock/package.json @@ -0,0 +1,4 @@ +{ + "name": "varlock", + "version": "1.25.0" +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/.fixture/vite-integration/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/.fixture/vite-integration/package.json new file mode 100644 index 0000000000..5cada35abe --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/.fixture/vite-integration/package.json @@ -0,0 +1,4 @@ +{ + "name": "@varlock/vite-integration", + "version": "1.5.6" +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/package.json new file mode 100644 index 0000000000..71186511b3 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/package.json @@ -0,0 +1,11 @@ +{ + "name": "migration-varlock", + "type": "module", + "dependencies": { + "varlock": "file:.fixture/varlock" + }, + "devDependencies": { + "@varlock/vite-integration": "file:.fixture/vite-integration", + "vite": "^7.0.0" + } +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/snapshots.toml new file mode 100644 index 0000000000..196e16e7d2 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/snapshots.toml @@ -0,0 +1,31 @@ +[[case]] +name = "migration_varlock" +vp = "local" +comment = "varlock and its Vite integration come from local stub packages so the install stays offline" +steps = [ + { argv = ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], comment = "the varlock Vite setup should migrate automatically", continue-on-failure = true }, + { argv = ["vpt", "print-file", "vite.config.ts"], comment = "Vite+ adds the varlock integration, so varlockVitePlugin() is gone", continue-on-failure = true }, + { argv = ["vpt", "print-file", ".env.schema"], comment = "the types also cover vite-plus/dotenv, and the other settings stay", continue-on-failure = true }, + { argv = ["vpt", "print-file", "package.json"], comment = "nothing else uses varlock, so both dependencies are gone", continue-on-failure = true }, +] + +[[case]] +name = "migration_varlock_kept" +vp = "local" +steps = [ + { argv = ["vpt", "write-file", "src/env.ts", "export { ENV } from 'varlock/env';\n"], snapshot = false }, + { argv = ["vpt", "write-file", "vite.config.ts", "import { varlockVitePlugin } from '@varlock/vite-integration';\nimport { defineConfig } from 'vite';\n\nexport default defineConfig({\n plugins: [varlockVitePlugin({ ssrInjectMode: 'resolved-env' })],\n});\n"], snapshot = false }, + { argv = ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], comment = "a plugin call with options and code that imports varlock keep their dependencies, with a warning for each", continue-on-failure = true }, + { argv = ["vpt", "print-file", "package.json"], comment = "both varlock dependencies stay", continue-on-failure = true }, +] + +[[case]] +name = "migration_varlock_already_vite_plus" +vp = "local" +comment = "On a project already using Vite+, the varlock migration belongs to `vp migrate --full`." +steps = [ + { argv = ["vpt", "json-edit", "package.json", "devDependencies.vite-plus", "latest"], snapshot = false }, + { argv = ["vp", "migrate", "--no-interactive"], comment = "a plain upgrade leaves the varlock setup to --full", continue-on-failure = true }, + { argv = ["vp", "migrate", "--no-interactive", "--full", "--no-hooks", "--no-agent", "--no-editor"], comment = "--full migrates the varlock setup", continue-on-failure = true }, + { argv = ["vpt", "print-file", "vite.config.ts"], comment = "varlockVitePlugin() is gone", continue-on-failure = true }, +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/snapshots/migration_varlock.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/snapshots/migration_varlock.md new file mode 100644 index 0000000000..e30c09e090 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/snapshots/migration_varlock.md @@ -0,0 +1,61 @@ +# migration_varlock + +varlock and its Vite integration come from local stub packages so the install stays offline + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +the varlock Vite setup should migrate automatically + +``` +VITE+ - The Unified Toolchain for the Web + +● varlock Vite integration detected. Auto-migrating to Vite+... +β—‡ Migrated . to Vite+ +β€’ Node pnpm +β€’ 1 file had imports rewritten +β€’ varlock setup migrated to Vite+ (`vp dotenv`) +``` + +## `vpt print-file vite.config.ts` + +Vite+ adds the varlock integration, so varlockVitePlugin() is gone + +``` +import { defineConfig } from 'vite-plus'; + +export default defineConfig({ + fmt: {}, + lint: {"jsPlugins":[{"name":"vite-plus","specifier":"vite-plus/oxlint-plugin"}],"rules":{"vite-plus/prefer-vite-plus-imports":"error"},"options":{"typeAware":true,"typeCheck":true}}, +}); +``` + +## `vpt print-file .env.schema` + +the types also cover vite-plus/dotenv, and the other settings stay + +``` +# @defaultSensitive=false @currentEnv=$APP_ENV +# @plugin(vite-plus) @generateVitePlusTypes(path=env.d.ts) +# --- + +# @type=enum(development, production) +APP_ENV=development + +# @type=url +VITE_API_URL=http://localhost:3000 +``` + +## `vpt print-file package.json` + +nothing else uses varlock, so both dependencies are gone + +``` +{ + "name": "migration-varlock", + "type": "module", + "devDependencies": { + "vite": "catalog:", + "vite-plus": "catalog:" + } +} +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/snapshots/migration_varlock_already_vite_plus.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/snapshots/migration_varlock_already_vite_plus.md new file mode 100644 index 0000000000..10142736a1 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/snapshots/migration_varlock_already_vite_plus.md @@ -0,0 +1,49 @@ +# migration_varlock_already_vite_plus + +On a project already using Vite+, the varlock migration belongs to `vp migrate --full`. + +## `vpt json-edit package.json devDependencies.vite-plus latest` + + +## `vp migrate --no-interactive` + +a plain upgrade leaves the varlock setup to --full + +``` +VITE+ - The Unified Toolchain for the Web + +β—‡ Updated . to Vite+ +β€’ Node pnpm +β€’ Dependencies: + vite-plus latest β†’ + vite β†’ +β€’ 1 file had imports rewritten +β€’ Package manager settings configured +β€’ Skipped editor, hooks, and lint setup. Run `vp migrate --full` to apply them. +``` + +## `vp migrate --no-interactive --full --no-hooks --no-agent --no-editor` + +--full migrates the varlock setup + +``` +VITE+ - The Unified Toolchain for the Web + +β–² No package manager is declared in package.json; using pnpm for this migration without adding a pin. Run `vp env pin` to declare it explicitly. +● varlock Vite integration detected. Auto-migrating to Vite+... +β—‡ Updated . to Vite+ +β€’ Node pnpm +β€’ Dependencies: + vite β†’ +β€’ varlock setup migrated to Vite+ (`vp dotenv`) +``` + +## `vpt print-file vite.config.ts` + +varlockVitePlugin() is gone + +``` +import { defineConfig } from 'vite-plus'; + +export default defineConfig({}); +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/snapshots/migration_varlock_kept.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/snapshots/migration_varlock_kept.md new file mode 100644 index 0000000000..d8cbe9a77f --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/snapshots/migration_varlock_kept.md @@ -0,0 +1,52 @@ +# migration_varlock_kept + +## `vpt write-file src/env.ts 'export { ENV } from '\''varlock/env'\''; +'` + + +## `vpt write-file vite.config.ts 'import { varlockVitePlugin } from '\''@varlock/vite-integration'\''; +import { defineConfig } from '\''vite'\''; + +export default defineConfig({ + plugins: [varlockVitePlugin({ ssrInjectMode: '\''resolved-env'\'' })], +}); +'` + + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +a plugin call with options and code that imports varlock keep their dependencies, with a warning for each + +``` +VITE+ - The Unified Toolchain for the Web + +● varlock Vite integration detected. Auto-migrating to Vite+... +β—‡ Migrated . to Vite+ +β€’ Node pnpm +β€’ 1 config update applied, 1 file had imports rewritten +β€’ varlock setup migrated to Vite+ (`vp dotenv`) +β€’ Inline Vite plugins wrapped with lazyPlugins for check/lint/fmt +! Warnings: + - 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. + - Kept the varlock dependency in package.json: src/env.ts still uses it. Keep it at 1.25.0, the version that Vite+ bundles. +``` + +## `vpt print-file package.json` + +both varlock dependencies stay + +``` +{ + "name": "migration-varlock", + "type": "module", + "dependencies": { + "varlock": "file:.fixture/varlock" + }, + "devDependencies": { + "@varlock/vite-integration": "file:.fixture/vite-integration", + "vite": "catalog:", + "vite-plus": "catalog:" + } +} +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/src/main.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/src/main.ts new file mode 100644 index 0000000000..580e8e38af --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/src/main.ts @@ -0,0 +1 @@ +console.log(import.meta.env.VITE_API_URL); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/vite.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/vite.config.ts new file mode 100644 index 0000000000..840bdc74fe --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_varlock/vite.config.ts @@ -0,0 +1,6 @@ +import { varlockVitePlugin } from '@varlock/vite-integration'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [varlockVitePlugin()], +}); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/vp_help/snapshots/help.global.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/vp_help/snapshots/help.global.md index f10214320d..12128947b0 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/vp_help/snapshots/help.global.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/vp_help/snapshots/help.global.md @@ -24,6 +24,7 @@ Develop: lint Lint code fmt, format Format code test Run tests + dotenv Validate and inspect project environment variables using .env.schema Execute: run Run tasks (also available as standalone `vpr`) diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/vp_help/snapshots/help.local.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/vp_help/snapshots/help.local.md index aef30c124e..c343d5274f 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/vp_help/snapshots/help.local.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/vp_help/snapshots/help.local.md @@ -26,6 +26,7 @@ Core Commands: config Configure hooks and agent integration hooks Manage the Git hook dispatcher staged Run linters on staged files + dotenv Validate and inspect project environment variables using .env.schema toolchain Show Vite+ tool versions and relationships Package Manager Commands: diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/vp_help/snapshots/help_background_job.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/vp_help/snapshots/help_background_job.md index 705db4481c..649d05eedc 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/vp_help/snapshots/help_background_job.md +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/vp_help/snapshots/help_background_job.md @@ -24,6 +24,7 @@ Develop: lint Lint code fmt, format Format code test Run tests + dotenv Validate and inspect project environment variables using .env.schema Execute: run Run tasks (also available as standalone `vpr`) diff --git a/crates/vp_global_cli/src/cli.rs b/crates/vp_global_cli/src/cli.rs index 610c50dddd..7a668b09ed 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, }, + /// Validate and inspect project environment variables using .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/commands/version.rs b/crates/vp_global_cli/src/commands/version.rs index b92a26cc13..8073252c1b 100644 --- a/crates/vp_global_cli/src/commands/version.rs +++ b/crates/vp_global_cli/src/commands/version.rs @@ -37,7 +37,7 @@ struct ToolSpec { bundled_version_key: Option<&'static str>, } -const TOOL_SPECS: [ToolSpec; 7] = [ +const TOOL_SPECS: [ToolSpec; 8] = [ ToolSpec { id: "vite", package_name: "@voidzero-dev/vite-plus-core", @@ -57,6 +57,7 @@ const TOOL_SPECS: [ToolSpec; 7] = [ package_name: "@voidzero-dev/vite-plus-core", bundled_version_key: Some("tsdown"), }, + ToolSpec { id: "varlock", package_name: "varlock", bundled_version_key: None }, ]; const NOT_FOUND: &str = "Not found"; diff --git a/crates/vp_global_cli/src/help.rs b/crates/vp_global_cli/src/help.rs index 915fe4af75..2ce646cc9a 100644 --- a/crates/vp_global_cli/src/help.rs +++ b/crates/vp_global_cli/src/help.rs @@ -277,6 +277,10 @@ pub fn top_level_help_doc() -> HelpDoc { row("lint", "Lint code"), row("fmt, format", "Format code"), row("test", "Run tests"), + row( + "dotenv", + "Validate and inspect project environment variables using .env.schema", + ), ], ), section_rows( @@ -333,7 +337,10 @@ pub fn top_level_help_doc() -> HelpDoc { fn env_help_doc() -> HelpDoc { HelpDoc { usage: "vp env [COMMAND]".into(), - summary: vec!["Manage Node.js and package-manager environments".into()], + summary: vec![ + "Manage Node.js and package-manager environments".into(), + "For project environment variables, see vp dotenv.".into(), + ], sections: vec![ section_rows( "Setup", @@ -432,6 +439,7 @@ fn skip_clap_unified_help(command: &str) -> bool { | "config" | "hooks" | "staged" + | "dotenv" | "dev" | "build" | "preview" diff --git a/crates/vp_shared/src/env_vars.rs b/crates/vp_shared/src/env_vars.rs index 6d35d9e4fe..2253db85c1 100644 --- a/crates/vp_shared/src/env_vars.rs +++ b/crates/vp_shared/src/env_vars.rs @@ -241,6 +241,15 @@ pub const VP_GLOBAL_VERSION: &str = "VP_GLOBAL_VERSION"; /// `npm_config_user_agent`, which the underlying package manager overwrites. pub const VP_USER_AGENT: &str = "VP_USER_AGENT"; +/// The Vite mode of the `vp dev`, `vp build`, `vp preview`, or `vp test` +/// command that starts the process: the `--mode` value, or else the default +/// mode of the command (`development`, `production`, or `test`). +/// +/// The local CLI sets it for each of these commands, and replaces an inherited +/// value. The `viteMode()` function of the vite-plus varlock plugin reads it, +/// so `.env.schema` can select its environment from the Vite mode. +pub const VP_VITE_MODE: &str = "VP_VITE_MODE"; + // ── HTTP client configuration ─────────────────────────────────────────── /// Override the per-request timeout (in seconds) for large file downloads 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..7721cd640a --- /dev/null +++ b/docs/config/dotenv.md @@ -0,0 +1,50 @@ +# 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. + +## 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 + // project root has `.env.schema`, off otherwise. + schema: 'auto', + // Fail `vp build` when a sensitive value appears in the client output. + // Defaults to true. + scanBuildOutput: true, + }, +}); +``` + +## `schema` + +- **Type:** `'auto' | boolean` +- **Default:** `'auto'` + +Controls whether the schema loads: + +- `'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. + +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 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. + +## Redaction + +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/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/guide/cache.md b/docs/guide/cache.md index 0e0d241077..dd3fc3f1bb 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, 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. ## Cache Sharing diff --git a/docs/guide/dotenv.md b/docs/guide/dotenv.md new file mode 100644 index 0000000000..7c82f804f8 --- /dev/null +++ b/docs/guide/dotenv.md @@ -0,0 +1,352 @@ +# 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 + +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=inferFromPrefix('VITE_') +# @currentEnv=$APP_ENV +# @plugin(vite-plus) +# @generateVitePlusTypes(path='env.d.ts', importMetaEnv=none) +# --- + +# @public @type=enum(development, staging, production, test) +APP_ENV=fallback(viteMode(), development) + +# @required @type=url +VITE_API_URL=http://localhost:3000 + +# @public @type=port +API_PORT=3000 + +# @required @sensitive @type=string(startsWith=sk_) +STRIPE_SECRET_KEY= +``` + +`@defaultSensitive=inferFromPrefix('VITE_')` follows the rule of Vite: `VITE_*` variables are public, and all other variables are sensitive. Mark a public variable without the prefix with `@public`, as `APP_ENV` and `API_PORT` show. `APP_ENV` follows the Vite mode through `viteMode()`, so `vp build` loads `.env.production` as in Vite (see [Vite modes](#vite-modes)). + +`.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 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. +::: + +## Quick start + +Run `vp dotenv init` in a project that already has `.env` files: + +```bash +vp dotenv init +``` + +`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. Make sure that each secret is sensitive, and that each variable for client code is public. + +`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. +- 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: + +- Code imports `ENV` from `varlock/env` and you use TypeScript, which must resolve that module from your project. +- A production server starts with `varlock run` (see [Server-side rendering](#server-side-rendering)). + +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. + +A project that already uses varlock through `@varlock/vite-integration` can run `vp migrate` (`vp migrate --full` on a project that already uses Vite+). It removes `varlockVitePlugin()`, switches the schema to `@generateVitePlusTypes`, and removes the varlock dependencies that nothing else uses. See [varlock Rules](/guide/migrate-rules#varlock-rules). + +In CI or for a coding agent, run `vp dotenv init --no-interactive` to use the default answers instead of prompts. + +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. `vp build` and `vp preview` stop with exit code 1, and `vp test` fails before any test runs. 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/dotenv'; + +fetch(`${ENV.VITE_API_URL}/items`); // string, inlined at build time +ENV.API_PORT; // number, not string +ENV.STRIPE_SECRET_KEY; // sensitive: never inlined into client code +``` + +`import.meta.env.VITE_*` keeps working for the `VITE_*` variables that the schema declares (see [Sensitive values](#sensitive-values)). `ENV` is the recommended API: it is typed, it coerces numbers and booleans, and a variable marked `@public` reaches client code without the 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. + +## The `.env.schema` file + +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: + +| Decorator | Meaning | +| ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `@defaultSensitive=inferFromPrefix('VITE_')` | The rule of Vite: `VITE_*` is public, everything else is sensitive. `vp dotenv init` writes it. | +| `@defaultSensitive=false` | Every variable is public unless marked `@sensitive`. Use `true` to make every variable sensitive. | +| `@currentEnv=$APP_ENV` | The variable that selects the environment, and so which `.env.[env]` files load. | +| `@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. | + +Common item decorators: + +| Decorator | Meaning | +| -------------- | ---------------------------------------------------------------------------------------- | +| `@required` | Fail validation when the value is empty. | +| `@sensitive` | Treat as a secret: never inline into client code, redact in logs. | +| `@public` | Treat as public: allow in client code. Use it for a variable without the `VITE_` prefix. | +| `@type=` | Validate and coerce, for example `url`, `port`, or `enum(a, b)`. | +| `@docs(url)` | Link to documentation for the variable. | + +A value can reference another variable: `VITE_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 entries override earlier ones: + +1. `.env.schema`: the committed schema and default values +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 + +`[env]` is the value of the variable that `@currentEnv` names. With the schema above, it follows the Vite mode, so `vp build --mode staging` loads `.env.staging`. A value that you set wins over the mode: + +```bash +APP_ENV=staging vp build +``` + +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. + +Vite+ looks for `.env.schema` in the `root` set in `vite.config.ts`, or else in the directory where you run `vp`. A root given on the command line, as in `vp dev ./app`, is not part of this check, so a schema there is not loaded. With `dotenv.schema: true`, the command fails and names that schema. Run `vp` from the project directory, or use `vp -C ./app dev`. + +One `vp` process loads one schema. Every test project, including `defineProject` files and projects with `extends: false`, uses the root config's schema. When two project configs in one `vp test` run have different `.env.schema` files, the command fails instead of mixing their values. Use one schema at the workspace root, which can `@import` package files, or run `vp test` in each package. + +When you change an env file, `vp dev` restarts and loads the new values. A restart without an env file change does not load again, so values from a secret manager or an `exec()` call stay the same. To get new values from them, stop and start `vp dev`. + +### Vite modes + +varlock selects the environment from the `@currentEnv` variable, not from Vite's mode. Vite still reads `.env.[mode]` files, but the values that varlock resolves override them, because Vite gives the process environment priority. To make the environment follow the mode, give the variable the default `fallback(viteMode(), development)`, as `vp dotenv init` does. + +`viteMode()` comes from `@plugin(vite-plus)`. It returns the mode of `vp dev`, `vp build`, `vp preview`, or `vp test`: the `--mode` value, or else the default mode of the command. + +| Command | `viteMode()` | Files that load | +| ------------------------- | ------------- | -------------------------- | +| `vp dev` | `development` | `.env.development[.local]` | +| `vp build`, `vp preview` | `production` | `.env.production[.local]` | +| `vp test` | `test` | `.env.test[.local]` | +| `vp build --mode staging` | `staging` | `.env.staging[.local]` | + +The mode is only a default. A value from the process environment (`APP_ENV=staging vp build`) or from an env file wins over it, and so does a value that the schema lists before `viteMode()` in `fallback()`. Outside these commands, as in `varlock run` or a script that runs `vite build` directly, `viteMode()` returns nothing and the schema uses the next value. To check the values for one mode, pass the same `--mode` to `vp dotenv check`, `print`, `explain`, `scan`, or `exec`. + +Vite+ prints a warning when the mode does not select the varlock environment: + +- With a mode that you pass, when the `@currentEnv` variable has another value. +- With the default mode, when `.env.[mode]` or `.env.[mode].local` exists, because Vite would read it. A variable that you set in the environment for the run turns this warning off. + +The warning names what takes priority, or how to make the schema follow the mode. `mode` in `vite.config.ts` does not change `viteMode()`, because Vite+ reads the mode from the command line. Pass `--mode` instead. + +## Using `ENV` in `vite.config.ts` + +`vite.config.ts` can read `ENV` too: + +```ts [vite.config.ts] +import { defineConfig } from 'vite-plus'; +import { ENV } from 'vite-plus/dotenv'; + +export default defineConfig({ + server: { port: ENV.API_PORT }, +}); +``` + +The first read loads `.env.schema` from the directory where you run `vp`, not from a `root` that the config sets. `vp dev`, `vp build`, `vp preview`, and `vp test` then use the same result, so the schema loads only one time. After an env file changes, the `vp dev` restart gives the config the new values. If the env config is invalid, each read returns `undefined` with a warning, and the Vite commands report the errors as usual. + +A command that runs `vite.config.ts` for other settings, such as `vp lint`, then loads the schema too. Prefer `ENV` to Vite's `loadEnv()`, which reads the `.env` files without the schema: it does not validate the values, convert their types, or follow `@currentEnv`. + +## Sensitive values + +A variable is sensitive when the schema marks it `@sensitive`, or when `@defaultSensitive` makes it sensitive. `inferFromPrefix('VITE_')` does that for every variable without the prefix that is not marked `@public`. A sensitive value is protected in these places: + +- **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). +- **`import.meta.env`.** Vite copies every `VITE_*` key from the process environment into `import.meta.env`, which reaches the browser. Vite+ removes the keys that varlock treats as sensitive and prints a warning that names them. varlock also treats a variable as sensitive when an env file sets it but the schema does not declare it, so declare each `VITE_*` variable that client code reads in `.env.schema`. Read sensitive values in server code through `ENV`. +- **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/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. + +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` + +Create `.env.schema` from the existing `.env` files. See [Quick start](#quick-start). + +### `vp dotenv check` + +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 +``` + +`--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`, `keychain`, and `encrypt` without `--file` do not load it. + +### `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, secrets masked +vp dotenv print --reveal --format shell # export lines in plaintext, for `eval` +vp dotenv print --reveal --format env # plaintext, for a deploy step that needs it +``` + +Masked output is for reading. Do not `eval` it: the shell would get the masked placeholders instead of the values. Treat `--reveal` output like the contents of `.env.local`: do not send it to a log. + +### `vp dotenv explain` + +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 +vp dotenv explain VITE_API_URL +``` + +### `vp dotenv scan` + +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 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, for scripts and tools that are not Vite: + +```bash +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. 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`. + +### `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. + +### `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`: + +```ts [vite.config.ts] +export default defineConfig({ + run: { + tasks: { + seed: { command: 'vp dotenv exec -- node scripts/seed.ts' }, + }, + }, +}); +``` + +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, because those commands load the schema themselves. + +The clean environment also hides variables that come from your shell or from CI, such as the `@currentEnv` variable (`APP_ENV`) or secrets that CI injects. Inside a task, varlock cannot see them until you pass them through. Put `APP_ENV` in [`cache.env`](/config/run#cache-env), so that a change runs the task again. Put secrets in [`cache.untrackedEnv`](/config/run#cache-untrackedenv), so that their values stay out of the cache key. A change to an untracked value does not run the task again. + +```ts [vite.config.ts] +export default defineConfig({ + run: { + tasks: { + build: { + command: 'vp build', + cache: { env: ['APP_ENV'], untrackedEnv: ['STRIPE_SECRET_KEY'] }, + }, + }, + }, +}); +``` + +## 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 +``` + +In CI, run `vp dotenv check` before the build. See [Commit Hooks](/guide/commit-hooks) and [CI](/guide/ci). + +## Server-side rendering + +The varlock integration adds startup code to server entry points. Vite+ bundles varlock's runtime into server builds, so the server output does not need `varlock` at run time. The startup code reads the resolved environment that `varlock run` injects, so start the server with `vp dotenv exec --`, or install `varlock` and use `varlock run --`. + +## Coding agents + +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 + +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/docs/guide/migrate-rules.md b/docs/guide/migrate-rules.md index cdbaece81f..1d7180e2ec 100644 --- a/docs/guide/migrate-rules.md +++ b/docs/guide/migrate-rules.md @@ -18,7 +18,7 @@ Migration is idempotent: running it again after a successful migration should no On a project that already depends on `vite-plus`, `vp migrate` performs an upgrade only: it updates dependencies and package-manager configuration and finalizes imports. It does not touch project setup. -- `--full` also runs the setup actions: git hooks, editor config, agent files, ESLint, Prettier, tsup, and tsx migration, framework shims, the tsconfig `baseUrl` fix, and the Volta to `.node-version` conversion. +- `--full` also runs the setup actions: git hooks, editor config, agent files, ESLint, Prettier, tsup, tsx, and varlock migration, framework shims, the tsconfig `baseUrl` fix, and the Volta to `.node-version` conversion. - `--full` checks an existing Renovate config for the `group:vitePlus` preset. See [Dependency Bots](./upgrade-project.md#dependency-bots). - `--hooks`, `--agent`, and `--editor` opt into a single setup action without `--full`. @@ -411,6 +411,19 @@ Entries with static imports or re-exports of CommonJS values also stay unchanged As with oxnode, migration rewrites package scripts, JSON lint-staged tasks, and supported env shebangs. Shebangs that need a pinned config stay unchanged because the config path depends on the caller's working directory. Existing Vite+ projects use `vp migrate --full`. The `ts-node` development dependency is removed only when no remaining command, loader, API import, or config reference needs it. Runtime and peer dependencies remain, and `typescript` is not removed. +## varlock Rules + +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. +- Removes the `@varlock/vite-integration` dependency when no source file imports it. +- Removes the `varlock` dependency when nothing uses it: no import of `varlock` or a subpath such as `varlock/env` in source (the generated types file does not count), no varlock command in `package.json` scripts, CI workflows, git hooks, or shell scripts, no other `@varlock/*` plugin package, and no other `@plugin(...)` in the schema. The root's dependency stays while any workspace package still uses varlock. + +When a dependency stays, the warning names what uses it. For `varlock`, the warning also names the version that Vite+ bundles: the Vite integration runs the varlock CLI from the project's `node_modules/.bin`, so keep the project's copy at that version. + +Imports from `varlock/env` are not rewritten to `vite-plus/dotenv`. Server code that Vite does not bundle would then need `vite-plus`, which is usually a devDependency, at run time. A project without these imports and commands also stops seeing pnpm 12's "Agent skills awaiting approval: varlock" prompt, which pnpm shows only for a direct dependency. + ## Continuous Integration Rules Migration replaces exact `voidzero-dev/setup-vp@v1` references in GitHub Actions workflows and composite actions under `.github` with the latest exact `setup-vp` release known to that Vite+ version. The frozen `v1` tag does not receive new releases. Existing exact versions and commit SHAs are left unchanged. diff --git a/packages/cli/README.md b/packages/cli/README.md index e715f9bbf4..a567184474 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -110,6 +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` (experimental) #### Execute 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..df0c623c60 100644 --- a/packages/cli/binding/index.d.cts +++ b/packages/cli/binding/index.d.cts @@ -3905,6 +3905,31 @@ 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' + | 'encrypt' + | 'lock' + | 'keychain'; + env?: string; + mode?: string; + format: 'env' | 'json' | 'shell'; + reveal: boolean; + key?: string; + targets: Array; + staged: boolean; + includeIgnored: boolean; + interactive: boolean; + execCommand: Array; + file?: string; + keychainArgs: Array; +} + /** * Download a package manager, or use the one on PATH when no global install manages it. * @@ -4145,6 +4170,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..74d0b7175b 100644 --- a/packages/cli/binding/src/cli/help.rs +++ b/packages/cli/binding/src/cli/help.rs @@ -200,6 +200,7 @@ pub(super) fn print_help() { {bold}config{reset} Configure hooks and agent integration {bold}hooks{reset} Manage the Git hook dispatcher {bold}staged{reset} Run linters on staged files + {bold}dotenv{reset} Validate and inspect project environment variables using .env.schema {bold}toolchain{reset} Show Vite+ tool versions and relationships {bold_underline}Package Manager Commands:{reset} @@ -360,7 +361,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/cli/mod.rs b/packages/cli/binding/src/cli/mod.rs index 851b673122..6811520eae 100644 --- a/packages/cli/binding/src/cli/mod.rs +++ b/packages/cli/binding/src/cli/mod.rs @@ -303,6 +303,9 @@ fn vp_untracked_env_vars() -> Vec { env_vars::VP_DOWNLOAD_TIMEOUT, env_vars::VP_INSECURE_TLS, env_vars::VP_TRAMPOLINE_PATH, + // Set for a `vp build`, `vp dev`, `vp preview`, or `vp test` that a task + // runs, from its arguments, which the cache key already holds. + env_vars::VP_VITE_MODE, "VP_VERSION", "VP_NO_UPDATE_CHECK", ] diff --git a/packages/cli/binding/src/cli/resolver.rs b/packages/cli/binding/src/cli/resolver.rs index 02d0c0112f..071a0b944b 100644 --- a/packages/cli/binding/src/cli/resolver.rs +++ b/packages/cli/binding/src/cli/resolver.rs @@ -1,5 +1,6 @@ use std::{env, ffi::OsStr, iter, sync::Arc}; +use vp_shared::env_vars; use vp_static_config::FieldValue; use vt::config::user::{ AutoTracking, EnabledCacheConfig, GlobWithBase, InputBase, UserCacheConfig, UserInputEntry, @@ -109,6 +110,7 @@ impl SubcommandResolver { }) } SynthesizableSubcommand::Build { args } => { + let mode = vite_mode(&args, "production", true).to_owned(); let cli_options = self.cli_options()?; let resolved = (cli_options.vite)(cwd, &args).await?; let js_path = resolved.bin_path; @@ -123,10 +125,14 @@ impl SubcommandResolver { .chain(args.into_iter().map(Str::from)) .collect(), cache_config, - envs: merge_resolved_envs_with_version(envs, resolved.envs), + envs: with_vite_mode( + merge_resolved_envs_with_version(envs, resolved.envs), + &mode, + ), }) } SynthesizableSubcommand::Test { args } => { + let mode = vite_mode(&args, "test", false).to_owned(); let cli_options = self.cli_options()?; let resolved = (cli_options.test)(cwd, &args).await?; let js_path = resolved.bin_path; @@ -144,7 +150,10 @@ impl SubcommandResolver { program: Arc::clone(&cli_options.node_exec_path), args: iter::once(Str::from(js_path_str)).chain(vitest_args).collect(), cache_config, - envs: merge_resolved_envs_with_version(envs, resolved.envs), + envs: with_vite_mode( + merge_resolved_envs_with_version(envs, resolved.envs), + &mode, + ), }) } SynthesizableSubcommand::Pack { args } => { @@ -165,6 +174,7 @@ impl SubcommandResolver { }) } SynthesizableSubcommand::Dev { args } => { + let mode = vite_mode(&args, "development", true).to_owned(); let cli_options = self.cli_options()?; let resolved = (cli_options.vite)(cwd, &args).await?; let js_path = resolved.bin_path; @@ -179,10 +189,14 @@ impl SubcommandResolver { .chain(args.into_iter().map(Str::from)) .collect(), cache_config, - envs: merge_resolved_envs_with_version(envs, resolved.envs), + envs: with_vite_mode( + merge_resolved_envs_with_version(envs, resolved.envs), + &mode, + ), }) } SynthesizableSubcommand::Preview { args } => { + let mode = vite_mode(&args, "production", true).to_owned(); let cli_options = self.cli_options()?; let resolved = (cli_options.vite)(cwd, &args).await?; let js_path = resolved.bin_path; @@ -197,7 +211,10 @@ impl SubcommandResolver { .chain(args.into_iter().map(Str::from)) .collect(), cache_config, - envs: merge_resolved_envs_with_version(envs, resolved.envs), + envs: with_vite_mode( + merge_resolved_envs_with_version(envs, resolved.envs), + &mode, + ), }) } SynthesizableSubcommand::Doc { args } => { @@ -363,6 +380,37 @@ fn merge_resolved_envs_with_version( merged } +/// The Vite mode that a Vite or Vitest command runs with: the last `--mode` +/// value (also `-m` when `short_flag` is set, as in Vite), or else `default`. +/// Arguments after `--` are not options. +fn vite_mode<'a>(args: &'a [String], default: &'a str, short_flag: bool) -> &'a str { + let mut mode = default; + let mut args = args.iter(); + while let Some(arg) = args.next() { + if arg == "--" { + break; + } + if arg == "--mode" || (short_flag && arg == "-m") { + if let Some(value) = args.next() { + mode = value; + } + } else if let Some(value) = arg.strip_prefix("--mode=") { + mode = value; + } + } + mode +} + +/// Set `VP_VITE_MODE` for a Vite or Vitest command. It replaces an inherited +/// value, which belongs to the command that started this one. +fn with_vite_mode(mut envs: Arc, mode: &str) -> Arc { + Arc::make_mut(&mut envs).insert( + EnvName::new(Arc::from(OsStr::new(env_vars::VP_VITE_MODE))), + Arc::from(OsStr::new(mode)), + ); + envs +} + #[cfg(test)] mod tests { use vt_path::AbsolutePathBuf; @@ -423,6 +471,52 @@ mod tests { } } + fn strings(values: &[&str]) -> Vec { + values.iter().map(|value| (*value).to_owned()).collect() + } + + #[test] + fn vite_mode_reads_the_mode_option() { + assert_eq!(vite_mode(&strings(&[]), "production", true), "production"); + assert_eq!(vite_mode(&strings(&["--mode", "staging"]), "production", true), "staging"); + assert_eq!(vite_mode(&strings(&["app", "--mode=staging"]), "production", true), "staging"); + assert_eq!(vite_mode(&strings(&["-m", "staging"]), "production", true), "staging"); + assert_eq!(vite_mode(&strings(&["--mode", "a", "--mode", "b"]), "test", false), "b"); + // Vitest has no `-m`, and arguments after `--` are not options. + assert_eq!(vite_mode(&strings(&["-m", "staging"]), "test", false), "test"); + assert_eq!( + vite_mode(&strings(&["--", "--mode", "staging"]), "production", true), + "production" + ); + } + + #[tokio::test] + async fn vite_commands_receive_their_mode() { + let temp = tempfile::tempdir().unwrap(); + let cwd = AbsolutePathBuf::new(temp.path().to_path_buf()).unwrap(); + let resolver = SubcommandResolver::new(cwd.clone().into()) + .with_cli_options(cli_options(Arc::from(OsStr::new("node")))); + let key = EnvName::new(Arc::from(OsStr::new(env_vars::VP_VITE_MODE))); + let mut inherited = EnvMap::default(); + inherited.insert(key.clone(), Arc::from(OsStr::new("development"))); + let inherited = Arc::new(inherited); + for (command, expected) in [ + (SynthesizableSubcommand::Dev { args: vec![] }, Some("development")), + (SynthesizableSubcommand::Build { args: vec![] }, Some("production")), + ( + SynthesizableSubcommand::Build { args: strings(&["--mode", "staging"]) }, + Some("staging"), + ), + (SynthesizableSubcommand::Preview { args: vec![] }, Some("production")), + (SynthesizableSubcommand::Test { args: vec![] }, Some("test")), + (SynthesizableSubcommand::Lint { args: vec![] }, None), + ] { + let envs = if expected.is_some() { &inherited } else { &Arc::new(EnvMap::default()) }; + let resolved = resolver.resolve(command, envs, &cwd).await.unwrap(); + assert_eq!(resolved.envs.get(&key).map(|value| value.to_str().unwrap()), expected); + } + } + #[tokio::test] async fn vite_config_skips_javascript_only_when_static() { use crate::check::CHECK_CONFIG_FIELDS as CHECK_FIELDS; 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..7f7b6d69d8 --- /dev/null +++ b/packages/cli/binding/src/js_command_args/commands/dotenv.rs @@ -0,0 +1,467 @@ +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)"; +const MODE_HELP: &str = "Vite mode for viteMode() in .env.schema, as in vp build --mode"; + +#[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), + /// 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), + /// Manage the macOS Keychain items that keychain() reads (macOS only) + #[command(disable_help_flag = true)] + Keychain(KeychainArgs), +} + +#[derive(Debug, Args)] +struct InitArgs { + #[arg( + long = "no-interactive", + action = ArgAction::SetTrue, + help = "Use the default answers instead of prompting" + )] + no_interactive: bool, + + #[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(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 PrintArgs { + #[arg(long, value_name = "name", value_parser = NonEmptyStringValueParser::new(), help = ENV_HELP)] + env: Option, + + #[arg(long, value_name = "name", value_parser = NonEmptyStringValueParser::new(), help = MODE_HELP)] + mode: 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(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 ScanArgs { + #[arg( + value_name = "PATH", + help = "Files, directories, or globs to scan (default: the current directory)" + )] + targets: Vec, + + #[arg(long, value_name = "name", value_parser = NonEmptyStringValueParser::new(), help = MODE_HELP)] + mode: Option, + + #[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(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, + + #[arg( + value_name = "COMMAND", + required = true, + num_args = 1.., + trailing_var_arg = true, + help = "Command and arguments to run" + )] + 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, +} + +/// 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") + .about( + "Validate project environment variables against .env.schema, including values supplied by CI.", + ) + .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' | 'encrypt' | 'lock' | 'keychain'" + )] + pub command: String, + pub env: Option, + pub mode: 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 interactive: bool, + pub exec_command: Vec, + pub file: Option, + pub keychain_args: Vec, +} + +impl DotenvArgs { + fn new(command: &str) -> Self { + Self { + command: command.into(), + env: None, + mode: None, + format: "env".into(), + reveal: false, + key: None, + targets: Vec::new(), + staged: false, + include_ignored: false, + interactive: true, + exec_command: Vec::new(), + file: None, + keychain_args: Vec::new(), + } + } +} + +impl From for DotenvArgs { + fn from(value: DotenvCliArgs) -> Self { + match value.command { + DotenvSubcommand::Init(args) => { + Self { interactive: !args.no_interactive, ..Self::new("init") } + } + DotenvSubcommand::Check(args) => { + Self { env: args.env, mode: args.mode, ..Self::new("check") } + } + DotenvSubcommand::Print(args) => Self { + env: args.env, + mode: args.mode, + format: args.format, + reveal: args.reveal, + ..Self::new("print") + }, + DotenvSubcommand::Explain(args) => { + Self { env: args.env, mode: args.mode, key: args.key, ..Self::new("explain") } + } + DotenvSubcommand::Scan(args) => Self { + mode: args.mode, + targets: args.targets, + staged: args.staged, + include_ignored: args.include_ignored, + ..Self::new("scan") + }, + 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"), + DotenvSubcommand::Keychain(args) => { + Self { keychain_args: args.args, ..Self::new("keychain") } + } + } + } +} + +#[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(), + " vp dotenv encrypt --file .env.local".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() { + let args = parsed(&["init"]); + assert_eq!(args.command, "init"); + assert!(args.interactive); + assert!(!parsed(&["init", "--no-interactive"]).interactive); + + let args = parsed(&["check", "--env", "production"]); + assert_eq!(args.command, "check"); + assert_eq!(args.env.as_deref(), Some("production")); + assert_eq!(args.mode, None); + } + + #[test] + fn loading_commands_accept_a_vite_mode() { + for argv in [ + &["check", "--mode", "staging"][..], + &["print", "--mode", "staging"][..], + &["explain", "--mode", "staging"][..], + &["scan", "--mode", "staging"][..], + &["exec", "--mode", "staging", "--", "node"][..], + ] { + assert_eq!(parsed(argv).mode.as_deref(), Some("staging"), "argv: {argv:?}"); + } + assert_eq!(parse_error(&["check", "--mode", ""]).kind, "invalid-value"); + assert_eq!(parse_error(&["init", "--mode", "staging"]).kind, "unknown-argument"); + } + + #[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 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 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 + [&[][..], &["-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"); + // An option before the command must not become the command to run. + assert_eq!( + parse_error(&["exec", "--env", "production", "--", "node"]).kind, + "unknown-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..1d71f70865 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -62,6 +62,12 @@ "./bin": { "import": "./dist/bin.js" }, + "./dotenv": { + "types": "./dist/dotenv.d.ts", + "node": "./dist/dotenv-node.js", + "default": "./dist/dotenv.js" + }, + "./plugin": "./dist/dotenv/varlock-plugin.cjs", "./fmt": { "types": "./dist/fmt.d.ts", "import": "./dist/fmt.js" @@ -355,6 +361,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 +372,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..640a2fbeb6 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,24 @@ 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, + interactive: true, + 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 +121,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 +133,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..24fd8bc5d6 100644 --- a/packages/cli/src/define-config.ts +++ b/packages/cli/src/define-config.ts @@ -31,6 +31,13 @@ import type { InlineConfig as VitestInlineConfig } from 'vitest/node'; import { withConfigMetadataResolution } from './config-metadata.ts'; import type { CreateTemplateEntry } from './create/org-manifest.ts'; +import type { DotenvOptions } from './dotenv/vite-plugin.ts'; +import { + detectSchemaRoot, + dotenvPlugins, + dotenvProjectPlugins, + isDotenvEntry, +} 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 +93,11 @@ declare module 'vite' { staged?: StagedConfig; + /** + * Load and validate `.env` files against `.env.schema`. + */ + dotenv?: DotenvOptions; + /** * Options for `vp create`. * @@ -889,6 +901,9 @@ function withoutVitePlusTestPlugins(plugin: PluginOption): PluginOption { } function keepUserPlugin(plugin: PluginOption): boolean { + if (isDotenvEntry(plugin)) { + return false; + } return !plugin || !('name' in plugin) || !VITE_PLUS_TEST_PLUGIN_NAMES.has(plugin.name); } @@ -929,38 +944,44 @@ function injectPluginIntoInlineConfig< * sub-configs or bare directory projects β€” there a provider/runner skew falls * back to Vitest's own (softer) warning instead of the guard's hard error. */ -function injectPluginIntoProject(project: TestProjectConfiguration): TestProjectConfiguration { +function injectPluginIntoProject( + project: TestProjectConfiguration, + schemaRoot?: string, +): TestProjectConfiguration { if (typeof project === 'string') { return project; } + const inject = (config: UserWorkspaceConfig & { extends?: string | boolean }) => + injectIndependentProject(config, schemaRoot); if (typeof project === 'function') { const wrapped: UserProjectConfigFn = (env: ConfigEnv) => { const result = project(env); if (types.isPromise(result)) { - return result.then(injectIndependentProject); + return result.then(inject); } - return injectIndependentProject(result); + return inject(result); }; return wrapped; } if (types.isPromise(project)) { - return project.then(injectIndependentProject); + return project.then(inject); } if (typeof project === 'object' && project !== null) { - return injectIndependentProject(project); + return inject(project); } return project; } function injectIndependentProject( config: UserWorkspaceConfig & { extends?: string | boolean }, + schemaRoot?: string, ): UserWorkspaceConfig { return config.extends === false || typeof config.extends === 'string' - ? injectPlugin(config) + ? injectProjectPlugins(config, schemaRoot) : config; } -function injectPlugin(config: T): T { +function injectPlugin(config: T, schemaRoot?: string): T { const injected = injectPluginIntoInlineConfig(config); const projects = injected.test?.projects; if (!projects || projects.length === 0) { @@ -970,25 +991,52 @@ function injectPlugin(config: T): T { ...injected, test: { ...injected.test, - projects: projects.map(injectPluginIntoProject), + projects: projects.map((project) => injectPluginIntoProject(project, schemaRoot)), }, }; } +/** + * An independent Vitest project has its own Vite server without the root + * plugins, so it reuses the root's loaded schema through follower plugins. + * `schemaRoot` is the schema of the root config that declares the project. + */ +function injectProjectPlugins(config: T, schemaRoot?: string): T { + const injected = injectPlugin(config, schemaRoot); + const dotenv = dotenvProjectPlugins(injected, schemaRoot); + return dotenv.length === 0 + ? injected + : { ...injected, plugins: [...(injected.plugins ?? []), ...dotenv] }; +} + +/** + * A root config also loads `.env.schema`. Projects and nested test projects + * share the root's env, so they do not load it again. `injectPlugin` drops the + * dotenv entries of composed configs first, so only this config's options + * decide, and a dropped entry never starts its import. + */ +function injectRootPlugins(config: T): T { + const injected = injectPlugin(config, detectSchemaRoot(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); } /** @@ -1012,13 +1060,15 @@ function injectPluginIntoProjectExport(config: UserProjectConfigExport): UserPro if (typeof config === 'function') { return (env: ConfigEnv) => { const result = config(env); - return types.isPromise(result) ? result.then(injectPlugin) : injectPlugin(result); + return types.isPromise(result) + ? result.then((project) => injectProjectPlugins(project)) + : injectProjectPlugins(result); }; } if (types.isPromise(config)) { - return config.then(injectPlugin); + return config.then((project) => injectProjectPlugins(project)); } - return injectPlugin(config); + return injectProjectPlugins(config); } /** diff --git a/packages/cli/src/dotenv-node.ts b/packages/cli/src/dotenv-node.ts new file mode 100644 index 0000000000..dcecf061b1 --- /dev/null +++ b/packages/cli/src/dotenv-node.ts @@ -0,0 +1,118 @@ +// `vite-plus/dotenv` for Node.js (the `node` export condition). It has the +// exports of `dotenv.ts`, and its `ENV` loads the schema the first time code +// reads it when nothing has loaded the env yet. Vite+ adds the varlock +// integration when Vite resolves the plugins, after `vite.config.ts` has run, +// so without this a config file could not read `ENV`. Browser bundles use +// `dotenv.ts`, and Vite builds resolve this module to `varlock/env`. + +import { createRequire } from 'node:module'; + +import type { ensureVarlockEnvFresh, varlockLastError } from '@varlock/vite-integration'; +import { ENV as varlockEnv, initVarlockEnv } from 'varlock/env'; + +import { setVarlockIntegrationEnv } from './dotenv/integration.ts'; +import { hasDotenvSchema } from './dotenv/varlock.ts'; + +// oxlint-disable-next-line import/export -- varlock/env re-exports its named exports from an internal chunk, which this rule does not follow. +export * from 'varlock/env'; + +// The variable that `varlock run` uses to pass the resolved env to a child. +const VARLOCK_ENV_BLOB = '__VARLOCK_ENV'; + +/** The parts of `@varlock/vite-integration` that this module uses. */ +interface VarlockIntegration { + ensureVarlockEnvFresh: typeof ensureVarlockEnvFresh; + varlockLastError: typeof varlockLastError; +} + +// `require()` of an ES module loads the integration synchronously, from a +// proxy trap. Every supported Node.js version supports it. +const requireIntegration: (id: '@varlock/vite-integration') => VarlockIntegration = createRequire( + import.meta.url, +); + +let loadAttempted = false; +/** The integration, when this module loaded it. */ +let integration: VarlockIntegration | undefined; +let checkedThisTurn = false; + +/** + * Load the schema in the working directory, unless a parent `varlock run`, + * `varlock/auto-load`, or an earlier load already provided the env. + * + * The varlock Vite integration loads the schema when it is imported, so this + * imports it now instead of when Vite+ adds it to the plugins. Then one load + * serves the config file and the Vite command, the integration copies + * `process.env` before varlock adds the resolved values to it, and an invalid + * config stops `vp build` and shows the `vp dev` error page as before. + */ +function loadSchema(): void { + if (loadAttempted) { + return; + } + loadAttempted = true; + if ( + process.env[VARLOCK_ENV_BLOB] !== undefined || + '__varlockLoadedEnv' in globalThis || + !hasDotenvSchema(process.cwd()) + ) { + return; + } + // `varlock/env` is already loaded (see `setVarlockIntegrationEnv`). + const restoreEnv = setVarlockIntegrationEnv(); + try { + integration = requireIntegration('@varlock/vite-integration'); + } finally { + restoreEnv(); + } +} + +/** + * Make `ENV` match the env files before code reads it. A `vp dev` restart runs + * the config file again before the integration checks the env files, so a + * changed file is loaded here. The check reads every env file, so it runs once + * per synchronous turn, for example once for the top level of a config file. + */ +function prepareEnv(): void { + if (checkedThisTurn) { + return; + } + checkedThisTurn = true; + queueMicrotask(() => { + checkedThisTurn = false; + }); + if (integration === undefined) { + loadSchema(); + } else { + integration.ensureVarlockEnvFresh(); + } + // After a failed load, the integration prints the errors and does not + // update the runtime, so `ENV` would throw or keep old values. Initialize + // it from the graph of the failed load instead: varlock then returns no + // values and warns on each read. + if (integration?.varlockLastError !== undefined) { + initVarlockEnv({ allowFail: true }); + } +} + +/** varlock's `ENV`, which loads the schema on first use when the env is not loaded. */ +export const ENV: typeof varlockEnv = new Proxy(varlockEnv, { + get(target, key, receiver) { + prepareEnv(); + // oxlint-disable-next-line quality/no-reflect-get -- A proxy trap forwards to its target. + const value: unknown = Reflect.get(target, key, receiver); + return value; + }, + has(target, key) { + prepareEnv(); + return Reflect.has(target, key); + }, + ownKeys(target) { + prepareEnv(); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(target, key) { + prepareEnv(); + return Reflect.getOwnPropertyDescriptor(target, key); + }, +}); diff --git a/packages/cli/src/dotenv.ts b/packages/cli/src/dotenv.ts new file mode 100644 index 0000000000..af6a070416 --- /dev/null +++ b/packages/cli/src/dotenv.ts @@ -0,0 +1,9 @@ +/** + * 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. + */ +// oxlint-disable-next-line import/export -- varlock/env re-exports its named exports from an internal chunk, which this rule does not follow. +export * from 'varlock/env'; diff --git a/packages/cli/src/dotenv/__tests__/dotenv-node.spec.ts b/packages/cli/src/dotenv/__tests__/dotenv-node.spec.ts new file mode 100644 index 0000000000..9298f63f1d --- /dev/null +++ b/packages/cli/src/dotenv/__tests__/dotenv-node.spec.ts @@ -0,0 +1,93 @@ +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'; + +// Imports the built `vite-plus/dotenv` with Node.js, the way a config file +// does before the Vite integration has loaded the env. +describe('vite-plus/dotenv under the node condition', () => { + let dir: string; + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-dotenv-node-')); + fs.mkdirSync(path.join(dir, 'node_modules')); + fs.symlinkSync(pkgRoot, path.join(dir, 'node_modules', 'vite-plus'), 'junction'); + fs.writeFileSync(path.join(dir, 'package.json'), '{ "name": "app", "private": true }\n'); + }); + + afterEach(() => { + fs.rmSync(dir, { recursive: true, force: true }); + }); + + function readEnv(script: string, env: NodeJS.ProcessEnv = {}) { + const { __VARLOCK_ENV: _parentEnv, ...inherited } = process.env; + return spawnSync(process.execPath, ['--input-type=module', '-e', script], { + cwd: dir, + env: { ...inherited, VARLOCK_TELEMETRY_DISABLED: '1', ...env }, + encoding: 'utf8', + }); + } + + it('loads the schema the first time code reads ENV', () => { + fs.writeFileSync( + path.join(dir, '.env.schema'), + '# @defaultSensitive=false\n# ---\n# @type=port\nAPI_PORT=3000\n', + ); + + const result = readEnv( + "import { ENV } from 'vite-plus/dotenv'; console.log(JSON.stringify({ port: ENV.API_PORT, loaded: process.env.__VARLOCK_ENV !== undefined }));", + ); + + expect(result.stderr).toBe(''); + expect(JSON.parse(result.stdout)).toEqual({ port: 3000, loaded: true }); + }); + + it('reads changed env files again in a later turn', () => { + fs.writeFileSync( + path.join(dir, '.env.schema'), + '# @defaultSensitive=false\n# ---\n# @type=port\nAPI_PORT=3000\n', + ); + + const result = readEnv( + [ + "import fs from 'node:fs';", + "import { ENV } from 'vite-plus/dotenv';", + 'const first = ENV.API_PORT;', + String.raw`fs.writeFileSync('.env.local', 'API_PORT=4000\n');`, + 'const sameTurn = ENV.API_PORT;', + 'await new Promise((resolve) => setTimeout(resolve, 0));', + 'console.log(JSON.stringify({ first, sameTurn, later: ENV.API_PORT }));', + ].join('\n'), + ); + + expect(result.stderr).toBe(''); + expect(JSON.parse(result.stdout)).toEqual({ first: 3000, sameTurn: 3000, later: 4000 }); + }); + + it('reports an invalid config and returns no values instead of throwing', () => { + fs.writeFileSync( + path.join(dir, '.env.schema'), + '# @defaultSensitive=false\n# ---\n# @type=port\nAPI_PORT=3000\n# @required\nSECRET=\n', + ); + + const result = readEnv( + "import { ENV } from 'vite-plus/dotenv'; console.log(JSON.stringify({ port: ENV.API_PORT ?? null }));", + ); + + expect(JSON.parse(result.stdout)).toEqual({ port: null }); + expect(result.stderr).toContain('SECRET'); + expect(result.stderr).toContain('config has errors'); + }); + + it('leaves ENV alone without a schema', () => { + const result = readEnv( + String.raw`import { ENV } from 'vite-plus/dotenv'; try { ENV.API_PORT; } catch (error) { console.log(error.message.split('\n')[0]); }`, + ); + + expect(result.stdout).toContain('varlock ENV not initialized'); + }); +}); 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..f1fe005a05 --- /dev/null +++ b/packages/cli/src/dotenv/__tests__/encrypt.spec.ts @@ -0,0 +1,78 @@ +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('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')); + + 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__/schema-header.spec.ts b/packages/cli/src/dotenv/__tests__/schema-header.spec.ts new file mode 100644 index 0000000000..5a73e1c6b6 --- /dev/null +++ b/packages/cli/src/dotenv/__tests__/schema-header.spec.ts @@ -0,0 +1,287 @@ +import { describe, expect, it } from 'vitest'; + +import type { ModeCheck } from '../schema-header.ts'; +import { + addModeEnvironment, + adoptVitePlusSchemaHeader, + currentEnvVariable, + detectViteUsage, + environmentNames, + followsViteMode, + modeMismatchWarning, +} from '../schema-header.ts'; + +// The header that `varlock init` writes in a project with a package.json. +const INIT_SCHEMA = `# This env file uses @env-spec - see https://varlock.dev/env-spec for more info +# +# @defaultRequired=infer @defaultSensitive=false +# @generateTsTypes(path=env.d.ts) +# ---------- + +# @type=url +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( + INIT_SCHEMA.replace( + '@defaultSensitive=false', + "@defaultSensitive=inferFromPrefix('VITE_')", + ).replace( + '# @generateTsTypes(path=env.d.ts)', + '# @plugin(vite-plus) @generateVitePlusTypes(path=env.d.ts, importMetaEnv=none)', + ), + ); + }); + + 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('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'; + + expect(adoptVitePlusSchemaHeader(schema)).toBe( + '# @plugin(vite-plus)\n# @generateVitePlusTypes(path=env.d.ts, importMetaEnv=loose)\n# ---\n', + ); + }); + + it('changes only the header', () => { + const schema = + '# @defaultSensitive=true\n# ---\n# @generateTsTypes(path=env.d.ts)\n# @defaultSensitive=false\nAPI_URL=\n'; + + expect(adoptVitePlusSchemaHeader(schema)).toBe(schema); + 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", + ); + }); +}); + +describe('currentEnvVariable', () => { + it('reads the variable that @currentEnv names in the header', () => { + expect(currentEnvVariable('# @defaultSensitive=false\n# @currentEnv=$APP_ENV\n# ---\n')).toBe( + 'APP_ENV', + ); + expect(currentEnvVariable('# @currentEnv=$APP_ENV @defaultRequired=infer\n# ---\n')).toBe( + 'APP_ENV', + ); + }); + + 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(); + expect(currentEnvVariable('# @currentEnv=fallback($VERCEL_ENV, dev)\n# ---\n')).toBeUndefined(); + }); +}); + +describe('addModeEnvironment', () => { + const adopted = adoptVitePlusSchemaHeader(INIT_SCHEMA); + + it('adds @currentEnv and an APP_ENV item that follows the Vite mode', () => { + const schema = addModeEnvironment(adopted, ['development', 'production', 'test', 'staging']); + + expect(currentEnvVariable(schema)).toBe('APP_ENV'); + expect(followsViteMode(schema)).toBe(true); + expect(schema).toContain( + '# ----------\n\n# The environment, which selects the .env.[env] files to load.', + ); + expect(schema).toContain( + '# @public @type=enum(development, production, test, staging)\nAPP_ENV=fallback(viteMode(), development)\n\n# @type=url\nAPI_URL=\n', + ); + }); + + 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); + const withItem = `${adopted}APP_ENV=development\n`; + expect(addModeEnvironment(withItem, ['development'])).toBe(withItem); + expect(addModeEnvironment(INIT_SCHEMA, ['development'])).toBe(INIT_SCHEMA); + }); +}); + +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( + environmentNames([ + '.env', + '.env.local', + '.env.schema', + '.env.example', + '.env.staging', + '.env.qa.local', + '.env.production', + 'package.json', + ]), + ).toEqual(['development', 'production', 'test', 'qa', 'staging']); + }); +}); + +describe('modeMismatchWarning', () => { + const build: Pick = { + defaultMode: 'production', + command: 'build', + }; + const check = (overrides: Partial): string | undefined => + modeMismatchWarning({ + ...build, + mode: 'production', + currentEnvVariable: 'APP_ENV', + currentEnvValue: 'development', + followsMode: false, + modeFileExists: false, + setInEnvironment: false, + viteModeValue: undefined, + ...overrides, + }); + + it('stays quiet when the environment matches the mode', () => { + expect(check({ mode: 'staging', currentEnvValue: 'staging' })).toBeUndefined(); + }); + + it('checks the default mode only when Vite would read .env.[mode]', () => { + expect(check({})).toBeUndefined(); + expect(check({ modeFileExists: true })).toContain( + 'Vite mode "production" does not select the varlock environment: APP_ENV is "development", so varlock does not load .env.production', + ); + // A variable set for this run chooses the environment on purpose. + expect(check({ modeFileExists: true, setInEnvironment: true })).toBeUndefined(); + }); + + it('suggests viteMode() or a variable when the schema does not follow the mode', () => { + expect(check({ mode: 'staging' })).toBe( + 'Vite mode "staging" does not select the varlock environment: APP_ENV is "development", so varlock does not load .env.staging, and its values override the ones Vite reads from that file. To follow the Vite mode, set `APP_ENV=fallback(viteMode(), development)` in .env.schema, or run `APP_ENV=staging vp build`.', + ); + }); + + it('names why the environment does not follow viteMode()', () => { + const staging = { mode: 'staging', followsMode: true, viteModeValue: 'staging' }; + expect(check({ ...staging, setInEnvironment: true })).toContain( + 'APP_ENV is "development" in the environment, which takes priority over viteMode()', + ); + expect(check(staging)).toContain( + 'APP_ENV is "development" from an env file or an earlier source in .env.schema', + ); + expect(check({ ...staging, viteModeValue: undefined })).toContain( + 'viteMode() returns nothing, because Vite did not start through vp dev, vp build, vp preview, or vp test', + ); + expect(check({ ...staging, viteModeValue: 'production' })).toContain( + 'viteMode() returns "production" from the command line, and `mode` in vite.config.ts does not change it', + ); + }); + + it('points to @currentEnv when the schema has none', () => { + expect( + check({ mode: 'staging', currentEnvVariable: undefined, currentEnvValue: undefined }), + ).toContain('add `@currentEnv=$APP_ENV` and `APP_ENV=fallback(viteMode(), development)`'); + expect( + check({ currentEnvVariable: undefined, currentEnvValue: undefined, modeFileExists: true }), + ).toContain('.env.schema has no @currentEnv, so varlock does not load .env.production'); + }); +}); diff --git a/packages/cli/src/dotenv/__tests__/typegen.spec.ts b/packages/cli/src/dotenv/__tests__/typegen.spec.ts new file mode 100644 index 0000000000..e811fa4c2a --- /dev/null +++ b/packages/cli/src/dotenv/__tests__/typegen.spec.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest'; + +import { addVitePlusDotenvTypes } from '../typegen.ts'; + +// The shape of varlock 1.25's `@generateTsTypes` output with `exposeEnv=global`. +const GLOBAL_TYPES = `/* eslint-disable */ +// @ts-nocheck +export type CoercedEnvSchema = { + API_PORT: number; +}; + +type _CoercedEnvSchema_3a158ead = CoercedEnvSchema; + +declare module 'varlock/env' { + export interface TypedEnvSchema extends Readonly<_CoercedEnvSchema_3a158ead> {} + export interface PublicTypedEnvSchema extends Readonly> {} +} + +export type EnvSchemaAsStrings = { API_PORT: string }; +`; + +describe('addVitePlusDotenvTypes', () => { + it('adds the same augmentation for vite-plus/dotenv and keeps the varlock/env one', () => { + const types = addVitePlusDotenvTypes(GLOBAL_TYPES); + + expect(types).toContain(`declare module 'varlock/env' { + export interface TypedEnvSchema extends Readonly<_CoercedEnvSchema_3a158ead> {}`); + expect(types).toContain(`} + +declare module 'vite-plus/dotenv' { + export interface TypedEnvSchema extends Readonly<_CoercedEnvSchema_3a158ead> {} + export interface PublicTypedEnvSchema extends Readonly> {} +} +`); + expect(addVitePlusDotenvTypes(types)).toBe(types); + }); + + it('imports ENV from vite-plus/dotenv with exposeEnv=local', () => { + const local = "import { ENV as _ENV } from 'varlock/env';\n\nexport const ENV = _ENV;\n"; + + expect(addVitePlusDotenvTypes(local)).toBe( + "import { ENV as _ENV } from 'vite-plus/dotenv';\n\nexport const ENV = _ENV;\n", + ); + }); + + it('leaves output without varlock/env unchanged', () => { + const none = 'export type CoercedEnvSchema = { API_PORT: number };\n'; + + expect(addVitePlusDotenvTypes(none)).toBe(none); + }); +}); diff --git a/packages/cli/src/dotenv/__tests__/varlock-plugin.spec.ts b/packages/cli/src/dotenv/__tests__/varlock-plugin.spec.ts new file mode 100644 index 0000000000..56d8439dfe --- /dev/null +++ b/packages/cli/src/dotenv/__tests__/varlock-plugin.spec.ts @@ -0,0 +1,97 @@ +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'; +import { resolveVarlockPackage } from '../varlock.ts'; + +// Runs the bundled varlock CLI with the built `./plugin` export, like a +// project that has `vite-plus` in node_modules and no `varlock` dependency. +describe('the vite-plus varlock plugin', () => { + let dir: string; + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-varlock-plugin-')); + fs.mkdirSync(path.join(dir, 'node_modules')); + fs.symlinkSync(pkgRoot, path.join(dir, 'node_modules', 'vite-plus'), 'junction'); + fs.writeFileSync(path.join(dir, 'package.json'), '{ "name": "app", "private": true }\n'); + fs.writeFileSync( + path.join(dir, '.env.schema'), + [ + '# @defaultSensitive=false', + '# @plugin(vite-plus) @generateVitePlusTypes(path=env.d.ts, importMetaEnv=none)', + '# ---', + '# @type=port', + 'API_PORT=3000', + '', + ].join('\n'), + ); + }); + + afterEach(() => { + fs.rmSync(dir, { recursive: true, force: true }); + }); + + function load(env: NodeJS.ProcessEnv = {}) { + const { VP_VITE_MODE: _mode, APP_ENV: _appEnv, ...inherited } = process.env; + return spawnSync( + process.execPath, + [resolveVarlockPackage().cli, 'load', '--format', 'json', '--agent'], + { + cwd: dir, + env: { ...inherited, VARLOCK_TELEMETRY_DISABLED: '1', ...env }, + encoding: 'utf8', + }, + ); + } + + it('makes varlock write types for vite-plus/dotenv itself', () => { + const first = load(); + expect(first.stderr).toBe(''); + expect(first.status).toBe(0); + const file = path.join(dir, 'env.d.ts'); + const types = fs.readFileSync(file, 'utf8'); + expect(types).toContain("declare module 'varlock/env' {"); + expect(types).toContain("declare module 'vite-plus/dotenv' {"); + expect(types).toContain('API_PORT: number;'); + expect(types).not.toContain('interface ImportMetaEnv'); + + // The next load generates the same text, so varlock leaves the file alone. + const writtenAt = fs.statSync(file).mtimeMs; + expect(load().status).toBe(0); + expect(fs.readFileSync(file, 'utf8')).toBe(types); + expect(fs.statSync(file).mtimeMs).toBe(writtenAt); + }); + + it('selects the environment from the Vite mode through viteMode()', () => { + fs.writeFileSync( + path.join(dir, '.env.schema'), + [ + '# @defaultSensitive=false @currentEnv=$APP_ENV', + '# @plugin(vite-plus)', + '# ---', + '# @type=enum(development, production, staging)', + 'APP_ENV=fallback(viteMode(), development)', + 'API_URL=http://localhost:3000', + '', + ].join('\n'), + ); + fs.writeFileSync(path.join(dir, '.env.production'), 'API_URL=https://example.com\n'); + + expect(JSON.parse(load({ VP_VITE_MODE: 'production' }).stdout)).toMatchObject({ + APP_ENV: 'production', + API_URL: 'https://example.com', + }); + // Outside a vp command, and below a value that the user sets. + expect(JSON.parse(load().stdout)).toMatchObject({ + APP_ENV: 'development', + API_URL: 'http://localhost:3000', + }); + expect( + JSON.parse(load({ VP_VITE_MODE: 'production', APP_ENV: 'staging' }).stdout), + ).toMatchObject({ APP_ENV: 'staging' }); + }); +}); 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..9c8bfec60e --- /dev/null +++ b/packages/cli/src/dotenv/__tests__/varlock.spec.ts @@ -0,0 +1,276 @@ +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 type { JsonObject } from '../../utils/json-value.ts'; +import { hasVitePlusInstalled, preseedVarlockDependency } from '../dependency.ts'; +import { + buildVarlockInvocation, + findPackageRoot, + formatCheckPassMessage, + hasDotenvSchema, + parseLoadOutput, + renderMaskedValues, + withVarlockDefaults, +} from '../varlock.ts'; + +function dotenvArgs(overrides: Partial & Pick): DotenvArgs { + return { + format: 'env', + reveal: false, + targets: [], + staged: false, + includeIgnored: false, + interactive: true, + execCommand: [], + keychainArgs: [], + ...overrides, + }; +} + +describe('buildVarlockInvocation', () => { + it('maps init to varlock init, with --agent when prompts are off', () => { + expect(buildVarlockInvocation(dotenvArgs({ command: 'init' }))).toEqual({ + argv: ['init'], + output: 'inherit', + }); + expect(buildVarlockInvocation(dotenvArgs({ command: 'init', interactive: false }))).toEqual({ + argv: ['init', '--agent'], + output: 'inherit', + }); + }); + + it('validates with redacted JSON so check never prints values', () => { + expect(buildVarlockInvocation(dotenvArgs({ command: 'check', env: 'production' }))).toEqual({ + argv: ['load', '--format', 'json-full', '--compact', '--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' }); + }); + + 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', + }); + }); + + 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', () => { + const values = { + API_URL: 'http://localhost:3000', + API_PORT: 3000, + DEBUG: false, + GREETING: 'hello "world"', + PRICE: '$5', + QUOTE: "it's\nfine", + 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"'`, + "PRICE='$5'", + String.raw`QUOTE="it's\nfine"`, + "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(); + }); + + it('skips lines that varlock prints before the JSON object', () => { + expect(parseLoadOutput('warning: plugin is outdated\n{\n "A": "1"\n}\n')).toEqual({ A: '1' }); + }); + + it('skips lines that varlock prints after the JSON object', () => { + expect(parseLoadOutput('{\n "A": "1"\n}\nA new varlock version is available\n')).toEqual({ + A: '1', + }); + expect(parseLoadOutput('note: cached\n{"A":"1"}\ndone\n')).toEqual({ A: '1' }); + }); +}); + +function graph(config: JsonObject): JsonObject { + return { config }; +} + +describe('formatCheckPassMessage', () => { + it('counts config items', () => { + 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'); + }); +}); + +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('detects .env.schema or a varlock.loadPath in package.json', () => { + expect(hasDotenvSchema(dir)).toBe(false); + fs.writeFileSync( + path.join(dir, 'package.json'), + JSON.stringify({ varlock: { loadPath: './env/' } }), + ); + expect(hasDotenvSchema(dir)).toBe(true); + fs.rmSync(path.join(dir, 'package.json')); + fs.writeFileSync(path.join(dir, '.env.schema'), '# @defaultSensitive=false\n# ---\n'); + expect(hasDotenvSchema(dir)).toBe(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('adds varlock at the bundled version in sorted order, keeping the formatting', () => { + const file = path.join(dir, 'package.json'); + const original = + '{\n\t"name": "app",\n\t"dependencies": {\n\t\t"react": "^19.0.0",\n\t\t"zod": "^4.0.0"\n\t}\n}\n'; + fs.writeFileSync(file, original); + + expect(preseedVarlockDependency(dir, '1.25.0')).toBe(original); + expect(fs.readFileSync(file, 'utf8')).toBe( + '{\n\t"name": "app",\n\t"dependencies": {\n\t\t"react": "^19.0.0",\n\t\t"varlock": "1.25.0",\n\t\t"zod": "^4.0.0"\n\t}\n}\n', + ); + }); + + it('adds a dependencies field when there is none', () => { + fs.writeFileSync(path.join(dir, 'package.json'), '{\n "name": "app"\n}\n'); + + expect(preseedVarlockDependency(dir, '1.25.0')).toBe('{\n "name": "app"\n}\n'); + expect(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).toBe( + '{\n "name": "app",\n "dependencies": {\n "varlock": "1.25.0"\n }\n}\n', + ); + }); + + it('finds vite-plus in node_modules of the directory or a parent', () => { + const app = path.join(dir, 'packages', 'app'); + fs.mkdirSync(app, { recursive: true }); + expect(hasVitePlusInstalled(app)).toBe(false); + fs.mkdirSync(path.join(dir, 'node_modules', 'vite-plus'), { recursive: true }); + fs.writeFileSync(path.join(dir, 'node_modules', 'vite-plus', 'package.json'), '{}'); + expect(hasVitePlusInstalled(app)).toBe(true); + }); + + it('leaves an existing varlock dependency and a missing package.json alone', () => { + expect(preseedVarlockDependency(dir, '1.25.0')).toBeUndefined(); + const content = JSON.stringify({ dependencies: { varlock: '^1.20.0' } }); + fs.writeFileSync(path.join(dir, 'package.json'), content); + + expect(preseedVarlockDependency(dir, '1.25.0')).toBeUndefined(); + expect(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).toBe(content); + }); +}); 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..1a1532125c --- /dev/null +++ b/packages/cli/src/dotenv/__tests__/vite-plugin.spec.ts @@ -0,0 +1,616 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import type { ConfigEnv, Plugin, UserConfig } from 'vite'; +import { mergeConfig } from 'vite'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { defineConfig } from '../../define-config.ts'; +import { CONFIG_METADATA_ENV } from '../../utils/constants.ts'; +import { pkgRoot } from '../../utils/path.ts'; +import { findDependencyBinDir, prependPathEntry } from '../integration.ts'; +import { + dotenvPlugins, + dotenvProjectPlugins, + isDotenvEntry, + scanFailureMessage, + varlockResolvePlugin, + clientEnvFilterPlugin, + validationGuardPlugin, +} from '../vite-plugin.ts'; + +const importTime = vi.hoisted(() => ({ + order: [] as Array, + telemetry: undefined as string | undefined, + runtimeTelemetry: 'not imported' as string | undefined, + pluginOptions: [] as Array, +})); + +vi.mock('varlock/env', () => { + importTime.order.push('varlock/env'); + importTime.runtimeTelemetry = process.env.VARLOCK_TELEMETRY_DISABLED; + return { getPreInjectionProcessEnv: () => process.env }; +}); + +vi.mock('@varlock/vite-integration', () => { + importTime.order.push('@varlock/vite-integration'); + importTime.telemetry = process.env.VARLOCK_TELEMETRY_DISABLED; + return { + varlockVitePlugin: (options: unknown) => { + importTime.pluginOptions.push(options); + return [{ name: 'varlock-lifecycle' }, { name: 'varlock-main' }]; + }, + }; +}); + +function isPlugin(value: unknown): value is Plugin { + return ( + typeof value === 'object' && value !== null && 'name' in value && typeof value.name === 'string' + ); +} + +function isThenable(value: unknown): value is PromiseLike { + return ( + typeof value === 'object' && + value !== null && + 'then' in value && + typeof value.then === 'function' + ); +} + +function flattenPlugins(value: unknown): Array { + if (Array.isArray(value)) { + return value.flatMap((item: unknown) => flattenPlugins(item)); + } + return isPlugin(value) ? [value] : []; +} + +async function loadPlugins(config: UserConfig): Promise> { + const plugins: Array = await Promise.all( + dotenvPlugins(config).map((plugin) => Promise.resolve(plugin)), + ); + return flattenPlugins(plugins); +} + +function pluginNames(plugins: Array): Array { + return flattenPlugins(plugins).map((plugin) => plugin.name); +} + +/** The plugins that Vite keeps for one resolution, filtered like Vite's `filterPlugin`. */ +function applied(plugins: Array, config: UserConfig, env: ConfigEnv): Array { + return plugins.flatMap((plugin) => { + const keep = + typeof plugin.apply === 'function' + ? plugin.apply({ ...config }, env) + : plugin.apply === undefined || plugin.apply === env.command; + return keep ? [plugin.name] : []; + }); +} + +function buildEnv(): ConfigEnv { + return { command: 'build', mode: 'production', isSsrBuild: false, isPreview: false }; +} + +// The owner record lives on globalThis; keep it out of other test files. +afterEach(() => { + resetIntegrationOwner(); +}); + +describe('dotenv Vite plugins', () => { + let root: string; + + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-dotenv-plugin-')); + vi.stubEnv(CONFIG_METADATA_ENV, undefined); + vi.stubEnv('VARLOCK_TELEMETRY_DISABLED', undefined); + resetIntegrationOwner(); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + fs.rmSync(root, { recursive: true, force: true }); + }); + + // Must stay first: the integration import is cached for the whole file. + it('does not import the integration until Vite awaits the entry', async () => { + fs.writeFileSync(path.join(root, '.env.schema'), ''); + const [entry] = dotenvPlugins({ root }); + expect(isDotenvEntry(entry)).toBe(true); + expect(importTime.order).toEqual([]); + const pending: unknown = entry; + if (!isThenable(pending)) { + throw new TypeError('Expected the lazy dotenv entry'); + } + await pending; + expect(importTime.order).toEqual(['varlock/env', '@varlock/vite-integration']); + }); + + it('detects a schema through varlock.loadPath in package.json', async () => { + expect(dotenvPlugins({ root })).toEqual([]); + fs.writeFileSync( + path.join(root, 'package.json'), + JSON.stringify({ varlock: { loadPath: './env/' } }), + ); + expect(await loadPlugins({ root })).not.toHaveLength(0); + }); + + 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'), ''); + vi.stubEnv(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('imports the integration with telemetry off, then restores the environment', async () => { + fs.writeFileSync(path.join(root, '.env.schema'), ''); + const plugins = await loadPlugins({ root }); + expect(plugins.map((plugin) => plugin.name)).toEqual([ + 'vite-plus:dotenv-resolve', + 'varlock-lifecycle', + 'varlock-main', + 'vite-plus:dotenv-client-env', + 'vite-plus:dotenv-validation', + 'vite-plus:dotenv-scan-build-output', + ]); + expect(importTime.telemetry).toBe('1'); + expect(process.env.VARLOCK_TELEMETRY_DISABLED).toBeUndefined(); + }); + + it('loads the varlock runtime before it changes the environment', async () => { + fs.writeFileSync(path.join(root, '.env.schema'), ''); + await loadPlugins({ root }); + // The runtime snapshots process.env on first load and restores it on reload. + expect(importTime.order).toEqual(['varlock/env', '@varlock/vite-integration']); + expect(importTime.runtimeTelemetry).toBeUndefined(); + }); + + it('keeps only the first group when composed configs carry several', async () => { + fs.writeFileSync(path.join(root, '.env.schema'), ''); + const first = await loadPlugins({ root }); + const second = await loadPlugins({ root }); + const plugins = [...first, ...second]; + const expected = [ + 'vite-plus:dotenv-resolve', + 'varlock-lifecycle', + 'varlock-main', + 'vite-plus:dotenv-client-env', + 'vite-plus:dotenv-validation', + 'vite-plus:dotenv-scan-build-output', + ]; + expect(applied(plugins, { root }, buildEnv())).toEqual(expected); + // A new resolution, such as a dev server restart, is claimed again. + expect(applied(plugins, { root }, buildEnv())).toEqual(expected); + }); + + it('fails when a second config loads a different schema in the same process', async () => { + fs.writeFileSync(path.join(root, '.env.schema'), ''); + const app = path.join(root, 'packages/app'); + fs.mkdirSync(app, { recursive: true }); + fs.writeFileSync(path.join(app, '.env.schema'), ''); + const first = await loadPlugins({ root }); + const second = await loadPlugins({ root: app }); + expect(applied(first, { root }, buildEnv())).toContain('varlock-main'); + expect(() => applied(second, { root: app }, buildEnv())).toThrow( + 'Two configs in one vp process load different .env.schema files', + ); + }); + + it('fails when merged configs bring different schemas into one resolution', async () => { + fs.writeFileSync(path.join(root, '.env.schema'), ''); + const app = path.join(root, 'app'); + fs.mkdirSync(app); + fs.writeFileSync(path.join(app, '.env.schema'), ''); + const plugins = [...(await loadPlugins({ root })), ...(await loadPlugins({ root: app }))]; + expect(() => applied(plugins, { root: app }, buildEnv())).toThrow( + 'Two configs in one vp process load different .env.schema files', + ); + }); + + it('reuses the claimed schema in independent projects, without validation or scan', async () => { + fs.writeFileSync(path.join(root, '.env.schema'), ''); + expect(dotenvProjectPlugins({})).toEqual([]); + applied(await loadPlugins({ root }), { root }, buildEnv()); + const [entry] = dotenvProjectPlugins({ root: path.join(root, 'packages/a') }); + expect(isDotenvEntry(entry)).toBe(true); + const plugins = flattenPlugins(await Promise.resolve(entry)); + expect(applied(plugins, { root: path.join(root, 'packages/a') }, buildEnv())).toEqual([ + 'vite-plus:dotenv-resolve', + 'varlock-lifecycle', + 'varlock-main', + 'vite-plus:dotenv-client-env', + ]); + expect(dotenvProjectPlugins({ dotenv: { schema: false } })).toEqual([]); + }); + + it('keeps the integration on the detected schema root in every project', async () => { + fs.writeFileSync(path.join(root, '.env.schema'), ''); + const plugins = await loadPlugins({ root }); + // The integration loads from rootDir, so another Vite root does not reload it. + expect(importTime.pluginOptions.at(-1)).toEqual({ rootDir: root }); + expect(applied(plugins, { root }, buildEnv())).toContain('varlock-main'); + // An inherited project with its own root keeps the transforms and ENV setup. + expect(applied(plugins, { root: path.join(root, 'packages/a') }, buildEnv())).toContain( + 'varlock-main', + ); + }); + + it('accepts a config evaluated again for another root with the same schema', async () => { + fs.writeFileSync(path.join(root, '.env.schema'), ''); + const first = await loadPlugins({ root }); + // Vitest loads the parent config again for an inline project with its own root. + const again = await loadPlugins({ root }); + expect(applied(first, { root }, buildEnv())).toContain('varlock-main'); + expect(applied(again, { root: path.join(root, 'packages/a') }, buildEnv())).toContain( + 'varlock-main', + ); + }); + + it('reads the dotenv options from the merged config', async () => { + fs.writeFileSync(path.join(root, '.env.schema'), ''); + const plugins = await loadPlugins({ root }); + expect(applied(plugins, { root, dotenv: { scanBuildOutput: false } }, buildEnv())).toEqual([ + 'vite-plus:dotenv-resolve', + 'varlock-lifecycle', + 'varlock-main', + 'vite-plus:dotenv-client-env', + 'vite-plus:dotenv-validation', + ]); + expect(applied(plugins, { root, dotenv: { schema: false } }, buildEnv())).toEqual([]); + expect( + applied(plugins, { root }, { ...buildEnv(), command: 'serve', mode: 'development' }), + ).toEqual([ + 'vite-plus:dotenv-resolve', + 'varlock-lifecycle', + 'varlock-main', + 'vite-plus:dotenv-client-env', + 'vite-plus:dotenv-validation', + ]); + }); + + it('requires a schema only when the merged config keeps dotenv.schema: true', () => { + const plugins = flattenPlugins(dotenvPlugins({ root, dotenv: { schema: true } })); + expect(pluginNames(plugins)).toEqual(['vite-plus:dotenv-require-schema']); + expect(applied(plugins, { root, dotenv: { schema: false } }, buildEnv())).toEqual([]); + expect(applied(plugins, { root, dotenv: { schema: true } }, buildEnv())).toEqual([ + 'vite-plus:dotenv-require-schema', + ]); + expect(() => resolveWith(plugins[0], { root })).toThrow( + `\`dotenv.schema\` is true, but ${root} has no .env.schema`, + ); + }); + + it('names a schema that exists only in the final Vite root', () => { + const app = path.join(root, 'app'); + fs.mkdirSync(app); + fs.writeFileSync(path.join(app, '.env.schema'), ''); + const [plugin] = flattenPlugins(dotenvPlugins({ root, dotenv: { schema: true } })); + expect(() => resolveWith(plugin, { root: app })).toThrow( + `\`dotenv.schema\` is true, and ${app} has a schema, but it was not loaded`, + ); + }); +}); + +/** Run a plugin's `configResolved` with a minimal resolved config. */ +function resolveWith(plugin: Plugin, config: UserConfig & { root: string }): void { + const hook = plugin.configResolved as (config: unknown) => void; + hook(config); +} + +describe('varlockResolvePlugin', () => { + it('resolves varlock imports from the vite-plus package', async () => { + const plugin = varlockResolvePlugin(); + const hook = plugin.resolveId as { + filter: { id: RegExp }; + handler: ( + this: unknown, + source: string, + importer: string, + options: { ssr?: boolean }, + ) => Promise<{ id: string } | null>; + }; + expect(hook.filter.id.test('varlock')).toBe(true); + expect(hook.filter.id.test('varlock/env')).toBe(true); + expect(hook.filter.id.test('vite-plus/dotenv')).toBe(true); + expect(hook.filter.id.test('varlock-plugin')).toBe(false); + expect(hook.filter.id.test('vite-plus/test')).toBe(false); + + const resolve = vi.fn< + ( + id: string, + importer: string, + options: { ssr?: boolean; skipSelf?: boolean }, + ) => Promise<{ id: string }> + >(async () => ({ id: '/resolved/env.js' })); + const result = await hook.handler.call({ resolve }, 'varlock/env', '/app/src/main.ts', { + ssr: true, + }); + expect(result).toEqual({ id: '/resolved/env.js' }); + expect(resolve).toHaveBeenCalledWith('varlock/env', path.join(pkgRoot, 'package.json'), { + ssr: true, + skipSelf: true, + }); + }); + + it('resolves vite-plus/dotenv to the same varlock/env module', async () => { + const hook = varlockResolvePlugin().resolveId as { + handler: ( + this: unknown, + source: string, + importer: string, + options: { ssr?: boolean }, + ) => Promise<{ id: string } | null>; + }; + const resolve = vi.fn< + ( + id: string, + importer: string, + options: { ssr?: boolean; skipSelf?: boolean }, + ) => Promise<{ id: string }> + >(async () => ({ id: '/resolved/env.js' })); + await hook.handler.call({ resolve }, 'vite-plus/dotenv', '/app/src/main.ts', {}); + expect(resolve).toHaveBeenCalledWith('varlock/env', path.join(pkgRoot, 'package.json'), { + skipSelf: true, + }); + }); + + it('bundles varlock in server environments only', () => { + const configEnvironment = varlockResolvePlugin().configEnvironment as ( + name: string, + config: { consumer?: 'client' | 'server' }, + ) => { resolve: { noExternal: Array } } | undefined; + expect(configEnvironment('ssr', {})).toEqual({ resolve: { noExternal: ['varlock'] } }); + expect(configEnvironment('worker', { consumer: 'server' })).toEqual({ + resolve: { noExternal: ['varlock'] }, + }); + expect(configEnvironment('client', {})).toBeUndefined(); + expect(configEnvironment('browser', { consumer: 'client' })).toBeUndefined(); + }); +}); + +describe('scanFailureMessage', () => { + it('passes on exit code 0', () => { + expect(scanFailureMessage({ status: 0, signal: null, error: undefined }, 'dist')).toBe( + undefined, + ); + }); + + it('tells a spawn error and a signal apart from scan findings', () => { + expect( + scanFailureMessage({ status: null, signal: null, error: new Error('spawn ENOENT') }, 'dist'), + ).toBe('Could not run `varlock scan` on dist: spawn ENOENT'); + expect(scanFailureMessage({ status: null, signal: 'SIGTERM', error: undefined }, 'dist')).toBe( + '`varlock scan` on dist was stopped by SIGTERM.', + ); + expect(scanFailureMessage({ status: 1, signal: null, error: undefined }, 'dist')).toContain( + 'it found sensitive values from the env config, or it could not load the config', + ); + }); +}); + +/** Resolve the guard plugin for one command; returns the check to run. */ +function resolveGuard( + state: { varlockLastError?: string; varlockLoadedEnv?: unknown }, + run: 'vitest' | 'preview' | 'dev' | 'build' = 'vitest', + options: { + mode?: string; + schemaRoot?: string; + warnings?: Array; + userEnv?: NodeJS.ProcessEnv; + } = {}, +) { + const schemaRoot = options.schemaRoot ?? path.join(os.tmpdir(), 'vp-dotenv-no-schema'); + const userEnv = options.userEnv ?? {}; + const plugin = validationGuardPlugin(state as never, schemaRoot, () => userEnv); + const config = plugin.config as { handler: (config: UserConfig, env: ConfigEnv) => void }; + config.handler( + { environments: run === 'vitest' ? { __vitest__: {} } : {} }, + { + command: run === 'build' ? 'build' : 'serve', + mode: options.mode ?? 'test', + isSsrBuild: false, + isPreview: run === 'preview', + }, + ); + const logger = { warn: (message: string) => options.warnings?.push(message) }; + return () => (plugin.configResolved as (config: unknown) => void)({ logger }); +} + +function resetIntegrationOwner(): void { + Reflect.deleteProperty(globalThis, Symbol.for('vite-plus:dotenv-integration-owner')); +} + +function dotenvEntries(config: UserConfig): Array { + return (config.plugins ?? []).filter((plugin) => isDotenvEntry(plugin)); +} + +describe('validationGuardPlugin', () => { + it('fails a Vitest run or a preview when the last load reported errors', () => { + expect(resolveGuard({ varlockLastError: 'STRIPE_SECRET_KEY is required' })).toThrow( + 'The env config failed validation, so the tests did not run.', + ); + expect(resolveGuard({ varlockLoadedEnv: { errors: { STRIPE_SECRET_KEY: [] } } })).toThrow( + 'The env config failed validation', + ); + expect(resolveGuard({ varlockLastError: 'invalid' }, 'preview')).toThrow( + 'The env config failed validation, so the preview did not start.', + ); + }); + + it('lets a valid config run, and leaves `vp dev` to the error page', () => { + expect(resolveGuard({ varlockLoadedEnv: { config: {} } })).not.toThrow(); + expect(resolveGuard({ varlockLastError: 'invalid' }, 'dev')).not.toThrow(); + }); +}); + +function loadedAs(appEnv: string) { + return { varlockLoadedEnv: { config: { APP_ENV: { value: appEnv } } } }; +} + +describe('validationGuardPlugin mode check', () => { + let root: string; + + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-dotenv-mode-')); + fs.writeFileSync( + path.join(root, '.env.schema'), + '# @currentEnv=$APP_ENV\n# ---\nAPP_ENV=development\n', + ); + }); + + afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); + }); + + it('warns when a Vite mode does not match the varlock environment', () => { + const warnings: Array = []; + resolveGuard(loadedAs('development'), 'build', { + mode: 'staging', + schemaRoot: root, + warnings, + })(); + expect(warnings).toEqual([expect.stringContaining('or run `APP_ENV=staging vp build`')]); + }); + + it('warns for the default mode only when Vite would read .env.[mode]', () => { + const warnings: Array = []; + const build = { mode: 'production', schemaRoot: root, warnings }; + resolveGuard(loadedAs('development'), 'build', build)(); + expect(warnings).toEqual([]); + + fs.writeFileSync(path.join(root, '.env.production.local'), 'API_URL=https://example.com\n'); + resolveGuard(loadedAs('development'), 'build', { + ...build, + userEnv: { APP_ENV: 'development' }, + })(); + expect(warnings).toEqual([]); + resolveGuard(loadedAs('development'), 'build', build)(); + expect(warnings).toEqual([ + expect.stringContaining('Vite mode "production" does not select the varlock environment'), + ]); + }); + + it('stays quiet for a matching environment', () => { + const warnings: Array = []; + resolveGuard(loadedAs('staging'), 'build', { mode: 'staging', schemaRoot: root, warnings })(); + resolveGuard(loadedAs('test'), 'vitest', { mode: 'test', schemaRoot: root, warnings })(); + expect(warnings).toEqual([]); + }); +}); + +describe('clientEnvFilterPlugin', () => { + it('removes sensitive keys from import.meta.env and keeps public ones', () => { + const plugin = clientEnvFilterPlugin({ + varlockLoadedEnv: { + config: { VITE_SECRET: { isSensitive: true }, VITE_API_URL: { isSensitive: false } }, + }, + } as never); + const warnings: Array = []; + const env = { VITE_SECRET: 'sk_live', VITE_API_URL: 'https://api', MODE: 'development' }; + (plugin.configResolved as (config: unknown) => void)({ + env, + logger: { warn: (message: string) => warnings.push(message) }, + }); + expect(env).toEqual({ VITE_API_URL: 'https://api', MODE: 'development' }); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain( + 'Removed values that varlock treats as sensitive from import.meta.env: VITE_SECRET.', + ); + expect(warnings[0]).toContain('or when the schema does not declare it'); + }); + + it('stays quiet when no sensitive key reached the client env', () => { + const plugin = clientEnvFilterPlugin({ + varlockLoadedEnv: { config: { STRIPE_SECRET_KEY: { isSensitive: true } } }, + } as never); + const warnings: Array = []; + (plugin.configResolved as (config: unknown) => void)({ + env: { MODE: 'development' }, + logger: { warn: (message: string) => warnings.push(message) }, + }); + expect(warnings).toEqual([]); + }); +}); + +describe('defineConfig and dotenv entries', () => { + let root: string; + + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-dotenv-define-')); + fs.writeFileSync(path.join(root, '.env.schema'), ''); + vi.stubEnv(CONFIG_METADATA_ENV, undefined); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + fs.rmSync(root, { recursive: true, force: true }); + }); + + it('keeps one entry when defineConfig calls compose', () => { + expect(dotenvEntries(defineConfig({ root }))).toHaveLength(1); + expect(dotenvEntries(defineConfig(defineConfig({ root })))).toHaveLength(1); + }); + + it('adds a follower entry to independent projects of a root with a schema', () => { + const config = defineConfig({ + root, + test: { + projects: [{ extends: false, test: { name: 'browser' } }, { test: { name: 'inherited' } }], + }, + }); + const [independent, inherited] = config.test!.projects! as Array; + expect(dotenvEntries(independent)).toHaveLength(1); + expect(inherited.plugins).toBeUndefined(); + }); + + it('drops the entry when an outer defineConfig disables the schema', () => { + const config = defineConfig(mergeConfig(defineConfig({ root }), { dotenv: { schema: false } })); + expect(dotenvEntries(config)).toEqual([]); + }); +}); + +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: String.raw`C:\bin;C:\tools` }; + prependPathEntry(env, String.raw`C:\vp\.bin`, ';'); + prependPathEntry(env, String.raw`C:\vp\.bin`, ';'); + expect(env).toEqual({ Path: String.raw`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..8fa92d0fbd --- /dev/null +++ b/packages/cli/src/dotenv/bin.ts @@ -0,0 +1,190 @@ +// `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 { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; + +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, +} from './schema-header.ts'; +import type { VarlockPackage } from './varlock.ts'; +import { + buildVarlockInvocation, + DOTENV_SCHEMA_FILE, + formatCheckPassMessage, + hasDotenvSchema, + parseLoadOutput, + renderMaskedValues, + resolveVarlockPackage, + 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` + * dependency. The dependency written first only makes `varlock init` skip its + * own ` add varlock`, and `package.json` goes back to how it + * was. A new schema then uses `@generateVitePlusTypes` from + * `@plugin(vite-plus)`, and one load writes its types. + * + * A project without `vite-plus` in `node_modules` cannot load that plugin, and + * a project with its own `varlock` keeps its setup, so `varlock init` runs as + * it is for them. + */ +async function runInit(options: RunCommandOptions, varlock: VarlockPackage): Promise { + const { cwd } = options; + const originalManifest = hasVitePlusInstalled(cwd) + ? preseedVarlockDependency(cwd, varlock.version) + : undefined; + if (originalManifest === undefined) { + return (await runCommand(options)).exitCode; + } + const schemaFile = path.join(cwd, DOTENV_SCHEMA_FILE); + const hadSchema = fs.existsSync(schemaFile); + let exitCode: number; + try { + ({ exitCode } = await runCommand(options)); + } finally { + fs.writeFileSync(path.join(cwd, 'package.json'), originalManifest); + } + // varlock exits with code 0 on a cancelled prompt, so check for the schema too. + if (exitCode !== 0 || hadSchema || !fs.existsSync(schemaFile)) { + return exitCode; + } + const schema = fs.readFileSync(schemaFile, 'utf8'); + 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`. + spawnSync(options.command, [varlock.cli, 'load', '--format', 'json', '--agent'], { + cwd, + env: options.envs, + stdio: 'ignore', + }); + const prefixDefault = + adopted.includes("inferFromPrefix('VITE_')") && !schema.includes('inferFromPrefix') + ? " Only `VITE_*` variables are public by default (`@defaultSensitive=inferFromPrefix('VITE_')`), like in Vite." + : ''; + const modeEnvironment = + followsViteMode(adopted) && !followsViteMode(schema) + ? ' `APP_ENV` follows the Vite mode, so `vp build` loads `.env.production` as in Vite.' + : ''; + passMsg( + `Set up \`.env.schema\` to type \`ENV\` from \`vite-plus/dotenv\` with \`@plugin(vite-plus)\` and \`@generateVitePlusTypes\`.${prefixDefault}${modeEnvironment} The project needs no \`varlock\` dependency.`, + ); + } + return 0; +} + +async function main(): Promise { + const args = unwrapCliParseOutcome(parseDotenvArgs(process.argv.slice(3))); + const invocation = buildVarlockInvocation(args); + const cwd = process.cwd(); + + // 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, 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( + `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.`, + ); + return 1; + } + + let varlock: VarlockPackage; + try { + varlock = resolveVarlockPackage(); + } catch (error) { + errorMsg( + `Could not find the varlock package bundled with Vite+. Run \`vp install\` to restore dependencies.\n${error instanceof Error ? error.message : String(error)}`, + ); + return 1; + } + + const options = { + command: process.execPath, + args: [varlock.cli, ...invocation.argv], + cwd, + envs: withVarlockDefaults( + args.mode ? { ...process.env, [VITE_MODE_ENV]: args.mode } : process.env, + ), + forwardSignals: true, + }; + + if (invocation.output === 'inherit') { + if (args.command === 'init') { + return runInit(options, varlock); + } + return (await runCommand(options)).exitCode; + } + + const { exitCode, stdout } = await runCommandCapturingStdout(options); + if (exitCode !== 0) { + return exitCode; + } + const values = parseLoadOutput(stdout.toString('utf8')); + if (invocation.output === 'check') { + passMsg(formatCheckPassMessage(values)); + return 0; + } + if (!values) { + errorMsg('Could not read the resolved values from varlock.'); + return 1; + } + const rendered = renderMaskedValues(values, args.format); + if (rendered) { + // `log` goes through console, which ignores a closed pipe + // (`vp dotenv print | head -n 1`); a raw stdout write throws EPIPE. + log(rendered.endsWith('\n') ? rendered.slice(0, -1) : rendered); + } + 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/dependency.ts b/packages/cli/src/dotenv/dependency.ts new file mode 100644 index 0000000000..37dca7d6e8 --- /dev/null +++ b/packages/cli/src/dotenv/dependency.ts @@ -0,0 +1,49 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +import { editJsonFile } from '../utils/json.ts'; + +/** + * Add `varlock` at the version that Vite+ bundles to `dependencies`, before + * `varlock init` runs. Without it, `varlock init` runs ` add + * varlock`, which installs the latest release with a range. Returns the + * original `package.json` text, so the caller can restore it, or `undefined` + * when nothing changed. + */ +export function preseedVarlockDependency(projectDir: string, version: string): string | undefined { + const file = path.join(projectDir, 'package.json'); + if (!fs.existsSync(file)) { + return undefined; + } + const original = fs.readFileSync(file, 'utf8'); + let changed = false; + editJsonFile<{ dependencies?: Record }>(file, (manifest) => { + if (manifest.dependencies?.varlock) { + return undefined; + } + // Package managers keep `dependencies` sorted when they add one. + const entries = Object.entries({ ...manifest.dependencies, varlock: version }); + manifest.dependencies = Object.fromEntries(entries.toSorted(([a], [b]) => (a < b ? -1 : 1))); + changed = true; + return manifest; + }); + return changed ? original : undefined; +} + +/** + * Whether `vite-plus` is installed for `projectDir`, the way varlock resolves + * `@plugin(vite-plus)`: in `node_modules` of the directory or a parent. + */ +export function hasVitePlusInstalled(projectDir: string): boolean { + let dir = path.resolve(projectDir); + while (true) { + if (fs.existsSync(path.join(dir, 'node_modules', 'vite-plus', 'package.json'))) { + return true; + } + const parent = path.dirname(dir); + if (parent === dir) { + return false; + } + dir = parent; + } +} diff --git a/packages/cli/src/dotenv/integration.ts b/packages/cli/src/dotenv/integration.ts new file mode 100644 index 0000000000..14ea1d3f77 --- /dev/null +++ b/packages/cli/src/dotenv/integration.ts @@ -0,0 +1,79 @@ +// The environment that `@varlock/vite-integration` needs while it loads. + +import fs from 'node:fs'; +import path from 'node:path'; + +import { pkgRoot } from '../utils/path.ts'; + +/** + * 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; +} + +function pathKey(env: NodeJS.ProcessEnv): string { + return Object.keys(env).find((name) => name.toUpperCase() === 'PATH') ?? 'PATH'; +} + +export function prependPathEntry( + env: NodeJS.ProcessEnv, + dir: string, + delimiter: string = path.delimiter, +): void { + const key = pathKey(env); + const entries = (env[key] ?? '').split(delimiter).filter(Boolean); + if (!entries.includes(dir)) { + env[key] = [dir, ...entries].join(delimiter); + } +} + +function restoreEnv(key: string, value: string | undefined): void { + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } +} + +/** + * Change `process.env` for the import of the varlock Vite integration, and + * return a function that undoes the changes. The integration loads the schema + * when it is imported, copies `process.env` at that time, and passes that copy + * to every varlock CLI call. Undo the changes right after the import, so that + * they do not reach other child processes: + * + * - varlock telemetry is off unless the user set it. + * - The 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 vite-plus's own bin directory goes first + * on PATH. + * + * The varlock runtime also copies `process.env` when `varlock/env` first + * loads, and writes that copy back on every later reload (a dev restart, or a + * Vite root that differs from the working directory). Load `varlock/env` + * before this call, so that the copy holds the user's own PATH, not the + * changed one. The copy lives on `globalThis`, so the first load wins for + * every copy of the module. + */ +export function setVarlockIntegrationEnv(): () => void { + const key = pathKey(process.env); + const savedPath = process.env[key]; + const savedTelemetry = process.env.VARLOCK_TELEMETRY_DISABLED; + process.env.VARLOCK_TELEMETRY_DISABLED ??= '1'; + const binDir = findDependencyBinDir(pkgRoot, 'varlock'); + if (binDir) { + prependPathEntry(process.env, binDir); + } + return () => { + restoreEnv(key, savedPath); + restoreEnv('VARLOCK_TELEMETRY_DISABLED', savedTelemetry); + }; +} diff --git a/packages/cli/src/dotenv/schema-header.ts b/packages/cli/src/dotenv/schema-header.ts new file mode 100644 index 0000000000..6b64912701 --- /dev/null +++ b/packages/cli/src/dotenv/schema-header.ts @@ -0,0 +1,290 @@ +// Text helpers for the `.env.schema` header: the comment blocks with the root +// decorators before the first item. + +// 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/; +const CURRENT_ENV_DECORATOR = /@currentEnv=\$([A-Za-z_]\w*)\b/; +const ANY_CURRENT_ENV_DECORATOR = /@(?:currentEnv|envFlag)\b/; +const VITE_MODE_CALL = /\bviteMode\(\s*\)/; + +/** The variable through which `vp` passes the Vite mode to varlock. */ +export const VITE_MODE_ENV = 'VP_VITE_MODE'; +/** The name of the resolver function that reads `VITE_MODE_ENV` in the schema. */ +export const VITE_MODE_FUNCTION = 'viteMode'; + +/** The environment variable that `vp dotenv init` adds. */ +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 header = findHeader(schema); + return header === undefined ? undefined : schema.slice(0, header.end); +} + +/** + * Replace `@generateTsTypes(...)` in the header with `@plugin(vite-plus) + * @generateVitePlusTypes(...)` and the same options, so that the generated + * types also apply to `ENV` from `vite-plus/dotenv`. `defaultImportMetaEnv` + * sets `importMetaEnv` when the options do not. A schema without a header + * stays unchanged. + */ +export function adoptVitePlusTypeGenerator(schema: string, defaultImportMetaEnv?: string): string { + const header = schemaHeader(schema); + if (header === undefined) { + return schema; + } + const rewritten = header.replace(TS_TYPES_DECORATOR, (_match, args: string) => { + const options = args.trim() ? args : ''; + const withImportMeta = + defaultImportMetaEnv === undefined || /\bimportMetaEnv\s*=/.test(options) + ? options + : [options, `importMetaEnv=${defaultImportMetaEnv}`].filter(Boolean).join(', '); + const pluginDecorator = VITE_PLUS_PLUGIN_DECORATOR.test(header) ? '' : '@plugin(vite-plus) '; + return `${pluginDecorator}@generateVitePlusTypes(${withImportMeta})`; + }); + return rewritten + schema.slice(header.length); +} + +/** + * Adapt the header that `varlock init` writes to a Vite+ project: + * + * - `@generateTsTypes(...)` becomes `@plugin(vite-plus) + * @generateVitePlusTypes(...)` with the same options, plus + * `importMetaEnv=none`, because Vite exposes only `VITE_*` variables on + * `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, + options: { inferVitePrefix?: boolean } = {}, +): string { + const adopted = adoptVitePlusTypeGenerator(schema, 'none'); + const header = schemaHeader(adopted); + if (header === undefined || options.inferVitePrefix === false) { + return adopted; + } + return ( + header.replace(PUBLIC_BY_DEFAULT, "@defaultSensitive=inferFromPrefix('VITE_')") + + adopted.slice(header.length) + ); +} + +/** + * Add `@currentEnv=$APP_ENV` and an `APP_ENV` item that follows the Vite + * mode, so that `vp build` loads `.env.production` as Vite does. The item + * defaults to `viteMode()` and then to `development`, so a value from the + * environment or an env file still takes priority. `environments` are the + * names for the enum. `viteMode()` comes from `@plugin(vite-plus)`, so a + * schema without that decorator stays unchanged, like a schema without a + * header, or with `@currentEnv` or an `APP_ENV` item already. + */ +export function addModeEnvironment(schema: string, environments: ReadonlyArray): string { + const range = findHeader(schema); + const header = range === undefined ? '' : schema.slice(0, range.end); + if ( + range === undefined || + !VITE_PLUS_PLUGIN_DECORATOR.test(header) || + ANY_CURRENT_ENV_DECORATOR.test(header) || + new RegExp(`^${MODE_ENVIRONMENT_VARIABLE}=`, 'm').test(schema) + ) { + return schema; + } + const item = [ + '', + '', + '# The environment, which selects the .env.[env] files to load. It follows the', + '# Vite mode of vp dev, vp build, vp preview, and vp test (or their --mode).', + `# @public @type=enum(${environments.join(', ')})`, + `${MODE_ENVIRONMENT_VARIABLE}=fallback(${VITE_MODE_FUNCTION}(), development)`, + ].join('\n'); + return ( + `${schema.slice(0, range.commentsEnd)}\n# @currentEnv=$${MODE_ENVIRONMENT_VARIABLE}` + + schema.slice(range.commentsEnd, range.end) + + item + + schema.slice(range.end) + ); +} + +/** + * The environment names for the enum that `addModeEnvironment` writes: the + * default Vite modes, then the names of `.env.` and `.env..local` + * files among `fileNames`. + */ +export function environmentNames(fileNames: ReadonlyArray): Array { + const found = new Set(); + for (const fileName of fileNames) { + const name = /^\.env\.([\w-]+?)(?:\.local)?$/.exec(fileName)?.[1]; + if (name !== undefined && !NOT_ENVIRONMENTS.has(name)) { + found.add(name); + } + } + const defaults = ['development', 'production', 'test']; + return [...defaults, ...[...found].filter((name) => !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); +} + +/** + * The variable that `@currentEnv=$NAME` in the header names, or `undefined` + * when the header has no `@currentEnv` or computes it with a function. + */ +export function currentEnvVariable(schema: string): string | undefined { + const header = schemaHeader(schema); + return header === undefined ? undefined : CURRENT_ENV_DECORATOR.exec(header)?.[1]; +} + +export interface ModeCheck { + /** Vite's resolved mode. */ + mode: string; + /** The mode that Vite uses when none is given, for this command. */ + defaultMode: string; + /** The `vp` command, for the suggested command line. */ + command: string; + /** The variable that `@currentEnv` names, if any. */ + currentEnvVariable: string | undefined; + /** The value that varlock resolved for that variable. */ + currentEnvValue: string | undefined; + /** Whether the schema uses `viteMode()`. */ + followsMode: boolean; + /** Whether `.env.[mode]` or `.env.[mode].local` exists, which Vite would load. */ + modeFileExists: boolean; + /** Whether the user set the `@currentEnv` variable in the environment. */ + setInEnvironment: boolean; + /** The value of `VITE_MODE_ENV`, which `viteMode()` returns. */ + viteModeValue: string | undefined; +} + +/** + * The warning for a Vite mode that does not select the varlock environment. + * varlock picks `.env.[env]` files from the `@currentEnv` variable, and the + * values it resolves override the ones Vite reads from `.env.[mode]`. + * + * For the default mode of the command, it warns only when `.env.[mode]` + * exists, because Vite would read no other file, and not when the user set + * the variable in the environment for this run. + */ +export function modeMismatchWarning(check: ModeCheck): string | undefined { + const { mode, defaultMode, command, currentEnvVariable: variable, currentEnvValue } = check; + if (variable !== undefined && currentEnvValue === mode) { + return undefined; + } + if (mode === defaultMode && (!check.modeFileExists || check.setInEnvironment)) { + return undefined; + } + const ignored = `varlock does not load .env.${mode}, and its values override the ones Vite reads from that file`; + if (variable === undefined) { + return `Vite mode "${mode}" does not select an env file: .env.schema has no @currentEnv, so ${ignored}. To follow the Vite mode, add \`@currentEnv=$${MODE_ENVIRONMENT_VARIABLE}\` and \`${MODE_ENVIRONMENT_VARIABLE}=fallback(${VITE_MODE_FUNCTION}(), development)\` to .env.schema.`; + } + const current = currentEnvValue === undefined ? 'not set' : `"${currentEnvValue}"`; + if (check.followsMode) { + let reason: string; + if (check.setInEnvironment) { + reason = `${variable} is ${current} in the environment, which takes priority over ${VITE_MODE_FUNCTION}()`; + } else if (check.viteModeValue === undefined) { + reason = `${VITE_MODE_FUNCTION}() returns nothing, because Vite did not start through vp dev, vp build, vp preview, or vp test`; + } else if (check.viteModeValue === mode) { + reason = `${variable} is ${current} from an env file or an earlier source in .env.schema, which takes priority over ${VITE_MODE_FUNCTION}()`; + } else { + reason = `${VITE_MODE_FUNCTION}() returns "${check.viteModeValue}" from the command line, and \`mode\` in vite.config.ts does not change it`; + } + return `Vite mode "${mode}" does not select the varlock environment: ${reason}, so ${ignored}.`; + } + return `Vite mode "${mode}" does not select the varlock environment: ${variable} is ${current}, so ${ignored}. To follow the Vite mode, set \`${variable}=fallback(${VITE_MODE_FUNCTION}(), development)\` in .env.schema, or run \`${variable}=${mode} vp ${command}\`.`; +} diff --git a/packages/cli/src/dotenv/typegen.ts b/packages/cli/src/dotenv/typegen.ts new file mode 100644 index 0000000000..0d22fcd0d9 --- /dev/null +++ b/packages/cli/src/dotenv/typegen.ts @@ -0,0 +1,32 @@ +/** The module that Vite+ projects import `ENV` from. */ +export const VITE_PLUS_DOTENV_MODULE = 'vite-plus/dotenv'; + +const VARLOCK_ENV_BLOCK = /declare module 'varlock\/env' \{[\s\S]*?\n\}\n/; +const VARLOCK_ENV_IMPORT = "import { ENV as _ENV } from 'varlock/env';"; + +/** + * Make the output of varlock's `@generateTsTypes` generator type + * `vite-plus/dotenv` too. + * + * - With `exposeEnv=global` (the default), add a copy of the `varlock/env` + * augmentation for `vite-plus/dotenv`. TypeScript merges it into varlock's + * interfaces through the re-export, so `ENV` is typed without a direct + * `varlock` dependency. The `varlock/env` block stays for code that imports + * from there. + * - With `exposeEnv=local`, import the runtime `ENV` from `vite-plus/dotenv`. + * + * Other output stays unchanged. + */ +export function addVitePlusDotenvTypes(source: string): string { + const block = VARLOCK_ENV_BLOCK.exec(source)?.[0]; + if (block === undefined) { + return source.replace(VARLOCK_ENV_IMPORT, () => + VARLOCK_ENV_IMPORT.replace('varlock/env', VITE_PLUS_DOTENV_MODULE), + ); + } + if (source.includes(`declare module '${VITE_PLUS_DOTENV_MODULE}'`)) { + return source; + } + const copy = block.replace("'varlock/env'", `'${VITE_PLUS_DOTENV_MODULE}'`); + return source.replace(block, () => `${block}\n${copy}`); +} diff --git a/packages/cli/src/dotenv/varlock-plugin.ts b/packages/cli/src/dotenv/varlock-plugin.ts new file mode 100644 index 0000000000..f34fc43526 --- /dev/null +++ b/packages/cli/src/dotenv/varlock-plugin.ts @@ -0,0 +1,39 @@ +// The varlock plugin that `@plugin(vite-plus)` loads through the `./plugin` +// export. It is built as one CommonJS file: varlock runs it with its own +// `varlock/plugin-lib`, so it works with the varlock copy that loads it. + +import type { CodeGenContext } from 'varlock/plugin-lib'; +import { plugin } from 'varlock/plugin-lib'; + +import { VITE_MODE_ENV, VITE_MODE_FUNCTION } from './schema-header.ts'; +import { addVitePlusDotenvTypes } from './typegen.ts'; + +/** + * `@generateVitePlusTypes` takes the options of `@generateTsTypes`. It runs + * varlock's own TypeScript generator, then adds types for `vite-plus/dotenv`, + * so varlock writes the final file itself on every load. + */ +plugin.registerCodeGenerator({ + decoratorName: 'generateVitePlusTypes', + async generate(ctx: CodeGenContext) { + const typescript = ctx.graph.codeGeneratorsRegistry.generateTsTypes; + if (typescript === undefined) { + throw new Error('This varlock version has no built-in @generateTsTypes generator.'); + } + return addVitePlusDotenvTypes(await typescript.generate(ctx)); + }, +}); + +/** + * `viteMode()` resolves to the Vite mode of the `vp dev`, `vp build`, + * `vp preview`, or `vp test` command that loads the schema, and to nothing + * outside them. `APP_ENV=fallback(viteMode(), development)` then selects the + * environment from the mode, below values from the environment and env files. + */ +plugin.registerResolverFunction({ + name: VITE_MODE_FUNCTION, + description: 'The Vite mode of the vp command that loads the schema', + resolve() { + return process.env[VITE_MODE_ENV] || undefined; + }, +}); diff --git a/packages/cli/src/dotenv/varlock.ts b/packages/cli/src/dotenv/varlock.ts new file mode 100644 index 0000000000..bb6094fc8d --- /dev/null +++ b/packages/cli/src/dotenv/varlock.ts @@ -0,0 +1,282 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +import type { DotenvArgs } from '../../binding/index.js'; +import { resolveBundled } from '../utils/constants.ts'; +import type { JsonObject, JsonValue } from '../utils/json-value.ts'; +import { isObjectValue, parseJsonObject, parseJsonValue } from '../utils/json-value.ts'; + +export type DotenvFormat = 'env' | 'json' | 'shell'; + +// This module is part of the config graph that `defineConfig` loads, so it +// reads JSON without `utils/json.ts`, which pulls in `jsonc-parser`. +function readJsonObject(file: string): JsonObject { + return parseJsonObject(fs.readFileSync(file, 'utf8'), file); +} + +export const DOTENV_SCHEMA_FILE = '.env.schema'; + +/** + * Whether varlock has a schema to load in `root`: a `.env.schema` file, or a + * `varlock.loadPath` in `package.json`, which varlock reads from the working + * directory. + */ +export function hasDotenvSchema(root: string): boolean { + if (fs.existsSync(path.join(root, DOTENV_SCHEMA_FILE))) { + return true; + } + try { + const config = readJsonObject(path.join(root, 'package.json')).varlock; + return isObjectValue(config) && Boolean(config.loadPath); + } catch { + return false; + } +} + +/** + * 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: Array; + output: VarlockOutputMode; +} + +function envArgs(env: string | undefined | null): Array { + return env ? ['--env', env] : []; +} + +export function buildVarlockInvocation(args: DotenvArgs): VarlockInvocation { + switch (args.command) { + case 'init': + // `--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-full', '--compact', '--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' }; + 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' }; + 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)}`); + } + } +} + +const SAFE_VALUE = /^[\w@%+=:,./-]*$/; + +function stringifyValue(value: JsonValue | undefined): string { + if (typeof value === 'string') { + return value; + } + if (typeof value === 'number' || typeof value === 'boolean') { + return String(value); + } + if (value === null || value === undefined) { + return ''; + } + return JSON.stringify(value) ?? ''; +} + +function quoteEnvValue(value: string): string { + if (SAFE_VALUE.test(value)) { + return value; + } + // Single quotes are literal in dotenv files: no `$` expansion and no escapes. + if (!/['\n\r]/.test(value)) { + return `'${value}'`; + } + const escaped = value + .replaceAll('\\', String.raw`\\`) + .replaceAll('"', String.raw`\"`) + .replaceAll('\n', String.raw`\n`) + .replaceAll('\r', String.raw`\r`); + 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: JsonObject, 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` : ''; +} + +function tryParseJsonObject(text: string): JsonObject | undefined { + try { + const parsed = parseJsonValue(text); + return isObjectValue(parsed) ? parsed : undefined; + } catch { + return undefined; + } +} + +/** + * Parse the JSON object that `varlock load --format json` prints. varlock may + * write other lines (such as plugin warnings) to stdout before or after it. + */ +export function parseLoadOutput(stdout: string): JsonObject | undefined { + const whole = tryParseJsonObject(stdout); + if (whole) { + return whole; + } + const lines = stdout.split(/\r?\n/); + const first = lines.findIndex((line) => line.startsWith('{')); + if (first === -1) { + return undefined; + } + for (let end = lines.length; end > first; end--) { + const parsed = tryParseJsonObject(lines.slice(first, end).join('\n')); + if (parsed) { + return parsed; + } + } + return undefined; +} + +/** + * 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 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`. */ +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 (readJsonObject(manifest).name === name) { + return dir; + } + } catch { + // Not a readable manifest; keep walking. + } + } + const parent = path.dirname(dir); + if (parent === dir) { + return undefined; + } + dir = parent; + } +} + +/** + * The bundled varlock package: its CLI script and its version. + * + * varlock does not export `./package.json`, so resolve a public entry and walk + * up to the package root. + */ +/** The bundled varlock CLI script and the version of its package. */ +export interface VarlockPackage { + cli: string; + version: string; +} + +export function resolveVarlockPackage(): VarlockPackage { + 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 = readJsonObject(path.join(root, 'package.json')); + const bins = manifest.bin; + const bin = typeof bins === 'string' ? bins : isObjectValue(bins) ? bins.varlock : undefined; + if (typeof bin !== 'string' || !bin) { + throw new Error(`Could not find the 'varlock' bin entry in ${root}/package.json`); + } + const version = typeof manifest.version === 'string' ? manifest.version : 'unknown'; + return { cli: path.join(root, bin), version }; +} + +/** Absolute path of the bundled varlock CLI script. */ +export function resolveVarlockCli(): string { + return resolveVarlockPackage().cli; +} + +/** 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. + */ diff --git a/packages/cli/src/dotenv/vite-plugin.ts b/packages/cli/src/dotenv/vite-plugin.ts new file mode 100644 index 0000000000..a9ce60759d --- /dev/null +++ b/packages/cli/src/dotenv/vite-plugin.ts @@ -0,0 +1,563 @@ +import type { SpawnSyncReturns } from 'node:child_process'; +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; + +import type { + varlockLastError, + varlockLoadedEnv, + varlockVitePlugin, +} from '@varlock/vite-integration'; +import type { ConfigEnv, Plugin, PluginOption, UserConfig } from 'vite'; + +import { CONFIG_METADATA_ENV } from '../utils/constants.ts'; +import { pkgRoot } from '../utils/path.ts'; +import { setVarlockIntegrationEnv } from './integration.ts'; +import type { ModeCheck } from './schema-header.ts'; +import { + currentEnvVariable, + followsViteMode, + modeMismatchWarning, + VITE_MODE_ENV, +} from './schema-header.ts'; +import { + DOTENV_SCHEMA_FILE, + hasDotenvSchema, + 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; +} + +const VITE_PLUS_DOTENV = 'vite-plus/dotenv'; +const VARLOCK_IMPORT = /^(?:varlock(?:\/|$)|vite-plus\/dotenv$)/; + +/** Resolving from vite-plus's own manifest reaches its direct dependencies under pnpm. */ +const VITE_PLUS_ANCHOR = path.join(pkgRoot, 'package.json'); + +/** The parts of `@varlock/vite-integration` that Vite+ uses. */ +interface VarlockIntegration { + varlockLastError: typeof varlockLastError; + varlockLoadedEnv: typeof varlockLoadedEnv; + varlockVitePlugin: typeof varlockVitePlugin; +} +let varlockIntegration: Promise | undefined; + +/** + * Import the varlock Vite integration with the environment it needs (see + * `setVarlockIntegrationEnv`). A config file that reads `ENV` from + * `vite-plus/dotenv` may have loaded it already (`dotenv-node.ts`). + */ +async function importVarlockIntegration(): Promise { + await import('varlock/env'); + const restoreEnv = setVarlockIntegrationEnv(); + try { + return await import('@varlock/vite-integration'); + } finally { + restoreEnv(); + } +} + +/** + * The dotenv plugin group that owns each config resolution. Vite passes the + * same `ConfigEnv` object to every plugin's `apply` during one resolution, so + * the first group claims it and later copies stay out. Copies appear when + * configs compose, for example `mergeConfig(defineConfig(a), defineConfig(b))`. + */ +/** One `defineConfig` call's dotenv plugins, and the schema root they load. */ +interface DotenvGroup { + schemaRoot: string; +} + +const resolutionOwners = new WeakMap(); + +function schemaConflict(first: string, second: string): Error { + return new Error( + `Two configs in one vp process load different ${DOTENV_SCHEMA_FILE} files: ${first} and ${second}. varlock keeps one loaded env per process, so the second would replace the values of the first. Use one schema at the workspace root (it can \`@import\` package files), or run vp separately in each package.`, + ); +} + +/** + * The first group to reach a resolution owns it. A later group with the same + * schema root is a copy from composed configs and stays out. A later group + * with another schema root comes from merged configs that detected different + * schemas, as in `mergeConfig(defineConfig(base), defineConfig(app))`, and the + * resolution fails instead of silently using the first schema. + */ +function claimResolution(env: ConfigEnv, group: DotenvGroup): boolean { + const owner = resolutionOwners.get(env); + if (owner === undefined) { + resolutionOwners.set(env, group); + return true; + } + if (owner === group) { + return true; + } + if (owner.schemaRoot !== group.schemaRoot) { + throw schemaConflict(owner.schemaRoot, group.schemaRoot); + } + return false; +} + +/** + * The schema root that the integration has loaded in this process. + * + * The integration keeps one loaded env in module state, and varlock's runtime + * env lives in `process.env` and on `globalThis`, so one process can hold one + * schema root. Kept on `globalThis`, so every vite-plus copy in the process + * sees the same owner. + */ +const INTEGRATION_OWNER = Symbol.for('vite-plus:dotenv-integration-owner'); + +function integrationOwner(): string | undefined { + const owner: unknown = Object.getOwnPropertyDescriptor(globalThis, INTEGRATION_OWNER)?.value; + return typeof owner === 'string' ? owner : undefined; +} + +/** + * Claim the integration for `schemaRoot`. A config that Vite or Vitest + * evaluates again (a dev restart, or Vitest loading the parent config for an + * inline project) has the same schema root. A config with a different schema + * root would mix the two schemas' values, so the resolution fails. + */ +function claimIntegration(schemaRoot: string): void { + const owner = integrationOwner(); + if (owner === undefined) { + Reflect.set(globalThis, INTEGRATION_OWNER, schemaRoot); + return; + } + if (owner !== schemaRoot) { + throw schemaConflict(owner, schemaRoot); + } +} + +interface GateOptions { + /** Whether the merged dotenv options keep this plugin on. */ + enabled?: (options: DotenvOptions) => boolean; + /** Claim the process-wide schema root when the plugin applies. */ + claimProcess?: boolean; +} + +/** + * Include `plugin` only for the group that owns the resolution, and only when + * the merged config, which `apply` receives, keeps the feature on. The plugin + * is changed in place: copies would lose properties that other tools read. + */ +export function gateDotenvPlugin( + plugin: Plugin, + group: DotenvGroup, + { enabled = () => true, claimProcess = false }: GateOptions = {}, +): Plugin { + const original = plugin.apply; + plugin.apply = (config, env) => { + const options = config.dotenv ?? {}; + if (options.schema === false || !enabled(options) || !claimResolution(env, group)) { + return false; + } + if (claimProcess) { + claimIntegration(group.schemaRoot); + } + if (typeof original === 'function') { + return original(config, env); + } + return original === undefined || original === env.command; + }; + return plugin; +} + +/** + * Resolve `varlock`, `varlock/*`, and `vite-plus/dotenv` to the varlock that + * vite-plus depends on, 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. + * - `vite-plus/dotenv` re-exports `varlock/env`. Resolving it to the same module + * keeps one varlock runtime per environment, the one that the SSR init code + * initializes. + * - Server environments externalize dependencies and resolve them again from + * the importer at run time, which skips this hook. varlock is therefore + * bundled (`noExternal`) in server environments, so the server output does + * not import it at run time. + */ +export function varlockResolvePlugin(): Plugin { + return { + name: 'vite-plus:dotenv-resolve', + enforce: 'pre', + configEnvironment(name, config) { + if (name === 'client' || config.consumer === 'client') { + return undefined; + } + return { resolve: { noExternal: ['varlock'] } }; + }, + resolveId: { + filter: { id: VARLOCK_IMPORT }, + handler(source, _importer, options) { + const target = source === VITE_PLUS_DOTENV ? 'varlock/env' : source; + return this.resolve(target, VITE_PLUS_ANCHOR, { ...options, skipSelf: true }); + }, + }, + }; +} + +export function scanFailureMessage( + result: Pick, 'status' | 'signal' | 'error'>, + target: string, +): string | undefined { + if (result.error) { + return `Could not run \`varlock scan\` on ${target}: ${result.error.message}`; + } + if (result.signal) { + return `\`varlock scan\` on ${target} was stopped by ${result.signal}.`; + } + if (result.status !== 0) { + return `\`varlock scan\` failed on ${target}: it found sensitive values from the env config, or it could not load the config. See its output above. To skip this check, set \`dotenv.scanBuildOutput: false\` in vite.config.ts.`; + } + return undefined; +} + +/** + * `varlock scan` resolves the schema from its working directory, so it runs in + * the schema root, which can differ from the Vite root. + */ +function scanBuildOutputPlugin(schemaRoot: string): Plugin { + 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', + 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(schemaRoot, outDir) || '.'; + // Build output is usually git-ignored, which `varlock scan` skips by default. + const result = spawnSync( + process.execPath, + [resolveVarlockCli(), 'scan', '--include-ignored', target], + { cwd: schemaRoot, env: withVarlockDefaults(process.env), stdio: 'inherit' }, + ); + const message = scanFailureMessage(result, target); + if (message) { + this.error(message); + } + }, + }, + }; +} + +/** The integration's exported load state: live bindings of its last load. */ +interface VarlockLoadState { + varlockLastError: VarlockIntegration['varlockLastError']; + /** Undefined when no load has printed JSON yet. */ + varlockLoadedEnv: VarlockIntegration['varlockLoadedEnv'] | undefined; +} + +/** The resolved value of `variable`, as text. */ +function loadedValue(state: VarlockLoadState, variable: string): string | undefined { + const value: unknown = state.varlockLoadedEnv?.config[variable]?.value; + if (typeof value === 'string') { + return value; + } + return typeof value === 'number' || typeof value === 'boolean' ? String(value) : undefined; +} + +/** + * Stop `vp test` and `vp preview` when the env config is invalid. Vite + * resolves both with `command: 'serve'`, and for `serve` the integration only + * installs a dev-server error page instead of exiting. Preview never calls + * `configureServer`, and tests that never read the invalid value would pass. + * + * Also warn when the Vite mode does not select the varlock environment: + * varlock picks `.env.[env]` files from its `@currentEnv` variable, and its + * values override Vite's `.env.[mode]` files (see `modeMismatchWarning`). + * `userEnv` returns the environment before varlock added resolved values. + * + * The checks run in `configResolved`, after the integration's `config` hook + * has loaded the schema. `configureVitest` would not run for a root config + * that only lists file-based projects, because Vitest calls it for runnable + * projects only. + */ +export function validationGuardPlugin( + state: VarlockLoadState, + schemaRoot: string, + userEnv: () => NodeJS.ProcessEnv = () => process.env, +): Plugin { + let blocked: 'tests' | 'preview' | undefined; + let modeCommand: Pick | undefined; + return { + name: 'vite-plus:dotenv-validation', + config: { + order: 'post', + handler(config, { command, isPreview, mode }) { + // Vitest adds this environment before post config hooks; `vp dev` keeps + // the integration's error page instead. + const vitest = command === 'serve' && config.environments?.['__vitest__'] !== undefined; + if (isPreview) { + blocked = 'preview'; + modeCommand = { mode, defaultMode: 'production', command: 'preview' }; + } else if (vitest) { + blocked = 'tests'; + modeCommand = { mode, defaultMode: 'test', command: 'test' }; + } else { + blocked = undefined; + modeCommand = + command === 'build' + ? { mode, defaultMode: 'production', command: 'build' } + : { mode, defaultMode: 'development', command: 'dev' }; + } + }, + }, + configResolved(config) { + const loaded = state.varlockLoadedEnv as { errors?: unknown } | undefined; + if (blocked && (state.varlockLastError !== undefined || loaded?.errors)) { + const outcome = blocked === 'tests' ? 'the tests did not run' : 'the preview did not start'; + throw new Error( + `The env config failed validation, so ${outcome}. Fix the varlock errors above, or set \`dotenv.schema: false\` in vite.config.ts.`, + ); + } + if (modeCommand === undefined) { + return; + } + // A schema at `varlock.loadPath` is not read here, so its header is unknown. + const schemaFile = path.join(schemaRoot, DOTENV_SCHEMA_FILE); + if (!fs.existsSync(schemaFile)) { + return; + } + const schema = fs.readFileSync(schemaFile, 'utf8'); + const variable = currentEnvVariable(schema); + const { mode } = modeCommand; + const warning = modeMismatchWarning({ + ...modeCommand, + currentEnvVariable: variable, + currentEnvValue: variable === undefined ? undefined : loadedValue(state, variable), + followsMode: followsViteMode(schema), + modeFileExists: [`.env.${mode}`, `.env.${mode}.local`].some((file) => + fs.existsSync(path.join(schemaRoot, file)), + ), + setInEnvironment: variable !== undefined && userEnv()[variable] !== undefined, + viteModeValue: userEnv()[VITE_MODE_ENV], + }); + if (warning !== undefined) { + config.logger.warn(warning, { timestamp: true }); + } + }, + }; +} + +/** + * Remove sensitive values from Vite's client env. + * + * varlock writes every resolved value into `process.env`, sensitive ones + * included, and Vite's `loadEnv` copies each `process.env` key with an env + * prefix (`VITE_`) into `config.env`, which becomes `import.meta.env` in the + * browser. A value that only varlock knows, such as a decrypted or + * secret-manager value, would then reach client code in `vp dev`. The keys are + * removed in `configResolved`, after the integration has loaded the schema + * and before Vite builds `import.meta.env`. + */ +export function clientEnvFilterPlugin(state: VarlockLoadState): Plugin { + return { + name: 'vite-plus:dotenv-client-env', + configResolved(config) { + const items = state.varlockLoadedEnv?.config ?? {}; + const removed = Object.keys(items).filter( + (key) => items[key]?.isSensitive && Object.hasOwn(config.env, key), + ); + for (const key of removed) { + delete config.env[key]; + } + if (removed.length > 0) { + config.logger.warn( + `Removed values that varlock treats as sensitive from import.meta.env: ${removed.join(', ')}. A variable is sensitive when the schema marks it @sensitive, or when the schema does not declare it. Declare public VITE_* variables in .env.schema, and read sensitive ones in server code through ENV from vite-plus/dotenv.`, + { timestamp: true }, + ); + } + }, + }; +} + +/** + * `root` loads the schema for a root config. `follower` reuses the loaded + * schema in an independent Vitest project (a `defineProject` file or an + * `extends: false` project), which has its own Vite server without the root + * plugins: it gets the resolver, the `ENV` transforms, and the client env + * filter. Validation and the build-output scan stay with the root. + */ +function isPlugin(value: unknown): value is Plugin { + return ( + typeof value === 'object' && value !== null && 'name' in value && typeof value.name === 'string' + ); +} + +/** The plugins in a nested plugin list. The integration returns no promises. */ +function flattenPlugins(option: unknown): Array { + if (Array.isArray(option)) { + return option.flatMap((item: unknown) => flattenPlugins(item)); + } + return isPlugin(option) ? [option] : []; +} + +type GroupRole = 'root' | 'follower'; + +async function loadDotenvPlugins( + group: DotenvGroup, + role: GroupRole, +): Promise> { + // Importing the integration runs `varlock load` at once, so import it only + // when a schema is present. + varlockIntegration ??= importVarlockIntegration(); + const integration = await varlockIntegration; + const { getPreInjectionProcessEnv } = await import('varlock/env'); + // The integration reloads whenever `rootDir ?? config.root` differs from the + // root it loaded. Vitest projects change `root` in ways `defineConfig` cannot + // see, and a reload would replace the env of every project, so the + // integration stays on the root where the schema was detected. + const varlockPlugins = flattenPlugins( + integration.varlockVitePlugin({ rootDir: group.schemaRoot }), + ); + const shared = [ + gateDotenvPlugin(varlockResolvePlugin(), group), + ...varlockPlugins.map((plugin) => gateDotenvPlugin(plugin, group, { claimProcess: true })), + gateDotenvPlugin(clientEnvFilterPlugin(integration), group), + ]; + if (role === 'follower') { + return shared; + } + return [ + ...shared, + gateDotenvPlugin( + validationGuardPlugin(integration, group.schemaRoot, getPreInjectionProcessEnv), + group, + ), + gateDotenvPlugin(scanBuildOutputPlugin(group.schemaRoot), group, { + enabled: (options) => options.scanBuildOutput !== false, + }), + ]; +} + +const DOTENV_ENTRY = Symbol.for('vite-plus:dotenv-entry'); +const REQUIRE_SCHEMA_PLUGIN_NAME = 'vite-plus:dotenv-require-schema'; + +/** + * A plugin entry that starts loading only when Vite awaits it. `defineConfig` + * strips older entries (`isDotenvEntry`) before it decides, so a config that + * an outer `defineConfig` disables, as in + * `defineConfig(mergeConfig(defineConfig(base), { dotenv: { schema: false } }))`, + * never imports the integration. + */ +function lazyDotenvEntry(group: DotenvGroup, role: GroupRole): PluginOption { + let loading: Promise> | undefined; + const load = () => (loading ??= loadDotenvPlugins(group, role)); + // A promise in shape only: the import starts when Vite awaits the entry. + const entry: Promise> & { [DOTENV_ENTRY]: true } = { + [DOTENV_ENTRY]: true, + [Symbol.toStringTag]: 'Promise', + // oxlint-disable-next-line unicorn/no-thenable -- Vite awaits plugin entries; a thenable defers the import until then. + then: (onFulfilled, onRejected) => load().then(onFulfilled, onRejected), + catch: (onRejected) => load().catch(onRejected), + finally: (onFinally) => load().finally(onFinally), + }; + return entry; +} + +/** Whether `plugin` was added by `dotenvPlugins` for an earlier config. */ +export function isDotenvEntry(plugin: unknown): boolean { + if (typeof plugin !== 'object' || plugin === null) { + return false; + } + return DOTENV_ENTRY in plugin || ('name' in plugin && plugin.name === REQUIRE_SCHEMA_PLUGIN_NAME); +} + +/** + * Fail the config resolution when the merged config sets `dotenv.schema: true` + * and no schema was loaded. + * + * `defineConfig` runs before Vite applies a root given on the command line + * (`vp build app`), so the error checks the final root and says so when only + * that root has a schema. Vite awaits plugin promises before it calls + * `apply`, so the check must not be a rejected promise, or a later + * `dotenv.schema: false` could not win. + */ +export function requireSchemaPlugin(detectedRoot: string): Plugin { + return { + name: REQUIRE_SCHEMA_PLUGIN_NAME, + apply: (config) => config.dotenv?.schema === true, + configResolved(config) { + const finalRoot = path.resolve(config.root); + if (finalRoot !== detectedRoot && hasDotenvSchema(finalRoot)) { + throw new Error( + `\`dotenv.schema\` is true, and ${finalRoot} has a schema, but it was not loaded. Vite+ looks for ${DOTENV_SCHEMA_FILE} in the \`root\` of vite.config.ts or the working directory (${detectedRoot}), not in a root given on the command line. Run vp from ${finalRoot}, or use \`vp -C \`.`, + ); + } + throw new Error( + `\`dotenv.schema\` is true, but ${finalRoot} has no ${DOTENV_SCHEMA_FILE} and its package.json sets no \`varlock.loadPath\`. Run \`vp dotenv init\` to create one.`, + ); + }, + }; +} + +/** + * The schema root that a root config loads, or `undefined` when it loads none. + * + * Detection uses the config's `root` or the working directory. A root given on + * the command line (`vp dev ./app`) is applied later by Vite and is not seen. + */ +export function detectSchemaRoot(config: UserConfig): string | undefined { + if (process.env[CONFIG_METADATA_ENV] === '1' || config.dotenv?.schema === false) { + return undefined; + } + const root = path.resolve(config.root ?? process.cwd()); + return hasDotenvSchema(root) ? root : undefined; +} + +/** The plugins that load `.env.schema` for a root Vite config, or none. */ +export function dotenvPlugins(config: UserConfig): Array { + if (process.env[CONFIG_METADATA_ENV] === '1' || config.dotenv?.schema === false) { + return []; + } + const schemaRoot = detectSchemaRoot(config); + if (schemaRoot === undefined) { + return config.dotenv?.schema === true + ? [requireSchemaPlugin(path.resolve(config.root ?? process.cwd()))] + : []; + } + return [lazyDotenvEntry({ schemaRoot }, 'root')]; +} + +/** + * The plugins that reuse a loaded schema in an independent Vitest project, or + * none. `enclosingSchemaRoot` is the schema of the root config that declares + * an inline project. A `defineProject` file is loaded after the root config + * has claimed its schema, so it uses the process-wide owner. + */ +export function dotenvProjectPlugins( + config: UserConfig, + enclosingSchemaRoot?: string, +): Array { + if (process.env[CONFIG_METADATA_ENV] === '1' || config.dotenv?.schema === false) { + return []; + } + const schemaRoot = enclosingSchemaRoot ?? integrationOwner(); + return schemaRoot === undefined ? [] : [lazyDotenvEntry({ schemaRoot }, 'follower')]; +} diff --git a/packages/cli/src/migration/__tests__/varlock.spec.ts b/packages/cli/src/migration/__tests__/varlock.spec.ts new file mode 100644 index 0000000000..0913631034 --- /dev/null +++ b/packages/cli/src/migration/__tests__/varlock.spec.ts @@ -0,0 +1,265 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import type { log as promptLog } from '@voidzero-dev/vite-plus-prompts'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { resolveVarlockPackage } from '../../dotenv/varlock.ts'; +import type { JsonObject } from '../../utils/json.ts'; +import { readJsonFile } from '../../utils/json.ts'; + +vi.mock('@voidzero-dev/vite-plus-prompts', () => ({ + log: { + info: vi.fn(), + success: vi.fn(), + warn: vi.fn(), + }, +})); + +import { + detectVarlockProject, + migrateVarlockToVitePlus, + removeVarlockVitePlugin, +} from '../migrator/varlock.ts'; +import { createMigrationReport } from '../report.ts'; + +const VITE_CONFIG = `import { defineConfig } from 'vite'; +import react from '@vitejs/plugin-react'; +import { varlockVitePlugin } from '@varlock/vite-integration'; + +export default defineConfig({ + plugins: [ + react(), + varlockVitePlugin(), + ], +}); +`; + +describe('removeVarlockVitePlugin', () => { + it('removes the plugin call and its import', () => { + expect(removeVarlockVitePlugin('vite.config.ts', VITE_CONFIG)).toEqual({ + source: `import { defineConfig } from 'vite'; +import react from '@vitejs/plugin-react'; + +export default defineConfig({ + plugins: [ + react(), + ], +}); +`, + removed: 1, + kept: 0, + }); + }); + + it('keeps the list punctuation on one line', () => { + const imports = "import { varlockVitePlugin } from '@varlock/vite-integration';\n"; + expect( + removeVarlockVitePlugin( + 'a.ts', + `${imports}export default { plugins: [a(), varlockVitePlugin()] };\n`, + ).source, + ).toBe('export default { plugins: [a()] };\n'); + expect( + removeVarlockVitePlugin( + 'a.ts', + `${imports}export default { plugins: [varlockVitePlugin(), a()] };\n`, + ).source, + ).toBe('export default { plugins: [a()] };\n'); + expect( + removeVarlockVitePlugin( + 'a.ts', + `${imports}export default { plugins: [varlockVitePlugin()] };\n`, + ).source, + ).toBe('export default {};\n'); + }); + + it('removes the plugins property when no plugin is left', () => { + const source = `import { varlockVitePlugin } from '@varlock/vite-integration'; +export default defineConfig({ + plugins: [varlockVitePlugin()], + server: { port: 3000 }, +}); +`; + expect(removeVarlockVitePlugin('vite.config.ts', source).source).toBe( + 'export default defineConfig({\n server: { port: 3000 },\n});\n', + ); + }); + + it('follows an aliased import and keeps other imports from the package', () => { + const source = `import { varlockVitePlugin as varlock, buildErrorPageHtml } from '@varlock/vite-integration'; +export default { plugins: [varlock()], html: buildErrorPageHtml }; +`; + expect(removeVarlockVitePlugin('vite.config.ts', source).source).toBe( + `import { buildErrorPageHtml } from '@varlock/vite-integration'; +export default { html: buildErrorPageHtml }; +`, + ); + }); + + it('keeps a call with options and its import', () => { + const source = VITE_CONFIG.replace( + 'varlockVitePlugin()', + "varlockVitePlugin({ ssrInjectMode: 'resolved-env' })", + ); + expect(removeVarlockVitePlugin('vite.config.ts', source)).toEqual({ + source, + removed: 0, + kept: 1, + }); + }); +}); + +describe('migrateVarlockToVitePlus', () => { + let dir: string; + + function write(file: string, content: string): void { + fs.mkdirSync(path.dirname(path.join(dir, file)), { recursive: true }); + fs.writeFileSync(path.join(dir, file), content); + } + + function read(file: string): string { + return fs.readFileSync(path.join(dir, file), 'utf8'); + } + + function packageJson(extra: JsonObject = {}): void { + write( + 'package.json', + `${JSON.stringify( + { + name: 'app', + private: true, + dependencies: { varlock: '^1.20.0' }, + devDependencies: { '@varlock/vite-integration': '^1.5.0', vite: '^7.0.0' }, + ...extra, + }, + null, + 2, + )}\n`, + ); + } + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vp-migrate-varlock-')); + // `vp migrate` runs in the project, and its warnings name files relative to it. + vi.spyOn(process, 'cwd').mockReturnValue(dir); + packageJson(); + write('vite.config.ts', VITE_CONFIG); + write( + '.env.schema', + '# @defaultSensitive=false @currentEnv=$APP_ENV\n# @generateTsTypes(path=env.d.ts)\n# ---\nAPP_ENV=development\n', + ); + write('src/main.ts', 'console.log(import.meta.env.MODE);\n'); + }); + + afterEach(() => { + vi.restoreAllMocks(); + fs.rmSync(dir, { recursive: true, force: true }); + }); + + it('moves the setup to Vite+ and removes the varlock dependencies', () => { + expect(detectVarlockProject(dir)).toBe(true); + const report = createMigrationReport(); + + expect(migrateVarlockToVitePlus(dir, undefined, report)).toEqual({ + changed: true, + dependencyRemoved: true, + }); + + expect(read('vite.config.ts')).not.toContain('varlock'); + // The types also cover vite-plus/dotenv; sensitivity and environment stay as they were. + expect(read('.env.schema')).toBe( + '# @defaultSensitive=false @currentEnv=$APP_ENV\n# @plugin(vite-plus) @generateVitePlusTypes(path=env.d.ts)\n# ---\nAPP_ENV=development\n', + ); + const pkg = readJsonFile(path.join(dir, 'package.json')); + expect(pkg).not.toHaveProperty('dependencies'); + expect(pkg).toMatchObject({ devDependencies: { vite: '^7.0.0' } }); + expect(report.varlockMigrated).toBe(true); + expect(report.warnings).toEqual([]); + expect(detectVarlockProject(dir)).toBe(false); + }); + + it('keeps varlock for code that imports it, but not for its generated types', () => { + write('src/env.ts', "export { ENV } from 'varlock/env';\n"); + write('env.d.ts', "import { ENV as _ENV } from 'varlock/env';\n"); + const report = createMigrationReport(); + + migrateVarlockToVitePlus(dir, undefined, report); + + const pkg = readJsonFile(path.join(dir, 'package.json')); + expect(pkg).toMatchObject({ dependencies: { varlock: '^1.20.0' } }); + expect(pkg.devDependencies).not.toHaveProperty('@varlock/vite-integration'); + expect(report.warnings).toEqual([ + `Kept the varlock dependency in package.json: src/env.ts still uses it. Keep it at ${resolveVarlockPackage().version}, the version that Vite+ bundles.`, + ]); + }); + + it('keeps varlock for a framework component that imports it', () => { + write('src/App.vue', "\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/packages/cli/src/utils/__tests__/command.spec.ts b/packages/cli/src/utils/__tests__/command.spec.ts index 3eb4bbb5ac..87c6087f1e 100644 --- a/packages/cli/src/utils/__tests__/command.spec.ts +++ b/packages/cli/src/utils/__tests__/command.spec.ts @@ -1,6 +1,11 @@ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; -import { runCommand, runCommandSilently } from '../command.ts'; +import { + forwardSignalsTo, + runCommand, + runCommandCapturingStdout, + runCommandSilently, +} from '../command.ts'; describe('command runners', () => { it('resolves with the child output when no timeout is set', async () => { @@ -63,4 +68,35 @@ describe('command runners', () => { expect(result.exitCode).toBe(132); }, ); + + it('captures stdout while stderr stays attached', async () => { + const result = await runCommandCapturingStdout({ + command: process.execPath, + args: ['-e', 'process.stdout.write("{}"); process.exit(2)'], + cwd: process.cwd(), + envs: process.env, + }); + expect(result.exitCode).toBe(2); + expect(result.stdout.toString()).toBe('{}'); + }); +}); + +function signalListenerCounts(): Array { + return (['SIGINT', 'SIGTERM', 'SIGHUP'] as const).map((signal) => process.listenerCount(signal)); +} + +describe('forwardSignalsTo', () => { + it('waits on SIGINT, forwards SIGTERM and SIGHUP, and removes its handlers', () => { + const before = signalListenerCounts(); + const child = { kill: vi.fn<(signal?: NodeJS.Signals | number) => boolean>(() => true) }; + + const stop = forwardSignalsTo(child); + process.emit('SIGINT', 'SIGINT'); + process.emit('SIGTERM', 'SIGTERM'); + process.emit('SIGHUP', 'SIGHUP'); + stop(); + + expect(child.kill.mock.calls).toEqual([['SIGTERM'], ['SIGHUP']]); + expect(signalListenerCounts()).toEqual(before); + }); }); diff --git a/packages/cli/src/utils/command.ts b/packages/cli/src/utils/command.ts index d9edc5d8e6..7302a70f88 100644 --- a/packages/cli/src/utils/command.ts +++ b/packages/cli/src/utils/command.ts @@ -1,3 +1,4 @@ +import type { ChildProcess } from 'node:child_process'; import { constants } from 'node:os'; import { fileURLToPath } from 'node:url'; @@ -13,6 +14,12 @@ export interface RunCommandOptions { * config worker executing a blocking plugin factory) hangs the caller forever. */ timeoutMs?: number; + /** + * Stay alive until the child exits: ignore SIGINT, which a terminal sends to + * the whole process group, and pass SIGTERM and SIGHUP on to the child. + * Without it, a supervisor that signals only this process orphans the child. + */ + forwardSignals?: boolean; } export interface ExecutionResult { @@ -102,17 +109,66 @@ export async function runCommandSilently(options: RunCommandOptions): Promise {}; + +/** Install the `forwardSignals` handlers for `child`. Returns the function that removes them. */ +export function forwardSignalsTo(child: Pick): () => void { + const forward = (signal: NodeJS.Signals) => { + child.kill(signal); + }; + process.on('SIGINT', ignoreSignal); + process.on('SIGTERM', forward); + process.on('SIGHUP', forward); + return () => { + process.off('SIGINT', ignoreSignal); + process.off('SIGTERM', forward); + process.off('SIGHUP', forward); + }; +} + export async function runCommand(options: RunCommandOptions): Promise { const child = spawn(options.command, options.args, { stdio: 'inherit', cwd: options.cwd, env: options.envs, }); + const stopForwarding = options.forwardSignals ? forwardSignalsTo(child) : undefined; return new Promise((resolve, reject) => { child.on('close', (code, signal) => { + stopForwarding?.(); resolve({ exitCode: exitCodeFromClose(code, signal) }); }); child.on('error', (err) => { + stopForwarding?.(); + reject(err); + }); + }); +} + +/** + * Capture stdout and keep stdin and stderr attached, so the child can still + * prompt (for example, a secret-manager sign-in) and report errors live. + */ +export async function runCommandCapturingStdout( + options: RunCommandOptions, +): Promise { + const child = spawn(options.command, options.args, { + stdio: ['inherit', 'pipe', 'inherit'], + cwd: options.cwd, + env: options.envs, + }); + const stopForwarding = options.forwardSignals ? forwardSignalsTo(child) : undefined; + return new Promise((resolve, reject) => { + const stdout: Array = []; + child.stdout?.on('data', (data: Buffer) => { + stdout.push(data); + }); + child.on('close', (code, signal) => { + stopForwarding?.(); + resolve({ exitCode: exitCodeFromClose(code, signal), stdout: Buffer.concat(stdout) }); + }); + child.on('error', (err) => { + stopForwarding?.(); 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..0cb03df9fa 100644 --- a/packages/cli/tsdown.config.ts +++ b/packages/cli/tsdown.config.ts @@ -70,6 +70,9 @@ export default defineConfig([ bin: './src/bin.ts', index: './src/index.ts', 'define-config': './src/define-config.ts', + dotenv: './src/dotenv.ts', + // `vite-plus/dotenv` under the `node` condition: loads the schema for config files. + 'dotenv-node': './src/dotenv-node.ts', fmt: './src/fmt.ts', lint: './src/lint.ts', 'lint-plugins': './src/lint-plugins.ts', @@ -85,6 +88,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