From 637bbaa544909862e5db3851a5fc30a4626d9cbc Mon Sep 17 00:00:00 2001 From: Edmund Hung Date: Fri, 6 Nov 2026 12:28:54 +0000 Subject: [PATCH] [deploy-helpers] Warn when a Build Output Preview is missing bindings without IDs --- .../preview-build-output-missing-bindings.md | 7 ++ .../deploy-helpers/src/preview/preview.ts | 85 +++++++++++++++++-- packages/deploy-helpers/src/preview/shared.ts | 18 ++++ .../tests/preview-build-output.test.ts | 85 +++++++++++++++++++ 4 files changed, 188 insertions(+), 7 deletions(-) create mode 100644 .changeset/preview-build-output-missing-bindings.md diff --git a/.changeset/preview-build-output-missing-bindings.md b/.changeset/preview-build-output-missing-bindings.md new file mode 100644 index 00000000000..94603a733c2 --- /dev/null +++ b/.changeset/preview-build-output-missing-bindings.md @@ -0,0 +1,7 @@ +--- +"@cloudflare/deploy-helpers": patch +--- + +Warn when a Preview from Build Output is missing bindings that have no resource ID + +`previewBuildOutput()` leaves out KV, D1, and R2 bindings without a resource ID so that the Preview can take them from the Preview base config. When the Preview base config doesn't define them either, the bindings were missing from the Preview without any warning, and code that used them failed at runtime. A warning now lists these bindings. It is written to stderr, so it also appears in JSON mode without changing the JSON output. diff --git a/packages/deploy-helpers/src/preview/preview.ts b/packages/deploy-helpers/src/preview/preview.ts index 29f9ce8c88f..febb8433eec 100644 --- a/packages/deploy-helpers/src/preview/preview.ts +++ b/packages/deploy-helpers/src/preview/preview.ts @@ -34,6 +34,7 @@ import { import { assemblePreviewScriptSettings, extractBuildOutputBindings, + extractIdentifierlessBuildOutputBindings, extractConfigBindings, getBranchName, getCommitSha, @@ -51,6 +52,8 @@ import type { Binding, CreatePreviewDeploymentRequestParams, DeploymentResource, + EnvBindings, + PreviewBaseConfig, PreviewDeploymentModule, PreviewResource, } from "./api"; @@ -1000,6 +1003,15 @@ function logMissingCustomDomainPreviewUrlsWarning( ); } +function formatBindingList(bindings: Record) { + return Object.entries(bindings) + .map( + ([name, binding]) => + ` ${chalk.cyan(name)} ${chalk.dim(getBindingTypeFriendlyName(binding.type as Parameters[0]))}` + ) + .join("\n"); +} + function logMissingPreviewsBindingsWarning( productionBindingsExpectedInPreview: Record, remotePreviewDefaultBindings: Record | undefined, @@ -1021,12 +1033,7 @@ function logMissingPreviewsBindingsWarning( logger.warn(`These bindings are configured for your production Worker but not for Previews: -${Object.entries(missingPreviewBindings) - .map( - ([name, binding]) => - ` ${chalk.cyan(name)} ${chalk.dim(getBindingTypeFriendlyName(binding.type as Parameters[0]))}` - ) - .join("\n")} +${formatBindingList(missingPreviewBindings)} Parts of your Worker that depend on these bindings may not work correctly in the Preview. If this is not intentional, add Preview-safe values to the ${chalk.cyan("previews")} field. @@ -1034,6 +1041,63 @@ Configuration: https://developers.cloudflare.com/workers/previews/configuration/ Resources: https://developers.cloudflare.com/workers/previews/resources/`); } +/** + * Warns about Build Output bindings that were left out of a Preview for having + * no resource identifier and that the Preview base config doesn't define + * either, so they are missing from the Preview. + * + * @param config The Preview config used for API requests. + * @param accountId Account that owns the parent Worker. + * @param workerName The parent Worker name. + * @param identifierlessBindings Bindings left out of the Preview deployment. + */ +async function logMissingIdentifierlessBindingsWarning( + config: Config, + accountId: string, + workerName: string, + identifierlessBindings: EnvBindings +): Promise { + if (Object.keys(identifierlessBindings).length === 0) { + return; + } + + let previewBaseConfig: PreviewBaseConfig; + try { + previewBaseConfig = await getPreviewBaseConfig( + config, + accountId, + workerName + ); + } catch { + // The deployment is already live, so a failed lookup for a warning + // shouldn't fail the command. + logger.warn(`These bindings have no resource ID, so they were left out of this Preview. The Preview base config could not be retrieved to check whether it defines them: + +${formatBindingList(identifierlessBindings)}`); + return; + } + const missingBindings = Object.fromEntries( + Object.entries(identifierlessBindings).filter( + ([name]) => !Object.hasOwn(previewBaseConfig.env ?? {}, name) + ) + ); + + if (Object.keys(missingBindings).length === 0) { + return; + } + + // Logged even with `--json`: the warning goes to stderr, so it can't corrupt + // the payload, and CI runs that parse the payload would otherwise never see it. + logger.warn(`These bindings have no resource ID, so they were left out of this Preview, and the Preview base config doesn't define them either: + +${formatBindingList(missingBindings)} + +Code that uses these bindings will fail in the Preview. Set a resource ID on these bindings for Previews, or add them to the Preview base config. + +Configuration: https://developers.cloudflare.com/workers/previews/configuration/ +Resources: https://developers.cloudflare.com/workers/previews/resources/`); +} + /** * Creates the parent Worker required for a Preview, prompting when interactive. * @@ -1453,7 +1517,7 @@ export async function previewBuildOutput( }, run_worker_first: convertedConfig.assets?.run_worker_first, }; - return runPreview( + const result = await runPreview( accountId, { ...args, ignoreBaseConfig: false }, previewConfig, @@ -1467,6 +1531,13 @@ export async function previewBuildOutput( true, localImageReferences ); + await logMissingIdentifierlessBindingsWarning( + previewConfig, + accountId, + workerConfig.name, + extractIdentifierlessBuildOutputBindings(convertedConfig) + ); + return result; } /** diff --git a/packages/deploy-helpers/src/preview/shared.ts b/packages/deploy-helpers/src/preview/shared.ts index 584a312d8c6..5256c9bb9f2 100644 --- a/packages/deploy-helpers/src/preview/shared.ts +++ b/packages/deploy-helpers/src/preview/shared.ts @@ -725,6 +725,24 @@ export function extractBuildOutputBindings(config: RawConfig): EnvBindings { return extractBindings(config, config.assets, true); } +/** + * Lists the resource bindings that `extractBuildOutputBindings` leaves out + * because they have no identifier to upload. + * + * @param config Wrangler config converted from Build Output. + * @returns The bindings left out, keyed by binding name. + */ +export function extractIdentifierlessBuildOutputBindings( + config: RawConfig +): EnvBindings { + const uploadedBindings = extractBuildOutputBindings(config); + return Object.fromEntries( + Object.entries(extractBindings(config, config.assets)).filter( + ([name]) => !Object.hasOwn(uploadedBindings, name) + ) + ); +} + /** * Returns the DO `class_name`s this script declares, through `migrations` or * through `exports`, resolving them in the same order as wrangler's own diff --git a/packages/deploy-helpers/tests/preview-build-output.test.ts b/packages/deploy-helpers/tests/preview-build-output.test.ts index a2b4f1702e2..88dd34d5bf0 100644 --- a/packages/deploy-helpers/tests/preview-build-output.test.ts +++ b/packages/deploy-helpers/tests/preview-build-output.test.ts @@ -3,7 +3,9 @@ import path from "node:path"; import { verifyDockerInstalled } from "@cloudflare/containers-shared"; import { runInTempDir } from "@cloudflare/workers-utils/test-helpers"; import { beforeEach, describe, it, vi } from "vitest"; +import { stripAnsi } from "../src/preview/box"; import { previewBuildOutput } from "../src/preview/preview"; +import { logger } from "../src/shared/context"; import type { PreviewBuildOutput, PreviewOptions, @@ -19,6 +21,7 @@ const mocks = vi.hoisted(() => ({ createPreviewParentWorker: vi.fn(), editPreview: vi.fn(), getPreview: vi.fn(), + getPreviewBaseConfig: vi.fn(), getPreviewDeployment: vi.fn(), syncAssets: vi.fn(), })); @@ -30,6 +33,7 @@ vi.mock("../src/preview/api", async (importOriginal) => ({ createPreviewParentWorker: mocks.createPreviewParentWorker, editPreview: mocks.editPreview, getPreview: mocks.getPreview, + getPreviewBaseConfig: mocks.getPreviewBaseConfig, getPreviewDeployment: mocks.getPreviewDeployment, })); @@ -104,6 +108,7 @@ describe("previewBuildOutput", () => { beforeEach(() => { vi.clearAllMocks(); mocks.getPreview.mockResolvedValue(previewResource); + mocks.getPreviewBaseConfig.mockResolvedValue({}); mocks.getPreviewDeployment.mockResolvedValue(deploymentResource); mocks.editPreview.mockResolvedValue(previewResource); mocks.createPreview.mockResolvedValue(previewResource); @@ -637,6 +642,86 @@ describe("previewBuildOutput", () => { expect(request).not.toHaveProperty("env"); }); + it("warns in JSON mode about bindings without identifiers that the Preview base config doesn't define", async ({ + expect, + }) => { + mocks.getPreviewBaseConfig.mockResolvedValue({ + env: { D1: { type: "d1", database_id: "base-d1-id" } }, + }); + + await uploadPreview( + buildOutputConfig({ + env: { + KV: { type: "kv" }, + D1: { type: "d1" }, + R2: { type: "r2" }, + PREVIEW_KV: { type: "kv", id: "preview-kv-id" }, + }, + }) + ); + + expect(mocks.getPreviewBaseConfig).toHaveBeenCalledWith( + expect.objectContaining({ name: "preview-worker" }), + "account-id", + "preview-worker" + ); + expect(logger.warn).toHaveBeenCalledOnce(); + expect(stripAnsi(String(vi.mocked(logger.warn).mock.calls[0]?.[0]))) + .toMatchInlineSnapshot(` + "These bindings have no resource ID, so they were left out of this Preview, and the Preview base config doesn't define them either: + + KV KV Namespace + R2 R2 Bucket + + Code that uses these bindings will fail in the Preview. Set a resource ID on these bindings for Previews, or add them to the Preview base config. + + Configuration: https://developers.cloudflare.com/workers/previews/configuration/ + Resources: https://developers.cloudflare.com/workers/previews/resources/" + `); + }); + + it("does not warn when the Preview base config defines bindings without identifiers", async ({ + expect, + }) => { + mocks.getPreviewBaseConfig.mockResolvedValue({ + env: { KV: { type: "kv_namespace", namespace_id: "base-kv-id" } }, + }); + + await uploadPreview(buildOutputConfig({ env: { KV: { type: "kv" } } })); + + expect(logger.warn).not.toHaveBeenCalled(); + }); + + it("still resolves when the Preview base config can't be read", async ({ + expect, + }) => { + mocks.getPreviewBaseConfig.mockRejectedValue(new Error("Internal error")); + + await expect( + uploadPreview(buildOutputConfig({ env: { KV: { type: "kv" } } })) + ).resolves.toMatchObject({ deployment: deploymentResource }); + expect(logger.warn).toHaveBeenCalledOnce(); + expect(stripAnsi(String(vi.mocked(logger.warn).mock.calls[0]?.[0]))) + .toMatchInlineSnapshot(` + "These bindings have no resource ID, so they were left out of this Preview. The Preview base config could not be retrieved to check whether it defines them: + + KV KV Namespace" + `); + }); + + it("does not read the Preview base config when every binding has an identifier", async ({ + expect, + }) => { + await uploadPreview( + buildOutputConfig({ + env: { PREVIEW_KV: { type: "kv", id: "preview-kv-id" } }, + }) + ); + + expect(mocks.getPreviewBaseConfig).not.toHaveBeenCalled(); + expect(logger.warn).not.toHaveBeenCalled(); + }); + it("keeps secrets from the latest deployment of an existing Preview", async ({ expect, }) => {