From ebe4f348c183ddc962e65b21479b5b55c025835f Mon Sep 17 00:00:00 2001 From: Mathieu Laurent Date: Sat, 14 Nov 2026 23:07:51 +0100 Subject: [PATCH] feat(cloudflare): per-pull-request previews with void deploy --preview Add `void deploy --platform cloudflare --preview [--json]` and `void preview delete `, built on Cloudflare Workers Previews. A Preview is a named, isolated environment of the same Worker with a stable `-..workers.dev` URL. Deploying the same name again updates it; production traffic, the active deployment, routes and schedules are never touched, and a Preview gets no production secrets. - @void/deploy-cloudflare: `previews.deploy` / `previews.delete` operations, `deployCloudflarePreview` (sends only `previews.deploy`), `deleteCloudflarePreview` (a missing Preview, 10025, counts as deleted) and name validation. - void: the static deploy prepares its Build Output as a Preview build and publishes it through `cf previews deploy --prebuilt` instead of activating a version. Apps that need a Worker, an existing-Worker handoff, and --atomic/--provision/--require-email are refused before anything is built or uploaded. A preview never saves an account for the project. - --json prints one record on stdout (workerName, previewName, previewUrl, deploymentId, deploymentUrl); progress goes to stderr through an explicit progress stream in output.ts. - When the Worker has Preview URLs turned off, the deploy fails and points at `cloudflare.preview_urls` in void.config.ts. - Help, interactive hints, CLI reference, a pull request workflow in the Cloudflare integration guide, and the skill. Refs #467, #471. --- docs/integrations/cloudflare.md | 71 +++++++ docs/reference/cli.md | 4 +- docs/reference/cli/deploy.md | 43 +++++ packages/deploy-cloudflare/src/diagnostics.ts | 6 + packages/deploy-cloudflare/src/index.ts | 8 + packages/deploy-cloudflare/src/operations.ts | 19 ++ packages/deploy-cloudflare/src/preview.ts | 179 ++++++++++++++++++ packages/deploy-cloudflare/src/version.ts | 7 +- .../test/operation-fixture.ts | 4 + .../test/unit/preview.test.ts | 140 ++++++++++++++ packages/void/skills/void/SKILL.md | 2 + packages/void/src/cli/args.ts | 31 +++ packages/void/src/cli/cf-build-output.ts | 12 +- packages/void/src/cli/cf-command-values.ts | 44 +++++ packages/void/src/cli/cf-version-runner.ts | 20 ++ packages/void/src/cli/cli-main.ts | 16 +- .../src/cli/cloudflare-operation-process.ts | 16 ++ .../void/src/cli/deploy-cloudflare-helpers.ts | 8 +- .../void/src/cli/deploy-cloudflare-static.ts | 130 +++++++++++-- packages/void/src/cli/deploy-cloudflare.ts | 16 ++ packages/void/src/cli/deploy-helpers.ts | 27 ++- packages/void/src/cli/deploy-summary.ts | 3 +- packages/void/src/cli/deploy-types.ts | 7 + packages/void/src/cli/deploy.ts | 11 +- packages/void/src/cli/help.ts | 32 ++++ packages/void/src/cli/output.ts | 41 +++- packages/void/src/cli/preview-args.ts | 25 +++ packages/void/src/cli/preview-cmd.ts | 91 +++++++++ .../void/test/unit/cf-build-output.test.ts | 16 ++ .../void/test/unit/cf-version-runner.test.ts | 61 ++++++ .../void/test/unit/cloudflare-deploy.test.ts | 155 +++++++++++++++ packages/void/test/unit/deploy-args.test.ts | 35 ++++ packages/void/test/unit/preview-args.test.ts | 16 ++ 33 files changed, 1262 insertions(+), 34 deletions(-) create mode 100644 packages/deploy-cloudflare/src/preview.ts create mode 100644 packages/deploy-cloudflare/test/unit/preview.test.ts create mode 100644 packages/void/src/cli/preview-args.ts create mode 100644 packages/void/src/cli/preview-cmd.ts create mode 100644 packages/void/test/unit/preview-args.test.ts diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index a8ab0039c..f55236589 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -145,6 +145,77 @@ Set these CI secrets and variables as needed: For email, run `void email setup --platform cloudflare` locally, commit `void.lock.json`, and pass `--require-email` in CI. The token also needs Email Routing Edit and Email Sending Edit. +### Pull request previews + +Give each pull request its own URL with [Cloudflare Previews](https://developers.cloudflare.com/workers/previews/). A Preview belongs to the same Worker but never receives production traffic. Previews are available for static sites, SPAs and supported SSGs. + +```sh +void deploy --platform cloudflare --preview pr-64 --json # create or update +void preview delete pr-64 # remove +``` + +The CI job needs only `CLOUDFLARE_API_TOKEN` (Workers Scripts: Edit) and, when the token can access several accounts, `CLOUDFLARE_ACCOUNT_ID`. This workflow deploys a preview on every push to a pull request, comments its URL, and deletes it when the pull request closes: + +```yaml +name: Preview + +on: + pull_request: + types: [opened, synchronize, reopened, closed] + +permissions: + contents: read + pull-requests: write + +concurrency: + group: preview-${{ github.event.pull_request.number }} + +jobs: + preview: + # Repository secrets are not available to pull requests from forks. + if: github.event.action != 'closed' && github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: lts/* + check-latest: true + cache: pnpm + - run: pnpm install --frozen-lockfile + - id: preview + run: | + set -o pipefail + url="$(pnpm exec void deploy --platform cloudflare --preview "pr-${{ github.event.pull_request.number }}" --json | jq -er '.previewUrl')" + echo "url=$url" >> "$GITHUB_OUTPUT" + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + - run: gh pr comment "${{ github.event.pull_request.number }}" --edit-last --create-if-none --body "Preview: ${{ steps.preview.outputs.url }}" + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + cleanup: + if: github.event.action == 'closed' && github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: lts/* + check-latest: true + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm exec void preview delete "pr-${{ github.event.pull_request.number }}" + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} +``` + +If the build runs in an earlier job, download its output and add `--skip-build`. Preview URLs are public; protect them with [Cloudflare Access](https://developers.cloudflare.com/workers/configuration/cloudflare-access/) when needed. See [`void deploy --preview`](../reference/cli/deploy.md#void-deploy-preview) for the JSON output and naming rules. + #### Cloudflare Access For local deployment to an Access-protected Worker, you can use a short-lived user session: diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 129582f0f..5e043940c 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -23,7 +23,7 @@ Use this page as a command reference. If you are setting up a project for the fi | `init`, `prepare`, `info`, `migrate` | [Project setup](./cli/setup.md) | | `connect`, `auth`, `account`, `cloudflare` | [Connections and authentication](./cli/auth.md) | | `project` | [Projects, teams, logs, and rollback](./cli/project.md) | -| `deploy` | [Deployment](./cli/deploy.md) | +| `deploy`, `preview` | [Deployment](./cli/deploy.md) | | `db` | [Database](./cli/database.md) | | `gen` | [Code generation](./cli/generate.md) | | `secret`, `env` | [Secrets and environment](./cli/secrets.md) | @@ -40,6 +40,8 @@ Platform administrators can also choose AI Gateway logging [per project](./cli/p | --------------------------------- | ----------------------------------------------------------------------------- | | `void deploy` | Build and deploy to the configured platform | | `void deploy --skip-migrations` | Deploy code without applying application or authentication SQL migrations | +| `void deploy --preview ` | Deploy a Cloudflare Preview with its own URL; production is unchanged | +| `void preview delete ` | Delete a Cloudflare Preview | | `void prepare` | Generate `.void` artifacts without starting Vite | | `void info [--json]` | Inspect persistent resource names before moving their code | | `void gen model [cols...]` | Scaffold a Drizzle table and API routes | diff --git a/docs/reference/cli/deploy.md b/docs/reference/cli/deploy.md index 609481a14..bcd6cbca3 100644 --- a/docs/reference/cli/deploy.md +++ b/docs/reference/cli/deploy.md @@ -12,6 +12,7 @@ void deploy [--project ] [--dir ] [--spa] [--skip-build] [--skip-mig void deploy [--platform ] [--require-email] void deploy --platform cloudflare --atomic void deploy --platform cloudflare --provision +void deploy --platform cloudflare --preview [--json] ``` Auto-detects your project type and chooses the right pipeline. See [Supported App Types](../../guide/app-types.md) and [Deployment](../../guide/deployment.md) for details. @@ -39,6 +40,8 @@ For Drizzle projects, deploy performs a read-only schema drift check. If a new m | `--require-email` | Fail when email cannot be set up instead of deploying without it; requires `--platform cloudflare` | | `--provision` | Run resource provisioning again even when every resource exists, for example to enable D1 read replication on an existing database; requires `--platform cloudflare` | | `--atomic` | Publish an existing Durable Object Worker directly; readiness is checked after traffic changes | +| `--preview ` | Create or update a Cloudflare Preview instead of production; see [Previews](#void-deploy-preview) | +| `--json` | With `--preview`, print the result as one JSON record on stdout; progress goes to stderr | | `--debug` | Mirror the structured deploy log to stderr (also written to `~/.void/logs/`) | `--atomic` applies to one deployment. For an existing Durable Object Worker that consistently cannot stage, set `deploy: { cloudflare: { mode: 'atomic' } }` in `void.config.ts` so plain `void deploy` uses atomic publication. The default is `staged`. @@ -115,3 +118,43 @@ Sandbox requires [Workers Paid](https://dash.cloudflare.com/?to=/:account/worker For email, set `email.from` and run `void email setup --platform cloudflare` locally. Commit the lock file and pass `--require-email` in CI. See [Email setup](../../guide/email/domains.md#your-own-cloudflare-account). For Access credentials, Hyperdrive permissions, readiness, and rollback, see [Cloudflare deployment](../../integrations/cloudflare.md#deploy-to-your-own-cloudflare-account). + +## `void deploy --platform cloudflare --preview ` {#void-deploy-preview} + +Deploy the build to a named [Cloudflare Preview](https://developers.cloudflare.com/workers/previews/) of the same Worker: + +```sh +void deploy --platform cloudflare --skip-build --preview pr-64 --json +``` + +A Preview has its own stable URL, `https://-..workers.dev`, which always serves its latest deployment. Deploying the same name again updates that URL. Production traffic, the active deployment, routes and schedules are unchanged. + +Previews are available for static sites, SPAs and supported SSGs. Apps that need a Worker, such as server routes, bindings, migrations or secrets, are refused before anything is built or uploaded. A Preview does not inherit production secrets. + +The name uses lowercase letters, digits and hyphens. `-` must fit in 63 characters. Use a name derived from the pull request, such as `pr-64`, rather than a branch name. + +With `--json`, stdout carries one line: + +```json +{ + "workerName": "my-app", + "previewName": "pr-64", + "previewUrl": "https://pr-64-my-app.my-team.workers.dev", + "deploymentId": "…", + "deploymentUrl": "https://…-my-app.my-team.workers.dev" +} +``` + +`previewUrl` always serves the latest deployment of this Preview. `deploymentUrl` serves only this deployment. + +The Worker must allow Preview URLs. Void's production deploy turns them on when workers.dev is on. If you set `cloudflare.preview_urls` to `false` in `void.config.ts`, a preview deploy fails and says how to turn it back on. Workers Free allows 100 Previews per Worker; Cloudflare removes the least recently deployed one beyond that. + +See [Pull request previews](../../integrations/cloudflare.md#pull-request-previews) for a GitHub Actions workflow. + +## `void preview delete ` {#void-preview-delete} + +```sh +void preview delete pr-64 +``` + +Delete a Preview and all its deployments. Production is unchanged. Deleting a Preview that does not exist succeeds, so a cleanup job can run more than once. It uses the same account and Worker as `void deploy --platform cloudflare`. diff --git a/packages/deploy-cloudflare/src/diagnostics.ts b/packages/deploy-cloudflare/src/diagnostics.ts index d6804342b..684b0f749 100644 --- a/packages/deploy-cloudflare/src/diagnostics.ts +++ b/packages/deploy-cloudflare/src/diagnostics.ts @@ -82,3 +82,9 @@ export function cloudflareCommandDiagnostic(result: CloudflareCommandResult): st .slice(0, MAX_DIAGNOSTIC_LENGTH); return bounded.length < message.length ? `${bounded}\n[diagnostic truncated]` : bounded; } + +/** The uploader's diagnostic as an optional result field. */ +export function commandDiagnosticFields(result: CloudflareCommandResult): { diagnostic?: string } { + const diagnostic = cloudflareCommandDiagnostic(result); + return diagnostic ? { diagnostic } : {}; +} diff --git a/packages/deploy-cloudflare/src/index.ts b/packages/deploy-cloudflare/src/index.ts index 3d5507cd8..1e02de015 100644 --- a/packages/deploy-cloudflare/src/index.ts +++ b/packages/deploy-cloudflare/src/index.ts @@ -53,12 +53,20 @@ export { type CloudflareVersionMetadata, type CloudflareWorkersDevSubdomainLookup, } from './version.ts'; +export { + deleteCloudflarePreview, + deployCloudflarePreview, + validateCloudflarePreviewName, + type CloudflarePreviewDeleteResult, + type CloudflarePreviewDeployResult, +} from './preview.ts'; export { createCloudflareMetadataRunner } from './metadata.ts'; export { cloudflareCommandDiagnostic } from './diagnostics.ts'; export { VOID_SECRET_DRAFT_MESSAGE, VOID_SECRET_DRAFT_SOURCE } from './secret-draft.ts'; export type { CloudflareOperation, + CloudflarePreviewUploadResult, CloudflareUploadResult, CloudflareProviderError, } from './operations.ts'; diff --git a/packages/deploy-cloudflare/src/operations.ts b/packages/deploy-cloudflare/src/operations.ts index a590181a2..a7cff1e5a 100644 --- a/packages/deploy-cloudflare/src/operations.ts +++ b/packages/deploy-cloudflare/src/operations.ts @@ -56,6 +56,15 @@ export type CloudflareOperation = */ interactive?: boolean; } & WorkerTarget) + | ({ + /** + * Create or update a named Workers Preview from the prebuilt output. A Preview has its own + * URL and settings and never receives production traffic. + */ + type: 'previews.deploy'; + previewName: string; + } & WorkerTarget) + | ({ type: 'previews.delete'; previewName: string } & WorkerTarget) | ({ type: 'triggers.deploy'; assets?: boolean } & WorkerTarget) | ({ type: 'triggers.clear-crons' | 'triggers.clear-domains' } & WorkerTarget) | ({ type: 'tail'; search?: string; versionId?: string; status?: 'error' } & WorkerTarget); @@ -66,6 +75,16 @@ export type CloudflareUploadResult = { workersDevUrl?: string; }; +/** Structured `previews.deploy` data, decoded by the runner from the provider's response. */ +export type CloudflarePreviewUploadResult = { + previewId: string; + previewName: string; + deploymentId: string; + /** Absent when the Worker has Preview URLs turned off. */ + previewUrl?: string; + deploymentUrl?: string; +}; + export type CloudflareProviderError = { code?: number; message: string; diff --git a/packages/deploy-cloudflare/src/preview.ts b/packages/deploy-cloudflare/src/preview.ts new file mode 100644 index 000000000..bf9cabaef --- /dev/null +++ b/packages/deploy-cloudflare/src/preview.ts @@ -0,0 +1,179 @@ +import { isRecord } from '@void/deploy-core'; +import { commandDiagnosticFields } from './diagnostics.ts'; +import { + isCleanCommandExit, + isCompletedCommand, + isWorkerNotFound, + type CloudflareCommandRunner, +} from './execute.ts'; +import type { CloudflarePreviewUploadResult } from './operations.ts'; + +/** + * A Preview name becomes the first label of `-..workers.dev`. Accept only + * names Cloudflare uses unchanged, so the URL Void prints is the one CI expects. + */ +const PREVIEW_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/; +/** A DNS label holds at most 63 characters. */ +const MAX_HOST_LABEL = 63; +/** Cloudflare's "Preview not found" API error. */ +const PREVIEW_NOT_FOUND = 10025; + +/** Return why `name` cannot name a Preview of `workerName`, or null when it can. */ +export function validateCloudflarePreviewName(name: string, workerName?: string): string | null { + if (!PREVIEW_NAME.test(name)) { + return `"${name}" is not a valid preview name. Use lowercase letters, digits and hyphens, starting and ending with a letter or digit (for example "pr-64").`; + } + if (workerName !== undefined && name.length + 1 + workerName.length > MAX_HOST_LABEL) { + return `The preview name "${name}" is too long for the Worker "${workerName}": "${name}-${workerName}" must fit in ${MAX_HOST_LABEL} characters to be a workers.dev hostname.`; + } + return null; +} + +export type CloudflarePreviewDeployResult = + | { + ok: true; + previewId: string; + deploymentId: string; + /** The stable URL that always serves this Preview's latest deployment. */ + previewUrl: string; + /** The URL of this deployment only. */ + deploymentUrl: string | undefined; + } + | { + ok: false; + reason: 'uploader-changed' | 'invalid-name' | 'output-invalid'; + diagnostic?: string; + } + | { ok: false; reason: 'deploy-failed'; status: number; diagnostic?: string } + /** Cloudflare created the deployment but returned no Preview URL: `preview_urls` is off. */ + | { ok: false; reason: 'preview-urls-disabled' }; + +/** + * Create or update a named Workers Preview from the prepared output. This only ever sends + * `previews.deploy`: production versions, deployments, traffic and triggers are not read or + * changed, and no migration, provisioning or secret operation runs. + */ +export async function deployCloudflarePreview(options: { + runWrangler: CloudflareCommandRunner; + workerName: string; + previewName: string; + verifyUploader: () => boolean; + configPath?: string; +}): Promise { + const invalid = validateCloudflarePreviewName(options.previewName, options.workerName); + if (invalid) { + return { ok: false, reason: 'invalid-name', diagnostic: invalid }; + } + if (!options.verifyUploader()) { + return { ok: false, reason: 'uploader-changed' }; + } + const result = await options.runWrangler( + { + type: 'previews.deploy', + workerName: options.workerName, + previewName: options.previewName, + ...(options.configPath ? { configPath: options.configPath } : {}), + }, + { capture: true }, + ); + if (!isCleanCommandExit(result)) { + return { + ok: false, + reason: 'deploy-failed', + status: result.status, + ...commandDiagnosticFields(result), + }; + } + const uploaded = readPreviewUploadResult(result.data); + if (!uploaded || uploaded.previewName !== options.previewName) { + return { ok: false, reason: 'output-invalid' }; + } + if (!uploaded.previewUrl) { + return { ok: false, reason: 'preview-urls-disabled' }; + } + return { + ok: true, + previewId: uploaded.previewId, + deploymentId: uploaded.deploymentId, + previewUrl: uploaded.previewUrl, + deploymentUrl: uploaded.deploymentUrl, + }; +} + +export type CloudflarePreviewDeleteResult = + | { ok: true; deleted: boolean } + | { ok: false; reason: 'uploader-changed' | 'invalid-name'; diagnostic?: string } + | { ok: false; reason: 'delete-failed'; status: number; diagnostic?: string }; + +/** + * Delete a named Preview and all its deployments. A Preview that does not exist is reported as + * `deleted: false`, so a pull-request cleanup job can run more than once. + */ +export async function deleteCloudflarePreview(options: { + runWrangler: CloudflareCommandRunner; + workerName: string; + previewName: string; + verifyUploader: () => boolean; + configPath?: string; +}): Promise { + const invalid = validateCloudflarePreviewName(options.previewName); + if (invalid) { + return { ok: false, reason: 'invalid-name', diagnostic: invalid }; + } + if (!options.verifyUploader()) { + return { ok: false, reason: 'uploader-changed' }; + } + const result = await options.runWrangler( + { + type: 'previews.delete', + workerName: options.workerName, + previewName: options.previewName, + ...(options.configPath ? { configPath: options.configPath } : {}), + }, + { capture: true }, + ); + if (isCleanCommandExit(result)) { + return { ok: true, deleted: true }; + } + // Neither the Preview nor, with 10007, its Worker exists: there is nothing left to delete. + if ( + isWorkerNotFound(result) || + (isCompletedCommand(result) && result.errorCode === PREVIEW_NOT_FOUND) + ) { + return { ok: true, deleted: false }; + } + return { + ok: false, + reason: 'delete-failed', + status: result.status, + ...commandDiagnosticFields(result), + }; +} + +/** Validate the structured result the runner decoded from the provider's Preview record. */ +function readPreviewUploadResult(value: unknown): CloudflarePreviewUploadResult | null { + if (!isRecord(value)) { + return null; + } + const { previewId, previewName, deploymentId, previewUrl, deploymentUrl } = value; + const optionalUrl = (url: unknown) => + url === undefined || (typeof url === 'string' && url.startsWith('https://')); + if ( + typeof previewId !== 'string' || + !previewId || + typeof previewName !== 'string' || + typeof deploymentId !== 'string' || + !deploymentId || + !optionalUrl(previewUrl) || + !optionalUrl(deploymentUrl) + ) { + return null; + } + return { + previewId, + previewName, + deploymentId, + ...(previewUrl ? { previewUrl: previewUrl as string } : {}), + ...(deploymentUrl ? { deploymentUrl: deploymentUrl as string } : {}), + }; +} diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 5235a338f..ebb571c79 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -6,7 +6,7 @@ import { isDeepStrictEqual } from 'node:util'; import { canonicalJson, isRecord } from '@void/deploy-core'; import { join } from 'pathslash'; import { parseRootWranglerConfig } from './config.ts'; -import { cloudflareCommandDiagnostic } from './diagnostics.ts'; +import { commandDiagnosticFields } from './diagnostics.ts'; import { isCleanCommandExit, isCompletedCommand, @@ -2522,11 +2522,6 @@ function versionPercentages( }); } -function commandDiagnosticFields(result: CloudflareCommandResult): { diagnostic?: string } { - const diagnostic = cloudflareCommandDiagnostic(result); - return diagnostic ? { diagnostic } : {}; -} - function isContainersUnavailable(result: CloudflareCommandResult): boolean { return ( result.failure === 'containers-unavailable' || diff --git a/packages/deploy-cloudflare/test/operation-fixture.ts b/packages/deploy-cloudflare/test/operation-fixture.ts index cbc52bf49..3987da99c 100644 --- a/packages/deploy-cloudflare/test/operation-fixture.ts +++ b/packages/deploy-cloudflare/test/operation-fixture.ts @@ -193,6 +193,10 @@ export function operationFixtureArgs(operation: CloudflareOperation): Array) { + const calls: Array = []; + const runWrangler: CloudflareCommandRunner = vi.fn((operation: CloudflareOperation) => { + calls.push(operation); + return { status: 0, stdout: '', stderr: '', ...answer }; + }); + return { calls, runWrangler }; +} + +const target = { workerName: 'site', previewName: 'pr-64', verifyUploader: () => true }; + +describe('validateCloudflarePreviewName', () => { + it.each(['pr-64', 'a', 'feature-login', '0'])('accepts %s', (name) => { + expect(validateCloudflarePreviewName(name, 'site')).toBeNull(); + }); + + it.each(['', 'PR-64', 'pr_64', 'feature/login', '-pr', 'pr-', '--flag', 'pr 64'])( + 'rejects %j', + (name) => { + expect(validateCloudflarePreviewName(name, 'site')).toContain('not a valid preview name'); + }, + ); + + it('rejects a name whose workers.dev label would exceed 63 characters', () => { + expect(validateCloudflarePreviewName('pr-64', 'w'.repeat(58))).toContain('63 characters'); + expect(validateCloudflarePreviewName('pr-64', 'w'.repeat(57))).toBeNull(); + }); +}); + +describe('deployCloudflarePreview', () => { + it('sends only previews.deploy and returns the stable Preview URL', async () => { + const { calls, runWrangler } = runner({ data: uploaded }); + expect( + await deployCloudflarePreview({ ...target, runWrangler, configPath: '/app/wrangler.json' }), + ).toEqual({ + ok: true, + previewId: 'prv_1', + deploymentId: 'dep_1', + previewUrl: 'https://pr-64-site.team.workers.dev', + deploymentUrl: 'https://dep1-site.team.workers.dev', + }); + // Production is never read or changed: no versions, deployments, traffic or triggers. + expect(calls).toEqual([ + { + type: 'previews.deploy', + workerName: 'site', + previewName: 'pr-64', + configPath: '/app/wrangler.json', + }, + ]); + }); + + it('rejects an invalid name or a changed uploader before running anything', async () => { + const { calls, runWrangler } = runner({ data: uploaded }); + expect( + await deployCloudflarePreview({ ...target, runWrangler, previewName: '--force' }), + ).toMatchObject({ ok: false, reason: 'invalid-name' }); + expect( + await deployCloudflarePreview({ ...target, runWrangler, verifyUploader: () => false }), + ).toEqual({ ok: false, reason: 'uploader-changed' }); + expect(calls).toEqual([]); + }); + + it('reports a failed deploy', async () => { + const { runWrangler } = runner({ status: 1, errors: [{ message: 'Authentication error' }] }); + expect(await deployCloudflarePreview({ ...target, runWrangler })).toMatchObject({ + ok: false, + reason: 'deploy-failed', + status: 1, + }); + }); + + it('reports disabled Preview URLs when Cloudflare returns none', async () => { + const { previewUrl: _, ...withoutUrl } = uploaded; + const { runWrangler } = runner({ data: withoutUrl }); + expect(await deployCloudflarePreview({ ...target, runWrangler })).toEqual({ + ok: false, + reason: 'preview-urls-disabled', + }); + }); + + it.each([ + { ...uploaded, previewName: 'pr-65' }, + { ...uploaded, previewUrl: 'http://pr-64-site.team.workers.dev' }, + { ...uploaded, deploymentId: '' }, + undefined, + ])('rejects an unreadable or foreign Preview record %#', async (data) => { + const { runWrangler } = runner({ data }); + expect(await deployCloudflarePreview({ ...target, runWrangler })).toEqual({ + ok: false, + reason: 'output-invalid', + }); + }); +}); + +describe('deleteCloudflarePreview', () => { + it('deletes the named Preview of the Worker', async () => { + const { calls, runWrangler } = runner({}); + expect(await deleteCloudflarePreview({ ...target, runWrangler })).toEqual({ + ok: true, + deleted: true, + }); + expect(calls).toEqual([{ type: 'previews.delete', workerName: 'site', previewName: 'pr-64' }]); + }); + + // 10025: "Preview not found", as Cloudflare answered in a live run. 10007: no such Worker. + it.each([10025, 10007])('treats error %i as already deleted', async (errorCode) => { + const { runWrangler } = runner({ status: 1, errorCode }); + expect(await deleteCloudflarePreview({ ...target, runWrangler })).toEqual({ + ok: true, + deleted: false, + }); + }); + + it('reports other failures', async () => { + const { runWrangler } = runner({ status: 1, errorCode: 10000 }); + expect(await deleteCloudflarePreview({ ...target, runWrangler })).toMatchObject({ + ok: false, + reason: 'delete-failed', + status: 1, + }); + }); +}); diff --git a/packages/void/skills/void/SKILL.md b/packages/void/skills/void/SKILL.md index 24550f2c0..0f6400591 100644 --- a/packages/void/skills/void/SKILL.md +++ b/packages/void/skills/void/SKILL.md @@ -32,6 +32,8 @@ For a one-time deployment elsewhere, connect to that platform, then set `VOID_API_URL` for the deploy command and pass `--project `. This preserves the app's existing saved destination, including when the target project is new. +For a per-pull-request Cloudflare preview of a static site or SPA, use `void deploy --platform cloudflare --preview pr- --json` and `void preview delete pr-` on close; see `docs/reference/cli/deploy.md`. + Use `void deploy --skip-migrations` when database migrations run separately; it skips application and authentication SQL for that invocation. Ensure the code supports the current database schema and follow `docs/guide/deployment.md` for the release workflow. ## Task Routing diff --git a/packages/void/src/cli/args.ts b/packages/void/src/cli/args.ts index b61d5edcd..1e8557662 100644 --- a/packages/void/src/cli/args.ts +++ b/packages/void/src/cli/args.ts @@ -19,6 +19,8 @@ export function parseDeployArgs( provision: { type: 'boolean' }, 'require-email': { type: 'boolean' }, atomic: { type: 'boolean' }, + preview: { type: 'string' }, + json: { type: 'boolean' }, }, allowPositionals: true, strict: true, @@ -32,6 +34,9 @@ export function parseDeployArgs( if (optionMatch?.[1] === '--platform') { throw new Error("deploy: --platform requires a value ('cloudflare' or 'void')."); } + if (optionMatch?.[1] === '--preview') { + throw new Error('deploy: --preview requires a name (for example --preview pr-64).'); + } throw new Error('deploy: --project requires a slug.'); } @@ -106,7 +111,33 @@ export function parseDeployArgs( } } + if (tokens.filter((token) => token.kind === 'option' && token.name === 'preview').length > 1) { + throw new Error('deploy: --preview can only be specified once.'); + } + const preview = typeof parsed.values.preview === 'string' ? parsed.values.preview : undefined; + const json = parsed.values.json === true ? true : undefined; + if (preview !== undefined) { + if (platform !== 'cloudflare') { + throw new Error('deploy: --preview requires --platform cloudflare.'); + } + // The name itself is checked against the Worker name before the build. + for (const [flag, set] of [ + ['--atomic', atomic], + ['--provision', provision], + ['--require-email', requireEmail], + ] as const) { + if (set) { + throw new Error(`deploy: ${flag} cannot be combined with --preview.`); + } + } + } + if (json && preview === undefined) { + throw new Error('deploy: --json is available only with --preview.'); + } + return { + preview, + json, projectSlug, dir, spa, diff --git a/packages/void/src/cli/cf-build-output.ts b/packages/void/src/cli/cf-build-output.ts index 594aefaf2..3a8d6a897 100644 --- a/packages/void/src/cli/cf-build-output.ts +++ b/packages/void/src/cli/cf-build-output.ts @@ -156,6 +156,8 @@ export async function prepareCfBuildOutput( accountId?: string, mode?: string, projectRoot: string = workerDirectory, + /** Mark the output as a Preview build, which `cf previews deploy` requires. */ + options: { isPreview?: boolean } = {}, ): Promise { const source = resolve(workerDirectory); if (existsSync(getRootConfigPath(source))) { @@ -281,7 +283,7 @@ export async function prepareCfBuildOutput( await writeRootConfig( directory, typeof configuredAccountId === 'string' ? { accountId: configuredAccountId } : {}, - { isPreview: false, mode: mode ?? 'production' }, + { isPreview: options.isPreview === true, mode: mode ?? 'production' }, ); await writeWorkerConfig({ root: directory, @@ -546,6 +548,7 @@ async function prepareBundledBuildOutput(options: { assets: Record; accountId: string; external?: Array; + isPreview?: boolean; }): Promise { const scratch = mkdtempSync(join(tmpdir(), options.scratchPrefix)); try { @@ -576,7 +579,9 @@ async function prepareBundledBuildOutput(options: { JSON.stringify({ ...options.config, main: 'index.js', assets: options.assets }), { mode: 0o600 }, ); - return await prepareCfBuildOutput(scratch, options.accountId, undefined, options.projectRoot); + return await prepareCfBuildOutput(scratch, options.accountId, undefined, options.projectRoot, { + isPreview: options.isPreview, + }); } finally { rmSync(scratch, { recursive: true, force: true }); } @@ -588,6 +593,8 @@ export async function prepareCfStaticBuildOutput(options: { configPath: string; assetsDirectory: string; accountId: string; + /** Prepare the output for `cf previews deploy` instead of a production version. */ + isPreview?: boolean; }): Promise { const raw = record(JSON.parse(readFileSync(options.configPath, 'utf8'))); if (!raw || typeof raw.main !== 'string' || basename(raw.main) !== raw.main) { @@ -604,6 +611,7 @@ export async function prepareCfStaticBuildOutput(options: { config: raw, assets: { ...record(raw.assets), directory: resolve(options.assetsDirectory) }, accountId: options.accountId, + isPreview: options.isPreview, }); } diff --git a/packages/void/src/cli/cf-command-values.ts b/packages/void/src/cli/cf-command-values.ts index f14c5d240..92f649f9b 100644 --- a/packages/void/src/cli/cf-command-values.ts +++ b/packages/void/src/cli/cf-command-values.ts @@ -1,3 +1,5 @@ +import type { CloudflarePreviewUploadResult } from '@void/deploy-cloudflare'; +import { isRecord } from '@void/deploy-core'; // Leave room for a 64 MiB Worker, base64 expansion, and JSON metadata. export const CF_VERSION_SOURCE_MAX_OUTPUT_BYTES: number = 128 * 1024 * 1024; @@ -34,3 +36,45 @@ export function readCfUploadOutput(result: { workersDevUrl: output.match(/(https:\/\/[a-z0-9.-]+\.workers\.dev(?:\/[^\s]*)?)/i)?.[1], }; } + +/** + * Decode the Preview record `cf previews deploy` prints as JSON: the stable Preview URL and the + * URL of this deployment. Earlier provider lines may precede the record, so read the last line that + * starts a JSON object together with everything after it. + */ +export function readCfPreviewDeployOutput( + stdout: string, +): CloudflarePreviewUploadResult | undefined { + const lines = stdout.trim().split('\n'); + for (let index = lines.length - 1; index >= 0; index--) { + if (!lines[index]!.startsWith('{')) { + continue; + } + let record: unknown; + try { + record = JSON.parse(lines.slice(index).join('\n')); + } catch { + continue; + } + if (!isRecord(record)) { + return undefined; + } + const value = record; + const first = (urls: unknown) => + Array.isArray(urls) && typeof urls[0] === 'string' ? urls[0].replace(/\/$/, '') : undefined; + const previewUrl = first(value.preview_urls); + const deploymentUrl = first(value.deployment_urls); + return typeof value.preview_id === 'string' && + typeof value.preview_name === 'string' && + typeof value.deployment_id === 'string' + ? { + previewId: value.preview_id, + previewName: value.preview_name, + deploymentId: value.deployment_id, + ...(previewUrl ? { previewUrl } : {}), + ...(deploymentUrl ? { deploymentUrl } : {}), + } + : undefined; + } + return undefined; +} diff --git a/packages/void/src/cli/cf-version-runner.ts b/packages/void/src/cli/cf-version-runner.ts index bf1fb35b3..3a36f0197 100644 --- a/packages/void/src/cli/cf-version-runner.ts +++ b/packages/void/src/cli/cf-version-runner.ts @@ -15,6 +15,7 @@ import { dirname, join } from 'pathslash'; import type { CfBuildOutput } from './cf-build-output.ts'; import { CF_VERSION_SOURCE_MAX_OUTPUT_BYTES, + readCfPreviewDeployOutput, readCfUploadOutput, safePositional, } from './cf-command-values.ts'; @@ -727,6 +728,25 @@ export function createCfVersionRunner(options: { ); } + if (operation.type === 'previews.deploy') { + if (operation.workerName !== workerName) { + return failed('The Cloudflare preview target changed.'); + } + const verified = await verifyResources(output.directory); + if (!isCleanCloudflareExit(verified)) { + return verified; + } + // One argv item, so a name that starts with "-" is never read as a flag. + const deployed = await runCf( + ['previews', 'deploy', '--prebuilt', `--preview-name=${operation.previewName}`], + { cwd: output.directory, capture: command.capture }, + ); + if (!isCleanCloudflareExit(deployed)) { + return deployed; + } + return { ...deployed, data: readCfPreviewDeployOutput(deployed.stdout) }; + } + if (operation.type === 'versions.deploy') { if (operation.workerName !== workerName) { return failed('The Cloudflare deployment target changed.'); diff --git a/packages/void/src/cli/cli-main.ts b/packages/void/src/cli/cli-main.ts index 33b863b05..3e99fbbaf 100644 --- a/packages/void/src/cli/cli-main.ts +++ b/packages/void/src/cli/cli-main.ts @@ -22,6 +22,7 @@ import { OperatorClientError } from './operator-client.ts'; import { formatUrl, pc } from './output.ts'; import { parsePlatformArgs, platformSubcommands } from './platform-args.ts'; import { parsePrepareArgs } from './prepare-args.ts'; +import { parsePreviewArgs, previewSubcommands } from './preview-args.ts'; import { projectSubcommands, parseProjectArgs } from './project-args.ts'; import { secretSubcommands, parseSecretArgs } from './secret-args.ts'; import type { SubcommandDef, SubcommandResult } from './subcommand-prompt.ts'; @@ -135,6 +136,10 @@ const subcommandGroups: Record Promise> = { runCloudflareCommand(root, parsed), ), ), + preview: () => + runSubcommandGroup('preview', previewSubcommands, parsePreviewArgs, (root, parsed) => + import('./preview-cmd.ts').then(({ runPreviewCommand }) => runPreviewCommand(root, parsed)), + ), project: () => runSubcommandGroup('project', projectSubcommands, parseProjectArgs, (root, parsed) => import('./project-cmd.ts').then(({ runProjectCommand }) => runProjectCommand(root, parsed)), @@ -286,7 +291,16 @@ if (helpPath) { description: 'Inspect persistent resource names in this project', }, { name: 'connect', description: 'Connect to Cloudflare or a Void platform' }, - { name: 'deploy', description: 'Build and deploy, or link an existing Cloudflare Worker' }, + { + name: 'deploy', + hint: '--platform cloudflare --preview ', + description: 'Build and deploy, or link an existing Cloudflare Worker', + }, + { + name: 'preview', + hint: 'delete', + description: 'Delete a Cloudflare Preview created with void deploy --preview', + }, { name: 'auth', hint: 'login | status | logout', diff --git a/packages/void/src/cli/cloudflare-operation-process.ts b/packages/void/src/cli/cloudflare-operation-process.ts index e8be9ca40..88709660c 100644 --- a/packages/void/src/cli/cloudflare-operation-process.ts +++ b/packages/void/src/cli/cloudflare-operation-process.ts @@ -1494,6 +1494,22 @@ async function main(): Promise { if (operation.type.startsWith('email.')) { return email(); } + if (operation.type === 'previews.delete') { + // cf does not read a positional after "--", so refuse a name it could read as a flag. + if (!safePositional(operation.previewName)) { + throw new Error('Cloudflare Preview name is invalid.'); + } + return runCf([ + 'previews', + 'delete', + operation.previewName, + `--worker=${workerName()}`, + '--force', + ]); + } + if (operation.type === 'previews.deploy') { + throw new Error('Cloudflare Previews deploy only from the prepared Build Output.'); + } if ( operation.type.startsWith('deployments.') || (operation.type.startsWith('versions.') && operation.type !== 'versions.upload') diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index 895d7e56e..3e783bef1 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -97,12 +97,14 @@ export function discoverRootWranglerConfig(root: string): string { function createCloudflareUploaderPins( root: string, deps: CloudflareDeployDeps, + /** False for commands that never upload through the prebuilt cf uploader. */ + usesPrebuiltUploader = true, ): { usesCf: boolean; cfUploaderIsPinned: () => boolean; assertUploaderStillPinned: () => boolean; } { - const usesCf = !deps.activateVersion && !deps.runWrangler; + const usesCf = usesPrebuiltUploader && !deps.activateVersion && !deps.runWrangler; const hashUploader = deps.hashWranglerUploader ?? hashWranglerUploader; const wranglerUploaderHashBefore = hashUploader(root); const cfUploaderHashBefore = usesCf ? hashCfUploader() : undefined; @@ -170,6 +172,8 @@ export async function connectCloudflareDeployAccount(options: { readinessAccessOrigin: string | null | undefined; /** Scrubs and logs every child this connection runs. */ reporter: CloudflareChildReporter; + /** False skips pinning the prebuilt cf uploader, for commands that only call the API. */ + usesPrebuiltUploader?: boolean; }): Promise { const { root, configPath, deps, reporter } = options; let { rootConfig } = options; @@ -186,7 +190,7 @@ export async function connectCloudflareDeployAccount(options: { readWranglerTopLevelString(rootConfig, 'compliance_region'), ); // Pin the uploaders before the first authenticated command, including account discovery. - const pins = createCloudflareUploaderPins(root, deps); + const pins = createCloudflareUploaderPins(root, deps, options.usesPrebuiltUploader); let accountId = readWranglerTopLevelString(rootConfig, 'account_id') ?? (process.env.CLOUDFLARE_ACCOUNT_ID?.trim() || undefined); diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index ca2ed3674..b09d00246 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -2,6 +2,7 @@ import { execSync } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { activateCloudflareVersion, + deployCloudflarePreview, encodeCloudflareVersionMessage, parseRootWranglerConfig, readCloudflareTriggerConfig, @@ -11,6 +12,8 @@ import { writeCloudflareFrameworkDeployConfig, writeCloudflareStaticDeployConfig, assertExistingCloudflareConfig, + validateCloudflarePreviewName, + type CloudflarePreviewDeployResult, } from '@void/deploy-cloudflare'; import { dirname, join, relative } from 'pathslash'; import { analyzeApplicationSync } from '../application-analysis.ts'; @@ -62,7 +65,7 @@ import { import { type RunDeployOptions, type CloudflareDeployDeps } from './deploy-types.ts'; import { readGeneratedAssetHeadersFile } from './headers.ts'; import { type CliLogger } from './log-file.ts'; -import { getErrorMessage, note } from './output.ts'; +import { getErrorMessage, note, printJsonRecord, printSuccess, progressOutput } from './output.ts'; import { buildStaticManifest, readWranglerHtmlHandling } from './package.ts'; import { detectPreset, type StaticPreset, type FrameworkPreset } from './preset.ts'; import { deleteEnvVarCaseAware } from './provision.ts'; @@ -337,7 +340,9 @@ export async function runCloudflareStaticDeploy( configPath, rootConfig: parseRootWranglerConfig(configPath), deps, - persistAccount: !(options.reuseExistingWorker || initialCloudflareLink), + // A preview never saves an account for the project, as `void preview delete` does not. + persistAccount: + options.preview === undefined && !(options.reuseExistingWorker || initialCloudflareLink), readinessAccessOrigin: options.readinessAccessOrigin, reporter, }); @@ -374,7 +379,17 @@ export async function runCloudflareStaticDeploy( } const rootConfig = parseRootWranglerConfig(configPath); const workerName = readWranglerTopLevelString(rootConfig, 'name') ?? deriveWorkerName(root); - printDeployContext(workerName, 'Cloudflare'); + printDeployContext( + workerName, + options.preview === undefined ? 'Cloudflare' : `Cloudflare Preview ${options.preview}`, + ); + if (options.preview !== undefined) { + const invalid = validateCloudflarePreviewName(options.preview, workerName); + if (invalid) { + log.error(`deploy: ${invalid}`); + return exit(1); + } + } const rootConfigBeforeBuild = existsSync(configPath) ? readFileSync(configPath, 'utf-8') : null; if (preset.buildCommand && !options.skipBuild) { log.step('Building...'); @@ -386,7 +401,12 @@ export async function runCloudflareStaticDeploy( const runStaticBuild = deps.runStaticBuild ?? ((command: string, env: NodeJS.ProcessEnv) => { - execSync(command, { cwd: root, stdio: 'inherit', env }); + // With --json, stdout carries only the result record. + execSync(command, { + cwd: root, + stdio: ['inherit', progressOutput(), 'inherit'], + env, + }); }); try { runStaticBuild(preset.buildCommand, buildChildEnv); @@ -472,7 +492,6 @@ export async function runCloudflareStaticDeploy( headers: edgeRouting.assetHeaders, }); - const queueConsumerCleanup = readWranglerManagedQueueCleanupCandidates(configPath); assertCloudflareDeployTargetUnchanged({ root, existingWorker, @@ -490,6 +509,7 @@ export async function runCloudflareStaticDeploy( configPath: staticConfigPath, assetsDirectory: stagedAssetsDirectory, accountId, + isPreview: options.preview !== undefined, }) : null; if (!cfOutput && usesCf) { @@ -507,6 +527,27 @@ export async function runCloudflareStaticDeploy( verifyCompatibilityRunner: assertUploaderStillPinned, reporter, }); + const typeLabel = preset.appType === 'spa' ? 'Static SPA' : 'Static Site'; + if (options.preview !== undefined) { + log.step(`Deploying Preview ${options.preview}...`); + const result = await deployCloudflarePreview({ + runWrangler: activationRunner, + workerName, + previewName: options.preview, + verifyUploader: cfOutput ? cfUploaderIsPinned : assertUploaderStillPinned, + configPath: staticConfigPath, + }).finally(() => cfOutput?.dispose()); + return reportCloudflareStaticPreview(result, { + previewName: options.preview, + workerName, + typeLabel, + json: options.json === true, + reporter, + cliLog, + exit, + }); + } + const queueConsumerCleanup = readWranglerManagedQueueCleanupCandidates(configPath); const execution = await activateCloudflareVersionWithProgress( deps.activateVersion ?? activateCloudflareVersion, { @@ -559,12 +600,79 @@ export async function runCloudflareStaticDeploy( execution, cliLog, }); - note( - formatDeploySummary({ + note(formatDeploySummary({ workerName, typeLabel }), execution.previewUrl); + printDeploySuccess(); +} + +/** Print a preview deploy's result: the URL, or a JSON record with `--json`, or the failure. */ +function reportCloudflareStaticPreview( + result: CloudflarePreviewDeployResult, + options: { + previewName: string; + workerName: string; + typeLabel: string; + json: boolean; + reporter: CloudflareChildReporter; + cliLog: CliLogger; + exit: (code: number) => never; + }, +): void { + const { previewName, workerName } = options; + if (!result.ok) { + const message = options.reporter.redactor.redact( + formatCloudflarePreviewError(result, workerName), + ); + options.cliLog.error('cloudflare_preview_failed', new Error(message), { + reason: result.reason, + }); + log.error(message); + return options.exit(1); + } + options.cliLog.info('cloudflare_preview_deployed', { + previewName, + previewId: result.previewId, + deploymentId: result.deploymentId, + }); + if (options.json) { + printJsonRecord({ workerName, - typeLabel: preset.appType === 'spa' ? 'Static SPA' : 'Static Site', - }), - execution.previewUrl, + previewName, + previewUrl: result.previewUrl, + deploymentId: result.deploymentId, + deploymentUrl: result.deploymentUrl ?? null, + }); + } + note( + [ + formatDeploySummary({ workerName, typeLabel: options.typeLabel }), + `Preview: ${previewName}`, + ...(result.deploymentUrl ? [`This deployment: ${result.deploymentUrl}`] : []), + ].join('\n'), + result.previewUrl, ); - printDeploySuccess(); + printSuccess(`Preview ${previewName} deployed. Production is unchanged.`); +} + +function formatCloudflarePreviewError( + result: Extract, + workerName: string, +): string { + switch (result.reason) { + case 'invalid-name': + return `deploy: ${result.diagnostic}`; + case 'uploader-changed': + return 'deploy: the Cloudflare uploader changed during the preview deploy. Nothing was deployed.'; + case 'output-invalid': + return 'deploy: Cloudflare accepted the preview but did not return a readable Preview record. Check the Worker in the Cloudflare dashboard before retrying.'; + case 'preview-urls-disabled': + return [ + `deploy: the preview was deployed, but Preview URLs are turned off for the Worker "${workerName}", so it has no URL.`, + 'Set preview_urls: true in the cloudflare field of void.config.ts and run a production deploy (void deploy --platform cloudflare), or turn on Preview under Domains for the Worker in the Cloudflare dashboard. Then deploy the preview again.', + ].join('\n'); + case 'deploy-failed': + return [ + 'deploy: Cloudflare could not deploy the preview. Production is unchanged.', + ...(result.diagnostic ? [result.diagnostic] : []), + ].join('\n'); + } } diff --git a/packages/void/src/cli/deploy-cloudflare.ts b/packages/void/src/cli/deploy-cloudflare.ts index 84fde0d03..ee702e796 100644 --- a/packages/void/src/cli/deploy-cloudflare.ts +++ b/packages/void/src/cli/deploy-cloudflare.ts @@ -63,6 +63,12 @@ export async function runCloudflareDeploy( ); return exit(1); } + if (options.preview !== undefined && (options.reuseExistingWorker || initialCloudflareLink)) { + log.error( + 'deploy: previews are unavailable during the existing Worker handoff. Complete the handoff with a production deploy first.', + ); + return exit(1); + } const detectedFramework = detectFramework(root); const frameworkPreset = detectedFramework ? FRAMEWORK_PRESETS[detectedFramework.name] : undefined; cliLog.info('cloudflare_deploy_start', { @@ -114,6 +120,16 @@ export async function runCloudflareDeploy( ); } + if (options.preview !== undefined) { + log.error( + [ + 'deploy: --preview currently supports static sites and single-page apps only.', + 'This app needs a Worker (server routes, bindings, migrations or secrets), and a Preview would share or skip them. Deploy it without --preview.', + ].join('\n'), + ); + return exit(1); + } + // After the static branch: a static framework build is served by the thin // edge Worker, which applies the redirect itself. if (detectedFramework && voidConfig.routing?.alwaysUseHttps === true) { diff --git a/packages/void/src/cli/deploy-helpers.ts b/packages/void/src/cli/deploy-helpers.ts index 81b9df40b..3a39850fe 100644 --- a/packages/void/src/cli/deploy-helpers.ts +++ b/packages/void/src/cli/deploy-helpers.ts @@ -1,5 +1,6 @@ import { execSync } from 'node:child_process'; import { readFileSync } from 'node:fs'; +import type { Writable } from 'node:stream'; import { isCancel, log as clackLog, text } from '@voidzero-dev/vite-plus-prompts'; import { join, resolve } from 'pathslash'; import { findEnvFile } from '../codegen/env-types.ts'; @@ -23,7 +24,7 @@ import { } from './deploy-types.ts'; import { fetchRemoteSecretNames, formatEnvReport, validateProdEnv } from './env-validation.ts'; import { type CliLogger } from './log-file.ts'; -import { formatCount, getErrorMessage, pc } from './output.ts'; +import { formatCount, getErrorMessage, pc, progressOptions } from './output.ts'; import { detectPreset, formatProjectCommand, @@ -50,15 +51,29 @@ import { import type { WrapperFeatures } from './wrapper.ts'; import { needsWrapper, generateWrapper } from './wrapper.ts'; +/** Format a Cloudflare message and send it to the progress stream a `--json` command chose. */ +function progressLog( + write: (message: string, options?: { output?: Writable }) => void, + message: string, +): void { + const formatted = formatCloudflareUserMessage(message); + const options = progressOptions(); + if (options.output) { + write(formatted, options); + } else { + write(formatted); + } +} + export const log: Record< 'error' | 'info' | 'message' | 'step' | 'warn', (message: string) => void > = { - error: (message: string) => clackLog.error(formatCloudflareUserMessage(message)), - info: (message: string) => clackLog.info(formatCloudflareUserMessage(message)), - message: (message: string) => clackLog.message(formatCloudflareUserMessage(message)), - step: (message: string) => clackLog.step(formatCloudflareUserMessage(message)), - warn: (message: string) => clackLog.warn(formatCloudflareUserMessage(message)), + error: (message: string) => progressLog(clackLog.error, message), + info: (message: string) => progressLog(clackLog.info, message), + message: (message: string) => progressLog(clackLog.message, message), + step: (message: string) => progressLog(clackLog.step, message), + warn: (message: string) => progressLog(clackLog.warn, message), }; export class DeployEventError extends Error {} diff --git a/packages/void/src/cli/deploy-summary.ts b/packages/void/src/cli/deploy-summary.ts index 9a328e90e..4c8397bd9 100644 --- a/packages/void/src/cli/deploy-summary.ts +++ b/packages/void/src/cli/deploy-summary.ts @@ -1,9 +1,10 @@ import { intro } from '@voidzero-dev/vite-plus-prompts'; -import { formatCount, pc, printSuccess, sanitizeTerminalText } from './output.ts'; +import { formatCount, pc, printSuccess, progressOptions, sanitizeTerminalText } from './output.ts'; export function printDeployContext(project: string, destination: string): void { intro( `${pc.dim(sanitizeTerminalText(project))} ${pc.dim('→')} ${pc.blue(sanitizeTerminalText(destination))}`, + progressOptions(), ); } diff --git a/packages/void/src/cli/deploy-types.ts b/packages/void/src/cli/deploy-types.ts index a7fd077ff..d65072a0d 100644 --- a/packages/void/src/cli/deploy-types.ts +++ b/packages/void/src/cli/deploy-types.ts @@ -49,6 +49,13 @@ export type RunDeployOptions = { requireEmail?: boolean; /** Publish an existing Durable Object Worker atomically after explicit operator choice. */ atomic?: boolean; + /** + * Create or update this named Cloudflare Preview instead of deploying production. + * `--platform cloudflare` only; production traffic is never changed. + */ + preview?: string; + /** Print the deployment result as one JSON record on stdout; logs go to stderr. */ + json?: boolean; /** * `CF_ACCESS_READINESS_ORIGIN` as recorded before project code ran (`null` when unset). * `--platform cloudflare` only. diff --git a/packages/void/src/cli/deploy.ts b/packages/void/src/cli/deploy.ts index 282ae7f08..336bfb6a2 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -35,6 +35,7 @@ import { openDeployLog, type CliLogger } from './log-file.ts'; import { buildDeployLogSummary } from './log-summary.ts'; import { promptForLoginToken } from './login.ts'; import { migrateLegacyVoidConfig } from './migrate.ts'; +import { setProgressOutput } from './output.ts'; import { listPlatformConnections } from './platform-registry.ts'; import { detectPreset, FRAMEWORK_PRESETS } from './preset.ts'; import { @@ -58,7 +59,14 @@ export function resolveDeploymentPlatform( export async function runDeploy(root: string, options?: RunDeployOptions): Promise { // The Cloudflare link check can evaluate void.config.ts, so record operator input first. options = withRecordedReadinessAccessOrigin(options ?? {}); - console.log(); + if (options.json) { + // stdout carries only the result record. Kept for the rest of the process, so the CLI's own + // report of a thrown error also goes to stderr. + setProgressOutput(process.stderr); + process.stderr.write('\n'); + } else { + console.log(); + } const cliLog = openDeployLog({ mirrorToStderr: options?.debug === true || process.env.VOID_DEPLOY_DEBUG === '1', @@ -70,6 +78,7 @@ export async function runDeploy(root: string, options?: RunDeployOptions): Promi spa: options?.spa === true ? true : undefined, skipBuild: options?.skipBuild === true ? true : undefined, skipMigrations: options?.skipMigrations === true ? true : undefined, + preview: options?.preview, nodeVersion: process.version, platform: process.platform, arch: process.arch, diff --git a/packages/void/src/cli/help.ts b/packages/void/src/cli/help.ts index a69948db2..1a3497b76 100644 --- a/packages/void/src/cli/help.ts +++ b/packages/void/src/cli/help.ts @@ -190,6 +190,15 @@ const HELP_TREE: HelpTree = { description: 'Publish a Durable Object Worker without pre-traffic staging (Cloudflare only)', }, + { + command: '--preview ', + description: + 'Create or update a Cloudflare Preview with its own URL; production is unchanged (static sites and SPAs, with --platform cloudflare)', + }, + { + command: '--json', + description: 'Print the preview result as JSON on stdout (with --preview)', + }, { command: '--debug', description: 'Mirror the deploy log to stderr (always written to ~/.void/logs)', @@ -203,6 +212,27 @@ const HELP_TREE: HelpTree = { command: 'void deploy --platform cloudflare', description: 'Deploy to your own Cloudflare account', }, + { + command: 'void deploy --platform cloudflare --preview pr-64 --json', + description: 'Deploy a pull request preview and print its URL as JSON', + }, + ], + }, + preview: { + summary: + 'Manage Cloudflare Previews created with `void deploy --platform cloudflare --preview`.', + usage: ['void preview delete '], + commands: [ + { command: 'delete ', description: 'Delete a Preview and all its deployments' }, + ], + children: { + delete: basicSubcommand( + 'Delete a Preview and all its deployments. Production is unchanged; a Preview that does not exist is not an error.', + 'void preview delete ', + ), + }, + examples: [ + { command: 'void preview delete pr-64', description: 'Remove a pull request preview' }, ], }, auth: { @@ -1565,6 +1595,8 @@ export function printGlobalHelp(): void { globalCommandLine(['deploy'], 'void deploy'), ...globalOptionLines(['deploy']), '', + ...globalCommandGroup('preview'), + '', ...globalCommandGroup('auth'), '', ...globalCommandGroup('account'), diff --git a/packages/void/src/cli/output.ts b/packages/void/src/cli/output.ts index 5dc9bb7e2..2871fc08b 100644 --- a/packages/void/src/cli/output.ts +++ b/packages/void/src/cli/output.ts @@ -28,10 +28,41 @@ export function formatUrl(url: string): string { return formatLink(text, text); } +let progressStream: Writable | undefined; + +/** + * Choose where Void's progress output goes. `--json` commands send it to stderr so stdout carries + * only their result record. Pass undefined to restore stdout. + */ +export function setProgressOutput(stream: Writable | undefined): void { + progressStream = stream; +} + +/** The stream Void's progress renderers write to: stdout unless a `--json` command chose stderr. */ +export function progressOutput(): Writable { + return progressStream ?? process.stdout; +} + +/** + * Renderer options that route output to the chosen progress stream. Empty unless a `--json` + * command chose one, so ordinary runs call the renderers exactly as before. + */ +export function progressOptions(): { output?: Writable } { + return progressStream ? { output: progressStream } : {}; +} + +/** Print one machine-readable JSON record on stdout. */ +export function printJsonRecord(record: unknown): void { + process.stdout.write(`${JSON.stringify(record)}\n`); +} + /** Complete an action with the same spacing, checkmark, and color on every target. */ export function printSuccess(message: string): void { // Remove nested styles so a blue URL or dim hint cannot override the success color. - outro(`\n${pc.green(`✓ ${stripVTControlCharacters(message)}`)}`, { withGuide: false }); + outro(`\n${pc.green(`✓ ${stripVTControlCharacters(message)}`)}`, { + withGuide: false, + ...progressOptions(), + }); } export function formatCount(count: number, singular: string, plural = `${singular}s`): string { @@ -127,11 +158,15 @@ export function note(...args: Parameters): void { const urlTitle = plainTitle && /^https?:\/\/\S+$/.test(plainTitle) ? plainTitle : undefined; // Native macOS Terminal recognizes URLs by whitespace boundaries. const boxedTitle = urlTitle ? ` ${urlTitle} ` : title; - const output = opts?.output ?? process.stdout; + const output = opts?.output ?? progressOutput(); const columns = (output as { columns?: unknown }).columns; const needsWidthFallback = typeof columns === 'number' && columns < MIN_NOTE_COLUMNS; if (!urlTitle && !needsWidthFallback) { - promptsNote(...args); + if (opts?.output || !progressStream) { + promptsNote(...args); + } else { + promptsNote(message, title, { ...opts, output }); + } return; } // The box renderer only reads `columns` and calls `write()`. diff --git a/packages/void/src/cli/preview-args.ts b/packages/void/src/cli/preview-args.ts new file mode 100644 index 000000000..5811b6f3b --- /dev/null +++ b/packages/void/src/cli/preview-args.ts @@ -0,0 +1,25 @@ +import type { SubcommandDef } from './subcommand-prompt.ts'; + +export const previewSubcommands: Array = [ + { + name: 'delete', + hint: '', + description: 'Delete a Cloudflare Preview and all its deployments', + }, +]; + +export type PreviewArgs = { subcommand: 'delete'; name: string }; + +export function parsePreviewArgs(args: Array): PreviewArgs { + const [subcommand, name, extra] = args; + if (subcommand !== 'delete') { + throw new Error('preview: Usage: void preview delete .'); + } + if (!name || name.startsWith('-')) { + throw new Error('preview: delete requires a preview name (for example pr-64).'); + } + if (extra) { + throw new Error(`preview: Unexpected argument '${extra}'.`); + } + return { subcommand, name }; +} diff --git a/packages/void/src/cli/preview-cmd.ts b/packages/void/src/cli/preview-cmd.ts new file mode 100644 index 000000000..2f6e8c04c --- /dev/null +++ b/packages/void/src/cli/preview-cmd.ts @@ -0,0 +1,91 @@ +import { + deleteCloudflarePreview, + parseRootWranglerConfig, + readWranglerTopLevelString, + type CloudflarePreviewDeleteResult, +} from '@void/deploy-cloudflare'; +import { createCloudflareChildReporter } from './cloudflare-child-report.ts'; +import { + confirmCloudflareDeployAuthentication, + connectCloudflareDeployAccount, + discoverRootWranglerConfig, +} from './deploy-cloudflare-helpers.ts'; +import { log } from './deploy-helpers.ts'; +import { deriveWorkerName } from './deploy-resources.ts'; +import type { CloudflareDeployDeps } from './deploy-types.ts'; +import { openDeployLog } from './log-file.ts'; +import { printSuccess } from './output.ts'; +import type { PreviewArgs } from './preview-args.ts'; + +/** + * Delete a Preview of this project's Cloudflare Worker. Production is not read or changed. A + * Preview that no longer exists is not an error, so a pull-request cleanup job can rerun. + */ +export async function runPreviewCommand( + root: string, + args: PreviewArgs, + deps: CloudflareDeployDeps = {}, +): Promise { + const cliLog = openDeployLog(); + try { + const reporter = createCloudflareChildReporter(cliLog); + const configPath = discoverRootWranglerConfig(root); + const connection = await connectCloudflareDeployAccount({ + root, + configPath, + rootConfig: parseRootWranglerConfig(configPath), + deps, + // Deleting a Preview never chooses or saves an account for the project. + persistAccount: false, + readinessAccessOrigin: undefined, + reporter, + // Deleting is one API call: there is no prebuilt upload to pin. + usesPrebuiltUploader: false, + }); + if (!connection || !(await confirmCloudflareDeployAuthentication(connection, configPath))) { + throw new Error('preview: could not connect to Cloudflare.'); + } + const workerName = + readWranglerTopLevelString(connection.rootConfig, 'name') ?? deriveWorkerName(root); + const result = await deleteCloudflarePreview({ + runWrangler: connection.runWrangler, + workerName, + previewName: args.name, + verifyUploader: connection.assertUploaderStillPinned, + configPath, + }); + if (!result.ok) { + const message = reporter.redactor.redact(formatDeleteError(result, args.name, workerName)); + cliLog.error('cloudflare_preview_delete_failed', new Error(message), { + reason: result.reason, + }); + throw new Error(message); + } + cliLog.info('cloudflare_preview_deleted', { previewName: args.name, deleted: result.deleted }); + if (result.deleted) { + printSuccess(`Deleted the preview ${args.name} of ${workerName}.`); + } else { + log.info(`The preview ${args.name} of ${workerName} does not exist. Nothing to delete.`); + } + } finally { + await cliLog.close().catch(() => {}); + } +} + +function formatDeleteError( + result: Extract, + name: string, + workerName: string, +): string { + switch (result.reason) { + case 'invalid-name': + return `preview: ${result.diagnostic}`; + case 'uploader-changed': + return 'preview: the Cloudflare uploader changed. Nothing was deleted.'; + case 'delete-failed': + return [ + `preview: Cloudflare could not delete the preview "${name}" of the Worker "${workerName}".`, + ...(result.diagnostic ? [result.diagnostic] : []), + ].join('\n'); + } +} diff --git a/packages/void/test/unit/cf-build-output.test.ts b/packages/void/test/unit/cf-build-output.test.ts index 0a499d846..b44c4266a 100644 --- a/packages/void/test/unit/cf-build-output.test.ts +++ b/packages/void/test/unit/cf-build-output.test.ts @@ -1171,9 +1171,25 @@ it('bundles a generated static Worker and staged assets into prebuilt cf output' expect(built.workers.default.config.manifest?.mainModule).toBe('index.js'); expect(built.workers.default.assetsDir).toBeDefined(); expect(prepared.assetsDirectory).toBe(toSlash(assets)); + expect(built.rootConfig.buildContext.isPreview).toBe(false); expectCfDryRun(prepared.directory, ['deploy']); }, ); + // `cf previews deploy` accepts only output marked as a Preview build. + await withPrepared( + prepareCfStaticBuildOutput({ + projectRoot: root, + configPath, + assetsDirectory: assets, + accountId: 'account-id', + isPreview: true, + }), + async (prepared) => { + const built = await readBuildOutput(prepared.directory); + expect(built.rootConfig.buildContext.isPreview).toBe(true); + expectCfDryRun(prepared.directory, ['previews', 'deploy', '--preview-name=pr-1']); + }, + ); }); /** The comment line `void domain add` writes, in the format of writeWranglerPublishedTrafficSnapshot. */ diff --git a/packages/void/test/unit/cf-version-runner.test.ts b/packages/void/test/unit/cf-version-runner.test.ts index 558f71af1..7054c71f9 100644 --- a/packages/void/test/unit/cf-version-runner.test.ts +++ b/packages/void/test/unit/cf-version-runner.test.ts @@ -3327,3 +3327,64 @@ describe('settings credential before activation', () => { } }); }); + +it('deploys a named Preview from the prebuilt output without touching versions or traffic', async () => { + const prepared = await output(); + try { + const calls: Array<{ args: Array; cwd: string | undefined }> = []; + const verified: Array = []; + const preview = { + type: 'preview', + preview_id: 'prv_1', + preview_name: 'pr-64', + preview_urls: ['https://pr-64-void-test.team.workers.dev'], + deployment_id: 'dep_1', + deployment_urls: ['https://dep1-void-test.team.workers.dev'], + }; + const runner = createCfVersionRunner({ + output: prepared, + workerName: 'void-test', + verifyResources: async (directory) => { + verified.push(directory); + return { status: 0, stdout: '', stderr: '' }; + }, + runCf: (args, run) => { + calls.push({ args, cwd: run.cwd }); + return { + status: 0, + // Provider lines may precede the JSON record. + stdout: `Uploading assets\n${JSON.stringify(preview, null, 2)}\n`, + stderr: '', + }; + }, + }); + const result = await runner( + { type: 'previews.deploy', workerName: 'void-test', previewName: 'pr-64' }, + { capture: true }, + ); + expect(result.status).toBe(0); + expect(result.data).toEqual({ + previewId: 'prv_1', + previewName: 'pr-64', + deploymentId: 'dep_1', + previewUrl: 'https://pr-64-void-test.team.workers.dev', + deploymentUrl: 'https://dep1-void-test.team.workers.dev', + }); + expect(verified).toEqual([prepared.directory]); + expect(calls).toEqual([ + { + args: ['previews', 'deploy', '--prebuilt', '--preview-name=pr-64'], + cwd: prepared.directory, + }, + ]); + + const moved = await runner( + { type: 'previews.deploy', workerName: 'other-worker', previewName: 'pr-64' }, + { capture: true }, + ); + expect(moved.status).not.toBe(0); + expect(calls).toHaveLength(1); + } finally { + prepared.dispose(); + } +}); diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 3f3017be8..82976f321 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -12410,3 +12410,158 @@ describe('runCloudflareDeploy — `addresses` is whole-object pinned across the expect(dropped.reason).toMatch(/addresses/); }); }); + +describe('runCloudflareDeploy — previews', () => { + // What the cf runner decodes from `cf previews deploy`. + const previewRecord: Record = { + previewId: 'prv_1', + previewName: 'pr-64', + deploymentId: 'dep_1', + previewUrl: 'https://pr-64-spaapp.team.workers.dev', + deploymentUrl: 'https://dep1-spaapp.team.workers.dev', + }; + + function previewHarness(record: unknown = previewRecord) { + const base = harness(); + const wranglerArgs: Array> = []; + const activateVersion = vi.fn(base.deps.activateVersion!); + const runWrangler = operationFixture((args) => { + wranglerArgs.push(args); + if (args[0] === 'whoami') { + return { ...cleanExit, stdout: '{"loggedIn":true,"accounts":[]}' }; + } + if (args[0] === 'preview') { + return { ...cleanExit, stdout: JSON.stringify(record) }; + } + return cleanExit; + }); + return { + deps: { ...base.deps, runWrangler, activateVersion } satisfies CloudflareDeployDeps, + exitCalls: base.exitCalls, + wranglerArgs, + activateVersion, + }; + } + + const spa = () => + makeProject({ + 'package.json': JSON.stringify({ name: 'spaapp' }), + 'void.json': JSON.stringify({ inference: { appType: 'spa' } }), + 'wrangler.jsonc': JSON.stringify({ account_id: 'acc123' }), + 'dist/index.html': '
', + }); + + it('deploys a named Preview without activating, moving traffic or recording production state', async () => { + const root = spa(); + const { deps, exitCalls, wranglerArgs, activateVersion } = previewHarness(); + const output = await captureDeployOutput(() => + runCloudflareDeploy(root, { platform: 'cloudflare', preview: 'pr-64' }, silentCliLog, deps), + ); + + expect(exitCalls).toEqual([]); + expect(activateVersion).not.toHaveBeenCalled(); + // Only the session check and the Preview deploy reach Cloudflare: no version upload, + // deployment, traffic split, trigger or secret operation. + expect(wranglerArgs.map((args) => args.slice(0, 1))).toEqual([['whoami'], ['preview']]); + expect(wranglerArgs[1]).toEqual( + expect.arrayContaining(['--preview-name', 'pr-64', '--name', 'spaapp']), + ); + expect(existsSync(join(root, '.void/cloudflare-candidate.json'))).toBe(false); + expect(parseRootWranglerConfig(join(root, 'wrangler.jsonc'))).toEqual({ + account_id: 'acc123', + }); + expect(output).toContain('spaapp → Cloudflare Preview pr-64'); + expect(output).toContain('https://pr-64-spaapp.team.workers.dev'); + expect(output).toContain('Preview pr-64 deployed. Production is unchanged.'); + }); + + it('prints one JSON record on stdout and keeps the logs on stderr', async () => { + const root = spa(); + const { deps, exitCalls } = previewHarness(); + const stdout: Array = []; + const stderr: Array = []; + const out = vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => { + stdout.push(String(chunk)); + return true; + }); + const err = vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => { + stderr.push(String(chunk)); + return true; + }); + const { setProgressOutput } = await import('../../src/cli/output.ts'); + try { + // As runDeploy does for --json. + setProgressOutput(process.stderr); + await runCloudflareDeploy( + root, + { platform: 'cloudflare', preview: 'pr-64', json: true }, + silentCliLog, + deps, + ); + } finally { + setProgressOutput(undefined); + out.mockRestore(); + err.mockRestore(); + } + + expect(exitCalls).toEqual([]); + expect(stdout).toHaveLength(1); + expect(JSON.parse(stdout[0]!)).toEqual({ + workerName: 'spaapp', + previewName: 'pr-64', + previewUrl: 'https://pr-64-spaapp.team.workers.dev', + deploymentId: 'dep_1', + deploymentUrl: 'https://dep1-spaapp.team.workers.dev', + }); + expect(stripVTControlCharacters(stderr.join(''))).toContain('Production is unchanged'); + }); + + it('fails clearly when the Worker has Preview URLs turned off', async () => { + const root = spa(); + const { previewUrl: _, ...withoutUrl } = previewRecord; + const { deps, exitCalls } = previewHarness(withoutUrl); + const output = await captureDeployOutput(() => + expect( + runCloudflareDeploy(root, { platform: 'cloudflare', preview: 'pr-64' }, silentCliLog, deps), + ).rejects.toThrow(ExitError), + ); + expect(exitCalls).toEqual([1]); + expect(output).toContain('Preview URLs are turned off'); + expect(output).toContain('preview_urls: true in the cloudflare field of void.config.ts'); + }); + + it('rejects a name too long for the Worker before building or uploading', async () => { + const root = spa(); + const { deps, exitCalls, wranglerArgs } = previewHarness(); + const output = await captureDeployOutput(() => + expect( + runCloudflareDeploy( + root, + { platform: 'cloudflare', preview: `pr-${'1'.repeat(60)}` }, + silentCliLog, + deps, + ), + ).rejects.toThrow(ExitError), + ); + expect(exitCalls).toEqual([1]); + expect(output).toContain('63 characters'); + expect(wranglerArgs.some((args) => args[0] === 'preview')).toBe(false); + }); + + it('refuses an app that needs a Worker before any Cloudflare operation', async () => { + const root = makeProject({ + 'package.json': JSON.stringify({ name: 'workerapp' }), + 'wrangler.jsonc': JSON.stringify({ account_id: 'acc123' }), + 'routes/index.ts': 'export const GET = () => "hi";\n', + }); + const { deps, exitCalls, wranglerArgs } = previewHarness(); + const output = await captureDeployOutput(() => + expect( + runCloudflareDeploy(root, { platform: 'cloudflare', preview: 'pr-64' }, silentCliLog, deps), + ).rejects.toThrow(ExitError), + ); + expect(exitCalls).toEqual([1]); + expect(output).toContain('--preview currently supports static sites and single-page apps'); + expect(wranglerArgs).toEqual([]); + }); +}); diff --git a/packages/void/test/unit/deploy-args.test.ts b/packages/void/test/unit/deploy-args.test.ts index 4d8a5dc63..7fbfa32a8 100644 --- a/packages/void/test/unit/deploy-args.test.ts +++ b/packages/void/test/unit/deploy-args.test.ts @@ -157,3 +157,38 @@ describe('parseDeployArgs', () => { }); }); }); + +describe('parseDeployArgs --preview', () => { + it('parses a Cloudflare preview with JSON output', () => { + expect( + parseDeployArgs(['--platform', 'cloudflare', '--skip-build', '--preview', 'pr-64', '--json']), + ).toMatchObject({ platform: 'cloudflare', skipBuild: true, preview: 'pr-64', json: true }); + }); + + it('requires --platform cloudflare and a name', () => { + expect(() => parseDeployArgs(['--preview', 'pr-64'])).toThrow( + '--preview requires --platform cloudflare', + ); + expect(() => parseDeployArgs(['--platform', 'void', '--preview', 'pr-64'])).toThrow( + '--preview requires --platform cloudflare', + ); + expect(() => parseDeployArgs(['--platform', 'cloudflare', '--preview'])).toThrow( + '--preview requires a name', + ); + expect(() => + parseDeployArgs(['--platform', 'cloudflare', '--preview', 'a', '--preview', 'b']), + ).toThrow('only be specified once'); + }); + + it.each(['--atomic', '--provision', '--require-email'])('rejects %s with --preview', (flag) => { + expect(() => parseDeployArgs(['--platform', 'cloudflare', '--preview', 'pr-64', flag])).toThrow( + `${flag} cannot be combined with --preview`, + ); + }); + + it('accepts --json only with --preview', () => { + expect(() => parseDeployArgs(['--platform', 'cloudflare', '--json'])).toThrow( + '--json is available only with --preview', + ); + }); +}); diff --git a/packages/void/test/unit/preview-args.test.ts b/packages/void/test/unit/preview-args.test.ts new file mode 100644 index 000000000..9300ba6ac --- /dev/null +++ b/packages/void/test/unit/preview-args.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vite-plus/test'; +import { parsePreviewArgs } from '../../src/cli/preview-args.ts'; + +describe('parsePreviewArgs', () => { + it('parses delete with a name', () => { + expect(parsePreviewArgs(['delete', 'pr-64'])).toEqual({ subcommand: 'delete', name: 'pr-64' }); + }); + + it('rejects missing, unknown and extra arguments', () => { + expect(() => parsePreviewArgs([])).toThrow('void preview delete '); + expect(() => parsePreviewArgs(['list'])).toThrow('void preview delete '); + expect(() => parsePreviewArgs(['delete'])).toThrow('requires a preview name'); + expect(() => parsePreviewArgs(['delete', '--force'])).toThrow('requires a preview name'); + expect(() => parsePreviewArgs(['delete', 'pr-64', 'pr-65'])).toThrow('Unexpected argument'); + }); +});