From 09afe01344115f5304e2d85ee7987e0d4b938073 Mon Sep 17 00:00:00 2001 From: Pete Bacon Darwin Date: Mon, 16 Nov 2026 13:12:49 +0000 Subject: [PATCH 1/3] feat: run native Vite and Vite+ commands --- .changeset/native-vite-fallback.md | 9 + docs/architecture.md | 35 ++ fixtures/vite-plugin-project/README.md | 6 +- fixtures/vite-plugin-project/package.json | 1 + fixtures/wrangler-bundler-project/README.md | 2 +- packages/cli/AGENTS.md | 2 +- packages/cli/README.md | 5 +- .../__tests__/commands/build/index.test.ts | 177 ++++++- .../__tests__/commands/deploy/index.test.ts | 46 ++ .../__tests__/commands/dev/discover.test.ts | 143 +++--- .../src/__tests__/commands/dev/index.test.ts | 451 +++++++++++++++--- .../dev/project-command-process.test.ts | 175 +++++++ .../src/__tests__/commands/dev/spawn.test.ts | 25 +- .../cli/src/__tests__/commands/init.test.ts | 15 + .../src/__tests__/commands/migrate.test.ts | 7 +- .../lib/autoconfig-migration.test.ts | 47 +- .../cli/src/__tests__/lib/process.test.ts | 87 ++++ packages/cli/src/commands/build/index.ts | 26 +- packages/cli/src/commands/dev/discover.ts | 16 +- packages/cli/src/commands/dev/impl.ts | 4 + packages/cli/src/commands/dev/index.ts | 5 + packages/cli/src/commands/dev/known-impls.ts | 29 +- packages/cli/src/commands/dev/spawn.ts | 20 +- packages/cli/src/lib/autoconfig.ts | 93 +++- packages/cli/src/lib/delegate.ts | 22 +- packages/cli/src/lib/process.ts | 45 +- packages/cli/src/lib/wrangler-migration.ts | 7 +- pnpm-lock.yaml | 3 + 28 files changed, 1244 insertions(+), 259 deletions(-) create mode 100644 .changeset/native-vite-fallback.md create mode 100644 packages/cli/src/__tests__/commands/dev/project-command-process.test.ts diff --git a/.changeset/native-vite-fallback.md b/.changeset/native-vite-fallback.md new file mode 100644 index 0000000000..c80de9aee0 --- /dev/null +++ b/.changeset/native-vite-fallback.md @@ -0,0 +1,9 @@ +--- +"cf": minor +--- + +Run Vite and Vite+ commands selected by autoconfig + +Stop requiring the experimental internal `cf-vite` executable from `@cloudflare/vite-plugin`. Autoconfig selects the project's installed Vite or Vite+ executable for dev, build, and workflows that build before deploying, including projects without a detected framework command. cf executes the returned commands with argument forwarding, plugin compatibility checks, and Preview context, while preserving Pages and unsupported project setup guards. Support framework dependencies installed in the application or hoisted within its workspace. Recognize an existing Cloudflare configuration before dependencies are installed, and provide install guidance when a development or build command cannot run. Let Vite evaluate dynamic configurations and custom config files, and suggest checking `cloudflare()` when a successful Vite build produces no Build Output. Keep the Vite plugin's binding defaults unchanged. To explicitly disable remote bindings, set `remoteBindings: false` in the plugin configuration; the internal delegate's `--local` flag is no longer available. + +Forward shutdown signals to the command tree, force termination on a repeated interrupt, and attempt synchronous cleanup when cf exits before its command. Preserve graceful shutdown through global-to-local cf delegation by avoiding duplicate terminal interrupts. On POSIX, also forward SIGHUP when the terminal closes. Cleanup cannot run when cf itself receives SIGKILL. diff --git a/docs/architecture.md b/docs/architecture.md index 7b47c4132e..9de78394fb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -391,6 +391,41 @@ delegated build, recording `--mode` and Preview context, before the command continues through the normal Build Output upload path. Without `[directory]`, these commands consume Build Output from a delegated build or `--prebuilt`. +Autoconfig owns the dev/build command choice, including Vite versus Vite+. +Autoconfig reports command-readiness problems as data so inspection can recognize +configured projects before dependencies are installed. cf raises those problems +before executing a development or build command. Autoconfig owns the minimum +Vite plugin version for auth-profile support (`>=2.0.0-beta.v.13 <3`). +Pages detection and migration checks take precedence over native fallbacks. +Other unsupported frameworks can use a native fallback after the project has +been configured for cf; their automatic setup restrictions still apply. +Autoconfig validates plugin compatibility for eligible cf projects that declare +the plugin. When neither framework command is detected, it returns the installed +native executable in `devCommand` / `buildCommand`. cf executes those commands using the same +argument forwarding, environment, signals, and exit handling as other framework +commands. Vite evaluates its own configuration, including dynamic plugin arrays +and custom config files. If a Vite build succeeds without Build Output, cf hints +that the Vite config should include `cloudflare()`. On POSIX, framework commands +run in a separate process group so +shutdown signals also reach tools started by launchers such as `vp`. Windows +keeps console Ctrl+C delivery and terminates the command tree for SIGTERM. +On POSIX, a second interrupt forces termination, and terminal closure forwards +SIGHUP. With inherited terminal streams, global-to-local cf delegation relies +on the terminal's SIGINT delivery to both CLIs, so one Ctrl+C does not trigger +escalation. Non-interactive delegation relays SIGINT, and SIGTERM is always relayed. +A synchronous exit hook makes a best-effort attempt to stop an active +command tree if cf exits before shutdown completes. SIGKILL of cf itself cannot +run cleanup; cf does not start a supervisor process. +Bare commands prepend autoconfig's ordered `nodeModulesPaths`, from the +application's `node_modules/.bin` through its validated workspace root, and retain +the inherited PATH. This supports hoisted workspace toolchains without adding +unrelated parent installations. The shared build +path supplies `CLOUDFLARE_PREVIEW_BUILD` for Preview deployments. Delegate discovery +is reserved for Wrangler, Python, and Rust implementations. Binding defaults +remain unchanged. To explicitly disable remote bindings, configure +`cloudflare({ remoteBindings: false })` in the Vite configuration; the internal +Vite delegate's `--local` flag is no longer available. + This keeps Worker-definition validation lazy: `cf dns records list` cannot fail merely because a binding field in the configured Worker is invalid. Loading account settings still evaluates the TypeScript module and default config diff --git a/fixtures/vite-plugin-project/README.md b/fixtures/vite-plugin-project/README.md index e12d55e578..7d5a9c8894 100644 --- a/fixtures/vite-plugin-project/README.md +++ b/fixtures/vite-plugin-project/README.md @@ -6,7 +6,7 @@ No automated test currently starts this fixture. ## Layout -- `package.json` declares the Vite plugin, Vite, Wrangler, and Workers types, and provides the `vp dev` script. +- `package.json` declares the Vite plugin, Vite, Vite+, Wrangler, and Workers types, and provides the `vp dev` script. - `vite.config.ts` registers `cloudflare()` and disables inspector-port and persisted-state behavior for the smoke session. - `cloudflare.config.ts`'s default export contains the Worker entrypoint, compatibility date, name, and `MY_VAR` text binding. Mode `test` produces `Test var`; other modes produce `Default var`. - `src/worker.ts` returns `MY_VAR` from `/var` and a JSON fixture description from Worker-handled paths. @@ -19,7 +19,7 @@ cf supplies `CLOUDFLARE_VITE_FORCE_BUILD_OUTPUT=true` to the detected Vite comma The fixture is included by the root `fixtures/*` workspace glob. Its committed dependencies are registry semver ranges, not environment-specific `link:` targets. A root `pnpm install` resolves them and creates the fixture-local package links expected by the tools. -The workspace aliases `vite` to Vite+ core, which provides no `vite` CLI. The root `vite-plus` dependency supplies the `vp` CLI used by the fixture script. +The workspace aliases `vite` to Vite+ core, which provides no `vite` CLI. The fixture declares `vite-plus` directly so autoconfig selects its `vp` CLI for `cf dev` as well as the fixture script. ## Running the dev script @@ -32,7 +32,7 @@ cd fixtures/vite-plugin-project pnpm dev ``` -Pass custom Vite arguments to the script, for example `pnpm dev --mode test`. The current autoconfig route used by `cf dev` delegates to `npx vite`; it does not yet use this fixture's `vp dev` script. +Pass custom Vite arguments to the script, for example `pnpm dev --mode test`. Alternatively, `cf dev` runs the project command selected by autoconfig and forwards the mode and server arguments, for example `cf dev --mode test`. The server prints its URL. Representative checks are: diff --git a/fixtures/vite-plugin-project/package.json b/fixtures/vite-plugin-project/package.json index 33e239f27e..35d5ec3b6b 100644 --- a/fixtures/vite-plugin-project/package.json +++ b/fixtures/vite-plugin-project/package.json @@ -10,6 +10,7 @@ "@cloudflare/workers-types": "5.20261116.1", "cf": "workspace:*", "vite": "catalog:", + "vite-plus": "catalog:", "wrangler": "4.163.0" } } diff --git a/fixtures/wrangler-bundler-project/README.md b/fixtures/wrangler-bundler-project/README.md index 118e5b0bb5..5b2b12d3d3 100644 --- a/fixtures/wrangler-bundler-project/README.md +++ b/fixtures/wrangler-bundler-project/README.md @@ -18,7 +18,7 @@ The current `cf-wrangler` delegate uses Wrangler's TypeScript configuration load The fixture is included by the root `fixtures/*` workspace glob. There are no environment-specific `link:` targets. -cf requires Wrangler 4.161.0 or newer for this delegate, shared authentication profile selection, and output contract. For an unpublished workers-sdk worktree, a temporary fixture-local link may be used instead, but no such link belongs to the committed fixture. The relevant upstream executable is `packages/wrangler/bin/cf-wrangler.js`. +cf requires Wrangler 4.163.0 or newer for this delegate, shared authentication profile selection, and output contract. For an unpublished workers-sdk worktree, a temporary fixture-local link may be used instead, but no such link belongs to the committed fixture. The relevant upstream executable is `packages/wrangler/bin/cf-wrangler.js`. ## Running through cf diff --git a/packages/cli/AGENTS.md b/packages/cli/AGENTS.md index 3721d36e4f..c37eea0a77 100644 --- a/packages/cli/AGENTS.md +++ b/packages/cli/AGENTS.md @@ -83,7 +83,7 @@ public AI Search endpoint, outside the platform API/SDK, and returns ranked JSON page metadata without authentication. Agents fetch returned URLs with `Accept: text/markdown` to read complete pages. -`auth`, `complete`, `dev`, `build`, `deploy`, `migrate`, `cli`, `schema`, and `tools` are root entries in `src/commands/hand-written.ts`, registered lazily by `src/index.ts`. `cf cli telemetry` is the telemetry-settings path. `cf migrate` uses `@cloudflare/codemods` to convert a Wrangler configuration to `cloudflare.config.ts` and report manual follow-up work. `cf dev` analyzes and, when needed, configures a project before running its canonical framework command, with an installed Cloudflare implementation as fallback. `cf build` follows the same routing and validates the resulting Build Output. `cf deploy`, `cf previews deploy`, and `cf workers versions create` accept an optional `[directory]` containing already-built, assets-only content and write it into Build Output without delegation; Preview output is marked with Preview context. The directory form reuses an optional source Worker config but rejects configured entrypoints and Containers, so server-side projects omit it and use the normal build path. Without the positional argument, these commands build first unless `--prebuilt` is passed, then read Build Output and call `@cloudflare/deploy-helpers`; Preview names use `--preview-name`, and version creation uploads without deploying. `cf workers triggers deploy` likewise builds by default or consumes `--prebuilt` Build Output, but only applies the configured triggers and does not accept an assets directory. Deploy-helper provisioning is enabled for supported bindings. +`auth`, `complete`, `dev`, `build`, `deploy`, `migrate`, `cli`, `schema`, and `tools` are root entries in `src/commands/hand-written.ts`, registered lazily by `src/index.ts`. `cf cli telemetry` is the telemetry-settings path. `cf migrate` uses `@cloudflare/codemods` to convert a Wrangler configuration to `cloudflare.config.ts` and report manual follow-up work. `cf dev` analyzes and, when needed, configures a project before running its canonical framework command, with an installed Cloudflare implementation as fallback. Autoconfig owns Vite/Vite+ command selection and plugin compatibility checks, including the minimum version for cf profiles and projects without a detected framework command. Vite evaluates its own configuration; cf adds a `cloudflare()` hint when a successful Vite build produces no Build Output. Execute its returned dev/build commands through the project command runner; reserve delegate discovery for Wrangler, Python, and Rust. Bare commands prepend autoconfig's ordered `nodeModulesPaths`: the application's `node_modules/.bin` and ancestor directories up to its validated workspace root. Inherited PATH remains available for ordinary project commands. `cf build` follows the same routing and validates the resulting Build Output. `cf deploy`, `cf previews deploy`, and `cf workers versions create` accept an optional `[directory]` containing already-built, assets-only content and write it into Build Output without delegation; Preview output is marked with Preview context. The directory form reuses an optional source Worker config but rejects configured entrypoints and Containers, so server-side projects omit it and use the normal build path. Without the positional argument, these commands build first unless `--prebuilt` is passed, then read Build Output and call `@cloudflare/deploy-helpers`; Preview names use `--preview-name`, and version creation uploads without deploying. `cf workers triggers deploy` likewise builds by default or consumes `--prebuilt` Build Output, but only applies the configured triggers and does not accept an assets directory. Deploy-helper provisioning is enabled for supported bindings. `previews` uses a generated group containing the hand-written `previews deploy` workflow. Its parent override opts into `createIfMissing`, so generation creates an empty API parent when the pinned schema has no Preview CLI operations. Future schema operations join the same group without colliding with a hand-written root. diff --git a/packages/cli/README.md b/packages/cli/README.md index 414e025c21..2c142d2903 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -44,8 +44,9 @@ named profiles. `cf auth login` and `cf auth logout` manage the default profile. commands and Cloudflare dev-server implementations through `CLOUDFLARE_AUTH_PROFILE`, overriding any inherited value. The development server needs `@cloudflare/workers-auth` 0.17.0 or newer to use the selected -credentials. Cloudflare delegates require Wrangler 4.163.0 or newer, or Vite -plugin v2 starting at 2.0.0-rc.0; older delegates fail with an upgrade hint. +credentials. Wrangler delegates require Wrangler 4.163.0 or newer. For Vite +projects, use `@cloudflare/vite-plugin` 2.0.0-rc.0 or newer to produce compatible +Build Output. Use `cf auth login --use-keyring` to encrypt OAuth credentials with a key stored in your OS keychain. The choice is saved across invocations and applies to all diff --git a/packages/cli/src/__tests__/commands/build/index.test.ts b/packages/cli/src/__tests__/commands/build/index.test.ts index 729c7ac228..43e606e8e1 100644 --- a/packages/cli/src/__tests__/commands/build/index.test.ts +++ b/packages/cli/src/__tests__/commands/build/index.test.ts @@ -50,7 +50,7 @@ describe("cf build", () => { expect(unframe(std.err)).not.toMatch(/wrangler .* is not installed/); }); - it("uses the vite delegate when vite and wrangler are both declared", async () => { + it("uses the native Vite CLI when the plugin and wrangler are both declared", async () => { await seed({ "package.json": JSON.stringify({ devDependencies: { @@ -62,8 +62,14 @@ describe("cf build", () => { name: "@cloudflare/vite-plugin", version: "2.0.0-rc.0", }), - "node_modules/@cloudflare/vite-plugin/bin/cf-vite": - buildScript("vite-worker"), + "cloudflare.config.ts": "export default {};", + "vite.config.ts": `import { cloudflare } from "@cloudflare/vite-plugin"; export default { plugins: [cloudflare()] };`, + "node_modules/vite/package.json": JSON.stringify({ + name: "vite", + version: "8.1.0", + bin: { vite: "bin/vite.js" }, + }), + "node_modules/vite/bin/vite.js": buildScript("vite-worker"), "node_modules/wrangler/package.json": JSON.stringify({ name: "wrangler", version: "4.163.0", @@ -72,7 +78,7 @@ describe("cf build", () => { 'require("node:fs").writeFileSync("wrangler-argv.out", process.argv.slice(2).join("\\n") + "\\n"); process.exit(99);' ), }); - chmod("node_modules/@cloudflare/vite-plugin/bin/cf-vite"); + chmod("node_modules/vite/bin/vite.js"); chmod("node_modules/wrangler/bin/cf-wrangler.js"); const result = await runCf(["build"]); @@ -81,6 +87,121 @@ describe("cf build", () => { expect(readArgv("argv.out")).toEqual(["build"]); }); + it.each([false, true])( + "passes mode and Preview context to native Vite (Preview: %s)", + async (isPreview) => { + vi.stubEnv("CLOUDFLARE_PREVIEW_BUILD", undefined); + vi.stubEnv("CLOUDFLARE_API_TOKEN", undefined); + await seed({ + "package.json": JSON.stringify({ + devDependencies: { "@cloudflare/vite-plugin": "^2.0.0-rc.0" }, + }), + "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ + name: "@cloudflare/vite-plugin", + version: "2.0.0-rc.0", + }), + "cloudflare.config.ts": "export default {};", + "vite.config.ts": `import { cloudflare } from "@cloudflare/vite-plugin"; export default { plugins: [cloudflare()] };`, + "node_modules/vite/package.json": JSON.stringify({ + name: "vite", + version: "8.1.0", + bin: { vite: "bin/vite.js" }, + }), + "node_modules/vite/bin/vite.js": buildScript( + "vite-worker", + 'fs.writeFileSync("env.out", JSON.stringify([process.env.CLOUDFLARE_PREVIEW_BUILD, process.env.CLOUDFLARE_CF_AUTH, process.env.CLOUDFLARE_API_TOKEN]));' + ), + ".env": "CLOUDFLARE_API_TOKEN=file-token", + }); + chmod("node_modules/vite/bin/vite.js"); + + await runBuild("staging", {}, { isPreview }); + + expect(readArgv("argv.out")).toEqual(["build", "--mode", "staging"]); + expect(JSON.parse(readFileSync("env.out", "utf8"))).toEqual([ + isPreview ? "true" : null, + "true", + null, + ]); + } + ); + + it("builds a Preview through Vite+ selected by autoconfig", async () => { + vi.stubEnv("CLOUDFLARE_PREVIEW_BUILD", undefined); + await seed({ + "cloudflare.config.ts": "export default {};", + "vite.config.ts": `import { cloudflare } from "@cloudflare/vite-plugin"; export default { plugins: [cloudflare()] };`, + "package.json": JSON.stringify({ + devDependencies: { + "@cloudflare/vite-plugin": "^2.0.0-rc.0", + "vite-plus": "1.5.0", + wrangler: "^4.136.0", + }, + }), + "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ + version: "2.0.0-rc.0", + }), + "node_modules/vite-plus/package.json": JSON.stringify({ + name: "vite-plus", + version: "1.5.0", + bin: { vp: "bin/vp.js" }, + }), + "node_modules/.bin/vp": nodeScript('require("../vite-plus/bin/vp.js");'), + "node_modules/vite-plus/bin/vp.js": buildScript( + "vite-plus-worker", + 'fs.writeFileSync("preview.out", process.env.CLOUDFLARE_PREVIEW_BUILD ?? "");' + ), + }); + chmod("node_modules/vite-plus/bin/vp.js"); + makeExecutable("node_modules/.bin/vp", { npmBin: true }); + + await runBuild("staging", {}, { isPreview: true }); + + expect(readArgv("argv.out")).toEqual(["build", "--mode", "staging"]); + expect(readFileSync("preview.out", "utf8")).toBe("true"); + }); + + it.each([ + ["deploy"], + ["workers", "versions", "create"], + ["previews", "deploy", "--preview-name", "feature"], + ])("runs the native Vite build before %s", async (...command) => { + vi.stubEnv("CLOUDFLARE_PREVIEW_BUILD", undefined); + await seed({ + "package.json": JSON.stringify({ + devDependencies: { "@cloudflare/vite-plugin": "^2.0.0-rc.0" }, + }), + "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ + name: "@cloudflare/vite-plugin", + version: "2.0.0-rc.0", + }), + "cloudflare.config.ts": "export default {};", + "vite.config.ts": `import { cloudflare } from "@cloudflare/vite-plugin"; export default { plugins: [cloudflare()] };`, + "node_modules/vite/package.json": JSON.stringify({ + name: "vite", + version: "8.1.0", + bin: { vite: "bin/vite.js" }, + }), + "node_modules/vite/bin/vite.js": nodeScript( + [ + 'const fs = require("node:fs");', + 'fs.writeFileSync("argv.out", process.argv.slice(2).join("\\n"));', + 'fs.writeFileSync("env.out", process.env.CLOUDFLARE_PREVIEW_BUILD ?? "");', + "process.exit(17);", + ].join("\n") + ), + }); + chmod("node_modules/vite/bin/vite.js"); + + const { exitCode } = await runCf([...command, "--mode", "staging"]); + + expect(exitCode).toBe(17); + expect(readArgv("argv.out")).toEqual(["build", "--mode", "staging"]); + expect(readFileSync("env.out", "utf8")).toBe( + command[0] === "previews" ? "true" : "" + ); + }); + it("uses wrangler as the fallback delegate", async () => { await seed({ "package.json": JSON.stringify({ @@ -369,6 +490,54 @@ describe("cf build", () => { expect(readArgv("argv.out")).toEqual(["build"]); }); + it.each([ + { output: "missing", canonical: false }, + { output: "missing", canonical: true }, + { output: "malformed", canonical: false }, + ])( + "explains $output Build Output after running Vite (canonical: $canonical)", + async ({ output, canonical }) => { + await seed({ + "package.json": JSON.stringify({ + devDependencies: { + "@cloudflare/vite-plugin": "^2.0.0-rc.0", + ...(canonical ? { vite: "8.1.0" } : {}), + }, + }), + "cloudflare.config.ts": "export default {};", + "vite.config.ts": "export default { plugins: [] };", + "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ + version: "2.0.0-rc.0", + }), + "node_modules/vite/package.json": JSON.stringify({ + bin: { vite: "cli.js" }, + }), + "node_modules/.bin/vite": nodeScript( + 'require("node:fs").writeFileSync("argv.out", process.argv.slice(2).join("\\n"));' + ), + "node_modules/vite/cli.js": nodeScript( + 'require("node:fs").writeFileSync("argv.out", process.argv.slice(2).join("\\n"));' + ), + ...(output === "malformed" + ? { ".cloudflare/output/v1/config.json": "{ invalid json" } + : {}), + }); + makeExecutable("node_modules/vite/cli.js"); + makeExecutable("node_modules/.bin/vite", { npmBin: true }); + const build = runBuild(); + await expect(build).rejects.toThrow(BuildOutputError); + if (output === "missing") { + await expect(build).rejects.toThrow( + "Check that your Vite config includes cloudflare() from @cloudflare/vite-plugin." + ); + } else { + await expect(build).rejects.toThrow("could not parse JSON"); + await expect(build).rejects.not.toThrow("Check that your Vite config"); + } + expect(readArgv("argv.out")).toEqual(["build"]); + } + ); + it("fails when a successful delegate does not emit build output", async () => { await seed({ "package.json": JSON.stringify({ diff --git a/packages/cli/src/__tests__/commands/deploy/index.test.ts b/packages/cli/src/__tests__/commands/deploy/index.test.ts index fbe08a643d..a0a3f932ce 100644 --- a/packages/cli/src/__tests__/commands/deploy/index.test.ts +++ b/packages/cli/src/__tests__/commands/deploy/index.test.ts @@ -14,6 +14,7 @@ import { it, vi, } from "vite-plus/test"; +import { makeExecutable, nodeScript } from "../../helpers/executable.js"; import { createMockDeployContext } from "../../helpers/mock-deploy-context.js"; import { createFetchResult, msw, setupMsw } from "../../helpers/msw.js"; import { runCf } from "../../helpers/run-cf.js"; @@ -64,6 +65,51 @@ describe("cf deploy", () => { }); describe("simple worker", () => { + it("builds and deploys through native Vite without a framework command", async () => { + const upload = mockWorkerUpload(); + await seed({ + "package.json": JSON.stringify({ + devDependencies: { + "@cloudflare/vite-plugin": "^2.0.0-rc.0", + wrangler: "^4.136.0", + }, + }), + "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ + name: "@cloudflare/vite-plugin", + version: "2.0.0-rc.0", + }), + "cloudflare.config.ts": "export default {};", + "vite.config.ts": `import { cloudflare } from '@cloudflare/vite-plugin'; export default { plugins: [cloudflare()] };`, + "node_modules/vite/package.json": JSON.stringify({ + name: "vite", + version: "8.1.0", + bin: { vite: "bin/vite.js" }, + }), + "node_modules/vite/bin/vite.js": nodeScript( + 'require("node:fs").writeFileSync("vite-argv.out", JSON.stringify(process.argv.slice(2)));' + ), + ".cloudflare/output/v1/config.json": buildOutputRootConfig({ + buildContext: { isPreview: false, mode: "staging" }, + }), + ".cloudflare/output/v1/workers/default/worker.config.json": + workerConfig(), + ".cloudflare/output/v1/workers/default/bundle/index.js": + "export default { fetch() { return new Response('ok'); } }", + }); + makeExecutable("node_modules/vite/bin/vite.js"); + + const { exitCode } = await runCf(["deploy", "--mode", "staging"]); + + expect(exitCode).toBe(0); + expect(JSON.parse(readFileSync("vite-argv.out", "utf8"))).toEqual([ + "build", + "--mode", + "staging", + ]); + expect(buildDelegateWasCalled()).toBe(false); + expect(upload.metadata?.main_module).toBe("index.js"); + }); + it.each([ ["D1", { type: "d1", name: "my-database" }, "database_id"], ["R2", { type: "r2" }, "bucket_name"], diff --git a/packages/cli/src/__tests__/commands/dev/discover.test.ts b/packages/cli/src/__tests__/commands/dev/discover.test.ts index ac4ffe1642..d1e9228c9c 100644 --- a/packages/cli/src/__tests__/commands/dev/discover.test.ts +++ b/packages/cli/src/__tests__/commands/dev/discover.test.ts @@ -39,118 +39,96 @@ describe("discoverImpls", () => { runInTempDir(); describe("npm", () => { - it("returns the declared impl when installed", async () => { + it("returns the declared Wrangler delegate when installed", async () => { await seed({ "package.json": JSON.stringify({ - devDependencies: { "@cloudflare/vite-plugin": "beta" }, + devDependencies: { wrangler: "^4.136.0" }, }), - "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ - name: "@cloudflare/vite-plugin", - version: "2.0.0-beta.sha-805ec1ff3", + "node_modules/wrangler/package.json": JSON.stringify({ + name: "wrangler", + version: "4.136.0", }), - "node_modules/@cloudflare/vite-plugin/bin/cf-vite": - "#!/usr/bin/env node\n", + "node_modules/wrangler/bin/cf-wrangler.js": "#!/usr/bin/env node\n", }); - const results = discoverImpls(process.cwd()); expect(results).toHaveLength(1); - expect(results[0]?.impl.pkg).toBe("@cloudflare/vite-plugin"); - expect(results[0]?.binary).toBe( - resolve("node_modules/@cloudflare/vite-plugin/bin/cf-vite") - ); + expect(results[0]).toMatchObject({ + installed: true, + installedVersion: "4.136.0", + binary: resolve("node_modules/wrangler/bin/cf-wrangler.js"), + }); }); - it("returns binary=null when declared but not installed", async () => { + it("reports a missing local installation", async () => { await seed({ "package.json": JSON.stringify({ - devDependencies: { "@cloudflare/vite-plugin": "beta" }, + dependencies: { wrangler: "^4.136.0" }, }), }); - - const results = discoverImpls(process.cwd()); - expect(results).toHaveLength(1); - expect(results[0]?.binary).toBeNull(); - expect(results[0]?.installed).toBe(false); + expect(discoverImpls(process.cwd())[0]).toMatchObject({ + installed: false, + binary: null, + }); }); - it("tracks installed packages with missing delegate binaries", async () => { + it("reports a missing delegate in an installed package", async () => { await seed({ "package.json": JSON.stringify({ - devDependencies: { "@cloudflare/vite-plugin": "beta" }, + devDependencies: { wrangler: "^4.136.0" }, }), - "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ - name: "@cloudflare/vite-plugin", - version: "2.0.0-beta.sha-805ec1ff3", + "node_modules/wrangler/package.json": JSON.stringify({ + name: "wrangler", + version: "4.136.0", }), }); - - const results = discoverImpls(process.cwd()); - expect(results).toHaveLength(1); - expect(results[0]?.binary).toBeNull(); - expect(results[0]?.installed).toBe(true); + expect(discoverImpls(process.cwd())[0]).toMatchObject({ + installed: true, + binary: null, + }); }); - it("returns no result when no known impl is declared", async () => { + it("ignores a parent project's installation", async () => { await seed({ - "package.json": JSON.stringify({ - devDependencies: { "some-unrelated-package": "^1.0.0" }, + "node_modules/wrangler/package.json": JSON.stringify({ + name: "wrangler", + version: "4.136.0", + }), + "node_modules/wrangler/bin/cf-wrangler.js": "#!/usr/bin/env node\n", + "child/package.json": JSON.stringify({ + devDependencies: { wrangler: "^4.136.0" }, }), }); - - expect(discoverImpls(process.cwd())).toEqual([]); + expect(discoverImpls(resolve("child"))[0]).toMatchObject({ + installed: false, + binary: null, + }); }); - it("ignores hoisted parent node_modules (uses local install only)", async () => { - // Simulate a workspace situation where the package is hoisted - // to a parent node_modules but NOT in the project's own. cf - // must treat this as not-installed, per the AGENTS.md note - // about workspaces. + it("leaves Vite command selection to autoconfig", async () => { await seed({ "package.json": JSON.stringify({ devDependencies: { "@cloudflare/vite-plugin": "beta" }, }), - // Note: NO node_modules/@cloudflare/vite-plugin/ entry here. }); - - const results = discoverImpls(process.cwd()); - expect(results).toHaveLength(1); - expect(results[0]?.binary).toBeNull(); - }); - - it("handles malformed package.json without crashing", async () => { - await seed({ - "package.json": "{ this is not valid JSON", - }); - expect(discoverImpls(process.cwd())).toEqual([]); }); - it("collects fallback deps from devDependencies and dependencies alike", async () => { - // Either field counts; the discoverer doesn't differentiate. - await seed({ - "package.json": JSON.stringify({ - dependencies: { wrangler: "^1.0.0" }, - }), - }); - - const results = discoverImpls(process.cwd()); - expect(results).toHaveLength(1); - expect(results[0]?.impl.pkg).toBe("wrangler"); + it("handles malformed package.json", async () => { + await seed({ "package.json": "{ this is not valid JSON" }); + expect(discoverImpls(process.cwd())).toEqual([]); }); - it("uses primary npm impls before wrangler fallback", async () => { + it("uses primary implementations before Wrangler", async () => { await seed({ "package.json": JSON.stringify({ - devDependencies: { - "@cloudflare/vite-plugin": "beta", - wrangler: "^4.0.0", - }, + devDependencies: { wrangler: "^4.136.0" }, }), + "pyproject.toml": + '[project]\ndependencies = ["cloudflare-py-dev-server"]\n', }); - const results = discoverImpls(process.cwd()); expect(results).toHaveLength(1); - expect(results[0]?.impl.pkg).toBe("@cloudflare/vite-plugin"); + expect(results[0]?.impl.pkg).toBe("cloudflare-py-dev-server"); }); }); @@ -256,26 +234,17 @@ describe("discoverImpls", () => { }); describe("multi-manifest", () => { - it("returns one entry per declared impl across ecosystems", async () => { + it("returns primary implementations across ecosystems", async () => { await seed({ - "package.json": JSON.stringify({ - devDependencies: { "@cloudflare/vite-plugin": "beta" }, - }), - "pyproject.toml": [ - "[project]", - 'name = "x"', - 'dependencies = ["cloudflare-py-dev-server"]', - "", - ].join("\n"), + "pyproject.toml": + '[project]\ndependencies = ["cloudflare-py-dev-server"]\n', + "Cargo.toml": '[dependencies]\ncloudflare-rs-dev-server = "0.1"\n', }); - - const results = discoverImpls(process.cwd()); - expect(results).toHaveLength(2); - const names = results.map((r) => r.impl.pkg).sort(); - expect(names).toEqual([ - "@cloudflare/vite-plugin", - "cloudflare-py-dev-server", - ]); + expect( + discoverImpls(process.cwd()) + .map((result) => result.impl.pkg) + .sort() + ).toEqual(["cloudflare-py-dev-server", "cloudflare-rs-dev-server"]); }); }); diff --git a/packages/cli/src/__tests__/commands/dev/index.test.ts b/packages/cli/src/__tests__/commands/dev/index.test.ts index 78c69f64c3..4265f65cc9 100644 --- a/packages/cli/src/__tests__/commands/dev/index.test.ts +++ b/packages/cli/src/__tests__/commands/dev/index.test.ts @@ -1,5 +1,5 @@ import { existsSync, readFileSync } from "node:fs"; -import { resolve } from "node:path"; +import { delimiter, dirname, resolve } from "node:path"; import * as clack from "@clack/prompts"; import { mockConsoleMethods, @@ -39,6 +39,116 @@ describe("cf dev", () => { const std = mockConsoleMethods(); afterEach(() => vi.restoreAllMocks()); + it.each(["dev", "build"])( + "keeps unsupported project setup blocked before %s delegation", + async (command) => { + await seed({ + "package.json": JSON.stringify({ + dependencies: { hono: "4", "@cloudflare/vite-plugin": "^2.0.0-rc.0" }, + }), + "public/index.html": "

