diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 5146252b6..a55741f9d 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -165,6 +165,86 @@ export CF_ACCESS_READINESS_ORIGIN="https://app.example.com" Set this variable in the shell or CI environment running `void deploy`. Use an exact HTTPS origin for a hostname you control that serves this Worker; Void sends your Access credentials there. +### 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. + +```sh +void deploy --platform cloudflare --preview pr-64 --json # create or update +void project preview delete pr-64 --platform cloudflare # remove +``` + +Deploy production once first and set the Worker name (`cloudflare.name`, or `name` in `wrangler.jsonc`). The token needs **Workers → Editor**, since the Worker already exists, and `CLOUDFLARE_ACCOUNT_ID` pins the account. The preview job runs the pull request's code with this token, which can also deploy production. Pull requests from forks and Dependabot get no preview. + +This workflow deploys a preview on every push, comments its URL once, 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: ${{ github.workflow }}-pr-${{ github.event.pull_request.number }} + # A new push cancels an older preview deploy; cleanup waits for it instead. + cancel-in-progress: ${{ github.event.action != 'closed' }} +jobs: + deploy: + # Fork and Dependabot pull requests get no repository secrets. + if: >- + github.event.action != 'closed' && + github.event.pull_request.head.repo.full_name == github.repository && + github.actor != 'dependabot[bot]' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: pnpm/action-setup@v5 + - uses: actions/setup-node@v6 + with: { node-version: lts/*, check-latest: true, cache: pnpm } + - run: pnpm install --frozen-lockfile + - id: preview + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + PREVIEW: pr-${{ github.event.pull_request.number }} + run: | + pnpm exec void deploy --platform cloudflare --preview "$PREVIEW" --json > preview.json + echo "url=$(jq -er .previewUrl preview.json)" >> "$GITHUB_OUTPUT" + # The preview URL never changes for a pull request, so comment once. + - env: + GH_TOKEN: ${{ github.token }} + PR: ${{ github.event.pull_request.number }} + URL: ${{ steps.preview.outputs.url }} + run: | + if ! gh pr view "$PR" --json comments --jq '.comments[].body' | grep -qF "$URL"; then + gh pr comment "$PR" --body "Preview: $URL" + fi + cleanup: + if: >- + github.event.action == 'closed' && + github.event.pull_request.head.repo.full_name == github.repository && + github.actor != 'dependabot[bot]' + runs-on: ubuntu-latest + steps: + # Trusted base-branch code; it still exists after the pull request closes. + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.base.ref }} + - uses: pnpm/action-setup@v5 + - uses: actions/setup-node@v6 + with: { node-version: lts/*, check-latest: true, cache: pnpm } + - run: pnpm install --frozen-lockfile + - env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + PREVIEW: pr-${{ github.event.pull_request.number }} + run: pnpm exec void project preview delete "$PREVIEW" --platform cloudflare +``` + +Using npm, Yarn or Bun? Use the setup steps that `void init --github` writes. If an earlier job builds the site, download its output and add `--skip-build`. Preview URLs are public; see [`void deploy --preview`](../reference/cli/deploy.md#void-deploy-preview) for the JSON output, naming rules and limits. + ### Databases and secrets For PostgreSQL and MySQL, supply `DATABASE_URL` to the deploy process. Void uses it for Hyperdrive and migrations without writing it to config. MySQL schema changes can partially apply before an error; see [failed MySQL migrations](../guide/database/mysql.md#failed-migrations). @@ -208,6 +288,7 @@ Void deploys native apps, static sites, SPAs, supported SSGs, and Cloudflare bui - Native apps support Void routing rules. Framework apps on the direct target must configure redirects, rewrites, fallbacks, and headers through their framework or Worker. - `--skip-build` works for existing static output. Worker apps require a fresh build. +- `--preview` works for static sites and SPAs only. - Named Cloudflare environments aren't supported. Use a separate Void project config for each target. - Sandbox requires Workers Paid and Docker. See [Sandbox requirements](../guide/sandboxes.md#deployment) for plan and token permissions. - Email to arbitrary recipients, and all sending from apps without `email/` handlers, requires Workers Paid. Apps with handlers keep inbound mail and verified recipients on Workers Free. See [Email](../guide/email/domains.md#your-own-cloudflare-account). @@ -217,7 +298,7 @@ Commit Durable Object migration history in `void.lock.json`. Do not delete or re ### Managing the deployed app -`void secret`, `void domain`, `void project status|list|logs|rollback`, and remote `void db` commands use the selected account and Worker. Logs are a live tail. +`void secret`, `void domain`, `void project status|list|logs|rollback`, `void project preview delete`, and remote `void db` commands use the selected account and Worker. Logs are a live tail. Custom domain commands update routes immediately. If a first deployment times out while DNS or TLS is propagating, check the domain in Cloudflare and retry once `/__void/ready` is reachable. diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 5dc4cc95d..fc140bf9a 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -34,53 +34,55 @@ Use this page as a command reference. If you are setting up a project for the fi ## Cheat Sheet {#cheat-sheet} -| Command | Purpose | -| --------------------------------- | ----------------------------------------------------------------------------- | -| `void deploy` | Build and deploy to the configured platform | -| `void deploy --skip-migrations` | Deploy code without applying application or authentication SQL migrations | -| `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 | -| `void gen route ` | Create an API route | -| `void db push` | Apply schema directly without migration files | -| `void db generate` | Generate SQL migrations from schema changes | -| `void db status` | Show local/remote migration status | -| `void db reset` | Drop and re-apply all migrations | -| `void db seed` | Reset + seed local database | -| `void db execute ` | Run SQL against the database (--remote for deployed) | -| `void db studio` | Open Drizzle Studio (--remote for a deployed external database) | -| `void db restore --bookmark ` | Restore the deployed D1 database to a restore point (direct Cloudflare) | -| `void secret put ` | Set a production secret | -| `void secret list` | List production secrets | -| `void secret sync ` | Bulk upload secrets from dotenv file | -| `void env check [--remote]` | Validate env.ts schema | -| `void env types` | Regenerate .void/env.d.ts from env.ts | -| `void auth login` | Authenticate with the project’s saved destination, or choose one | -| `void account login` | Authenticate with a Void platform | -| `void cloudflare login` | Authenticate with Cloudflare through Void | -| `void platform install` | Install a company Void platform in Cloudflare | -| `void platform security` | Administer security audits: scan mode, models, caps, findings, and alerts | -| `void connect ` | Connect the CLI to a Void platform; hostnames default to HTTPS | -| `void project link` | Link directory to a project | -| `void project logs` | Show runtime logs from deployed project | -| `void project requests` | Show request-level traffic (status, method, timing) | -| `void project rollback` | Roll back to a previous deployment | -| `void project cancel` | Cancel an active deployment | -| `void project zero-trust` | Inspect or override project Zero Trust protection, or bypass a security scan | -| `void project security` | Review findings and scans, set model and budget, scan, check code pre-deploy | -| `void project purge-cache` | Purge all cached pages (Void platform) | -| `void build logs` | Stream, tail, or download build logs | -| `void email status` | Show email readiness on your own Cloudflare account (`--platform cloudflare`) | -| `void email setup` | Set email up on your own Cloudflare account, without deploying | -| `void email usage` | Show monthly recipient attempts, inbound receipts, and quota | -| `void email logs` | Show recent email delivery activity | -| `void email destinations` | List verified recipient addresses | -| `void email allow
` | Add a recipient and send a verification email | -| `void email disallow
` | Remove a recipient from the allowlist | -| `void email alias [name]` | Show the shared mail address, or give it a shorter permanent name | -| `void email domain` | Send and receive at your own domain on a Cloudflare zone | -| `void init` | Set up a new or existing project, including coding agents | -| `void migrate` | Update project configuration | +| Command | Purpose | +| ---------------------------------------------------------- | ----------------------------------------------------------------------------- | +| `void deploy` | Build and deploy to the configured platform | +| `void deploy --skip-migrations` | Deploy code without applying application or authentication SQL migrations | +| `void deploy --platform cloudflare --preview ` | Deploy a static site to a Cloudflare Preview; production is unchanged | +| `void project preview delete --platform cloudflare` | 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 | +| `void gen route ` | Create an API route | +| `void db push` | Apply schema directly without migration files | +| `void db generate` | Generate SQL migrations from schema changes | +| `void db status` | Show local/remote migration status | +| `void db reset` | Drop and re-apply all migrations | +| `void db seed` | Reset + seed local database | +| `void db execute ` | Run SQL against the database (--remote for deployed) | +| `void db studio` | Open Drizzle Studio (--remote for a deployed external database) | +| `void db restore --bookmark ` | Restore the deployed D1 database to a restore point (direct Cloudflare) | +| `void secret put ` | Set a production secret | +| `void secret list` | List production secrets | +| `void secret sync ` | Bulk upload secrets from dotenv file | +| `void env check [--remote]` | Validate env.ts schema | +| `void env types` | Regenerate .void/env.d.ts from env.ts | +| `void auth login` | Authenticate with the project’s saved destination, or choose one | +| `void account login` | Authenticate with a Void platform | +| `void cloudflare login` | Authenticate with Cloudflare through Void | +| `void platform install` | Install a company Void platform in Cloudflare | +| `void platform security` | Administer security audits: scan mode, models, caps, findings, and alerts | +| `void connect ` | Connect the CLI to a Void platform; hostnames default to HTTPS | +| `void project link` | Link directory to a project | +| `void project logs` | Show runtime logs from deployed project | +| `void project requests` | Show request-level traffic (status, method, timing) | +| `void project rollback` | Roll back to a previous deployment | +| `void project cancel` | Cancel an active deployment | +| `void project zero-trust` | Inspect or override project Zero Trust protection, or bypass a security scan | +| `void project security` | Review findings and scans, set model and budget, scan, check code pre-deploy | +| `void project purge-cache` | Purge all cached pages (Void platform) | +| `void build logs` | Stream, tail, or download build logs | +| `void email status` | Show email readiness on your own Cloudflare account (`--platform cloudflare`) | +| `void email setup` | Set email up on your own Cloudflare account, without deploying | +| `void email usage` | Show monthly recipient attempts, inbound receipts, and quota | +| `void email logs` | Show recent email delivery activity | +| `void email destinations` | List verified recipient addresses | +| `void email allow
` | Add a recipient and send a verification email | +| `void email disallow
` | Remove a recipient from the allowlist | +| `void email alias [name]` | Show the shared mail address, or give it a shorter permanent name | +| `void email domain` | Send and receive at your own domain on a Cloudflare zone | +| `void init` | Set up a new or existing project, including coding agents | +| `void migrate` | Update project configuration | For platform administration, see [plans and account limits](../guide/platform/administration/plans.md), [users and projects](./cli/platform-users.md), and [AI logging](./cli/platform-users.md#ai-gateway-logging). diff --git a/docs/reference/cli/deploy.md b/docs/reference/cli/deploy.md index 9d889eb37..a09cf7716 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; requires `--platform cloudflare` | | `--atomic` | Publish an existing Durable Object Worker directly; readiness is checked after traffic changes | +| `--preview ` | Deploy a static site or SPA to a Cloudflare Preview; production is unchanged ([more](#void-deploy-preview)) | +| `--json` | With `--preview`, print one JSON object on stdout; everything else 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`. @@ -119,3 +122,54 @@ 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 a static site or SPA to a named [Cloudflare Preview](https://developers.cloudflare.com/workers/previews/) of the same Worker. Production traffic, routes and schedules are unchanged. + +```sh +void deploy --platform cloudflare --preview pr-64 +``` + +Add `--skip-build` or `--dir` to reuse an earlier build. + +A Preview keeps its URL across deploys: `https://-..workers.dev`, or `.` on a custom domain. + +Before the first preview: + +- Deploy the Worker to production once with `void deploy --platform cloudflare`. A preview never creates the Worker. +- Set the Worker name: `cloudflare.name` in `void.config.ts`, or `name` in `wrangler.jsonc`. +- Pin the account with `cloudflare.account_id` (`account_id` in `wrangler.jsonc`) or `CLOUDFLARE_ACCOUNT_ID`. +- Workers that serve only routes or custom domains need `preview_urls: true`. + +Only static sites and SPAs can deploy a preview. A static preview gets none of the Worker's bindings, vars or secrets. + +Use lowercase letters, digits and single hyphens, starting with a letter. On workers.dev, `-` must fit in 63 characters. Name previews after the pull request, such as `pr-64`. + +With `--json`, stdout carries one JSON object on a single line (shown formatted here): + +```json +{ + "type": "preview", + "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" +} +``` + +| Field | Type | Meaning | +| --------------- | ---------------- | ----------------------------------------------- | +| `type` | `"preview"` | Record type | +| `workerName` | `string` | The Worker the preview belongs to | +| `previewName` | `string` | The name passed to `--preview` | +| `previewUrl` | `string` | Always serves the latest deploy of this preview | +| `deploymentId` | `string` | This deployment | +| `deploymentUrl` | `string \| null` | Serves only this deployment | + +On failure, stdout is empty and the exit code is not 0; read stderr. + +Preview URLs are public. Protect them with [Cloudflare Access](https://developers.cloudflare.com/workers/configuration/cloudflare-access/) when needed. Workers Free allows 100 previews per Worker; Cloudflare removes the oldest one beyond that. + +Remove a preview with [`void project preview delete`](./project.md#void-project-preview-delete-name). See [Pull request previews](../../integrations/cloudflare.md#pull-request-previews) for a GitHub Actions workflow. diff --git a/docs/reference/cli/project.md b/docs/reference/cli/project.md index 7436ddea0..e1a65bd1c 100644 --- a/docs/reference/cli/project.md +++ b/docs/reference/cli/project.md @@ -241,6 +241,19 @@ Pass `--platform cloudflare` to roll back a one-off Cloudflare deployment. Database recovery is separate from code rollback. Void asks for confirmation when the earlier code may be incompatible with the current schema. For D1 on Cloudflare, use [`void db restore`](./database.md#void-db-restore) with the restore point printed during deployment. +## `void project preview delete ` {#void-project-preview-delete-name} + +``` +void project preview delete [--platform cloudflare] +``` + +Delete a Cloudflare Preview made with [`void deploy --preview`](./deploy.md#void-deploy-preview), and all its deployments. Production is unchanged. It needs the Worker name and a pinned account (`cloudflare.name` and `cloudflare.account_id`, the matching keys in `wrangler.jsonc`, or `CLOUDFLARE_ACCOUNT_ID`), the same ones the preview deploy used. + +- Exit code 0: the preview was deleted, or it did not exist. A cleanup job can run more than once. +- Exit code 1: the Worker was not found in the account, or Cloudflare returned another error. + +Pass `--platform cloudflare` when the project's saved platform is not Cloudflare. + ## `void project cancel [deployId]` {#void-project-cancel-deployid} ``` diff --git a/packages/deploy-cloudflare/src/diagnostics.ts b/packages/deploy-cloudflare/src/diagnostics.ts index 92d1c3a03..e1bb458e3 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 1474f73d1..a62c9e480 100644 --- a/packages/deploy-cloudflare/src/index.ts +++ b/packages/deploy-cloudflare/src/index.ts @@ -54,12 +54,22 @@ export { type CloudflareVersionMetadata, type CloudflareWorkersDevSubdomainLookup, } from './version.ts'; +export { + CLOUDFLARE_HOST_LABEL_MAX, + deleteCloudflarePreview, + cloudflarePreviewNameProblem, + deployCloudflarePreview, + previewStaticWorkerConfig, + 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 8c4033fb6..4ce493053 100644 --- a/packages/deploy-cloudflare/src/operations.ts +++ b/packages/deploy-cloudflare/src/operations.ts @@ -68,6 +68,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); @@ -78,6 +87,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..25231d3e2 --- /dev/null +++ b/packages/deploy-cloudflare/src/preview.ts @@ -0,0 +1,227 @@ +import { isRecord } from '@void/deploy-core'; +import { commandDiagnosticFields } from './diagnostics.ts'; +import { isCleanCommandExit, isCompletedCommand, isWorkerNotFound } from './execute.ts'; +import type { CloudflareCommandRunner } from './execute.ts'; +import type { CloudflarePreviewUploadResult } from './operations.ts'; + +/** A DNS label, such as a workers.dev Preview host, holds at most 63 characters. */ +export const CLOUDFLARE_HOST_LABEL_MAX = 63; +/** Cloudflare's "Preview not found" API error. */ +const PREVIEW_NOT_FOUND = 10_025; + +/** + * Return why `name` cannot name a Preview, or undefined when it can. Cloudflare uses the name + * unchanged as the start of a hostname label, so the URL Void prints is the one CI expects. + */ +export function cloudflarePreviewNameProblem(name: string): string | undefined { + if (name.length === 0 || name.length > CLOUDFLARE_HOST_LABEL_MAX) { + return `must be 1 to ${CLOUDFLARE_HOST_LABEL_MAX} characters`; + } + if (!isLowercaseLetter(name[0])) { + return 'must start with a lowercase letter'; + } + for (const character of name) { + if (!isLowercaseLetter(character) && !isDigit(character) && character !== '-') { + return 'may use only lowercase letters, digits and hyphens'; + } + } + if (name.endsWith('-')) { + return 'must end with a letter or digit'; + } + if (name.includes('--')) { + return 'cannot have two hyphens in a row'; + } + return undefined; +} + +function isLowercaseLetter(character: string | undefined): boolean { + return character !== undefined && character >= 'a' && character <= 'z'; +} + +function isDigit(character: string): boolean { + return character >= '0' && character <= '9'; +} + +/** Root config keys a static Preview keeps. Bindings, vars, migrations and triggers are dropped. */ +const PREVIEW_CONFIG_KEYS = [ + 'name', + 'account_id', + 'compliance_region', + 'compatibility_date', + 'compatibility_flags', + 'assets', + 'observability', + 'version_metadata', +]; + +/** + * The config a static site Preview is staged from. cf sends every binding in the Build Output to + * the Preview, so this copies only an allow-list: a binding kind added later never reaches it. + */ +export function previewStaticWorkerConfig( + config: Record, +): Record { + return Object.fromEntries( + PREVIEW_CONFIG_KEYS.flatMap((key) => (config[key] === undefined ? [] : [[key, config[key]]])), + ); +} + +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 | null; + } + | { ok: false; reason: 'worker-not-found' | 'uploader-changed' | 'output-invalid' } + | { + ok: false; + reason: 'worker-check-failed' | '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'; deploymentId: string }; + +/** + * Create or update a named Workers Preview from the prepared output. It reads the Worker's + * deployment status first, because cf would create a missing Worker without asking. Production + * versions, deployments, traffic and triggers are not 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 target = { + workerName: options.workerName, + ...(options.configPath ? { configPath: options.configPath } : {}), + }; + const status = await options.runWrangler( + { type: 'deployments.status', ...target }, + { capture: true }, + ); + if (isWorkerNotFound(status)) { + return { ok: false, reason: 'worker-not-found' }; + } + if (!isCleanCommandExit(status)) { + return { + ok: false, + reason: 'worker-check-failed', + status: status.status, + ...commandDiagnosticFields(status), + }; + } + if (!options.verifyUploader()) { + return { ok: false, reason: 'uploader-changed' }; + } + const result = await options.runWrangler( + { type: 'previews.deploy', previewName: options.previewName, ...target }, + { 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', deploymentId: uploaded.deploymentId }; + } + return { + ok: true, + previewId: uploaded.previewId, + deploymentId: uploaded.deploymentId, + previewUrl: uploaded.previewUrl, + deploymentUrl: uploaded.deploymentUrl ?? null, + }; +} + +export type CloudflarePreviewDeleteResult = + | { ok: true; deleted: boolean } + | { ok: false; reason: 'worker-not-found' } + | { 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. A missing Worker is an + * error: the name or account most likely points somewhere else. + */ +export async function deleteCloudflarePreview(options: { + runWrangler: CloudflareCommandRunner; + workerName: string; + previewName: string; + configPath?: string; +}): Promise { + 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 }; + } + // Checked first: "Preview not found" must never read as a missing Worker. + if (isCompletedCommand(result) && result.errorCode === PREVIEW_NOT_FOUND) { + return { ok: true, deleted: false }; + } + if (isWorkerNotFound(result)) { + return { ok: false, reason: 'worker-not-found' }; + } + 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; + if ( + typeof previewId !== 'string' || + !previewId || + typeof previewName !== 'string' || + typeof deploymentId !== 'string' || + !deploymentId || + !optionalUrl(previewUrl) || + !optionalUrl(deploymentUrl) + ) { + return null; + } + return { + previewId, + previewName, + deploymentId, + ...(isHttpsUrl(previewUrl) ? { previewUrl } : {}), + ...(isHttpsUrl(deploymentUrl) ? { deploymentUrl } : {}), + }; +} + +function isHttpsUrl(url: unknown): url is string { + return typeof url === 'string' && url.startsWith('https://'); +} + +function optionalUrl(url: unknown): boolean { + return url === undefined || isHttpsUrl(url); +} diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 82d7c3b40..2c5df0804 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, @@ -2764,11 +2764,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 f493c0536..ef5cd2d05 100644 --- a/packages/deploy-cloudflare/test/operation-fixture.ts +++ b/packages/deploy-cloudflare/test/operation-fixture.ts @@ -194,6 +194,16 @@ export function operationFixtureArgs(operation: CloudflareOperation): Array, + status: Partial = {}, +) { + const calls: Array = []; + const runWrangler: CloudflareCommandRunner = vi.fn((operation: CloudflareOperation) => { + calls.push(operation); + return { + status: 0, + stdout: '', + stderr: '', + ...(operation.type === 'deployments.status' ? status : answer), + }; + }); + return { calls, runWrangler }; +} + +const target = { workerName: 'site', previewName: 'pr-64', verifyUploader: () => true }; + +describe('cloudflarePreviewNameProblem', () => { + it.each(['pr-64', 'a', 'feature-login', 'a'.repeat(63)])('accepts %s', (name) => { + expect(cloudflarePreviewNameProblem(name)).toBeUndefined(); + }); + + it.each([ + ['', 'must be 1 to 63 characters'], + ['a'.repeat(64), 'must be 1 to 63 characters'], + ['1a', 'must start with a lowercase letter'], + ['-a', 'must start with a lowercase letter'], + ['A', 'must start with a lowercase letter'], + ['a_b', 'may use only lowercase letters, digits and hyphens'], + ['a-', 'must end with a letter or digit'], + ['a--b', 'cannot have two hyphens in a row'], + ])('refuses %j', (name, problem) => { + expect(cloudflarePreviewNameProblem(name)).toBe(problem); + }); +}); + +describe('previewStaticWorkerConfig', () => { + it('keeps only the allow-listed keys', () => { + expect( + previewStaticWorkerConfig({ + name: 'site', + account_id: 'acc', + compatibility_date: '2026-01-01', + compatibility_flags: ['nodejs_compat'], + assets: { html_handling: 'auto-trailing-slash' }, + observability: { enabled: true }, + version_metadata: { binding: 'CF_VERSION_METADATA' }, + kv_namespaces: [{ binding: 'KV', id: 'kv' }], + d1_databases: [{ binding: 'DB', database_id: 'db' }], + vars: { SECRET_LOOKING: 'x' }, + migrations: [{ tag: 'v1', new_sqlite_classes: ['Room'] }], + triggers: { crons: ['* * * * *'] }, + routes: ['example.com/*'], + preview_urls: true, + }), + ).toEqual({ + name: 'site', + account_id: 'acc', + compatibility_date: '2026-01-01', + compatibility_flags: ['nodejs_compat'], + assets: { html_handling: 'auto-trailing-slash' }, + observability: { enabled: true }, + version_metadata: { binding: 'CF_VERSION_METADATA' }, + }); + }); +}); + +describe('deployCloudflarePreview', () => { + it('checks the Worker, then deploys the Preview and returns its 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 changed: no versions, traffic or triggers. + expect(calls).toEqual([ + { type: 'deployments.status', workerName: 'site', configPath: '/app/wrangler.json' }, + { + type: 'previews.deploy', + workerName: 'site', + previewName: 'pr-64', + configPath: '/app/wrangler.json', + }, + ]); + }); + + it.each([ + [ + { status: 1, errorCode: 10_007 }, + { ok: false, reason: 'worker-not-found' }, + ], + [ + { status: 1, failure: 'not-found' as const }, + { ok: false, reason: 'worker-not-found' }, + ], + [ + { status: 1, stderr: 'Authentication error' }, + { + ok: false, + reason: 'worker-check-failed', + status: 1, + diagnostic: 'Authentication error', + }, + ], + ])('uploads nothing when the Worker check gives %j', async (status, expected) => { + const { calls, runWrangler } = runner({ data: uploaded }, status); + expect(await deployCloudflarePreview({ ...target, runWrangler })).toEqual(expected); + expect(calls.map((call) => call.type)).toEqual(['deployments.status']); + }); + + it('uploads nothing when the uploader changed', async () => { + const { calls, runWrangler } = runner({ data: uploaded }); + expect( + await deployCloudflarePreview({ ...target, runWrangler, verifyUploader: () => false }), + ).toEqual({ ok: false, reason: 'uploader-changed' }); + expect(calls.map((call) => call.type)).toEqual(['deployments.status']); + }); + + it('reports a failed deploy', async () => { + const { runWrangler } = runner({ status: 1, stderr: 'Authentication error' }); + expect(await deployCloudflarePreview({ ...target, runWrangler })).toEqual({ + ok: false, + reason: 'deploy-failed', + status: 1, + diagnostic: 'Authentication error', + }); + }); + + it('reports disabled Preview URLs with the deployment Cloudflare created', async () => { + const { previewUrl: _, ...withoutUrl } = uploaded; + const { runWrangler } = runner({ data: withoutUrl }); + expect(await deployCloudflarePreview({ ...target, runWrangler })).toEqual({ + ok: false, + reason: 'preview-urls-disabled', + deploymentId: 'dep_1', + }); + }); + + it('returns a null deployment URL when Cloudflare gives none', async () => { + const { deploymentUrl: _, ...withoutUrl } = uploaded; + const { runWrangler } = runner({ data: withoutUrl }); + expect(await deployCloudflarePreview({ ...target, runWrangler })).toMatchObject({ + ok: true, + deploymentUrl: null, + }); + }); + + 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', () => { + const deleteTarget = { workerName: 'site', previewName: 'pr-64' }; + + it('deletes the named Preview of the Worker', async () => { + const { calls, runWrangler } = runner({}); + expect(await deleteCloudflarePreview({ ...deleteTarget, runWrangler })).toEqual({ + ok: true, + deleted: true, + }); + expect(calls).toEqual([{ type: 'previews.delete', workerName: 'site', previewName: 'pr-64' }]); + }); + + // 10025 is "Preview not found"; 10007 and not-found mean the Worker itself is missing. + it.each([ + [ + { status: 1, errorCode: 10_025 }, + { ok: true, deleted: false }, + ], + [ + { status: 1, errorCode: 10_007 }, + { ok: false, reason: 'worker-not-found' }, + ], + [ + { status: 1, failure: 'not-found' as const }, + { ok: false, reason: 'worker-not-found' }, + ], + [ + { status: 1, errorCode: 10_000, stderr: 'Authentication error' }, + { ok: false, reason: 'delete-failed', status: 1, diagnostic: 'Authentication error' }, + ], + ])('maps %j', async (answer, expected) => { + const { runWrangler } = runner(answer); + expect(await deleteCloudflarePreview({ ...deleteTarget, runWrangler })).toEqual(expected); + }); +}); diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index 2df952b68..47418ac02 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -25,6 +25,8 @@ Unlinked projects with a root `wrangler.jsonc` or `wrangler.json` get a link-and Assets-only Workers report null or empty handlers alongside `script_runtime.assets`. Accept that shape during handoff; only the static adapter may add its `ASSETS` binding and sole `fetch` handler. Preserve every existing binding and reject name collisions. Missing handler metadata without verified assets must not bypass the handler checks. +Static previews (`deploy --preview`) send `deployments.status` then `previews.deploy` from a Build Output with `isPreview: true` and an allow-listed config (`previewStaticWorkerConfig`); they never create a Worker. + Handoff asks for an explicit ISR cache choice when the app requests caching and the verified Worker has no cache. Persist `routing.isr` in `void.config.ts` before provisioning: true allows only the new cache during this deployment; false disables ISR in native output and managed manifests until explicitly changed. Existing bindings and handlers remain protected; generated and uploaded cache IDs must match the approved pre-build identity, and the cache cannot alias an existing application namespace. Retrying may reuse the ID already recorded in `void.lock.json`. Never defer cache enablement implicitly to the next deploy. Existing D1 migration settings remain untouched during handoff, which applies no migrations. The main export `voidPlugin()` returns an array of Vite plugins. For the default Cloudflare target, this includes the `cloudflare()` plugin. For non-CF targets (`node`, `bun`, `deno`), it replaces `cloudflare()` with `nodeTargetPlugin()`: diff --git a/packages/void/skills/void/SKILL.md b/packages/void/skills/void/SKILL.md index b184b7be4..f35504e9d 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. +Static PR previews: `void deploy --platform cloudflare --preview pr- --json` (deploy production first); remove with `void project preview delete pr- --platform cloudflare`. + 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 feaaf015e..d5f706dda 100644 --- a/packages/void/src/cli/args.ts +++ b/packages/void/src/cli/args.ts @@ -3,7 +3,7 @@ import type { RunDeployOptions } from './deploy-types.ts'; export function parseDeployArgs( args: Array, -): Omit { +): Omit { let parsed: ReturnType; try { parsed = parseArgs({ @@ -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, @@ -34,6 +36,11 @@ export function parseDeployArgs( cause: error, }); } + if (optionMatch?.[1] === '--preview') { + throw new Error('deploy: --preview requires a name (for example --preview pr-64).', { + cause: error, + }); + } throw new Error('deploy: --project requires a slug.', { cause: error }); } @@ -108,7 +115,36 @@ 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 (preview === '') { + throw new Error('deploy: --preview requires a name (for example --preview pr-64).'); + } + if (platform !== 'cloudflare') { + throw new Error('deploy: --preview requires --platform cloudflare.'); + } + // The name and the Worker it targets are checked before connecting to Cloudflare. + 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 286a2fa6c..ec1548bcd 100644 --- a/packages/void/src/cli/cf-build-output.ts +++ b/packages/void/src/cli/cf-build-output.ts @@ -157,6 +157,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); const hasNativeOutput = existsSync(getRootConfigPath(source)); @@ -288,7 +290,7 @@ export async function prepareCfBuildOutput( await writeRootConfig({ root: directory, settings: typeof configuredAccountId === 'string' ? { accountId: configuredAccountId } : {}, - buildContext: { isPreview: false, mode: mode ?? 'production' }, + buildContext: { isPreview: options.isPreview === true, mode: mode ?? 'production' }, }); await writeWorkerConfig({ root: directory, @@ -561,6 +563,7 @@ async function prepareBundledBuildOutput(options: { assets: Record; accountId: string; external?: Array; + isPreview?: boolean; }): Promise { const scratch = mkdtempSync(join(tmpdir(), options.scratchPrefix)); try { @@ -598,7 +601,9 @@ async function prepareBundledBuildOutput(options: { JSON.stringify({ ...options.config, main: entry.fileName, 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 }); } @@ -610,6 +615,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) { @@ -626,6 +633,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 af6ac2866..fa10033d7 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,38 @@ export function readCfUploadOutput(result: { workersDevUrl: output.match(/(https:\/\/[a-z0-9.-]+\.workers\.dev(?:\/[^\s]*)?)/i)?.[1], }; } + +/** + * Map the Preview record `cf previews deploy` prints as JSON on stdout to the stable Preview URL + * and the URL of this deployment. Anything unreadable gives undefined, so the deploy fails closed. + */ +export function readCfPreviewDeployOutput( + data: unknown, +): CloudflarePreviewUploadResult | undefined { + if ( + !isRecord(data) || + typeof data.preview_id !== 'string' || + typeof data.preview_name !== 'string' || + typeof data.deployment_id !== 'string' + ) { + return undefined; + } + const previewUrl = firstUrl(data.preview_urls); + const deploymentUrl = firstUrl(data.deployment_urls); + return { + previewId: data.preview_id, + previewName: data.preview_name, + deploymentId: data.deployment_id, + ...(previewUrl ? { previewUrl } : {}), + ...(deploymentUrl ? { deploymentUrl } : {}), + }; +} + +/** The first URL of a cf URL list, without a trailing slash. */ +function firstUrl(urls: unknown): string | undefined { + const url: unknown = Array.isArray(urls) ? urls[0] : undefined; + if (typeof url !== 'string') { + return undefined; + } + return url.endsWith('/') ? url.slice(0, -1) : url; +} diff --git a/packages/void/src/cli/cf-version-runner.ts b/packages/void/src/cli/cf-version-runner.ts index 511ca0bc7..72982c92e 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'; @@ -735,6 +736,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 run( + ['previews', 'deploy', '--prebuilt', `--preview-name=${operation.previewName}`], + command.capture, + ); + if (!isCleanCloudflareExit(deployed)) { + return deployed; + } + return { ...deployed, data: readCfPreviewDeployOutput(deployed.data) }; + } + 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 cf8220a92..4795f2527 100644 --- a/packages/void/src/cli/cli-main.ts +++ b/packages/void/src/cli/cli-main.ts @@ -193,8 +193,8 @@ const subcommandGroups = { db: () => runSubcommandGroup('db', dbSubcommands, parseDbArgs, async (root, parsed) => { if (parsed.action === 'execute' && parsed.json) { - const { runDbExecuteProcess } = await import('./db-execute-process.ts'); - await runDbExecuteProcess(root, args); + const { runJsonCommandProcess } = await import('./json-command-process.ts'); + await runJsonCommandProcess(root, args); } else { const { runDbCommand } = await import('./db.ts'); await runDbCommand(root, parsed); @@ -235,15 +235,23 @@ if (helpPath) { try { deployArgs = parseDeployArgs(args.slice(1)); } catch (err) { - log.error(formatCloudflareUserMessage(err instanceof Error ? err.message : String(err))); + log.error( + formatCloudflareUserMessage(err instanceof Error ? err.message : String(err)), + args.includes('--json') ? { output: process.stderr } : undefined, + ); process.exit(1); } - const { runDeploy } = await import('./deploy.ts'); - await runDeploy(root, deployArgs).catch((err: unknown) => { - log.error(formatCloudflareUserMessage(err instanceof Error ? err.message : String(err))); - process.exit(1); - }); + if (deployArgs.json) { + const { runJsonCommandProcess } = await import('./json-command-process.ts'); + await runJsonCommandProcess(root, args); + } else { + const { runDeploy } = await import('./deploy.ts'); + await runDeploy(root, deployArgs).catch((err: unknown) => { + log.error(formatCloudflareUserMessage(err instanceof Error ? err.message : String(err))); + process.exit(1); + }); + } } else if (command === 'connect') { await (async () => { const parsed = parseConnectArgs(args.slice(1)); @@ -352,7 +360,7 @@ if (helpPath) { }, { name: 'project', - hint: 'status | link | list | team | token | zero-trust | security | logs | requests | rollback | cancel | delete | purge-cache', + hint: 'status | link | list | team | token | zero-trust | security | logs | requests | rollback | preview | cancel | delete | purge-cache', description: 'Manage projects, teams, deployments, and scoped CI credentials', }, { name: 'secret', hint: 'list | put | delete | sync', description: 'Manage project secrets' }, diff --git a/packages/void/src/cli/cloudflare-operation-process.ts b/packages/void/src/cli/cloudflare-operation-process.ts index 4bf36b154..0021394a4 100644 --- a/packages/void/src/cli/cloudflare-operation-process.ts +++ b/packages/void/src/cli/cloudflare-operation-process.ts @@ -1524,6 +1524,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/cloudflare-preview.ts b/packages/void/src/cli/cloudflare-preview.ts new file mode 100644 index 000000000..773ee5a5e --- /dev/null +++ b/packages/void/src/cli/cloudflare-preview.ts @@ -0,0 +1,203 @@ +import { + CLOUDFLARE_HOST_LABEL_MAX, + cloudflarePreviewNameProblem, + deleteCloudflarePreview, + deployCloudflarePreview, + readWranglerTopLevelString, +} from '@void/deploy-cloudflare'; +import type { + CloudflareCommandRunner, + CloudflarePreviewDeployResult, +} from '@void/deploy-cloudflare'; +import { log } from '@voidzero-dev/vite-plus-prompts'; +import { basename } from 'pathslash'; +import type { CfBuildOutput } from './cf-build-output.ts'; +import type { CloudflareChildReporter } from './cloudflare-child-report.ts'; +import type { CloudflareOperationRunner } from './cloudflare-operations.ts'; +import { log as deployLog } from './deploy-helpers.ts'; +import { formatDeploySummary } from './deploy-summary.ts'; +import type { RunDeployOptions } from './deploy-types.ts'; +import type { CliLogger } from './log-file.ts'; +import { formatUrl, note, printSuccess } from './output.ts'; + +/** Where the user sets a top-level Cloudflare config key, for messages. */ +export function cloudflareConfigKey(configPath: string, key: string): string { + const file = basename(configPath); + return file === 'wrangler.jsonc' || file === 'wrangler.json' + ? `${key} in ${file}` + : `cloudflare.${key} in void.config.ts`; +} + +/** + * Check a `deploy --preview` request before connecting to Cloudflare. A Worker name and a pinned + * account make the deploy and `void project preview delete` reach the same Worker. + */ +export function checkCloudflarePreviewRequest(options: { + previewName: string; + rootConfig: Record; + configPath: string; +}): string | undefined { + const { previewName, rootConfig, configPath } = options; + const problem = cloudflarePreviewNameProblem(previewName); + if (problem) { + return `deploy: "${previewName}" is not a valid preview name: ${problem}. For example: pr-64.`; + } + const workerName = readWranglerTopLevelString(rootConfig, 'name'); + if (!workerName) { + return `deploy: --preview needs the Worker name (${cloudflareConfigKey(configPath, 'name')}), so the preview and its cleanup reach the same Worker.`; + } + if ( + !readWranglerTopLevelString(rootConfig, 'account_id') && + !process.env.CLOUDFLARE_ACCOUNT_ID?.trim() + ) { + return `deploy: --preview needs a pinned Cloudflare account. Set ${cloudflareConfigKey(configPath, 'account_id')} or CLOUDFLARE_ACCOUNT_ID.`; + } + // Stricter than a Preview that serves only a custom domain needs, but CI reads the workers.dev + // URL. + const room = CLOUDFLARE_HOST_LABEL_MAX - 1 - workerName.length; + if (room < 1) { + return `deploy: Worker name "${workerName}" is too long for a preview. On workers.dev, "-${workerName}" must be at most ${CLOUDFLARE_HOST_LABEL_MAX} characters, so the Worker name can have at most ${CLOUDFLARE_HOST_LABEL_MAX - 2}.`; + } + if (previewName.length > room) { + return `deploy: preview name "${previewName}" is too long for Worker "${workerName}". On workers.dev, "${previewName}-${workerName}" must be at most ${CLOUDFLARE_HOST_LABEL_MAX} characters, so use at most ${room}.`; + } + return undefined; +} + +/** Deploy a static Preview from the prepared output and report it. Production is unchanged. */ +export async function runCloudflareStaticPreview(options: { + runWrangler: CloudflareCommandRunner; + cfOutput: CfBuildOutput | null; + workerName: string; + previewName: string; + accountId: string; + configPath: string; + staticConfigPath: string; + verifyUploader: () => boolean; + typeLabel: string; + writeResult: RunDeployOptions['writeResult']; + reporter: CloudflareChildReporter; + cliLog: CliLogger; + exit: (code: number) => never; +}): Promise { + const { previewName, workerName, cliLog } = options; + deployLog.step(`Deploying Preview ${previewName}...`); + let result: CloudflarePreviewDeployResult; + try { + result = await deployCloudflarePreview({ + runWrangler: options.runWrangler, + workerName, + previewName, + verifyUploader: options.verifyUploader, + configPath: options.staticConfigPath, + }); + } finally { + await options.cfOutput?.dispose(); + } + if (!result.ok) { + const message = options.reporter.redactor.redact(formatCloudflarePreviewError(result, options)); + cliLog.error('cloudflare_preview_failed', new Error(message), { reason: result.reason }); + deployLog.error(message); + return options.exit(1); + } + cliLog.info('cloudflare_preview_deployed', { + previewName, + previewId: result.previewId, + deploymentId: result.deploymentId, + }); + const record = { + type: 'preview', + workerName, + previewName, + previewUrl: result.previewUrl, + deploymentId: result.deploymentId, + deploymentUrl: result.deploymentUrl, + }; + options.writeResult?.(`${JSON.stringify(record)}\n`); + note( + [ + formatDeploySummary({ workerName, typeLabel: options.typeLabel }), + `Preview: ${previewName}`, + ...(result.deploymentUrl ? [`This deployment: ${formatUrl(result.deploymentUrl)}`] : []), + ].join('\n'), + result.previewUrl, + ); + printSuccess(`Preview ${previewName} deployed. Production is unchanged.`); +} + +function formatCloudflarePreviewError( + result: Extract, + options: { previewName: string; workerName: string; accountId: string; configPath: string }, +): string { + const { previewName, workerName } = options; + switch (result.reason) { + case 'worker-not-found': + return [ + `deploy: Worker "${workerName}" has no production deployment in Cloudflare account ${options.accountId}. Nothing was uploaded.`, + 'Deploy production first: void deploy --platform cloudflare', + ].join('\n'); + case 'worker-check-failed': + return [ + `deploy: could not check Worker "${workerName}" on Cloudflare. Nothing was uploaded.`, + ...(result.diagnostic ? [result.diagnostic] : []), + ].join('\n'); + 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: Cloudflare created deployment ${result.deploymentId} for preview "${previewName}", but Preview URLs are off for Worker "${workerName}", so it has no URL.`, + `Set preview_urls: true (${cloudflareConfigKey(options.configPath, 'preview_urls')}), run void deploy --platform cloudflare once, then deploy the preview again. This also turns on version URLs for production versions.`, + ].join('\n'); + case 'deploy-failed': + return [ + 'deploy: Cloudflare could not deploy the preview. Production is unchanged.', + ...(result.diagnostic ? [result.diagnostic] : []), + ].join('\n'); + } +} + +/** + * `void project preview delete `: delete a Preview of this project's Worker. Production is + * not read or changed. A Preview that does not exist is not an error, so a cleanup job can rerun. + */ +export async function runCloudflarePreviewDelete( + root: string, + { name }: { name: string }, + runner?: CloudflareOperationRunner, +): Promise { + const problem = cloudflarePreviewNameProblem(name); + if (problem) { + throw new Error(`project: "${name}" is not a valid preview name: ${problem}.`); + } + // The same Worker and account as rollback, logs and deploy --preview. + const { resolveCloudflareOperationContext } = await import('./cloudflare-operations.ts'); + const context = resolveCloudflareOperationContext(root, runner); + const { workerName } = context; + const result = await deleteCloudflarePreview({ + runWrangler: context.runWrangler, + workerName, + previewName: name, + configPath: context.configPath, + }); + if (result.ok) { + if (result.deleted) { + printSuccess(`Deleted preview ${name} of Worker ${workerName}. Production is unchanged.`); + } else { + log.info(`Preview ${name} does not exist on Worker ${workerName}. Nothing to delete.`); + } + return; + } + if (result.reason === 'worker-not-found') { + throw new Error( + `project: Worker "${workerName}" was not found in Cloudflare account ${context.accountId}. Nothing was deleted. Check ${cloudflareConfigKey(context.configPath, 'name')} and the pinned account.`, + ); + } + throw new Error( + [ + `project: Cloudflare could not delete preview "${name}" of Worker "${workerName}".`, + ...(result.diagnostic ? [result.diagnostic] : []), + ].join('\n'), + ); +} diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index 963532c03..0802faf3b 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -11,6 +11,7 @@ import { writeCloudflareFrameworkDeployConfig, writeCloudflareStaticDeployConfig, assertExistingCloudflareConfig, + previewStaticWorkerConfig, } from '@void/deploy-cloudflare'; import { dirname, join, relative } from 'pathslash'; import { analyzeApplicationSync } from '../application-analysis.ts'; @@ -30,6 +31,7 @@ import type { CloudflareCandidateReceipt } from './cloudflare-candidate.ts'; import type { CloudflareChildReporter } from './cloudflare-child-report.ts'; import { readCloudflareLink } from './cloudflare-link.ts'; import type { CloudflareLink } from './cloudflare-link.ts'; +import { checkCloudflarePreviewRequest, runCloudflareStaticPreview } from './cloudflare-preview.ts'; import { deduplicateGeneratedCompatibilityFlags } from './deploy-artifact-validation.ts'; import { deployPointerPath } from './deploy-binding-snapshot.ts'; import { prepareExistingCloudflareDeployWithAuth } from './deploy-cloudflare-auth.ts'; @@ -338,6 +340,17 @@ export async function runCloudflareStaticDeploy( ): Promise { const exit = deps.exit ?? ((code: number): never => process.exit(code)); const configPath = discoverRootWranglerConfig(root); + if (options.preview !== undefined) { + const problem = checkCloudflarePreviewRequest({ + previewName: options.preview, + rootConfig: parseRootWranglerConfig(configPath), + configPath, + }); + if (problem) { + log.error(problem); + return exit(1); + } + } const connection = await connectCloudflareDeployAccount({ root, configPath, @@ -380,7 +393,10 @@ 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}`, + ); const rootConfigBeforeBuild = existsSync(configPath) ? readFileSync(configPath, 'utf8') : null; if (preset.buildCommand && !options.skipBuild) { log.step('Building...'); @@ -432,7 +448,12 @@ export async function runCloudflareStaticDeploy( // Write the static config separately so the root config, with its Worker-only bindings and // comments, stays untouched for a later switch back to a Worker app. const staticConfigPath = join(dirname(entryPath), 'wrangler-static.json'); - writeFileSync(staticConfigPath, `${JSON.stringify(rootConfig, null, 2)}\n`, { mode: 0o600 }); + // A preview gets none of the Worker's bindings, vars or migrations. + writeFileSync( + staticConfigPath, + `${JSON.stringify(options.preview === undefined ? rootConfig : previewStaticWorkerConfig(rootConfig), null, 2)}\n`, + { mode: 0o600 }, + ); writeCloudflareStaticDeployConfig({ configPath: staticConfigPath, name: workerName, @@ -496,6 +517,7 @@ export async function runCloudflareStaticDeploy( configPath: staticConfigPath, assetsDirectory: stagedAssetsDirectory, accountId, + isPreview: options.preview !== undefined, }) : null; if (!cfOutput && usesCf) { @@ -513,6 +535,24 @@ export async function runCloudflareStaticDeploy( verifyCompatibilityRunner: assertUploaderStillPinned, reporter, }); + const typeLabel = preset.appType === 'spa' ? 'Static SPA' : 'Static Site'; + if (options.preview !== undefined) { + return runCloudflareStaticPreview({ + runWrangler: activationRunner, + cfOutput, + workerName, + previewName: options.preview, + accountId, + configPath, + staticConfigPath, + verifyUploader: cfOutput ? cfUploaderIsPinned : assertUploaderStillPinned, + typeLabel, + writeResult: options.writeResult, + reporter, + cliLog, + exit, + }); + } const execution = await activateCloudflareVersionWithProgress( deps.activateVersion ?? activateCloudflareVersion, { @@ -565,12 +605,6 @@ export async function runCloudflareStaticDeploy( execution, cliLog, }); - note( - formatDeploySummary({ - workerName, - typeLabel: preset.appType === 'spa' ? 'Static SPA' : 'Static Site', - }), - execution.previewUrl, - ); + note(formatDeploySummary({ workerName, typeLabel }), execution.previewUrl); printDeploySuccess(); } diff --git a/packages/void/src/cli/deploy-cloudflare.ts b/packages/void/src/cli/deploy-cloudflare.ts index 60fb9d90a..394ba1999 100644 --- a/packages/void/src/cli/deploy-cloudflare.ts +++ b/packages/void/src/cli/deploy-cloudflare.ts @@ -64,6 +64,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 && hasOwnKey(FRAMEWORK_PRESETS, detectedFramework.name) @@ -118,6 +124,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-types.ts b/packages/void/src/cli/deploy-types.ts index a486091ec..fec9064c7 100644 --- a/packages/void/src/cli/deploy-types.ts +++ b/packages/void/src/cli/deploy-types.ts @@ -52,6 +52,18 @@ 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; + /** + * Internal: receives the `--json` result record. Only the `--json` child process sets it; its + * stdout is the parent's stderr. + */ + writeResult?: (text: string) => void; /** * `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 c58117057..5ff6d329f 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -69,6 +69,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 dcc01e440..804c65aaa 100644 --- a/packages/void/src/cli/help.ts +++ b/packages/void/src/cli/help.ts @@ -193,6 +193,16 @@ const HELP_TREE = { description: 'Publish a Durable Object Worker without pre-traffic staging (Cloudflare only)', }, + { + command: '--preview ', + description: + 'Deploy a static site or SPA to a Cloudflare Preview with its own URL; production is unchanged (needs --platform cloudflare)', + }, + { + command: '--json', + description: + 'With --preview, print one JSON object on stdout; everything else goes to stderr', + }, { command: '--debug', description: 'Mirror the deploy log to stderr (always written to ~/.void/logs)', @@ -206,6 +216,10 @@ const HELP_TREE = { command: 'void deploy --platform cloudflare', description: 'Deploy to your own Cloudflare account', }, + { + command: 'void deploy --platform cloudflare --preview pr-64', + description: 'Deploy a pull request preview; production is unchanged', + }, ], }, auth: { @@ -657,6 +671,10 @@ const HELP_TREE = { { command: 'logs', description: 'Show runtime logs from the deployed project' }, { command: 'requests', description: 'Show request-level traffic (status, method, timing)' }, { command: 'rollback [deployId]', description: 'Roll back to a previous deployment' }, + { + command: 'preview delete ', + description: 'Delete a Cloudflare Preview made with void deploy --preview', + }, { command: 'cancel [deployId]', description: 'Cancel an active deployment' }, { command: 'delete [name]', description: 'Delete a project and all its resources' }, { command: 'purge-cache', description: 'Purge all cached pages (Void platform)' }, @@ -915,6 +933,23 @@ const HELP_TREE = { }, ], }, + preview: { + summary: + 'Delete a Cloudflare Preview made with void deploy --preview, and all its deployments. Production is unchanged.', + usage: ['void project preview delete [--platform cloudflare]'], + options: [ + { + command: '--platform cloudflare', + description: 'Delete it after a one-off Cloudflare deploy', + }, + ], + examples: [ + { + command: 'void project preview delete pr-64 --platform cloudflare', + description: 'Remove a pull request preview', + }, + ], + }, cancel: basicSubcommand('Cancel an active deployment.', 'void project cancel [deployId]'), delete: { summary: 'Delete a project and all its resources.', diff --git a/packages/void/src/cli/db-execute-process.ts b/packages/void/src/cli/json-command-process.ts similarity index 63% rename from packages/void/src/cli/db-execute-process.ts rename to packages/void/src/cli/json-command-process.ts index d08b26c97..b2442ba80 100644 --- a/packages/void/src/cli/db-execute-process.ts +++ b/packages/void/src/cli/json-command-process.ts @@ -5,11 +5,15 @@ import { log } from '@voidzero-dev/vite-plus-prompts'; import { formatCloudflareUserMessage } from './cloudflare-user-output.ts'; import { Buffer } from './node-buffer.ts'; -const CHILD_COMMAND = '__void-db-execute-json__'; +const CHILD_COMMAND = '__void-json-command__'; const RESULT_FD = 3; -/** Keep config output on stderr, including writes to fd 1 and output from its children. */ -export async function runDbExecuteProcess( +/** + * Run a `--json` command (`db execute` or `deploy`) in a child process whose stdout is our + * stderr, so config output, including writes to fd 1 and output from its children, never reaches + * stdout. Only the result the child writes to fd 3 is printed, and only on success. + */ +export async function runJsonCommandProcess( root: string, args: ReadonlyArray, ): Promise { @@ -51,10 +55,18 @@ if (process.argv[2] === CHILD_COMMAND) { try { // Keep the CLI arguments visible to project config evaluated by this process. process.argv.splice(1, 2); - const { parseDbArgs } = await import('./db-args.ts'); - const args = parseDbArgs(process.argv.slice(3)); - const { runDbCommand } = await import('./db.ts'); - await runDbCommand(process.cwd(), args, (text) => writeFileSync(RESULT_FD, text)); + const writeResult = (text: string) => writeFileSync(RESULT_FD, text); + // `.at()`, as TypeScript still narrows `argv[2]` to the marker after the splice. + if (process.argv.at(2) === 'deploy') { + const { parseDeployArgs } = await import('./args.ts'); + const { runDeploy } = await import('./deploy.ts'); + await runDeploy(process.cwd(), { ...parseDeployArgs(process.argv.slice(3)), writeResult }); + } else { + const { parseDbArgs } = await import('./db-args.ts'); + const args = parseDbArgs(process.argv.slice(3)); + const { runDbCommand } = await import('./db.ts'); + await runDbCommand(process.cwd(), args, writeResult); + } } catch (error) { log.error(formatCloudflareUserMessage(error instanceof Error ? error.message : String(error)), { output: process.stderr, diff --git a/packages/void/src/cli/project-args.ts b/packages/void/src/cli/project-args.ts index 488db82c6..529b15c73 100644 --- a/packages/void/src/cli/project-args.ts +++ b/packages/void/src/cli/project-args.ts @@ -49,6 +49,11 @@ export const projectSubcommands: Array = [ }, ], }, + { + name: 'preview', + hint: 'delete ', + description: 'Delete a Cloudflare Preview made by deploy --preview', + }, { name: 'cancel', arg: '[deployId]', description: 'Cancel an active deployment' }, { name: 'delete', @@ -205,6 +210,7 @@ export type ProjectArgs = } | { subcommand: 'requests'; status: string; range: string } | { subcommand: 'rollback'; deployId: string; platform?: 'cloudflare' } + | { subcommand: 'preview'; action: 'delete'; name: string; platform?: 'cloudflare' } | { subcommand: 'cancel'; deployId: string } | { subcommand: 'delete'; name: string; force: boolean } | { subcommand: 'purge-cache'; projectSlug: string }; @@ -359,6 +365,29 @@ export function parseProjectArgs(args: Array): ProjectArgs { }; } + if (subcommand === 'preview') { + const usage = 'project: Usage: void project preview delete [--platform cloudflare].'; + let platform: 'cloudflare' | undefined; + const positional: Array = []; + for (let i = 0; i < rest.length; i++) { + const arg = rest[i]; + if (arg === '--platform' || arg.startsWith('--platform=')) { + const value = arg === '--platform' ? rest[++i] : arg.slice('--platform='.length); + if (value !== 'cloudflare') { + throw new Error(usage); + } + platform = 'cloudflare'; + } else { + positional.push(arg); + } + } + const [action, name] = positional; + if (positional.length !== 2 || action !== 'delete' || !name || name.startsWith('-')) { + throw new Error(usage); + } + return { subcommand, action, name, ...(platform ? { platform } : {}) }; + } + if (subcommand === 'cancel') { return { subcommand, deployId: parseOptionalPositional(rest) }; } @@ -393,7 +422,7 @@ export function parseProjectArgs(args: Array): ProjectArgs { } throw new Error( - 'project: Usage: void project .', + 'project: Usage: void project .', ); } diff --git a/packages/void/src/cli/project-cmd.ts b/packages/void/src/cli/project-cmd.ts index 9ab0464e1..4538c1f8e 100644 --- a/packages/void/src/cli/project-cmd.ts +++ b/packages/void/src/cli/project-cmd.ts @@ -100,6 +100,16 @@ export async function runProjectCommand(root: string, args: ProjectArgs): Promis const { runRollbackCommand } = await import('./rollback.ts'); return runRollbackCommand(root, args.deployId || undefined, args.platform); } + if (args.subcommand === 'preview') { + // A one-off `deploy --platform cloudflare` keeps the saved platform, as for rollback. + if (args.platform !== 'cloudflare' && !cloudflare) { + throw new Error( + 'project: Previews from `void deploy --preview` exist only for direct Cloudflare deploys. Add --platform cloudflare.', + ); + } + const { runCloudflarePreviewDelete } = await import('./cloudflare-preview.ts'); + return runCloudflarePreviewDelete(root, { name: args.name }); + } if (args.subcommand === 'cancel') { if (cloudflare) { throw new Error( diff --git a/packages/void/test/unit/cf-build-output.test.ts b/packages/void/test/unit/cf-build-output.test.ts index eb2dced5b..f683356cd 100644 --- a/packages/void/test/unit/cf-build-output.test.ts +++ b/packages/void/test/unit/cf-build-output.test.ts @@ -27,8 +27,10 @@ import { } from '@cloudflare/build-output-utils'; import { cloudflare } from '@cloudflare/vite-plugin'; import { + previewStaticWorkerConfig, renderCloudflareStaticEntry, writeCloudflareFrameworkDeployConfig, + writeCloudflareStaticDeployConfig, } from '@void/deploy-cloudflare'; import { toSlash } from 'pathslash'; import { createBuilder } from 'vite'; @@ -1234,9 +1236,49 @@ it.each([ expect(built.workers.default.config.manifest?.mainModule).toBe(main); 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. Stage the config the way a + // preview deploy does, from a production config with bindings and migrations. + const previewConfigPath = join(generated, 'wrangler-preview.json'); + writeFileSync( + previewConfigPath, + JSON.stringify( + previewStaticWorkerConfig({ + name: 'void-static-test', + account_id: 'account-id', + vars: { SECRET_HINT: 'production' }, + kv_namespaces: [{ binding: 'CACHE', id: 'kv-id' }], + migrations: [{ tag: 'v1', new_sqlite_classes: ['Room'] }], + version_metadata: { binding: 'CF_VERSION_METADATA' }, + }), + ), + ); + writeCloudflareStaticDeployConfig({ + configPath: previewConfigPath, + name: 'void-static-test', + accountId: 'account-id', + main: 'static-edge.mjs', + assetsDirectory: './assets', + compatibilityDate: '2026-09-29', + assetConfig: { run_worker_first: true, not_found_handling: 'single-page-application' }, + }); + await withPrepared( + prepareCfStaticBuildOutput({ + projectRoot: root, + configPath: previewConfigPath, + 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 87954bbbd..3312ef5a5 100644 --- a/packages/void/test/unit/cf-version-runner.test.ts +++ b/packages/void/test/unit/cf-version-runner.test.ts @@ -3380,3 +3380,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, + // cf prints the record as JSON on stdout and its progress on stderr. + stdout: `${JSON.stringify(preview, null, 2)}\n`, + stderr: 'Uploading assets\n', + }; + }, + }); + 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 { + await prepared.dispose(); + } +}); diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index f43acc50f..d743dbc05 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -12768,3 +12768,230 @@ describe('runCloudflareDeploy — `addresses` is whole-object pinned across the expect(dropped.reason).toMatch(/addresses/); }); }); + +describe('runCloudflareDeploy — previews', () => { + /** Join the lines the terminal renderer wrapped, so long messages can be matched whole. */ + const unwrap = (text: string) => + text + .split('\n') + .map((line) => line.trim()) + .join(' '); + + // 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] === 'previews') { + return { ...cleanExit, stdout: JSON.stringify(record) }; + } + return cleanExit; + }); + return { + deps: { ...base.deps, runWrangler, activateVersion } satisfies CloudflareDeployDeps, + exitCalls: base.exitCalls, + wranglerArgs, + activateVersion, + }; + } + + const spa = (config: Record = { name: 'spaapp', account_id: 'acc123' }) => + makeProject({ + 'package.json': JSON.stringify({ name: 'spaapp' }), + 'void.json': JSON.stringify({ inference: { appType: 'spa' } }), + 'wrangler.jsonc': JSON.stringify(config), + '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, the Worker check and the Preview deploy reach Cloudflare: no + // version upload, traffic split, trigger or secret operation. + expect(wranglerArgs.map((args) => args.slice(0, 2))).toEqual([ + ['whoami', '--json'], + ['deployments', 'status'], + ['previews', 'deploy'], + ]); + expect(wranglerArgs[2]).toEqual(['previews', 'deploy', '--prebuilt', '--preview-name=pr-64']); + expect(existsSync(join(root, '.void/cloudflare-candidate.json'))).toBe(false); + expect(parseRootWranglerConfig(join(root, 'wrangler.jsonc'))).toEqual({ + name: 'spaapp', + 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('gives writeResult exactly one preview record', async () => { + const root = spa(); + const { deps, exitCalls } = previewHarness(); + const results: Array = []; + await captureDeployOutput(() => + runCloudflareDeploy( + root, + { + platform: 'cloudflare', + preview: 'pr-64', + json: true, + writeResult: (text) => results.push(text), + }, + silentCliLog, + deps, + ), + ); + + expect(exitCalls).toEqual([]); + expect(results).toHaveLength(1); + expect(results[0]?.endsWith('}\n')).toBe(true); + expect(JSON.parse(results[0] ?? '')).toEqual({ + type: 'preview', + workerName: 'spaapp', + previewName: 'pr-64', + previewUrl: 'https://pr-64-spaapp.team.workers.dev', + deploymentId: 'dep_1', + deploymentUrl: 'https://dep1-spaapp.team.workers.dev', + }); + }); + + it('stages a config without the Worker bindings, vars or migrations', async () => { + const root = spa({ + name: 'spaapp', + account_id: 'acc123', + kv_namespaces: [{ binding: 'KV', id: 'kv' }], + d1_databases: [{ binding: 'DB', database_name: 'db', database_id: 'db' }], + vars: { MODE: 'production' }, + migrations: [{ tag: 'v1', new_sqlite_classes: ['Room'] }], + }); + const { deps, exitCalls } = previewHarness(); + await captureDeployOutput(() => + runCloudflareDeploy(root, { platform: 'cloudflare', preview: 'pr-64' }, silentCliLog, deps), + ); + expect(exitCalls).toEqual([]); + const staged = parseRootWranglerConfig( + join(root, '.void/deploy/cloudflare/wrangler-static.json'), + ); + expect(staged).toMatchObject({ name: 'spaapp', account_id: 'acc123' }); + for (const key of ['kv_namespaces', 'd1_databases', 'vars', 'migrations']) { + expect(staged).not.toHaveProperty(key); + } + }); + + it('stops before uploading when the Worker has no production deployment', async () => { + const root = spa(); + const base = previewHarness(); + const runWrangler = operationFixture((args) => { + base.wranglerArgs.push(args); + if (args[0] === 'whoami') { + return { ...cleanExit, stdout: '{"loggedIn":true,"accounts":[]}' }; + } + return args[0] === 'deployments' ? { ...cleanExit, status: 1, errorCode: 10_007 } : cleanExit; + }); + const output = await captureDeployOutput(() => + expect( + runCloudflareDeploy(root, { platform: 'cloudflare', preview: 'pr-64' }, silentCliLog, { + ...base.deps, + runWrangler, + }), + ).rejects.toThrow(ExitError), + ); + expect(base.exitCalls).toEqual([1]); + expect(unwrap(output)).toContain( + 'deploy: Worker "spaapp" has no production deployment in Cloudflare account acc123. Nothing was uploaded.', + ); + expect(base.wranglerArgs.some((args) => args[0] === 'previews')).toBe(false); + }); + + 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(unwrap(output)).toContain( + 'Cloudflare created deployment dep_1 for preview "pr-64", but Preview URLs are off for Worker "spaapp", so it has no URL.', + ); + expect(unwrap(output)).toContain('Set preview_urls: true (preview_urls in wrangler.jsonc)'); + }); + + it.each([ + ['a bad name', 'PR_64', undefined, '"PR_64" is not a valid preview name'], + [ + 'no Worker name', + 'pr-64', + { account_id: 'acc123' }, + '--preview needs the Worker name (name in wrangler.jsonc)', + ], + [ + 'no pinned account', + 'pr-64', + { name: 'spaapp' }, + '--preview needs a pinned Cloudflare account. Set account_id in wrangler.jsonc', + ], + [ + 'a name too long for the Worker', + `pr-${'1'.repeat(60)}`, + undefined, + 'must be at most 63 characters, so use at most 56', + ], + [ + 'any name, when the Worker name leaves no room', + 'pr-1', + { name: 'w'.repeat(62), account_id: 'acc123' }, + 'so the Worker name can have at most 61', + ], + ])('refuses %s before any Cloudflare call', async (_case, preview, config, message) => { + vi.stubEnv('CLOUDFLARE_ACCOUNT_ID', undefined); + const root = spa(config); + const { deps, exitCalls, wranglerArgs } = previewHarness(); + const output = await captureDeployOutput(() => + expect( + runCloudflareDeploy(root, { platform: 'cloudflare', preview }, silentCliLog, deps), + ).rejects.toThrow(ExitError), + ); + expect(exitCalls).toEqual([1]); + expect(unwrap(output)).toContain(message); + expect(wranglerArgs).toEqual([]); + }); + + 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/cloudflare-operation-process.test.ts b/packages/void/test/unit/cloudflare-operation-process.test.ts index b2becab26..6f65f6308 100644 --- a/packages/void/test/unit/cloudflare-operation-process.test.ts +++ b/packages/void/test/unit/cloudflare-operation-process.test.ts @@ -1861,3 +1861,38 @@ it.each([ expect(redirected).toBe(false); expect(output.stdout + output.stderr).not.toContain('synthetic-token'); }); + +it('deletes a Preview through the pinned cf and reads its error code', async () => { + const directory = temporaryDirectory('void-cf-preview-delete-'); + const preload = join(directory, 'mock-cf.mjs'); + const callsPath = join(directory, 'calls.json'); + const configPath = join(directory, 'wrangler.json'); + writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' })); + writeFileSync( + preload, + `import child from 'node:child_process'; +import { syncBuiltinESMExports } from 'node:module'; +import { writeFileSync } from 'node:fs'; +child.spawnSync = (_executable, args) => { + writeFileSync(${JSON.stringify(callsPath)}, JSON.stringify(args.slice(1))); + return { status: 1, stdout: '', stderr: 'Preview not found [code: 10025]' }; +}; +syncBuiltinESMExports(); +`, + ); + const output = await runOperation( + directory, + { type: 'previews.delete', configPath, workerName: 'test-worker', previewName: 'pr-64' }, + { ...systemEnv, CI: 'true', CLOUDFLARE_AUTH_USE_KEYRING: 'false' }, + preload, + ); + expect(output.status).toBe(1); + expect(JSON.parse(output.stdout)).toMatchObject({ errorCode: 10_025 }); + expect(JSON.parse(readFileSync(callsPath, 'utf8'))).toEqual([ + 'previews', + 'delete', + 'pr-64', + '--worker=test-worker', + '--force', + ]); +}); diff --git a/packages/void/test/unit/deploy-args.test.ts b/packages/void/test/unit/deploy-args.test.ts index 4d8a5dc63..6973985ed 100644 --- a/packages/void/test/unit/deploy-args.test.ts +++ b/packages/void/test/unit/deploy-args.test.ts @@ -157,3 +157,41 @@ 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='])).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/deploy-json-stdout.test.ts b/packages/void/test/unit/deploy-json-stdout.test.ts new file mode 100644 index 000000000..1b4ff3d21 --- /dev/null +++ b/packages/void/test/unit/deploy-json-stdout.test.ts @@ -0,0 +1,60 @@ +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterEach, expect, it } from 'vite-plus/test'; + +const roots: Array = []; +afterEach(() => { + for (const root of roots.splice(0)) { + rmSync(root, { recursive: true, force: true }); + } +}); + +const cli = fileURLToPath(new URL('../../dist/cli/cli.mjs', import.meta.url)); + +function runVoid(root: string, args: Array) { + return spawnSync(process.execPath, [cli, ...args], { + cwd: root, + encoding: 'utf8', + timeout: 30_000, + env: { ...process.env, CI: '1', NO_COLOR: '1' }, + }); +} + +it('keeps config output and failures off `void deploy --json` stdout', () => { + const root = mkdtempSync(join(tmpdir(), 'void-deploy-json-stdout-')); + roots.push(root); + writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'workerapp' })); + writeFileSync( + join(root, 'void.config.ts'), + `import { writeSync } from 'node:fs'; +console.log('config log'); +writeSync(1, 'config fd\\n'); +export default {}; +`, + ); + mkdirSync(join(root, 'routes')); + writeFileSync(join(root, 'routes/index.ts'), 'export const GET = () => "hi";\n'); + + // A Worker app is refused before any Cloudflare call, after void.config.ts ran. + const refused = runVoid(root, [ + 'deploy', + '--platform', + 'cloudflare', + '--preview', + 'pr-1', + '--json', + ]); + expect(refused.status).toBe(1); + expect(refused.stdout).toBe(''); + expect(refused.stderr).toContain('config log'); + expect(refused.stderr).toContain('config fd'); + expect(refused.stderr).toContain('--preview currently supports static sites'); + + const parseError = runVoid(root, ['deploy', '--json']); + expect(parseError.status).toBe(1); + expect(parseError.stdout).toBe(''); + expect(parseError.stderr).toContain('--json is available only with --preview'); +}); diff --git a/packages/void/test/unit/project-args.test.ts b/packages/void/test/unit/project-args.test.ts index b1fa04144..965fa915f 100644 --- a/packages/void/test/unit/project-args.test.ts +++ b/packages/void/test/unit/project-args.test.ts @@ -405,3 +405,32 @@ describe('security', () => { ); }); }); + +describe('parseProjectArgs preview', () => { + it('parses preview delete with an optional platform', () => { + expect(parseProjectArgs(['preview', 'delete', 'pr-64'])).toEqual({ + subcommand: 'preview', + action: 'delete', + name: 'pr-64', + }); + expect(parseProjectArgs(['preview', '--platform=cloudflare', 'delete', 'pr-64'])).toEqual({ + subcommand: 'preview', + action: 'delete', + name: 'pr-64', + platform: 'cloudflare', + }); + }); + + it.each([ + [['preview', 'delete']], + [['preview', 'delete', '-x']], + [['preview', 'delete', 'pr-64', 'pr-65']], + [['preview', 'list']], + [['preview', 'delete pr-64']], + [['preview', 'delete', 'pr-64', '--platform', 'aws']], + ])('refuses %j', (args) => { + expect(() => parseProjectArgs(args)).toThrow( + 'project: Usage: void project preview delete [--platform cloudflare].', + ); + }); +}); diff --git a/packages/void/test/unit/project-preview.test.ts b/packages/void/test/unit/project-preview.test.ts new file mode 100644 index 000000000..7ff941ed1 --- /dev/null +++ b/packages/void/test/unit/project-preview.test.ts @@ -0,0 +1,83 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { CloudflareCommandResult, CloudflareOperation } from '@void/deploy-cloudflare'; +import { log } from '@voidzero-dev/vite-plus-prompts'; +import { afterEach, beforeEach, expect, it, vi } from 'vite-plus/test'; +import { runCloudflarePreviewDelete } from '../../src/cli/cloudflare-preview.ts'; +import { runProjectCommand } from '../../src/cli/project-cmd.ts'; + +const output = await import('../../src/cli/output.ts'); + +let root: string; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'void-project-preview-')); + writeFileSync( + join(root, 'wrangler.json'), + JSON.stringify({ name: 'my-app', account_id: 'acc123' }), + ); +}); +afterEach(() => { + rmSync(root, { recursive: true, force: true }); + vi.restoreAllMocks(); +}); + +function runner(answer: Partial) { + const calls: Array = []; + const run = (operation: CloudflareOperation) => { + calls.push(operation); + return { status: 0, stdout: '', stderr: '', ...answer }; + }; + return { calls, run }; +} + +it('deletes the preview of the configured Worker', async () => { + const success = vi.spyOn(output, 'printSuccess').mockImplementation(() => {}); + const { calls, run } = runner({}); + await runCloudflarePreviewDelete(root, { name: 'pr-64' }, run); + expect(calls).toMatchObject([ + { type: 'previews.delete', workerName: 'my-app', previewName: 'pr-64' }, + ]); + expect(success).toHaveBeenCalledWith( + 'Deleted preview pr-64 of Worker my-app. Production is unchanged.', + ); +}); + +it('succeeds when the preview does not exist', async () => { + const info = vi.spyOn(log, 'info').mockImplementation(() => {}); + const { run } = runner({ status: 1, errorCode: 10_025, stderr: 'Not found [code: 10025]' }); + await runCloudflarePreviewDelete(root, { name: 'pr-64' }, run); + expect(info).toHaveBeenCalledWith( + 'Preview pr-64 does not exist on Worker my-app. Nothing to delete.', + ); +}); + +it.each([ + [ + { status: 1, errorCode: 10_007 }, + 'project: Worker "my-app" was not found in Cloudflare account acc123. Nothing was deleted.', + ], + [ + { status: 1, errorCode: 10_000, stderr: 'Authentication error' }, + 'project: Cloudflare could not delete preview "pr-64" of Worker "my-app".\nAuthentication error', + ], +])('fails on %j', async (answer, message) => { + const { run } = runner(answer); + await expect(runCloudflarePreviewDelete(root, { name: 'pr-64' }, run)).rejects.toThrow(message); +}); + +it('refuses an invalid name before reading the config', async () => { + const { calls, run } = runner({}); + await expect(runCloudflarePreviewDelete(root, { name: 'PR_64' }, run)).rejects.toThrow( + 'project: "PR_64" is not a valid preview name: must start with a lowercase letter.', + ); + expect(calls).toEqual([]); +}); + +it('refuses a project that is not deployed to Cloudflare without --platform cloudflare', async () => { + await expect( + runProjectCommand(root, { subcommand: 'preview', action: 'delete', name: 'pr-64' }), + ).rejects.toThrow( + 'project: Previews from `void deploy --preview` exist only for direct Cloudflare deploys. Add --platform cloudflare.', + ); +}); diff --git a/packages/void/vite.config.ts b/packages/void/vite.config.ts index cf90d1b51..364144c08 100644 --- a/packages/void/vite.config.ts +++ b/packages/void/vite.config.ts @@ -140,7 +140,8 @@ export default defineConfig({ 'src/pages/serialize.ts', 'src/pages/islands-plugin.ts', 'src/cli/cli.ts', - 'src/cli/db-execute-process.ts', + // Runs `db execute --json` and `deploy --json` with stdout kept for the result. + 'src/cli/json-command-process.ts', // Stable entry that deploy spawns as an isolated child. 'src/cli/env-schema-probe.ts', // Private typed Cloudflare transport, spawned by deployment orchestrators.