Hono

", + }); + vi.mocked(x).mockClear(); + + await expect(runCf([command])).rejects.toThrow( + 'The detected framework ("Hono") cannot be automatically configured.' + ); + expect(x).not.toHaveBeenCalled(); + } + ); + + it.each([ + undefined, + "export default { plugins: [] };", + "export default vite.defineConfig({ plugins: [cloudflare()].filter(Boolean) });", + ])( + "runs Vite with a custom config without inspecting the default: %s", + async (config) => { + await seed({ + "package.json": JSON.stringify({ + devDependencies: { "@cloudflare/vite-plugin": "^2.0.0-rc.0" }, + }), + "cloudflare.config.ts": "export default {};", + ...(config === undefined ? {} : { "vite.config.ts": config }), + "vite.custom.ts": "export { default } from './shared-config';", + "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ + version: "2.0.0-rc.0", + }), + "node_modules/vite/package.json": JSON.stringify({ + bin: { vite: "cli.js" }, + }), + "node_modules/vite/cli.js": nodeScript( + 'require("node:fs").writeFileSync("argv.json", JSON.stringify(process.argv.slice(2)));' + ), + }); + makeExecutable("node_modules/vite/cli.js"); + const result = await runCf(["dev", "--", "--config", "vite.custom.ts"]); + expect(result.exitCode).toBe(0); + expect(JSON.parse(readFileSync("argv.json", "utf8"))).toEqual([ + "dev", + "--config", + "vite.custom.ts", + ]); + } + ); + + it.each([ + { vitePlus: false, version: "2.0.0-rc.0" }, + { vitePlus: true, version: "2.0.0-rc.0" }, + { vitePlus: false, version: "2.0.0-beta.v.12" }, + ])( + "checks and runs hoisted workspace tools (Vite+: $vitePlus, plugin: $version)", + async ({ vitePlus, version }) => { + const tool = vitePlus ? "vite-plus" : "vite"; + const binary = vitePlus ? "vp" : "vite"; + await seed({ + "package.json": JSON.stringify({ + name: "workspace", + workspaces: ["apps/*"], + }), + "apps/site/package.json": JSON.stringify({ + name: "site", + devDependencies: { + "@cloudflare/vite-plugin": "^2.0.0-rc.0", + ...(vitePlus ? { "vite-plus": "1.5.0" } : {}), + }, + }), + "apps/site/cloudflare.config.ts": "export default {};", + "apps/site/vite.config.ts": `import { cloudflare } from '@cloudflare/vite-plugin'; export default { plugins: [cloudflare()] };`, + "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ + version, + }), + [`node_modules/${tool}/package.json`]: JSON.stringify({ + bin: { [binary]: "cli.js" }, + }), + [`node_modules/.bin/${binary}`]: nodeScript( + `require("../${tool}/cli.js");` + ), + [`node_modules/${tool}/cli.js`]: nodeScript( + 'require("node:fs").writeFileSync("argv.json", JSON.stringify(process.argv.slice(2)));' + ), + }); + makeExecutable(`node_modules/${tool}/cli.js`); + makeExecutable(`node_modules/.bin/${binary}`, { npmBin: true }); + process.chdir(resolve("apps/site")); + const run = runCf(["dev", "--profile", "work", "--mode", "staging"]); + if (version === "2.0.0-beta.v.12") { + await expect(run).rejects.toThrow( + "cf requires @cloudflare/vite-plugin >=2.0.0-beta.v.13 <3" + ); + expect(existsSync("argv.json")).toBe(false); + return; + } + const result = await run; + expect(result.exitCode).toBe(0); + expect(JSON.parse(readFileSync("argv.json", "utf8"))).toEqual([ + "dev", + "--mode", + "staging", + ]); + } + ); + describe("no impl declared", () => { it("errors with install hints and exits 1 when no manifest exists", async () => { const result = await runCf(["dev"]); @@ -52,6 +162,9 @@ describe("cf dev", () => { expect(std.err).toMatch(/cloudflare-rs-dev-server/); // And surface install commands. expect(std.err).toMatch(/npm install --save-dev/); + expect(unframe(std.err)).toContain( + "npm install --save-dev @cloudflare/vite-plugin@rc vite" + ); expect(std.err).toMatch(/pip install/); expect(std.err).toMatch(/cargo install/); }); @@ -72,9 +185,7 @@ describe("cf dev", () => { describe("multiple impls declared", () => { it("errors when two ecosystems each declare an impl", async () => { await seed({ - "package.json": JSON.stringify({ - devDependencies: { "@cloudflare/vite-plugin": "^2.0.0-rc.0" }, - }), + "Cargo.toml": '[dependencies]\ncloudflare-rs-dev-server = "0.1"\n', "pyproject.toml": [ "[project]", 'name = "x"', @@ -88,13 +199,14 @@ describe("cf dev", () => { expect(std.err).toMatch( /Multiple Cloudflare dev-server implementations are configured/ ); - expect(std.err).toMatch(/@cloudflare\/vite-plugin/); + expect(std.err).toMatch(/cloudflare-rs-dev-server/); expect(std.err).toMatch(/cloudflare-py-dev-server/); expect(std.err).toMatch(/A project can only use one dev-server/); }); it("does not treat wrangler fallback as a second impl", async () => { await seed({ + "cloudflare.config.ts": "export default {};", "package.json": JSON.stringify({ devDependencies: { "@cloudflare/vite-plugin": "^2.0.0-rc.0", @@ -103,8 +215,7 @@ describe("cf dev", () => { }), }); - const result = await runCf(["dev"]); - expect(result.exitCode).toBe(1); + await expect(runCf(["dev"])).rejects.toThrow("is not installed"); expect(std.err).not.toMatch(/Multiple Cloudflare dev-server/); expect(unframe(std.err)).toMatch( /@cloudflare\/vite-plugin .* is not installed/ @@ -115,24 +226,25 @@ describe("cf dev", () => { describe("declared but not installed", () => { it("surfaces an install hint specific to the declared impl", async () => { await seed({ + "cloudflare.config.ts": "export default {};", "package.json": JSON.stringify({ devDependencies: { "@cloudflare/vite-plugin": "^2.0.0-rc.0" }, }), // No node_modules: declared but not installed. }); - const result = await runCf(["dev"]); - expect(result.exitCode).toBe(1); + await expect(runCf(["dev"])).rejects.toThrow("is not installed"); expect(unframe(std.err)).toMatch( /@cloudflare\/vite-plugin .* is not installed/ ); - expect(std.err).toMatch( - /npm install --save-dev "@cloudflare\/vite-plugin@\^2\.0\.0-rc\.0"/ + expect(unframe(std.err)).toMatch( + /npm install --save-dev @cloudflare\/vite-plugin@beta/ ); }); - it("surfaces the vite version requirement when the delegate is missing", async () => { + it("surfaces a Vite install hint when the plugin is installed without Vite", async () => { await seed({ + "cloudflare.config.ts": "export default {};", "package.json": JSON.stringify({ devDependencies: { "@cloudflare/vite-plugin": "^2.0.0-rc.0" }, }), @@ -142,11 +254,15 @@ describe("cf dev", () => { }), }); - const result = await runCf(["dev"]); - expect(result.exitCode).toBe(1); - expect(unframe(std.err)).toMatch(/does not include the cf delegate/); - expect(std.err).toMatch( - /@cloudflare\/vite-plugin v2 \(2\.0\.0-rc\.0 or newer\)/ + await expect(runCf(["dev"])).rejects.toThrow( + "executable could not be found" + ); + expect(unframe(std.err)).toMatch(/vite executable could not be found/); + expect(unframe(std.err)).toMatch( + /npm install --save-dev @cloudflare\/vite-plugin@beta vite/ + ); + expect(unframe(std.err)).toMatch( + /@cloudflare\/vite-plugin >=2\.0\.0-beta\.v\.13 <3/ ); expect(unframe(std.err)).toContain("cf dev"); expect(unframe(std.err)).toContain("cf build"); @@ -199,30 +315,31 @@ describe("cf dev", () => { describe.each([ { name: "@cloudflare/vite-plugin", - version: "2.0.0-beta.v.17", - minimum: "2.0.0-rc.0", - bin: "bin/cf-vite", - install: 'npm install --save-dev "@cloudflare/vite-plugin@^2.0.0-rc.0"', + version: "2.0.0-beta.v.12", + minimum: "2.0.0-beta.v.13", + executable: "node_modules/vite/bin/vite.js", + vite: true, + install: "npm install --save-dev @cloudflare/vite-plugin@beta", }, { name: "wrangler", version: "4.160.1", minimum: "4.163.0", - bin: "bin/cf-wrangler.js", + executable: "node_modules/wrangler/bin/cf-wrangler.js", + vite: false, install: "npm install --save-dev wrangler@latest", }, ])( "$name profile compatibility", - ({ name, version, minimum, bin, install }) => { + ({ name, version, minimum, executable, vite, install }) => { it.each([ { command: "dev", profile: undefined }, { command: "dev", profile: "work" }, { command: "build", profile: undefined }, { command: "build", profile: "work" }, ])( - "rejects $command with profile $profile before starting an older delegate", + "rejects $command with profile $profile before starting an older tool", async ({ command, profile }) => { - const executable = `node_modules/${name}/${bin}`; await seed({ "package.json": JSON.stringify({ devDependencies: { [name]: version }, @@ -234,18 +351,32 @@ describe("cf dev", () => { [executable]: nodeScript( 'require("node:fs").writeFileSync("delegate-started.out", "started");' ), + ...(vite + ? { + "cloudflare.config.ts": "export default {};", + "vite.config.ts": `import { cloudflare } from "@cloudflare/vite-plugin"; export default { plugins: [cloudflare()] };`, + "node_modules/vite/package.json": JSON.stringify({ + name: "vite", + version: "8.1.0", + bin: { vite: "bin/vite.js" }, + }), + } + : {}), }); makeExecutable(executable); - const result = await runCf([ + const run = runCf([ command, ...(profile ? ["--profile", profile] : []), ]); - - expect(result.exitCode).toBe(1); + if (vite) { + await expect(run).rejects.toThrow(minimum); + } else { + expect((await run).exitCode).toBe(1); + } expect(unframe(std.err)).toContain(`${name}@${version} is installed`); expect(unframe(std.err)).toContain(minimum); - expect(std.err).toContain(install); + expect(unframe(std.err)).toContain(install); expect(existsSync("delegate-started.out")).toBe(false); } ); @@ -256,10 +387,16 @@ describe("cf dev", () => { { name: "@cloudflare/vite-plugin", version: "2.0.0-rc.0", - bin: "bin/cf-vite", + executable: "node_modules/vite/bin/vite.js", + vite: true, }, - { name: "wrangler", version: "4.163.0", bin: "bin/cf-wrangler.js" }, - ])("$name auth profiles", ({ name, version, bin }) => { + { + name: "wrangler", + version: "4.163.0", + executable: "node_modules/wrangler/bin/cf-wrangler.js", + vite: false, + }, + ])("$name auth profiles", ({ name, version, executable, vite }) => { it.each([ { profile: "work", inherited: "personal", expected: "work" }, { profile: "default", inherited: "work", expected: "default" }, @@ -268,7 +405,6 @@ describe("cf dev", () => { ])( "passes profile $profile with inherited profile $inherited through the environment", async ({ profile, inherited, expected }) => { - const executable = `node_modules/${name}/${bin}`; await seed({ "package.json": JSON.stringify({ devDependencies: { [name]: version }, @@ -278,8 +414,19 @@ describe("cf dev", () => { version, }), [executable]: nodeScript( - 'require("node:fs").writeFileSync("profile.out", JSON.stringify({ argv: process.argv.slice(2), profile: process.env.CLOUDFLARE_AUTH_PROFILE ?? null }));' + 'require("node:fs").writeFileSync("profile.out", JSON.stringify({ argv: process.argv.slice(2), profile: process.env.CLOUDFLARE_AUTH_PROFILE ?? null, cfAuth: process.env.CLOUDFLARE_CF_AUTH ?? null }));' ), + ...(vite + ? { + "cloudflare.config.ts": "export default {};", + "vite.config.ts": `import { cloudflare } from "@cloudflare/vite-plugin"; export default { plugins: [cloudflare()] };`, + "node_modules/vite/package.json": JSON.stringify({ + name: "vite", + version: "8.1.0", + bin: { vite: "bin/vite.js" }, + }), + } + : {}), }); makeExecutable(executable); @@ -292,6 +439,7 @@ describe("cf dev", () => { expect(JSON.parse(readFileSync("profile.out", "utf8"))).toEqual({ argv: ["dev", "--port", "3000"], profile: expected, + cfAuth: vite ? "true" : null, }); expect(process.env.CLOUDFLARE_AUTH_PROFILE).toBe(inherited); } @@ -299,7 +447,7 @@ describe("cf dev", () => { }); describe("happy path", () => { - it("rejects an installed Vite plugin v1 delegate", async () => { + it("rejects an installed Vite plugin v1", async () => { await seed({ "package.json": JSON.stringify({ devDependencies: { "@cloudflare/vite-plugin": "1.61.0" }, @@ -308,16 +456,23 @@ describe("cf dev", () => { name: "@cloudflare/vite-plugin", version: "1.61.0", }), - "node_modules/@cloudflare/vite-plugin/bin/cf-vite": - nodeScript("process.exit(0);"), + "cloudflare.config.ts": "export default {};", + "vite.config.ts": `import { cloudflare } from "@cloudflare/vite-plugin"; export default { plugins: [cloudflare()] };`, + "node_modules/vite/package.json": JSON.stringify({ + name: "vite", + version: "8.1.0", + bin: { vite: "bin/vite.js" }, + }), + "node_modules/vite/bin/vite.js": nodeScript("process.exit(0);"), }); - makeExecutable("node_modules/@cloudflare/vite-plugin/bin/cf-vite"); + makeExecutable("node_modules/vite/bin/vite.js"); - const result = await runCf(["dev"]); + await expect(runCf(["dev"])).rejects.toThrow( + "cf requires @cloudflare/vite-plugin >=2.0.0-beta.v.13 <3" + ); - expect(result.exitCode).toBe(1); - expect(std.err).toMatch( - /@cloudflare\/vite-plugin v2 \(2\.0\.0-rc\.0 or newer\)/ + expect(unframe(std.err)).toMatch( + /@cloudflare\/vite-plugin >=2\.0\.0-beta\.v\.13 <3/ ); expect(std.err).toMatch(/@cloudflare\/vite-plugin@1\.61\.0 is installed/); expect(unframe(std.err)).toContain("cf dev"); @@ -391,6 +546,10 @@ describe("cf dev", () => { async ({ args, expected }) => { await seed({ "cloudflare.config.ts": "export default {};", + "vite.config.ts": `import { cloudflare } from '@cloudflare/vite-plugin'; export default { plugins: [cloudflare()] };`, + "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ + version: "2.0.0-rc.0", + }), "package.json": JSON.stringify({ name: "vite-project", devDependencies: { @@ -402,10 +561,12 @@ describe("cf dev", () => { "node_modules/vite/package.json": JSON.stringify({ name: "vite", version: "7.0.0", + bin: { vite: "cli.js" }, }), - "node_modules/.bin/vite": nodeScript( + "node_modules/vite/cli.js": nodeScript( 'require("node:fs").writeFileSync("vite-argv.json", JSON.stringify(process.argv.slice(2)));' ), + "node_modules/.bin/vite": nodeScript('require("../vite/cli.js");'), }); makeExecutable("node_modules/.bin/vite", { npmBin: true }); @@ -658,7 +819,27 @@ describe("cf dev", () => { ]); }); - it("resolves framework executables from an ancestor's node_modules", async () => { + it("uses explicit PATH overrides when preferring project executables", async () => { + const pathKey = process.platform === "win32" ? "Path" : "PATH"; + const inheritedPath = [ + dirname(process.execPath), + "explicit-path-override", + ].join(delimiter); + await runProjectCommand( + `node -e "require('node:fs').writeFileSync('path.out', process.env.PATH)"`, + process.cwd(), + { + preferLocal: true, + env: { [pathKey]: inheritedPath }, + output: "silent", + } + ); + expect(readFileSync("path.out", "utf8")).toBe( + [resolve("node_modules/.bin"), inheritedPath].join(delimiter) + ); + }); + + it("resolves framework executables within the supplied workspace boundary", async () => { await seed({ "node_modules/.bin/cf-local-framework": nodeScript( 'require("node:fs").writeFileSync("command.out", process.argv.slice(2).join("\\n"));' @@ -671,6 +852,10 @@ describe("cf dev", () => { expect( await runProjectCommand("cf-local-framework build", cwd, { preferLocal: true, + nodeModulesPaths: [ + resolve(cwd, "node_modules"), + resolve("node_modules"), + ], args: ["--mode", "staging"], output: "silent", }) @@ -680,6 +865,31 @@ describe("cf dev", () => { ); }); + it("excludes unrelated parent binaries when preferring local tools", async () => { + await seed({ + "node_modules/.bin/cf-parent-only": nodeScript( + 'require("node:fs").writeFileSync("unexpected.out", "started");' + ), + "child/package.json": "{}", + }); + makeExecutable("node_modules/.bin/cf-parent-only", { npmBin: true }); + const command = runProjectCommand( + "cf-parent-only build", + resolve("child"), + { + preferLocal: true, + output: "silent", + } + ); + if (process.platform === "win32") { + // The Windows shell reports a missing command through its exit code. + await expect(command).resolves.toEqual({ exitCode: 1 }); + } else { + await expect(command).rejects.toThrow(); + } + expect(existsSync("child/unexpected.out")).toBe(false); + }); + it("propagates non-zero project command exits", async () => { expect( await runProjectCommand('node -e "process.exit(42)"', process.cwd()) @@ -698,9 +908,54 @@ describe("cf dev", () => { } ); + it.skipIf(process.platform === "win32")( + "forwards shutdown to a tool started by the command launcher", + async () => { + await seed({ + "tool.cjs": nodeScript(` +const fs = require("node:fs"); +process.on("SIGTERM", () => { + fs.writeFileSync("tool-stopped", "true"); + process.exit(0); +}); +setInterval(() => {}, 1000); +fs.writeFileSync("tool-ready", "true"); +`), + "launcher.cjs": nodeScript(` +const { spawn } = require("node:child_process"); +spawn(process.execPath, ["tool.cjs"], { stdio: "inherit" }); +`), + }); + const before = new Set(process.listeners("SIGTERM")); + const execution = runProjectCommand("node launcher.cjs", process.cwd()); + const listener = process + .listeners("SIGTERM") + .find((fn) => !before.has(fn)); + if (!listener) { + throw new Error( + "Project command did not register its shutdown listener" + ); + } + try { + await vi.waitFor(() => { + expect(readFileSync("tool-ready", "utf8")).toBe("true"); + }); + } finally { + listener("SIGTERM"); + } + + await expect(execution).resolves.toMatchObject({ signal: "SIGTERM" }); + await vi.waitFor(() => { + expect(readFileSync("tool-stopped", "utf8")).toBe("true"); + }); + } + ); + it("reports missing project commands and restores signal listeners", async () => { const sigintListeners = process.listenerCount("SIGINT"); const sigtermListeners = process.listenerCount("SIGTERM"); + const sighupListeners = process.listenerCount("SIGHUP"); + const exitListeners = process.listenerCount("exit"); const execution = runProjectCommand( "cf-missing-project-command", process.cwd(), @@ -713,6 +968,8 @@ describe("cf dev", () => { } expect(process.listenerCount("SIGINT")).toBe(sigintListeners); expect(process.listenerCount("SIGTERM")).toBe(sigtermListeners); + expect(process.listenerCount("SIGHUP")).toBe(sighupListeners); + expect(process.listenerCount("exit")).toBe(exitListeners); }); it("hides environment overrides unless DEBUG is set", async () => { @@ -824,8 +1081,7 @@ describe("cf dev", () => { ]); }); - it("spawns the impl and propagates its exit code", async () => { - // Lay down a fake implementation at the conventional delegate path. + it("runs native Vite without a plugin delegate", async () => { await seed({ "package.json": JSON.stringify({ devDependencies: { "@cloudflare/vite-plugin": "^2.0.0-rc.0" }, @@ -834,10 +1090,16 @@ describe("cf dev", () => { name: "@cloudflare/vite-plugin", version: "2.0.0-rc.0", }), - "node_modules/@cloudflare/vite-plugin/bin/cf-vite": - nodeScript("process.exit(0);"), + "cloudflare.config.ts": "export default {};", + "vite.config.ts": `import { cloudflare } from "@cloudflare/vite-plugin"; export default { plugins: [cloudflare()] };`, + "node_modules/vite/package.json": JSON.stringify({ + name: "vite", + version: "8.1.0", + bin: { vite: "bin/vite.js" }, + }), + "node_modules/vite/bin/vite.js": nodeScript("process.exit(0);"), }); - makeExecutable("node_modules/@cloudflare/vite-plugin/bin/cf-vite"); + makeExecutable("node_modules/vite/bin/vite.js"); const result = await runCf(["dev"]); expect(result.exitCode).toBe(0); @@ -849,6 +1111,53 @@ describe("cf dev", () => { ]); }); + it("runs the Vite+ executable selected by autoconfig", async () => { + await seed({ + "cloudflare.config.ts": "export default {};", + "vite.config.ts": `import { cloudflare } from "@cloudflare/vite-plugin"; export default { plugins: [cloudflare()] };`, + "package.json": JSON.stringify({ + devDependencies: { + "@cloudflare/vite-plugin": "^2.0.0-rc.0", + "vite-plus": "1.5.0", + }, + }), + "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ + version: "2.0.0-rc.0", + }), + "node_modules/vite-plus/package.json": JSON.stringify({ + name: "vite-plus", + version: "1.5.0", + bin: { vp: "bin/vp with ' quote.js" }, + }), + "node_modules/.bin/vp": nodeScript( + `require("../vite-plus/bin/vp with ' quote.js");` + ), + "node_modules/vite-plus/bin/vp with ' quote.js": nodeScript( + 'require("node:fs").writeFileSync("argv.out", JSON.stringify(process.argv.slice(2)));' + ), + }); + makeExecutable("node_modules/vite-plus/bin/vp with ' quote.js"); + makeExecutable("node_modules/.bin/vp", { npmBin: true }); + + const result = await runCf([ + "dev", + "--mode", + "staging", + "--", + "--port", + "03000", + ]); + + expect(result.exitCode).toBe(0); + expect(JSON.parse(readFileSync("argv.out", "utf8"))).toEqual([ + "dev", + "--mode", + "staging", + "--port", + "03000", + ]); + }); + it("rejects future Vite plugin major versions", async () => { await seed({ "package.json": JSON.stringify({ @@ -858,15 +1167,22 @@ describe("cf dev", () => { name: "@cloudflare/vite-plugin", version: "3.0.0-beta.1", }), - "node_modules/@cloudflare/vite-plugin/bin/cf-vite": - nodeScript("process.exit(0);"), + "cloudflare.config.ts": "export default {};", + "vite.config.ts": `import { cloudflare } from "@cloudflare/vite-plugin"; export default { plugins: [cloudflare()] };`, + "node_modules/vite/package.json": JSON.stringify({ + name: "vite", + version: "8.1.0", + bin: { vite: "bin/vite.js" }, + }), + "node_modules/vite/bin/vite.js": nodeScript("process.exit(0);"), }); - makeExecutable("node_modules/@cloudflare/vite-plugin/bin/cf-vite"); + makeExecutable("node_modules/vite/bin/vite.js"); - const result = await runCf(["dev"]); - expect(result.exitCode).toBe(1); - expect(std.err).toMatch( - /@cloudflare\/vite-plugin v2 \(2\.0\.0-rc\.0 or newer\)/ + await expect(runCf(["dev"])).rejects.toThrow( + "cf requires @cloudflare/vite-plugin >=2.0.0-beta.v.13 <3" + ); + expect(unframe(std.err)).toMatch( + /@cloudflare\/vite-plugin >=2\.0\.0-beta\.v\.13 <3/ ); expect(std.err).toMatch( /@cloudflare\/vite-plugin@3\.0\.0-beta\.1 is installed/ @@ -882,10 +1198,16 @@ describe("cf dev", () => { name: "@cloudflare/vite-plugin", version: "2.0.0-rc.0", }), - "node_modules/@cloudflare/vite-plugin/bin/cf-vite": - nodeScript("process.exit(17);"), + "cloudflare.config.ts": "export default {};", + "vite.config.ts": `import { cloudflare } from "@cloudflare/vite-plugin"; export default { plugins: [cloudflare()] };`, + "node_modules/vite/package.json": JSON.stringify({ + name: "vite", + version: "8.1.0", + bin: { vite: "bin/vite.js" }, + }), + "node_modules/vite/bin/vite.js": nodeScript("process.exit(17);"), }); - makeExecutable("node_modules/@cloudflare/vite-plugin/bin/cf-vite"); + makeExecutable("node_modules/vite/bin/vite.js"); const result = await runCf(["dev"]); expect(result.exitCode).toBe(17); @@ -903,11 +1225,18 @@ describe("cf dev", () => { name: "@cloudflare/vite-plugin", version: "2.0.0-rc.0", }), - "node_modules/@cloudflare/vite-plugin/bin/cf-vite": nodeScript( + "cloudflare.config.ts": "export default {};", + "vite.config.ts": `import { cloudflare } from "@cloudflare/vite-plugin"; export default { plugins: [cloudflare()] };`, + "node_modules/vite/package.json": JSON.stringify({ + name: "vite", + version: "8.1.0", + bin: { vite: "bin/vite.js" }, + }), + "node_modules/vite/bin/vite.js": nodeScript( 'require("node:fs").writeFileSync("argv.out", process.argv.slice(2).join("\\n") + "\\n");' ), }); - makeExecutable("node_modules/@cloudflare/vite-plugin/bin/cf-vite"); + makeExecutable("node_modules/vite/bin/vite.js"); const result = await runCf([ "dev", diff --git a/packages/cli/src/__tests__/commands/dev/project-command-process.test.ts b/packages/cli/src/__tests__/commands/dev/project-command-process.test.ts new file mode 100644 index 0000000000..4f80960b2b --- /dev/null +++ b/packages/cli/src/__tests__/commands/dev/project-command-process.test.ts @@ -0,0 +1,175 @@ +import { spawn } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { pathToFileURL } from "node:url"; +import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers"; +import { describe, it, vi } from "vite-plus/test"; + +const loader = pathToFileURL( + createRequire(import.meta.url).resolve("tsx") +).href; +const projectSource = new URL("../../../lib/autoconfig.ts", import.meta.url); +const delegateSource = new URL("../../../lib/delegate.ts", import.meta.url); +const cases = [ + ["SIGINT", "graceful"], + ["SIGTERM", "graceful"], + ["SIGHUP", "graceful"], + ["SIGINT", "repeated"], + ["SIGTERM", "repeated"], + ["SIGINT", "parent-exit"], + ["SIGTERM", "parent-exit"], + ["SIGINT", "delegated"], + ["SIGTERM", "delegated"], + ["SIGINT", "delegated-programmatic"], +] as const; + +describe.skipIf(process.platform === "win32")( + "POSIX project command shutdown", + () => { + runInTempDir(); + + for (const [signal, scenario] of cases) { + const isDelegated = scenario.startsWith("delegated"); + it(`handles ${signal} during ${scenario} shutdown`, async ({ + expect, + }) => { + await seed({ + "tool.cjs": ` +const fs = require("node:fs"); +process.on(${JSON.stringify(signal)}, () => { + fs.writeFileSync("tool-signaled", "true"); + if (${JSON.stringify(scenario)} === "graceful") process.exit(0); + if (${isDelegated}) { + setTimeout(() => { + fs.writeFileSync("tool-cleaned", "true"); + process.exit(0); + }, 250); + } +}); +setInterval(() => {}, 1000); +fs.writeFileSync("tool-pid", String(process.pid)); +`, + "launcher.cjs": ` +const fs = require("node:fs"); +const { spawn } = require("node:child_process"); +process.on(${JSON.stringify(signal)}, () => {}); +spawn(process.execPath, ["tool.cjs"], { stdio: "inherit" }) + .on("exit", () => process.exit(0)); +fs.writeFileSync("launcher-pid", String(process.pid)); +`, + "node_modules/cf/package.json": JSON.stringify({ + name: "cf", + version: "9.9.9", + type: "module", + bin: { cf: "./local.mjs" }, + exports: { "./package.json": "./package.json" }, + }), + "node_modules/cf/local.mjs": ` +import { writeFileSync } from "node:fs"; +import { runProjectCommand } from ${JSON.stringify(projectSource.href)}; +writeFileSync("local-cf-pid", String(process.pid)); +const result = await runProjectCommand("node launcher.cjs", process.cwd(), { output: "silent" }); +writeFileSync("result.json", JSON.stringify(result)); +process.exit(result.exitCode); +`, + "parent.mts": ` +import { writeFileSync } from "node:fs"; +import { runProjectCommand } from ${JSON.stringify(projectSource.href)}; +if (${isDelegated}) { + Object.defineProperty(process.stdin, "isTTY", { value: ${scenario === "delegated"} }); + const { maybeDelegateToLocalInstall } = await import(${JSON.stringify(delegateSource.href)}); + const result = await maybeDelegateToLocalInstall({ ownPackageJsonPath: null }); + process.exit(result.exitCode ?? 1); +} +const execution = runProjectCommand("node launcher.cjs", process.cwd(), { output: "silent" }); +if (${JSON.stringify(scenario)} === "parent-exit") { + process.on(${JSON.stringify(signal)}, () => process.exit(42)); +} +const result = await execution; +writeFileSync("result.json", JSON.stringify(result)); +process.exit(result.exitCode); +`, + }); + const parent = spawn( + process.execPath, + ["--import", loader, "parent.mts"], + { + cwd: process.cwd(), + stdio: "ignore", + env: { + ...process.env, + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ""} --import ${loader}`, + }, + } + ); + const completed = new Promise((resolve, reject) => { + parent.once("error", reject); + parent.once("close", () => resolve()); + }); + try { + await vi.waitFor(() => expect(existsSync("tool-pid")).toBe(true), { + timeout: 10_000, + }); + if (scenario === "delegated" && signal === "SIGINT") { + // A terminal sends one interrupt to both CLIs. Let the local + // CLI begin cleanup before the global CLI handles its copy. + process.kill(Number(readFileSync("local-cf-pid", "utf8")), signal); + await vi.waitFor(() => + expect(existsSync("tool-signaled")).toBe(true) + ); + } + expect(parent.kill(signal)).toBe(true); + if (scenario === "repeated") { + await vi.waitFor(() => + expect(existsSync("tool-signaled")).toBe(true) + ); + expect(parent.kill(signal)).toBe(true); + } + await vi.waitFor(() => expect(parent.exitCode).not.toBeNull(), { + timeout: 2_000, + }); + await completed; + if (scenario === "parent-exit") { + expect(parent.exitCode).toBe(42); + expect(existsSync("result.json")).toBe(false); + } else { + expect(JSON.parse(readFileSync("result.json", "utf8"))).toEqual( + scenario === "repeated" + ? { exitCode: 137, signal: "SIGKILL" } + : { exitCode: 0, signal } + ); + } + if (isDelegated) { + expect(readFileSync("tool-cleaned", "utf8")).toBe("true"); + } + for (const name of [ + "launcher", + "tool", + ...(isDelegated ? ["local-cf"] : []), + ]) { + const pid = Number(readFileSync(`${name}-pid`, "utf8")); + await vi.waitFor(() => + expect(() => process.kill(pid, 0)).toThrow() + ); + } + } finally { + parent.kill("SIGKILL"); + for (const [name, processGroup] of [ + ["launcher", true], + ["local-cf", false], + ] as const) { + if (existsSync(`${name}-pid`)) { + try { + const pid = Number(readFileSync(`${name}-pid`, "utf8")); + process.kill(processGroup ? -pid : pid, "SIGKILL"); + } catch { + // Successful shutdown has already removed the process. + } + } + } + await completed; + } + }); + } + } +); diff --git a/packages/cli/src/__tests__/commands/dev/spawn.test.ts b/packages/cli/src/__tests__/commands/dev/spawn.test.ts index ef0155a98b..063422b469 100644 --- a/packages/cli/src/__tests__/commands/dev/spawn.test.ts +++ b/packages/cli/src/__tests__/commands/dev/spawn.test.ts @@ -21,11 +21,9 @@ describe("spawnImpl", () => { writeFileSync(binPath, `#!/usr/bin/env node\n${script}\n`); chmodSync(binPath, 0o755); - const impl = findKnownImpl( - binaryName === "cf-vite" ? "@cloudflare/vite-plugin" : "wrangler" - ); + const impl = findKnownImpl("wrangler"); if (!impl) { - throw new Error("Missing known Node delegate"); + throw new Error("Missing known Node implementation"); } return { impl, binary: binPath, manifestPath: "(test)" }; } @@ -45,10 +43,8 @@ describe("spawnImpl", () => { it.each([ ["cf-wrangler.js", "dev"], ["cf-wrangler.js", "build"], - ["cf-vite", "dev"], - ["cf-vite", "build"], ] as const)( - "forwards arguments to the %s Node delegate for %s without a shell", + "forwards arguments to the %s Node implementation for %s without a shell", async (binaryName, verb) => { const argFile = join( mkdtempSync(join(tmpdir(), "cf-spawn-args-")), @@ -86,9 +82,7 @@ describe("spawnImpl", () => { it.each([ ["cf-wrangler.js", false], - ["cf-vite", false], ["cf-wrangler.js", true], - ["cf-vite", true], ] as const)( "inherits registry settings without rewriting them for %s (configured: %s)", async (binaryName, configured) => { @@ -121,7 +115,7 @@ describe("spawnImpl", () => { it("throws when the impl has no resolved binary", async () => { const impl: KnownImpl = { ecosystem: "npm", - pkg: "@cloudflare/vite-plugin", + pkg: "test-implementation", description: "Test fixture", manifest: "package.json", binary: () => null, @@ -161,10 +155,13 @@ describe("spawnImpl", () => { expect(process.listenerCount("SIGTERM")).toBe(sigtermListeners); }); - it.skipIf(process.platform === "win32")( - "maps signal-killed exits to 128 + signal_number", - async () => { - const fake = makeFakeImpl('process.kill(process.pid, "SIGTERM")'); + it.skipIf(process.platform === "win32").each(["cf-wrangler.js"])( + "maps signal-killed exits from %s to 128 + signal_number", + async (binaryName) => { + const fake = makeFakeImpl( + 'process.kill(process.pid, "SIGTERM")', + binaryName + ); const result = await spawnImpl(fake, "dev", []); expect(result).toEqual({ exitCode: 143, signal: "SIGTERM" }); } diff --git a/packages/cli/src/__tests__/commands/init.test.ts b/packages/cli/src/__tests__/commands/init.test.ts index 47bc3a842c..9098f4f05a 100644 --- a/packages/cli/src/__tests__/commands/init.test.ts +++ b/packages/cli/src/__tests__/commands/init.test.ts @@ -553,6 +553,21 @@ describe("cf init", () => { expect(stderr()).toMatch(/cf dev\s+Start a local development server/); }); + it("recognizes an existing Vite-plugin project before dependencies are installed", async () => { + await seed({ + "configured/cloudflare.config.ts": "export default {};", + "configured/package.json": JSON.stringify({ + name: "configured", + devDependencies: { "@cloudflare/vite-plugin": "beta" }, + }), + }); + const result = await runCf(["init", "configured"]); + expect(result.exitCode).toBe(0); + expect(stderr()).toContain("Found an existing Cloudflare configuration"); + expect(configureProject).not.toHaveBeenCalled(); + expect(runProjectCommand).not.toHaveBeenCalled(); + }); + it("leaves an already configured project unchanged", async () => { await seed({ "configured/cloudflare.config.ts": "export default {};", diff --git a/packages/cli/src/__tests__/commands/migrate.test.ts b/packages/cli/src/__tests__/commands/migrate.test.ts index 69ff66dd3b..95f72cfd63 100644 --- a/packages/cli/src/__tests__/commands/migrate.test.ts +++ b/packages/cli/src/__tests__/commands/migrate.test.ts @@ -58,7 +58,12 @@ describe("cf migrate", () => { expect(std.err).toContain("Migration complete."); }); - it.each(["dependencies", "devDependencies"])( + it.each([ + "dependencies", + "devDependencies", + "peerDependencies", + "optionalDependencies", + ])( "selects Vite when @cloudflare/vite-plugin is declared in %s", async (dependencyField) => { await seed({ diff --git a/packages/cli/src/__tests__/lib/autoconfig-migration.test.ts b/packages/cli/src/__tests__/lib/autoconfig-migration.test.ts index e36cae4367..8a3dc6986a 100644 --- a/packages/cli/src/__tests__/lib/autoconfig-migration.test.ts +++ b/packages/cli/src/__tests__/lib/autoconfig-migration.test.ts @@ -80,7 +80,35 @@ describe("project preparation", () => { expect(mocks.runAutoConfig).not.toHaveBeenCalled(); }); - it("runs framework setup when Wrangler config conversion did not run", async () => { + it("offers Wrangler migration before validating missing project commands", async () => { + const details: AutoConfigDetails = { + ...unconfiguredDetails, + commandError: { + code: "vite-tool-not-installed", + message: "vite executable could not be found", + }, + }; + const configuredDetails = { ...unconfiguredDetails, configured: true }; + mocks.getDetailsForAutoConfig + .mockResolvedValueOnce(details) + .mockResolvedValueOnce(configuredDetails); + mocks.maybeMigrateWranglerProject.mockResolvedValue(true); + + await expect(prepareProject("/project")).resolves.toEqual({ + details: configuredDetails, + }); + expect(mocks.maybeMigrateWranglerProject).toHaveBeenCalledOnce(); + expect(mocks.runAutoConfig).not.toHaveBeenCalled(); + }); + + it("lets framework setup install missing commands before reanalyzing", async () => { + const details: AutoConfigDetails = { + ...unconfiguredDetails, + commandError: { + code: "vite-plugin-not-installed", + message: "@cloudflare/vite-plugin is not installed", + }, + }; const configuration = { scripts: {}, outputDir: "dist", @@ -93,7 +121,7 @@ describe("project preparation", () => { env: { CONFIGURED: "true" }, }; mocks.getDetailsForAutoConfig - .mockResolvedValueOnce(unconfiguredDetails) + .mockResolvedValueOnce(details) .mockResolvedValueOnce(configuredDetails); mocks.maybeMigrateWranglerProject.mockResolvedValue(false); mocks.runAutoConfig.mockResolvedValue(configuration); @@ -103,7 +131,7 @@ describe("project preparation", () => { configuration, }); expect(mocks.runAutoConfig).toHaveBeenCalledWith( - unconfiguredDetails, + details, expect.objectContaining({ runBuild: false }) ); expect(mocks.getDetailsForAutoConfig).toHaveBeenCalledTimes(2); @@ -132,18 +160,25 @@ describe("project preparation", () => { }); it("dry-runs framework setup when Wrangler config conversion did not run", async () => { - mocks.getDetailsForAutoConfig.mockResolvedValue(unconfiguredDetails); + const details: AutoConfigDetails = { + ...unconfiguredDetails, + commandError: { + code: "vite-plugin-incompatible", + message: "@cloudflare/vite-plugin needs to be upgraded", + }, + }; + mocks.getDetailsForAutoConfig.mockResolvedValue(details); mocks.maybeMigrateWranglerProject.mockResolvedValue(false); mocks.runAutoConfig.mockResolvedValue({ buildCommand: "npm run build" }); await expect( prepareProject("/project", { dryRun: true }) ).resolves.toMatchObject({ - details: unconfiguredDetails, + details, setupNeeded: true, }); expect(mocks.runAutoConfig).toHaveBeenCalledWith( - unconfiguredDetails, + details, expect.objectContaining({ dryRun: true, runBuild: false }) ); expect(mocks.getDetailsForAutoConfig).toHaveBeenCalledOnce(); diff --git a/packages/cli/src/__tests__/lib/process.test.ts b/packages/cli/src/__tests__/lib/process.test.ts index 3bf8db73ca..dfdef2b0eb 100644 --- a/packages/cli/src/__tests__/lib/process.test.ts +++ b/packages/cli/src/__tests__/lib/process.test.ts @@ -1,8 +1,11 @@ +import * as childProcess from "node:child_process"; import { EventEmitter } from "node:events"; import { afterEach, describe, it, vi } from "vite-plus/test"; import { createChildProcessController } from "../../lib/process.js"; import type { ChildProcess } from "node:child_process"; +vi.mock("node:child_process", { spy: true }); + function createMockProcess(): { child: ChildProcess; kill: ReturnType; @@ -113,6 +116,68 @@ describe("createChildProcessController", () => { await controller.exited; }); + it("signals a POSIX command group, including the forced-shutdown fallback", async ({ + expect, + }) => { + vi.useFakeTimers(); + vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + const signalGroup = vi.spyOn(process, "kill").mockReturnValue(true); + const { child, kill } = createMockProcess(); + Object.assign(child, { pid: 12345 }); + const controller = createChildProcessController(child, { + processGroup: true, + forceKillAfterMs: 100, + }); + + controller.terminate(); + await vi.advanceTimersByTimeAsync(100); + + expect(signalGroup).toHaveBeenNthCalledWith(1, -12345, "SIGTERM"); + expect(signalGroup).toHaveBeenNthCalledWith(2, -12345, "SIGKILL"); + expect(kill).not.toHaveBeenCalled(); + exit(child, null, "SIGKILL"); + await controller.exited; + }); + + it("ignores a POSIX group that already exited", async ({ expect }) => { + vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + vi.spyOn(process, "kill").mockImplementation(() => { + throw Object.assign(new Error("No such process"), { code: "ESRCH" }); + }); + const { child } = createMockProcess(); + Object.assign(child, { pid: 12345 }); + const controller = createChildProcessController(child, { + processGroup: true, + }); + + expect(() => controller.terminate()).not.toThrow(); + exit(child, 0, null); + await controller.exited; + }); + + it("terminates a Windows command tree without a shell", async ({ + expect, + }) => { + vi.spyOn(process, "platform", "get").mockReturnValue("win32"); + const taskkill = vi.spyOn(childProcess, "execFileSync").mockReturnValue(""); + const { child, kill } = createMockProcess(); + Object.assign(child, { pid: 12345 }); + const controller = createChildProcessController(child, { + processGroup: true, + }); + + controller.terminate(); + + expect(taskkill).toHaveBeenCalledWith( + "taskkill.exe", + ["/PID", "12345", "/T", "/F"], + { stdio: "ignore", windowsHide: true, timeout: 5_000 } + ); + expect(kill).not.toHaveBeenCalled(); + exit(child, null, "SIGTERM"); + await controller.exited; + }); + it("terminates idempotently and force kills after the deadline", async ({ expect, }) => { @@ -133,6 +198,28 @@ describe("createChildProcessController", () => { await controller.exited; }); + it("allows an explicit force kill during graceful group shutdown", async ({ + expect, + }) => { + vi.useFakeTimers(); + vi.spyOn(process, "platform", "get").mockReturnValue("linux"); + const signalGroup = vi.spyOn(process, "kill").mockReturnValue(true); + const { child } = createMockProcess(); + Object.assign(child, { pid: 12345 }); + const controller = createChildProcessController(child, { + processGroup: true, + }); + + controller.terminate("SIGINT"); + controller.terminate("SIGKILL"); + + expect(signalGroup).toHaveBeenNthCalledWith(1, -12345, "SIGINT"); + expect(signalGroup).toHaveBeenNthCalledWith(2, -12345, "SIGKILL"); + expect(vi.getTimerCount()).toBe(0); + exit(child, null, "SIGKILL"); + await controller.exited; + }); + it("can leave graceful shutdown timing to the child", async ({ expect }) => { vi.useFakeTimers(); const { child, kill } = createMockProcess(); diff --git a/packages/cli/src/commands/build/index.ts b/packages/cli/src/commands/build/index.ts index 855c188346..6a55778c38 100644 --- a/packages/cli/src/commands/build/index.ts +++ b/packages/cli/src/commands/build/index.ts @@ -1,4 +1,8 @@ -import { readBuildOutput } from "@cloudflare/build-output-utils"; +import { assertProjectCommandsAvailable } from "@cloudflare/autoconfig"; +import { + BuildOutputError, + readBuildOutput, +} from "@cloudflare/build-output-utils"; import { prepareProject, runProjectCommand } from "../../lib/autoconfig.js"; import { parseWorkerConfig, @@ -42,6 +46,9 @@ export async function runBuild( // configuration the build needs has not been written yet. return "setup-needed"; } + if (details) { + assertProjectCommandsAvailable(details); + } const buildCommand = configuration?.buildCommand ?? details?.buildCommand; const env: Record = { ...details?.env, @@ -64,6 +71,7 @@ export async function runBuild( result = await runProjectCommand(buildCommand, cwd, { ...options, preferLocal: true, + nodeModulesPaths: details?.nodeModulesPaths, env, args: buildArgs, }); @@ -82,7 +90,19 @@ export async function runBuild( throw new CliExit(result.exitCode, { signal: result.signal }); } - const { workers, rootConfig } = await readBuildOutput(cwd); + const { workers, rootConfig } = await readBuildOutput(cwd).catch( + (error: unknown) => { + if ( + env.CLOUDFLARE_VITE_FORCE_BUILD_OUTPUT === "true" && + error instanceof BuildOutputError && + error.code === "not-found" + ) { + error.message += + "\nCheck that your Vite config includes cloudflare() from @cloudflare/vite-plugin."; + } + throw error; + } + ); parseWorkerConfig( selectBuildOutputWorker(workers, selectedWorker), rootConfig @@ -95,8 +115,6 @@ export async function runBuild( function formatImplName(discovered: DiscoveredImpl): string { switch (discovered.impl.pkg) { - case "@cloudflare/vite-plugin": - return "Vite"; case "wrangler": return "Wrangler"; case "cloudflare-py-dev-server": diff --git a/packages/cli/src/commands/dev/discover.ts b/packages/cli/src/commands/dev/discover.ts index e9137715f4..d3c24e9fca 100644 --- a/packages/cli/src/commands/dev/discover.ts +++ b/packages/cli/src/commands/dev/discover.ts @@ -23,7 +23,7 @@ import { findKnownImpl, type KnownImpl } from "./known-impls.js"; * `declared` is always true for entries returned from `discoverImpls`. * `binary` is the resolved path to the impl's executable, or null if * the impl is declared in the manifest but not installed (e.g. - * `package.json` mentions `@cloudflare/vite-plugin` but + * `package.json` mentions `wrangler` but * `node_modules/` is missing). */ export interface DiscoveredImpl { @@ -67,10 +67,11 @@ interface PackageJsonShape { optionalDependencies?: Record; } -function discoverNpm(cwd: string): DiscoveredImpl[] { +/** Read declared npm dependencies independently of supported delegates. */ +export function readDeclaredNpmDependencies(cwd: string): Set { const manifestPath = join(cwd, "package.json"); if (!existsSync(manifestPath)) { - return []; + return new Set(); } let parsed: PackageJsonShape; @@ -80,10 +81,15 @@ function discoverNpm(cwd: string): DiscoveredImpl[] { } catch { // Unreadable / malformed package.json → caller will hit autoconfig // or surface its own error. Discovery treats it as no-match. - return []; + return new Set(); } - const declared = collectDepNames(parsed); + return collectDepNames(parsed); +} + +function discoverNpm(cwd: string): DiscoveredImpl[] { + const manifestPath = join(cwd, "package.json"); + const declared = readDeclaredNpmDependencies(cwd); const out: DiscoveredImpl[] = []; for (const name of declared) { diff --git a/packages/cli/src/commands/dev/impl.ts b/packages/cli/src/commands/dev/impl.ts index 993eee4a8e..3804521455 100644 --- a/packages/cli/src/commands/dev/impl.ts +++ b/packages/cli/src/commands/dev/impl.ts @@ -73,6 +73,10 @@ function noImplError(cwd: string): void { ) ); console.error("\nInstall one of these:"); + console.error( + `\n${theme.bold("@cloudflare/vite-plugin")} ${theme.muted("Vite-based dev server (recommended for JavaScript/TypeScript)")}\n` + + `${" ".repeat(GUIDE_WIDTH)}${theme.code("npm install --save-dev @cloudflare/vite-plugin@rc vite")}` + ); for (const impl of KNOWN_IMPLS) { console.error( `\n${theme.bold(impl.pkg)} ${theme.muted(impl.description)}` diff --git a/packages/cli/src/commands/dev/index.ts b/packages/cli/src/commands/dev/index.ts index 5311dcc34f..e5125cf3bc 100644 --- a/packages/cli/src/commands/dev/index.ts +++ b/packages/cli/src/commands/dev/index.ts @@ -6,6 +6,7 @@ * Cloudflare implementation from the project's npm, PyPI, or Cargo manifest * and spawns its delegate with inherited stdio and forwarded signals. */ +import { assertProjectCommandsAvailable } from "@cloudflare/autoconfig"; import { prepareProject, runProjectCommand } from "../../lib/autoconfig.js"; import { CliExit } from "../../lib/cli-exit.js"; import { theme } from "../../lib/ui/index.js"; @@ -65,6 +66,9 @@ const devCommand: CommandModule = { handler: async (argv: ArgumentsCamelCase): Promise => { const cwd = process.cwd(); const { details } = await prepareProject(cwd); + if (details) { + assertProjectCommandsAvailable(details); + } const implArgs = [...(argv.implArgs ?? []), ...(argv["--"] ?? [])]; const modeArgs = argv.mode ? ["--mode", argv.mode] : []; @@ -80,6 +84,7 @@ const devCommand: CommandModule = { } const result = await runProjectCommand(details.devCommand, cwd, { preferLocal: true, + nodeModulesPaths: details.nodeModulesPaths, env: { ...details.env, ...profileEnv }, args: [...modeArgs, ...implArgs], output: "inherit", diff --git a/packages/cli/src/commands/dev/known-impls.ts b/packages/cli/src/commands/dev/known-impls.ts index 29aae46d44..e4d24523e0 100644 --- a/packages/cli/src/commands/dev/known-impls.ts +++ b/packages/cli/src/commands/dev/known-impls.ts @@ -3,17 +3,15 @@ * * cf does not run a dev server itself — it discovers which impl is * installed in the user's project (one per project, picked by the - * project's manifest) and spawns its delegate binary as a subprocess. + * project's manifest) and spawns its executable as a subprocess. * * Adding an entry to this list is a deliberate cf release: the impl - * must ship a delegate binary at the path declared below, and that + * must provide an executable at the path declared below, and that * binary must accept a `dev` subcommand per the subprocess contract * (long-running with inherited stdio and forwarded signals). * - * Each impl owns its own binary name (`cf-vite`, `cf-wrangler`, etc.) - * so the impl can grow more subcommands later (`build`, `deploy`) - * without needing a separate executable per concern. The dev-loop - * is just one subcommand of the impl's overall delegate surface. + * Autoconfig supplies framework commands, including Vite and Vite+. + * These fallback impls ship delegate binaries such as `cf-wrangler`. * * This file is product knowledge in `src/`, but it's the same * unavoidable kind as "cf is the CLI for Cloudflare" — there's no @@ -29,7 +27,7 @@ export type Ecosystem = "npm" | "pypi" | "cargo"; /** * A known dev-server implementation. * - * `binary(ctx)` resolves the impl's delegate executable from a + * `binary(ctx)` resolves the impl's executable from a * discovery context; the discoverer fills in the right shape * (resolved package root for npm, Python environment hint for PyPI, * etc.). The function returns `null` when the impl is declared in the @@ -51,7 +49,7 @@ export interface KnownImpl { description: string; /** Manifest file the discoverer reads. */ manifest: string; - /** Resolve the impl's delegate binary path. */ + /** Resolve the impl's executable path. */ binary(ctx: ImplResolutionContext): string | null; /** Commands that install the impl, any one of which works. */ installCommands: readonly string[]; @@ -114,21 +112,6 @@ function resolveCargoBinary(): string | null { * deterministic. */ export const KNOWN_IMPLS: readonly KnownImpl[] = [ - { - ecosystem: "npm", - pkg: "@cloudflare/vite-plugin", - versionConstraint: { - range: ">=2.0.0-rc.0 <3.0.0-0", - display: "@cloudflare/vite-plugin v2 (2.0.0-rc.0 or newer)", - }, - description: - "Vite-based dev server (recommended for JavaScript/TypeScript)", - manifest: "package.json", - binary: npmBinaryResolver("cf-vite"), - installCommands: [ - 'npm install --save-dev "@cloudflare/vite-plugin@^2.0.0-rc.0"', - ], - }, { ecosystem: "npm", pkg: "wrangler", diff --git a/packages/cli/src/commands/dev/spawn.ts b/packages/cli/src/commands/dev/spawn.ts index 7f5e989d01..88c5bbb6be 100644 --- a/packages/cli/src/commands/dev/spawn.ts +++ b/packages/cli/src/commands/dev/spawn.ts @@ -1,19 +1,7 @@ /** - * Long-running `cf dev` implementation subprocess. - * - * - cf locates the impl's delegate executable and invokes - * ` dev [argv]`. - * - `cf dev` inherits stdio, so the impl owns the terminal; `build` sends - * the impl's stdout to stderr. - * - cf forwards SIGINT / SIGTERM and exits with the impl's exit code. - * - There is no protocol pipe, no JSON handshake, no capabilities - * negotiation. The `dev` subcommand either exists on the impl's - * delegate or it doesn't — the impl's own "unknown command" error - * surfaces directly to the user, which IS the version check. - * - * The `dev` subcommand is one of (potentially several) that an impl's - * delegate binary supports. Future subcommands like `build` / `deploy` - * will follow the same shape: ` [argv]`. + * Run a Cloudflare delegate as a subprocess. + * Dev inherits the terminal; builds route stdout to stderr. Both preserve + * the child's exit code and termination signal. */ import { constants } from "node:os"; import { x } from "tinyexec"; @@ -178,7 +166,7 @@ function implEnvironment( * (command, prefixArgs) pair. * * Most impls return a plain absolute path (e.g. - * `/path/to/node_modules/@cloudflare/vite-plugin/bin/cf-vite`) and we + * `/path/to/node_modules/wrangler/bin/cf-wrangler.js`) and we * pass it to tinyexec directly. PyPI impls under uv-managed projects return * `uv:` (the discoverer's sentinel), which we expand to * `uv run --no-sync ` so the impl runs in the project's uv diff --git a/packages/cli/src/lib/autoconfig.ts b/packages/cli/src/lib/autoconfig.ts index 279da0e74e..170dfd843d 100644 --- a/packages/cli/src/lib/autoconfig.ts +++ b/packages/cli/src/lib/autoconfig.ts @@ -1,4 +1,5 @@ import { constants } from "node:os"; +import { delimiter, join } from "node:path"; import { AutoConfigDetectionError, getDetailsForAutoConfig, @@ -38,6 +39,7 @@ export interface RunProjectCommandOptions extends CommandOutputOptions { env?: Readonly>; args?: readonly string[]; preferLocal?: boolean; + nodeModulesPaths?: readonly string[]; } export interface ProjectCommandResult { @@ -78,11 +80,6 @@ export async function analyzeProject( target: "cf", context, }); - // Keep using the installed cf delegate when native Vite detection - // cannot resolve a command for the project. - if (details.commandError && !details.devCommand && !details.buildCommand) { - return; - } return maybeApplyVinextCommandOverrides(details); } catch (error) { if (error instanceof AutoConfigDetectionError) { @@ -103,7 +100,11 @@ export async function configureProject( ): Promise { return runAutoConfig(details, { target: "cf", - context: createAutoConfigContext(options), + context: createAutoConfigContext({ + ...options, + env: details.env, + nodeModulesPaths: details.nodeModulesPaths, + }), dryRun: options.dryRun, runBuild: false, }); @@ -114,7 +115,8 @@ export async function configureProject( * takes precedence over framework setup. After either route is applied, the * returned details describe the configured project. In a dry run, * `setupNeeded` means a setup route was selected but not applied, so callers - * must skip the build. + * must skip the build. Callers validate command availability after setup has + * had a chance to install missing tools. */ export async function prepareProject( cwd: string, @@ -128,7 +130,6 @@ export async function prepareProject( if (details?.configured) { return { details }; } - const context = createAutoConfigContext(options); const migrationRan = await maybeMigrateWranglerProject( cwd, @@ -161,6 +162,41 @@ export async function prepareProject( }; } +function projectCommandEnvironment( + cwd: string, + options: RunProjectCommandOptions +): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = { + ...process.env, + ...options.env, + CLOUDFLARE_CF_AUTH: "true", + }; + if (options.preferLocal) { + const pathKey = + process.platform === "win32" + ? (Object.keys(env).findLast((key) => key.toUpperCase() === "PATH") ?? + "PATH") + : "PATH"; + const inheritedPath = env[pathKey]; + const localBins = ( + options.nodeModulesPaths ?? [join(cwd, "node_modules")] + ).map((directory) => join(directory, ".bin")); + env[pathKey] = [ + ...localBins, + ...(inheritedPath ? [inheritedPath] : []), + ].join(delimiter); + if (process.platform === "win32") { + // tinyexec merges process.env again; keep every PATH spelling in sync. + for (const key of Object.keys(env)) { + if (key.toUpperCase() === "PATH") { + env[key] = env[pathKey]; + } + } + } + } + return env; +} + export async function runProjectCommand( command: string, cwd: string, @@ -185,17 +221,21 @@ export async function runProjectCommand( `Delegating to ${command}${formattedArgs ? ` ${formattedArgs}` : ""}${environmentSuffix}` ); } + const env = projectCommandEnvironment(cwd, options); // Match the environment tinyexec gives the child so both resolve the same npm. const [file, ...commandArgs] = resolveNpmLauncher( parseProjectCommand(command), cwd, - { ...process.env, ...options.env } + env ); const subprocess = x(file, [...commandArgs, ...(options.args ?? [])], { - nodePath: options.preferLocal ?? false, + nodePath: false, nodeOptions: { cwd, - env: options.env, + env, + // Launchers can start another tool process (for example, vp starts + // Vite). Give the command a group so signals reach that tool too. + detached: process.platform !== "win32", // Inherited stdin/stderr preserve console Ctrl+C on Windows even // with tinyexec's windowsHide default. stdio: [ @@ -209,28 +249,45 @@ export async function runProjectCommand( ], }, }); - // Retain the five-second SIGTERM fallback for framework commands. + // Retain the five-second forced-shutdown fallback for framework commands. const controller = subprocess.process - ? createChildProcessController(subprocess.process) + ? createChildProcessController(subprocess.process, { processGroup: true }) : undefined; let forwardedSignal: NodeJS.Signals | undefined; const relay = (signal: NodeJS.Signals) => () => { + const repeated = forwardedSignal !== undefined; forwardedSignal ??= signal; // Windows broadcasts Ctrl+C to every process sharing the console. // Resending SIGINT would forcefully terminate the framework command // before its own Ctrl+C handler can finish graceful shutdown. if (shouldRelayProjectCommandSignal(signal)) { - if (signal === "SIGTERM" && controller) { - controller.terminate(signal); + const childSignal = repeated ? "SIGKILL" : signal; + if (controller) { + controller.terminate(childSignal); } else { - subprocess.kill(signal); + subprocess.kill(childSignal); } } }; const onSigInt = relay("SIGINT"); const onSigTerm = relay("SIGTERM"); + const onSigHup = relay("SIGHUP"); + const onExit = () => { + // Parent exit cannot wait for the graceful-shutdown timer. + try { + if (controller) { + controller.terminate("SIGKILL"); + } else { + subprocess.kill("SIGKILL"); + } + } catch { + // Cleanup is best effort once the parent is already exiting. + } + }; process.on("SIGINT", onSigInt); process.on("SIGTERM", onSigTerm); + process.on("SIGHUP", onSigHup); + process.on("exit", onExit); try { const result = await subprocess; @@ -242,6 +299,8 @@ export async function runProjectCommand( } finally { process.off("SIGINT", onSigInt); process.off("SIGTERM", onSigTerm); + process.off("SIGHUP", onSigHup); + process.off("exit", onExit); } } @@ -265,7 +324,7 @@ function parseProjectCommand(command: string): [string, ...string[]] { } function createAutoConfigContext( - commandOptions: CommandOutputOptions = {} + commandOptions: RunProjectCommandOptions = {} ): AutoConfigContext { const output = commandOptions.output ?? "stderr"; const info = output === "silent" ? () => {} : console.error; diff --git a/packages/cli/src/lib/delegate.ts b/packages/cli/src/lib/delegate.ts index d58d2ce74f..7042d161dc 100644 --- a/packages/cli/src/lib/delegate.ts +++ b/packages/cli/src/lib/delegate.ts @@ -267,8 +267,9 @@ function isCompletionInvocation(argv: string[]): boolean { * Spawn the local cf bin under the current Node executable and wait for * it to exit. stdio is fully inherited so the child owns the terminal; * an IPC channel is wired (matching wrangler) so a parent embedding cf - * still receives the child's messages. SIGINT/SIGTERM are relayed so - * Ctrl-C reaches the delegated process. + * still receives the child's messages. With inherited terminal streams, + * SIGINT reaches both CLIs. Without a terminal, SIGINT is relayed; + * SIGTERM is always relayed to the delegated process. */ function runDelegated( binPath: string, @@ -294,11 +295,20 @@ function runDelegated( } }); - const relay = (signal: NodeJS.Signals) => () => { - child.kill(signal); + const hasTerminal = + process.stdin.isTTY || process.stdout.isTTY || process.stderr.isTTY; + const onSigInt = (): void => { + // Terminal interrupts already reach both CLIs. Non-interactive + // callers signal the global PID, so their interrupt needs relaying. + // With a terminal attached, use SIGTERM for programmatic shutdown; + // SIGINT's source cannot be distinguished here. + if (!hasTerminal) { + child.kill("SIGINT"); + } + }; + const onSigTerm = (): void => { + child.kill("SIGTERM"); }; - const onSigInt = relay("SIGINT"); - const onSigTerm = relay("SIGTERM"); process.on("SIGINT", onSigInt); process.on("SIGTERM", onSigTerm); diff --git a/packages/cli/src/lib/process.ts b/packages/cli/src/lib/process.ts index d67f93ca7c..bbe1c2e88a 100644 --- a/packages/cli/src/lib/process.ts +++ b/packages/cli/src/lib/process.ts @@ -1,3 +1,4 @@ +import { execFileSync } from "node:child_process"; import type { ChildProcess } from "node:child_process"; const DEFAULT_FORCE_KILL_AFTER_MS = 5_000; @@ -5,6 +6,8 @@ const DEFAULT_FORCE_KILL_AFTER_MS = 5_000; export interface ChildProcessControllerOptions { /** Forward SIGINT and SIGTERM to the child until it exits. */ forwardSignals?: boolean; + /** Control the whole command tree; POSIX children must use `detached: true`. */ + processGroup?: boolean; /** * Time to wait after requesting shutdown before sending SIGKILL. * Set to `null` to leave graceful shutdown timing to the child. @@ -21,7 +24,7 @@ export interface ChildProcessController { /** Rejects on a process error; otherwise resolves when the child exits. */ exited: Promise; readonly terminationRequested: boolean; - /** Request graceful shutdown, with the configured forced-shutdown fallback. */ + /** Request shutdown; explicit SIGKILL also overrides a pending graceful shutdown. */ terminate(signal?: NodeJS.Signals): void; } @@ -38,22 +41,54 @@ export function createChildProcessController( options.forceKillAfterMs === undefined ? DEFAULT_FORCE_KILL_AFTER_MS : options.forceKillAfterMs; + const kill = (signal: NodeJS.Signals): void => { + if (!options.processGroup || child.pid === undefined) { + child.kill(signal); + return; + } + if (process.platform === "win32") { + // Windows has no POSIX process groups or graceful SIGTERM. Kill the + // tree before its launcher exits and leaves the actual tool running. + try { + execFileSync("taskkill.exe", ["/PID", String(child.pid), "/T", "/F"], { + stdio: "ignore", + windowsHide: true, + timeout: 5_000, + }); + } catch { + child.kill(signal); + } + return; + } + try { + process.kill(-child.pid, signal); + } catch (error) { + if ( + !(error instanceof Error && "code" in error && error.code === "ESRCH") + ) { + throw error; + } + } + }; const terminate = (signal: NodeJS.Signals = "SIGTERM"): void => { if ( child.exitCode !== null || child.signalCode !== null || - terminationRequested + (terminationRequested && signal !== "SIGKILL") ) { return; } terminationRequested = true; - child.kill(signal); + if (signal === "SIGKILL" && forceKillTimer) { + clearTimeout(forceKillTimer); + } + kill(signal); if (signal !== "SIGKILL" && forceKillAfterMs !== null) { forceKillTimer = setTimeout(() => { if (child.exitCode === null && child.signalCode === null) { - child.kill("SIGKILL"); + kill("SIGKILL"); } }, forceKillAfterMs); forceKillTimer.unref(); @@ -68,7 +103,7 @@ export function createChildProcessController( return; } if (terminationRequested) { - child.kill("SIGKILL"); + kill("SIGKILL"); return; } terminate(signal); diff --git a/packages/cli/src/lib/wrangler-migration.ts b/packages/cli/src/lib/wrangler-migration.ts index 8df059e20c..a65ce58198 100644 --- a/packages/cli/src/lib/wrangler-migration.ts +++ b/packages/cli/src/lib/wrangler-migration.ts @@ -95,9 +95,10 @@ export async function resolveWranglerConfigPath( export async function detectWranglerMigrationBundler( configPath: string ): Promise { - const { discoverImpls } = await import("../commands/dev/discover.js"); - return discoverImpls(path.dirname(configPath)).some( - ({ impl }) => impl.pkg === "@cloudflare/vite-plugin" + const { readDeclaredNpmDependencies } = + await import("../commands/dev/discover.js"); + return readDeclaredNpmDependencies(path.dirname(configPath)).has( + "@cloudflare/vite-plugin" ) ? "vite" : "wrangler"; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1148b97fb3..8de00cc793 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -242,6 +242,9 @@ importers: vite: specifier: 'catalog:' version: '@voidzero-dev/vite-plus-core@1.5.0(@types/node@26.6.6)(esbuild@0.28.2)(tsx@4.21.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' + vite-plus: + specifier: 'catalog:' + version: 1.5.0(@types/node@26.6.6)(@vitest/ui@5.1.0)(esbuild@0.28.2)(tsx@4.21.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0) wrangler: specifier: 4.163.0 version: 4.163.0(@cloudflare/workers-types@5.20261116.1)(@types/node@26.6.6) From 0773ab41bbfac5caf6d5a7e0ec43592e0a2dbc7f Mon Sep 17 00:00:00 2001 From: Pete Bacon Darwin Date: Mon, 16 Nov 2026 13:28:06 +0000 Subject: [PATCH 2/3] fix: require Vite plugin RC for Build Output v1 --- .changeset/native-vite-fallback.md | 2 +- packages/cli/AGENTS.md | 2 +- .../__tests__/commands/build/index.test.ts | 61 ++++++++++++++++++- .../src/__tests__/commands/dev/index.test.ts | 8 ++- packages/cli/src/lib/autoconfig.ts | 43 ++++++++++++- 5 files changed, 110 insertions(+), 6 deletions(-) diff --git a/.changeset/native-vite-fallback.md b/.changeset/native-vite-fallback.md index c80de9aee0..1aa1e4cab3 100644 --- a/.changeset/native-vite-fallback.md +++ b/.changeset/native-vite-fallback.md @@ -4,6 +4,6 @@ Run Vite and Vite+ commands selected by autoconfig -Stop requiring the experimental internal `cf-vite` executable from `@cloudflare/vite-plugin`. Autoconfig selects the project's installed Vite or Vite+ executable for dev, build, and workflows that build before deploying, including projects without a detected framework command. cf executes the returned commands with argument forwarding, plugin compatibility checks, and Preview context, while preserving Pages and unsupported project setup guards. Support framework dependencies installed in the application or hoisted within its workspace. Recognize an existing Cloudflare configuration before dependencies are installed, and provide install guidance when a development or build command cannot run. Let Vite evaluate dynamic configurations and custom config files, and suggest checking `cloudflare()` when a successful Vite build produces no Build Output. Keep the Vite plugin's binding defaults unchanged. To explicitly disable remote bindings, set `remoteBindings: false` in the plugin configuration; the internal delegate's `--local` flag is no longer available. +Stop requiring the experimental internal `cf-vite` executable from `@cloudflare/vite-plugin`. Autoconfig selects the project's installed Vite or Vite+ executable for dev, build, and workflows that build before deploying, including projects without a detected framework command. cf executes the returned commands with argument forwarding, plugin compatibility checks, and Preview context, while preserving Pages and unsupported project setup guards. Require `@cloudflare/vite-plugin >=2.0.0-rc.0 <3` for Build Output v1, rejecting older betas before starting their commands. Support framework dependencies installed in the application or hoisted within its workspace. Recognize an existing Cloudflare configuration before dependencies are installed, and provide install guidance when a development or build command cannot run. Let Vite evaluate dynamic configurations and custom config files, and suggest checking `cloudflare()` when a successful Vite build produces no Build Output. Keep the Vite plugin's binding defaults unchanged. To explicitly disable remote bindings, set `remoteBindings: false` in the plugin configuration; the internal delegate's `--local` flag is no longer available. Forward shutdown signals to the command tree, force termination on a repeated interrupt, and attempt synchronous cleanup when cf exits before its command. Preserve graceful shutdown through global-to-local cf delegation by avoiding duplicate terminal interrupts. On POSIX, also forward SIGHUP when the terminal closes. Cleanup cannot run when cf itself receives SIGKILL. diff --git a/packages/cli/AGENTS.md b/packages/cli/AGENTS.md index c37eea0a77..518cd513d2 100644 --- a/packages/cli/AGENTS.md +++ b/packages/cli/AGENTS.md @@ -83,7 +83,7 @@ public AI Search endpoint, outside the platform API/SDK, and returns ranked JSON page metadata without authentication. Agents fetch returned URLs with `Accept: text/markdown` to read complete pages. -`auth`, `complete`, `dev`, `build`, `deploy`, `migrate`, `cli`, `schema`, and `tools` are root entries in `src/commands/hand-written.ts`, registered lazily by `src/index.ts`. `cf cli telemetry` is the telemetry-settings path. `cf migrate` uses `@cloudflare/codemods` to convert a Wrangler configuration to `cloudflare.config.ts` and report manual follow-up work. `cf dev` analyzes and, when needed, configures a project before running its canonical framework command, with an installed Cloudflare implementation as fallback. Autoconfig owns Vite/Vite+ command selection and plugin compatibility checks, including the minimum version for cf profiles and projects without a detected framework command. Vite evaluates its own configuration; cf adds a `cloudflare()` hint when a successful Vite build produces no Build Output. Execute its returned dev/build commands through the project command runner; reserve delegate discovery for Wrangler, Python, and Rust. Bare commands prepend autoconfig's ordered `nodeModulesPaths`: the application's `node_modules/.bin` and ancestor directories up to its validated workspace root. Inherited PATH remains available for ordinary project commands. `cf build` follows the same routing and validates the resulting Build Output. `cf deploy`, `cf previews deploy`, and `cf workers versions create` accept an optional `[directory]` containing already-built, assets-only content and write it into Build Output without delegation; Preview output is marked with Preview context. The directory form reuses an optional source Worker config but rejects configured entrypoints and Containers, so server-side projects omit it and use the normal build path. Without the positional argument, these commands build first unless `--prebuilt` is passed, then read Build Output and call `@cloudflare/deploy-helpers`; Preview names use `--preview-name`, and version creation uploads without deploying. `cf workers triggers deploy` likewise builds by default or consumes `--prebuilt` Build Output, but only applies the configured triggers and does not accept an assets directory. Deploy-helper provisioning is enabled for supported bindings. +`auth`, `complete`, `dev`, `build`, `deploy`, `migrate`, `cli`, `schema`, and `tools` are root entries in `src/commands/hand-written.ts`, registered lazily by `src/index.ts`. `cf cli telemetry` is the telemetry-settings path. `cf migrate` uses `@cloudflare/codemods` to convert a Wrangler configuration to `cloudflare.config.ts` and report manual follow-up work. `cf dev` analyzes and, when needed, configures a project before running its canonical framework command, with an installed Cloudflare implementation as fallback. Autoconfig owns Vite/Vite+ command selection and plugin compatibility checks, including the minimum version for cf profiles and projects without a detected framework command. Until autoconfig raises its beta compatibility floor, cf additionally requires `@cloudflare/vite-plugin >=2.0.0-rc.0 <3` for Vite-based Build Output v1 producers, recording the failure during analysis and validating it after setup. Vite evaluates its own configuration; cf adds a `cloudflare()` hint when a successful Vite build produces no Build Output. Execute its returned dev/build commands through the project command runner; reserve delegate discovery for Wrangler, Python, and Rust. Bare commands prepend autoconfig's ordered `nodeModulesPaths`: the application's `node_modules/.bin` and ancestor directories up to its validated workspace root. Inherited PATH remains available for ordinary project commands. `cf build` follows the same routing and validates the resulting Build Output. `cf deploy`, `cf previews deploy`, and `cf workers versions create` accept an optional `[directory]` containing already-built, assets-only content and write it into Build Output without delegation; Preview output is marked with Preview context. The directory form reuses an optional source Worker config but rejects configured entrypoints and Containers, so server-side projects omit it and use the normal build path. Without the positional argument, these commands build first unless `--prebuilt` is passed, then read Build Output and call `@cloudflare/deploy-helpers`; Preview names use `--preview-name`, and version creation uploads without deploying. `cf workers triggers deploy` likewise builds by default or consumes `--prebuilt` Build Output, but only applies the configured triggers and does not accept an assets directory. Deploy-helper provisioning is enabled for supported bindings. `previews` uses a generated group containing the hand-written `previews deploy` workflow. Its parent override opts into `createIfMissing`, so generation creates an empty API parent when the pinned schema has no Preview CLI operations. Future schema operations join the same group without colliding with a hand-written root. diff --git a/packages/cli/src/__tests__/commands/build/index.test.ts b/packages/cli/src/__tests__/commands/build/index.test.ts index 43e606e8e1..adcd2f8541 100644 --- a/packages/cli/src/__tests__/commands/build/index.test.ts +++ b/packages/cli/src/__tests__/commands/build/index.test.ts @@ -1,4 +1,4 @@ -import { readFileSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import { resolve } from "node:path"; import { mockConsoleMethods, @@ -87,6 +87,65 @@ describe("cf build", () => { expect(readArgv("argv.out")).toEqual(["build"]); }); + describe.each(["native Vite", "Vite", "Vite+"])( + "Build Output v0 plugin (%s)", + (project) => { + const vitePlus = project === "Vite+"; + it.each([ + ["dev"], + ["build"], + ["deploy"], + ["workers", "versions", "create"], + ["previews", "deploy", "--preview-name", "feature"], + ])("rejects the beta plugin before %s starts", async (...command) => { + const tool = vitePlus ? "vite-plus" : "vite"; + const binary = vitePlus ? "vp" : "vite"; + await seed({ + "package.json": JSON.stringify({ + devDependencies: { + "@cloudflare/vite-plugin": "2.0.0-beta.v.17", + ...(vitePlus + ? { "vite-plus": "1.5.0" } + : project === "Vite" + ? { vite: "8.1.0" } + : {}), + }, + }), + "cloudflare.config.ts": "export default {};", + "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ + name: "@cloudflare/vite-plugin", + version: "2.0.0-beta.v.17", + dependencies: { "@cloudflare/build-output-utils": "0.9.14" }, + }), + [`node_modules/${tool}/package.json`]: JSON.stringify({ + name: tool, + bin: { [binary]: "cli.js" }, + }), + [`node_modules/.bin/${binary}`]: nodeScript( + `require("../${tool}/cli.js");` + ), + [`node_modules/${tool}/cli.js`]: buildScript( + "beta-worker" + ).replaceAll("/v1/", "/v0/"), + }); + makeExecutable(`node_modules/${tool}/cli.js`); + makeExecutable(`node_modules/.bin/${binary}`, { npmBin: true }); + + await expect(runCf(command)).rejects.toThrow( + "cf requires @cloudflare/vite-plugin >=2.0.0-rc.0 <3" + ); + + expect(unframe(std.err)).toContain( + "@cloudflare/vite-plugin@2.0.0-beta.v.17 is installed" + ); + expect(unframe(std.err)).toContain("Build Output v1"); + expect(unframe(std.err)).toContain("@cloudflare/vite-plugin@rc"); + expect(existsSync("argv.out")).toBe(false); + expect(existsSync(".cloudflare/output/v0")).toBe(false); + }); + } + ); + it.each([false, true])( "passes mode and Preview context to native Vite (Preview: %s)", async (isPreview) => { diff --git a/packages/cli/src/__tests__/commands/dev/index.test.ts b/packages/cli/src/__tests__/commands/dev/index.test.ts index 4265f65cc9..22e69a9ea4 100644 --- a/packages/cli/src/__tests__/commands/dev/index.test.ts +++ b/packages/cli/src/__tests__/commands/dev/index.test.ts @@ -96,6 +96,8 @@ describe("cf dev", () => { { vitePlus: false, version: "2.0.0-rc.0" }, { vitePlus: true, version: "2.0.0-rc.0" }, { vitePlus: false, version: "2.0.0-beta.v.12" }, + { vitePlus: false, version: "2.0.0-beta.v.17" }, + { vitePlus: true, version: "2.0.0-beta.v.17" }, ])( "checks and runs hoisted workspace tools (Vite+: $vitePlus, plugin: $version)", async ({ vitePlus, version }) => { @@ -132,9 +134,11 @@ describe("cf dev", () => { makeExecutable(`node_modules/.bin/${binary}`, { npmBin: true }); process.chdir(resolve("apps/site")); const run = runCf(["dev", "--profile", "work", "--mode", "staging"]); - if (version === "2.0.0-beta.v.12") { + if (version !== "2.0.0-rc.0") { await expect(run).rejects.toThrow( - "cf requires @cloudflare/vite-plugin >=2.0.0-beta.v.13 <3" + version === "2.0.0-beta.v.12" + ? "cf requires @cloudflare/vite-plugin >=2.0.0-beta.v.13 <3" + : "cf requires @cloudflare/vite-plugin >=2.0.0-rc.0 <3" ); expect(existsSync("argv.json")).toBe(false); return; diff --git a/packages/cli/src/lib/autoconfig.ts b/packages/cli/src/lib/autoconfig.ts index 170dfd843d..7000e8c090 100644 --- a/packages/cli/src/lib/autoconfig.ts +++ b/packages/cli/src/lib/autoconfig.ts @@ -1,3 +1,4 @@ +import { existsSync, readFileSync } from "node:fs"; import { constants } from "node:os"; import { delimiter, join } from "node:path"; import { @@ -5,6 +6,7 @@ import { getDetailsForAutoConfig, runAutoConfig, } from "@cloudflare/autoconfig"; +import satisfies from "semver/functions/satisfies.js"; import { parse as parseShell } from "shell-quote"; import { x } from "tinyexec"; import { CliExit } from "./cli-exit.js"; @@ -80,7 +82,9 @@ export async function analyzeProject( target: "cf", context, }); - return maybeApplyVinextCommandOverrides(details); + return withBuildOutputV1Compatibility( + maybeApplyVinextCommandOverrides(details) + ); } catch (error) { if (error instanceof AutoConfigDetectionError) { context.logger.debug("Autoconfig could not detect this project:", error); @@ -90,6 +94,43 @@ export async function analyzeProject( } } +// Autoconfig 0.13.0 accepts Vite plugin betas that emit Build Output v0. +// cf's v1 reader needs the RC, including for canonical framework commands. +function withBuildOutputV1Compatibility( + details: AutoConfigDetails +): AutoConfigDetails { + if ( + details.commandError || + details.env?.CLOUDFLARE_VITE_FORCE_BUILD_OUTPUT !== "true" + ) { + return details; + } + const manifest = ( + details.nodeModulesPaths ?? [join(details.projectPath, "node_modules")] + ) + .map((directory) => join(directory, "@cloudflare/vite-plugin/package.json")) + .find((path) => existsSync(path)); + if (!manifest) { + return details; + } + const { version } = JSON.parse(readFileSync(manifest, "utf8")) as { + version?: unknown; + }; + if ( + typeof version !== "string" || + satisfies(version, ">=2.0.0-rc.0 <3", { includePrerelease: true }) + ) { + return details; + } + return { + ...details, + commandError: { + code: "vite-plugin-incompatible", + message: `@cloudflare/vite-plugin@${version} is installed, but cf requires @cloudflare/vite-plugin >=2.0.0-rc.0 <3 to produce Build Output v1. Update to @cloudflare/vite-plugin@rc.`, + }, + }; +} + /** * Run framework autoconfig after detection, applying or dry-running setup * without building. From c8c96524fbd05e71ddc63ff89e876e69ae21e4d8 Mon Sep 17 00:00:00 2001 From: Pete Bacon Darwin Date: Mon, 16 Nov 2026 14:29:56 +0000 Subject: [PATCH 3/3] Apply suggestion from @edmundhung Co-authored-by: Edmund Hung --- .changeset/native-vite-fallback.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.changeset/native-vite-fallback.md b/.changeset/native-vite-fallback.md index 1aa1e4cab3..ed3bcbb7f2 100644 --- a/.changeset/native-vite-fallback.md +++ b/.changeset/native-vite-fallback.md @@ -2,8 +2,8 @@ "cf": minor --- -Run Vite and Vite+ commands selected by autoconfig +Run the project's own Vite or Vite+ commands -Stop requiring the experimental internal `cf-vite` executable from `@cloudflare/vite-plugin`. Autoconfig selects the project's installed Vite or Vite+ executable for dev, build, and workflows that build before deploying, including projects without a detected framework command. cf executes the returned commands with argument forwarding, plugin compatibility checks, and Preview context, while preserving Pages and unsupported project setup guards. Require `@cloudflare/vite-plugin >=2.0.0-rc.0 <3` for Build Output v1, rejecting older betas before starting their commands. Support framework dependencies installed in the application or hoisted within its workspace. Recognize an existing Cloudflare configuration before dependencies are installed, and provide install guidance when a development or build command cannot run. Let Vite evaluate dynamic configurations and custom config files, and suggest checking `cloudflare()` when a successful Vite build produces no Build Output. Keep the Vite plugin's binding defaults unchanged. To explicitly disable remote bindings, set `remoteBindings: false` in the plugin configuration; the internal delegate's `--local` flag is no longer available. +`cf dev`, `cf build` and `cf deploy` now run the project's installed `vite` or `vp` (Vite+) instead of the internal `cf-vite` executable from `@cloudflare/vite-plugin` when autoconfig identifies it as a Vite project. If you were running `cf dev -- --local`, set `remoteBindings: false` in `cloudflare()` to turn off remote bindings. -Forward shutdown signals to the command tree, force termination on a repeated interrupt, and attempt synchronous cleanup when cf exits before its command. Preserve graceful shutdown through global-to-local cf delegation by avoiding duplicate terminal interrupts. On POSIX, also forward SIGHUP when the terminal closes. Cleanup cannot run when cf itself receives SIGKILL. +Stopping cf now also stops tools that launchers such as `vp` start, and on macOS and Linux a second Ctrl+C force-stops the command.