@vinext/cloudflare 1.0.0-beta.5 → 1.0.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/deploy.js CHANGED
@@ -1,13 +1,19 @@
1
- import { readPrerenderWarmPaths, warmCdnCache } from "./cdn-warm.js";
1
+ import { writeCacheabilityManifestArtifact } from "./cacheability-artifact.js";
2
+ import { DEFAULT_CACHEABILITY_PROBE_RETRY_DELAY_MS, probeStagedWorkerCacheability, readPrerenderSecret } from "./cacheability-probe.js";
3
+ import { CdnOperationProgress, createCdnWarmTargets, readPrerenderWarmPlan, waitForCdnWarmTargetReadiness, warmCdnCache } from "./cdn-warm.js";
2
4
  import { parseWranglerConfig, runTPR } from "./tpr.js";
3
- import { formatImageOptimizationHint, formatMissingCacheAdapterError, resolveKvDataAdapterConfig, viteConfigHasCacheAdapter, viteConfigHasCloudflarePlugin, viteConfigHasImageAdapter, workerEntryHasCacheHandler } from "./deploy-config.js";
4
- import { runWranglerDeploymentStatus, runWranglerTriggersDeploy, runWranglerVersionDeploy, runWranglerVersionUpload } from "./version-deploy.js";
5
+ import { VINEXT_EXPECTED_WORKER_VERSION_HEADER } from "./version-headers.js";
6
+ import { formatImageOptimizationHint, formatMissingCacheAdapterError, resolveCdnAdapterConfig, resolveKvDataAdapterConfig, viteConfigHasCacheAdapter, viteConfigHasCloudflarePlugin, viteConfigHasImageAdapter, workerEntryHasCacheHandler } from "./deploy-config.js";
7
+ import { assertCdnVersionMetadataConfig } from "./wrangler-version-metadata.js";
5
8
  import { parseWorkerDeploymentUrl } from "./worker-deployment-url.js";
9
+ import { runWranglerDeploymentStatus, runWranglerTriggersDeploy, runWranglerVersionDeploy, runWranglerVersionUpload } from "./version-deploy.js";
6
10
  import { buildPrerenderKVPairs } from "./prerender-kv-populate.js";
7
11
  import { createRequire } from "node:module";
8
- import path from "node:path";
9
12
  import fs from "node:fs";
10
- import { emitPrerenderPathManifest } from "vinext/internal/build/prerender-paths";
13
+ import path from "node:path";
14
+ import { cacheabilityRoutePathname } from "vinext/internal/server/cacheability-manifest";
15
+ import { setTimeout } from "node:timers/promises";
16
+ import { DEFAULT_REMOTE_PATH_DISCOVERY_PHASE_TIMEOUT_MS, DEFAULT_REMOTE_PATH_DISCOVERY_RETRY_DELAY_MS, emitPrerenderPathManifest } from "vinext/internal/build/prerender-paths";
11
17
  import os from "node:os";
12
18
  import { spawn } from "node:child_process";
13
19
  import { parseArgs } from "node:util";
@@ -15,7 +21,7 @@ import { pathToFileURL } from "node:url";
15
21
  import { runPrerender } from "vinext/internal/build/run-prerender";
16
22
  import { loadDotenv } from "vinext/internal/config/dotenv";
17
23
  import { findVinextNextConfigInPlugins, loadNextConfig, resolveNextConfig, resolveNextConfigInput } from "vinext/internal/config/next-config";
18
- import { findVinextCacheConfigInPlugins, findVinextPrerenderConfigInPlugins, findVinextRouteRootConfigInPlugins, formatVinextPrerenderLabel, resolveVinextPrerenderDecision } from "vinext/internal/config/prerender";
24
+ import { findVinextCacheConfigInPlugins, findVinextPrerenderConfigInPlugins, findVinextRouteRootConfigInPlugins, formatVinextPrerenderLabel, hasBuildIdentityResponseHeader, hasVerbatimResponseVary, requiresRouteCacheabilityProbeManifest, resolveVinextPrerenderDecision } from "vinext/internal/config/prerender";
19
25
  import { detectProject, findInNodeModules, formatMissingCloudflarePluginError, getMissingDeps } from "vinext/internal/utils/project";
20
26
  import { PHASE_PRODUCTION_BUILD } from "vinext/shims/constants";
21
27
  //#region src/deploy.ts
@@ -28,6 +34,7 @@ import { PHASE_PRODUCTION_BUILD } from "vinext/shims/constants";
28
34
  * 2. Runs the Vite build
29
35
  * 3. Deploys to Cloudflare Workers via Wrangler
30
36
  */
37
+ const DEFAULT_CDN_WARM_PROMOTION_DELAY_MS = 15e3;
31
38
  function parsePositiveIntegerArg(raw, flag) {
32
39
  if (raw === "") throw new Error(`${flag} requires a value, but none was provided.`);
33
40
  const parsed = Number(raw);
@@ -40,6 +47,26 @@ function parseNonNegativeIntegerArg(raw, flag) {
40
47
  if (!Number.isInteger(parsed) || parsed < 0) throw new Error(`${flag} expects a non-negative integer, but got "${raw}".`);
41
48
  return parsed;
42
49
  }
50
+ const MAX_NODE_TIMER_DELAY_MS = 2147483647;
51
+ function validateTimerDelay(value, flag, raw = String(value)) {
52
+ if (!Number.isInteger(value) || value < 0) throw new Error(`${flag} expects a non-negative integer, but got "${raw}".`);
53
+ if (value > MAX_NODE_TIMER_DELAY_MS) throw new Error(`${flag} must not exceed ${MAX_NODE_TIMER_DELAY_MS} milliseconds, but got "${raw}".`);
54
+ return value;
55
+ }
56
+ function validatePromotionDelay(value, raw = String(value)) {
57
+ return validateTimerDelay(value, "--warm-cdn-promotion-delay", raw);
58
+ }
59
+ function validateCdnWarmTarget(raw) {
60
+ const value = raw.trim();
61
+ let url;
62
+ try {
63
+ url = new URL(value);
64
+ } catch {
65
+ throw new Error(`--warm-cdn-target expects an HTTPS origin, but got "${raw}".`);
66
+ }
67
+ if (url.protocol !== "https:" || url.username !== "" || url.password !== "" || url.port !== "" || url.pathname !== "/" || url.search !== "" || url.hash !== "") throw new Error(`--warm-cdn-target expects an HTTPS origin without a path, query, credentials, or port, but got "${raw}".`);
68
+ return url.origin;
69
+ }
43
70
  function formatUnknownError(error) {
44
71
  if (error instanceof Error && error.message) return error.message;
45
72
  return String(error);
@@ -66,6 +93,10 @@ const deployArgOptions = {
66
93
  type: "boolean",
67
94
  default: false
68
95
  },
96
+ verbose: {
97
+ type: "boolean",
98
+ default: false
99
+ },
69
100
  "prerender-all": {
70
101
  type: "boolean",
71
102
  default: false
@@ -75,13 +106,31 @@ const deployArgOptions = {
75
106
  type: "boolean",
76
107
  default: false
77
108
  },
109
+ "warm-cdn-target": { type: "string" },
78
110
  "warm-cdn-concurrency": { type: "string" },
79
111
  "warm-cdn-timeout": { type: "string" },
80
112
  "warm-cdn-retries": { type: "string" },
81
- "warm-cdn-strict": {
113
+ "warm-cdn-discovery-timeout": { type: "string" },
114
+ "warm-cdn-discovery-retries": { type: "string" },
115
+ "warm-cdn-probe-timeout": { type: "string" },
116
+ "warm-cdn-probe-retries": { type: "string" },
117
+ "warm-cdn-certify": {
82
118
  type: "boolean",
83
119
  default: false
84
120
  },
121
+ "warm-cdn-readiness-timeout": { type: "string" },
122
+ "warm-cdn-readiness-retries": { type: "string" },
123
+ "warm-cdn-readiness-probes": { type: "string" },
124
+ "warm-cdn-readiness-probe-delay": { type: "string" },
125
+ "dangerously-promote-on-cdn-warm-error": {
126
+ type: "boolean",
127
+ default: false
128
+ },
129
+ "warm-cdn-no-promote": {
130
+ type: "boolean",
131
+ default: false
132
+ },
133
+ "warm-cdn-promotion-delay": { type: "string" },
85
134
  "warm-cdn-include-fallbacks": {
86
135
  type: "boolean",
87
136
  default: false
@@ -100,6 +149,8 @@ function parseDeployArgs(args) {
100
149
  options: deployArgOptions,
101
150
  strict: true
102
151
  });
152
+ if (values["warm-cdn-certify"] && !values["experimental-warm-cdn-cache"]) throw new Error("--warm-cdn-certify requires --experimental-warm-cdn-cache.");
153
+ if (values["warm-cdn-target"] && !values["experimental-warm-cdn-cache"]) throw new Error("--warm-cdn-target requires --experimental-warm-cdn-cache.");
103
154
  function parseIntArg(name, raw) {
104
155
  if (!raw) return void 0;
105
156
  const n = parseInt(raw, 10);
@@ -117,13 +168,26 @@ function parseDeployArgs(args) {
117
168
  config: values.config?.trim() || void 0,
118
169
  skipBuild: values["skip-build"],
119
170
  dryRun: values["dry-run"],
171
+ verbose: values.verbose,
120
172
  prerenderAll: values["prerender-all"],
121
173
  prerenderConcurrency: values["prerender-concurrency"] === void 0 ? void 0 : parsePositiveIntegerArg(values["prerender-concurrency"], "--prerender-concurrency"),
122
174
  warmCdnCache: values["experimental-warm-cdn-cache"],
175
+ warmCdnTarget: values["warm-cdn-target"] === void 0 ? void 0 : validateCdnWarmTarget(values["warm-cdn-target"]),
123
176
  warmCdnConcurrency: values["warm-cdn-concurrency"] === void 0 ? void 0 : parsePositiveIntegerArg(values["warm-cdn-concurrency"], "--warm-cdn-concurrency"),
124
177
  warmCdnTimeout: values["warm-cdn-timeout"] === void 0 ? void 0 : parsePositiveIntegerArg(values["warm-cdn-timeout"], "--warm-cdn-timeout"),
125
178
  warmCdnRetries: values["warm-cdn-retries"] === void 0 ? void 0 : parseNonNegativeIntegerArg(values["warm-cdn-retries"], "--warm-cdn-retries"),
126
- warmCdnStrict: values["warm-cdn-strict"],
179
+ warmCdnDiscoveryTimeout: values["warm-cdn-discovery-timeout"] === void 0 ? void 0 : parsePositiveIntegerArg(values["warm-cdn-discovery-timeout"], "--warm-cdn-discovery-timeout"),
180
+ warmCdnDiscoveryRetries: values["warm-cdn-discovery-retries"] === void 0 ? void 0 : parseNonNegativeIntegerArg(values["warm-cdn-discovery-retries"], "--warm-cdn-discovery-retries"),
181
+ warmCdnProbeTimeout: values["warm-cdn-probe-timeout"] === void 0 ? void 0 : parsePositiveIntegerArg(values["warm-cdn-probe-timeout"], "--warm-cdn-probe-timeout"),
182
+ warmCdnProbeRetries: values["warm-cdn-probe-retries"] === void 0 ? void 0 : parseNonNegativeIntegerArg(values["warm-cdn-probe-retries"], "--warm-cdn-probe-retries"),
183
+ warmCdnCertify: values["warm-cdn-certify"],
184
+ warmCdnReadinessTimeout: values["warm-cdn-readiness-timeout"] === void 0 ? void 0 : parsePositiveIntegerArg(values["warm-cdn-readiness-timeout"], "--warm-cdn-readiness-timeout"),
185
+ warmCdnReadinessRetries: values["warm-cdn-readiness-retries"] === void 0 ? void 0 : parseNonNegativeIntegerArg(values["warm-cdn-readiness-retries"], "--warm-cdn-readiness-retries"),
186
+ warmCdnReadinessProbes: values["warm-cdn-readiness-probes"] === void 0 ? void 0 : parsePositiveIntegerArg(values["warm-cdn-readiness-probes"], "--warm-cdn-readiness-probes"),
187
+ warmCdnReadinessProbeDelay: values["warm-cdn-readiness-probe-delay"] === void 0 ? void 0 : validateTimerDelay(parseNonNegativeIntegerArg(values["warm-cdn-readiness-probe-delay"], "--warm-cdn-readiness-probe-delay"), "--warm-cdn-readiness-probe-delay", values["warm-cdn-readiness-probe-delay"]),
188
+ dangerouslyPromoteOnCdnWarmError: values["dangerously-promote-on-cdn-warm-error"],
189
+ warmCdnPromote: !values["warm-cdn-no-promote"],
190
+ warmCdnPromotionDelay: values["warm-cdn-promotion-delay"] === void 0 ? void 0 : validatePromotionDelay(parseNonNegativeIntegerArg(values["warm-cdn-promotion-delay"], "--warm-cdn-promotion-delay"), values["warm-cdn-promotion-delay"]),
127
191
  warmCdnIncludeFallbacks: values["warm-cdn-include-fallbacks"],
128
192
  experimentalTPR: values["experimental-tpr"],
129
193
  tprCoverage: parseIntArg("tpr-coverage", values["tpr-coverage"]),
@@ -164,13 +228,26 @@ async function loadProjectViteApi(root) {
164
228
  }
165
229
  return await (vitePath === "vite" ? import(vitePath) : import(pathToFileURL(vitePath).href));
166
230
  }
231
+ async function loadProjectWranglerApi(root) {
232
+ const req = createRequire(path.join(root, "package.json"));
233
+ let wranglerPath;
234
+ try {
235
+ wranglerPath = req.resolve("wrangler");
236
+ } catch {
237
+ wranglerPath = createRequire(req.resolve("@cloudflare/vite-plugin")).resolve("wrangler");
238
+ }
239
+ return await import(
240
+ /* @vite-ignore */
241
+ pathToFileURL(wranglerPath).href
242
+ );
243
+ }
167
244
  async function loadDeployViteConfigMetadata(root) {
168
245
  const plugins = (await (await loadProjectViteApi(root)).loadConfigFromFile({
169
246
  command: "build",
170
247
  mode: "production"
171
248
  }, void 0, root))?.config.plugins;
172
249
  return {
173
- cacheConfig: viteConfigHasCacheAdapter(root) ? await findVinextCacheConfigInPlugins(plugins) : null,
250
+ cacheConfig: await findVinextCacheConfigInPlugins(plugins),
174
251
  nextConfig: await findVinextNextConfigInPlugins(plugins),
175
252
  prerenderConfig: await findVinextPrerenderConfigInPlugins(plugins),
176
253
  routeRootConfig: await findVinextRouteRootConfigInPlugins(plugins)
@@ -346,88 +423,494 @@ async function runWranglerDeploy(root, options, execute = spawn) {
346
423
  });
347
424
  return parseWorkerDeploymentUrl(output) ?? "(URL not detected in wrangler output)";
348
425
  }
426
+ function hasCdnWarmRequests(plan) {
427
+ return plan.paths.length + (plan.pagesDataPaths?.length ?? 0) + (plan.routeHandlerPaths?.length ?? 0) + plan.rscPaths.length + plan.loadingShellPaths.length > 0;
428
+ }
429
+ function projectRequiresRouteCacheabilityProbeManifest(project, cacheConfig) {
430
+ return (project.isAppRouter || project.isPagesRouter) && requiresRouteCacheabilityProbeManifest(cacheConfig);
431
+ }
432
+ function cdnWarmTargetKey(target) {
433
+ return `${target.kind}\0${target.sourcePathname}`;
434
+ }
349
435
  async function deployWithCdnWarmup(root, paths, options) {
350
- const upload = runWranglerVersionUpload(root, options);
436
+ if (options.warmCdnTarget !== void 0) options = {
437
+ ...options,
438
+ warmCdnTarget: validateCdnWarmTarget(options.warmCdnTarget)
439
+ };
440
+ if (options.warmCdnDiscoveryTimeout !== void 0) parsePositiveIntegerArg(String(options.warmCdnDiscoveryTimeout), "--warm-cdn-discovery-timeout");
441
+ if (options.warmCdnDiscoveryRetries !== void 0) parseNonNegativeIntegerArg(String(options.warmCdnDiscoveryRetries), "--warm-cdn-discovery-retries");
442
+ if (options.warmCdnProbeTimeout !== void 0) parsePositiveIntegerArg(String(options.warmCdnProbeTimeout), "--warm-cdn-probe-timeout");
443
+ if (options.warmCdnProbeRetries !== void 0) parseNonNegativeIntegerArg(String(options.warmCdnProbeRetries), "--warm-cdn-probe-retries");
444
+ if (options.warmCdnReadinessTimeout !== void 0) parsePositiveIntegerArg(String(options.warmCdnReadinessTimeout), "--warm-cdn-readiness-timeout");
445
+ if (options.warmCdnReadinessRetries !== void 0) parseNonNegativeIntegerArg(String(options.warmCdnReadinessRetries), "--warm-cdn-readiness-retries");
446
+ if (options.warmCdnReadinessProbes !== void 0) parsePositiveIntegerArg(String(options.warmCdnReadinessProbes), "--warm-cdn-readiness-probes");
447
+ if (options.warmCdnReadinessProbeDelay !== void 0) validateTimerDelay(options.warmCdnReadinessProbeDelay, "--warm-cdn-readiness-probe-delay");
448
+ if (options.warmCdnPromotionDelay !== void 0) validatePromotionDelay(options.warmCdnPromotionDelay);
449
+ if (options.cacheabilityProbe) return deployWithCacheabilityProbe(root, options);
450
+ return deployUploadedVersionWithCdnWarmup(root, paths, options);
451
+ }
452
+ async function deployUploadedVersionWithCdnWarmup(root, paths, options) {
453
+ const allowUnverifiedPromotion = options.dangerouslyPromoteOnCdnWarmError === true && options.warmCdnCertify !== true;
454
+ let deploymentId = options.deploymentId;
455
+ let expectedBuildId = options.expectedBuildId;
456
+ let expectedRscBuildId = options.expectedRscBuildId;
457
+ const hasPreparedWarmPlan = options.uploadedVersion !== void 0;
458
+ let warmPlanDiscovered = hasPreparedWarmPlan || options.discoverWarmPlan === void 0;
459
+ let remainingWarmPlan = {
460
+ loadingShellPaths: [...options.loadingShellPaths ?? []],
461
+ pagesDataPaths: [...options.pagesDataPaths ?? []],
462
+ paths: [...paths],
463
+ routeHandlerPaths: [...options.routeHandlerPaths ?? []],
464
+ routePatterns: options.routePatterns ? { ...options.routePatterns } : void 0,
465
+ rscPaths: [...options.rscPaths ?? []]
466
+ };
467
+ let discoveredWarmRequests = remainingWarmPlan.paths.length + remainingWarmPlan.pagesDataPaths.length + (remainingWarmPlan.routeHandlerPaths?.length ?? 0) + remainingWarmPlan.rscPaths.length + remainingWarmPlan.loadingShellPaths.length;
468
+ const prepareWarmPlan = (plan) => {
469
+ if (plan.paths.length === 0 && plan.pagesDataPaths.length === 0 && (plan.routeHandlerPaths?.length ?? 0) === 0 || expectedBuildId !== void 0) return plan;
470
+ if (!allowUnverifiedPromotion) {
471
+ const warmupKind = plan.paths.length > 0 ? "CDN HTML warmup" : plan.pagesDataPaths.length > 0 ? "CDN Pages data warmup" : "CDN Route Handler warmup";
472
+ throw new Error(`${warmupKind} requires a CDN adapter that declares build-identity response headers. Configure that adapter capability or deploy without --experimental-warm-cdn-cache.`);
473
+ }
474
+ console.warn(` CDN warmup: skipping ${plan.paths.length} HTML, ${plan.pagesDataPaths.length} Pages data, and ${plan.routeHandlerPaths?.length ?? 0} Route Handler request(s) because the CDN adapter does not declare build-identity response headers.`);
475
+ return {
476
+ ...plan,
477
+ pagesDataPaths: [],
478
+ paths: [],
479
+ routeHandlerPaths: []
480
+ };
481
+ };
482
+ const discoverWarmPlan = async (targetUrl, headers) => {
483
+ if (!options.discoverWarmPlan) return;
484
+ const plan = await options.discoverWarmPlan({
485
+ headers,
486
+ targetUrl
487
+ });
488
+ deploymentId = plan.deploymentId;
489
+ expectedBuildId = plan.buildIdentity;
490
+ expectedRscBuildId = plan.rscBuildId;
491
+ remainingWarmPlan = {
492
+ loadingShellPaths: [...plan.loadingShellPaths],
493
+ pagesDataPaths: [...plan.pagesDataPaths ?? []],
494
+ paths: [...plan.paths],
495
+ routeHandlerPaths: [...plan.routeHandlerPaths ?? []],
496
+ routePatterns: plan.routePatterns ? { ...plan.routePatterns } : void 0,
497
+ rscPaths: [...plan.rscPaths]
498
+ };
499
+ discoveredWarmRequests = remainingWarmPlan.paths.length + remainingWarmPlan.pagesDataPaths.length + (remainingWarmPlan.routeHandlerPaths?.length ?? 0) + remainingWarmPlan.rscPaths.length + remainingWarmPlan.loadingShellPaths.length;
500
+ warmPlanDiscovered = true;
501
+ };
502
+ if (!options.discoverWarmPlan || hasPreparedWarmPlan) remainingWarmPlan = prepareWarmPlan(remainingWarmPlan);
503
+ const upload = options.uploadedVersion ?? runWranglerVersionUpload(root, options);
504
+ const warmUploadedVersion = (targetUrl, headers, propagatingTarget = false, plan = {
505
+ loadingShellPaths: remainingWarmPlan.loadingShellPaths,
506
+ pagesDataPaths: remainingWarmPlan.pagesDataPaths,
507
+ paths: remainingWarmPlan.paths,
508
+ routeHandlerPaths: remainingWarmPlan.routeHandlerPaths,
509
+ routePatterns: remainingWarmPlan.routePatterns,
510
+ rscPaths: remainingWarmPlan.rscPaths
511
+ }, requireCacheHit = false) => warmCdnCache({
512
+ targetUrl,
513
+ paths: plan.paths,
514
+ headers,
515
+ propagatingTarget,
516
+ deploymentId,
517
+ expectedBuildId,
518
+ expectedRscBuildId,
519
+ loadingShellPaths: plan.loadingShellPaths,
520
+ pagesDataPaths: plan.pagesDataPaths,
521
+ routeHandlerPaths: plan.routeHandlerPaths,
522
+ routePatterns: plan.routePatterns,
523
+ rscPaths: plan.rscPaths,
524
+ concurrency: options.warmCdnConcurrency,
525
+ timeoutMs: options.warmCdnTimeout,
526
+ retries: options.warmCdnRetries,
527
+ requireCacheHit,
528
+ strict: requireCacheHit || !allowUnverifiedPromotion
529
+ });
351
530
  const wranglerConfig = parseWranglerConfig(root, options.config);
352
- const stagingTraffic = getZeroPercentStagingTraffic(readWranglerDeploymentStatus(root, options), upload.versionId);
531
+ const deploymentStatus = runWranglerDeploymentStatus(root, options);
532
+ if (options.expectedDeploymentState && !deploymentStateEquals(deploymentStatus, options.expectedDeploymentState)) throw new Error("Two-stage CDN warming stopped because Worker deployment traffic or deployment identity changed before the final version could be staged. No final version was promoted.");
533
+ const stagingTraffic = getZeroPercentStagingTraffic(deploymentStatus, upload.versionId);
534
+ if (hasPreparedWarmPlan && !stagingTraffic) throw new Error("Two-stage CDN warming stopped because Worker deployment traffic changed before the final version could be staged. No final version was promoted.");
353
535
  let staged = null;
354
- let triggersDeployedUrl = null;
355
- let warmedBeforePromotion = false;
356
- let triggersApplied = false;
536
+ let triggersDeployedUrl = options.triggersDeployedUrl ?? null;
537
+ let stagedCacheFilled = false;
538
+ let stagedDeploymentState = null;
539
+ const initialWarmRequests = options.discoverWarmPlan === void 0 || hasPreparedWarmPlan ? remainingWarmPlan.paths.length + remainingWarmPlan.pagesDataPaths.length + (remainingWarmPlan.routeHandlerPaths?.length ?? 0) + remainingWarmPlan.rscPaths.length + remainingWarmPlan.loadingShellPaths.length : 1;
540
+ let triggersApplied = options.triggersAlreadyApplied === true;
357
541
  function applyTriggers() {
358
542
  if (triggersApplied) return;
359
543
  triggersDeployedUrl = runWranglerTriggersDeploy(root, options).deployedUrl;
360
544
  triggersApplied = true;
361
545
  }
362
546
  if (stagingTraffic) {
363
- staged = runWranglerVersionDeploy(root, stagingTraffic, options, "stage");
364
547
  try {
548
+ staged = runWranglerVersionDeploy(root, stagingTraffic, options, "stage");
549
+ } catch (error) {
550
+ throw reconcileVersionDeployFailure(root, options, error, {
551
+ desiredTraffic: stagingTraffic,
552
+ desiredDescription: "The uploaded version is staged at 0% with the previous version still serving 100% traffic; Worker triggers/routes were not changed.",
553
+ priorState: deploymentStatus,
554
+ priorDescription: "Worker deployment traffic was not changed and Worker triggers/routes were not changed."
555
+ });
556
+ }
557
+ try {
558
+ if (hasPreparedWarmPlan) {
559
+ stagedDeploymentState = runWranglerDeploymentStatus(root, options);
560
+ if (!deploymentTrafficEquals(stagedDeploymentState.versions, stagingTraffic)) throw new Error("Two-stage CDN warming stopped because Worker deployment traffic changed before production triggers could be applied. No final version was promoted.");
561
+ }
365
562
  applyTriggers();
366
563
  } catch (error) {
367
564
  throw withStagedVersionCleanupNote(error);
368
565
  }
369
- const targetUrl = resolveCdnWarmupTargetUrl(root, staged.deployedUrl ?? triggersDeployedUrl, options);
370
- const headers = buildVersionOverrideHeaders(resolveWorkerNameForVersionOverride(wranglerConfig, options), upload.versionId);
371
- if (targetUrl && headers) {
372
- try {
373
- await warmCdnCache({
566
+ const targetUrl = resolveCdnWarmupTargetUrl(root, triggersDeployedUrl, options) ?? staged.deployedUrl;
567
+ const headers = buildVersionOverrideHeaders(options.name ?? upload.workerName ?? resolveWorkerNameForVersionOverride(wranglerConfig, options), upload.versionId);
568
+ if (targetUrl && headers) try {
569
+ if (!warmPlanDiscovered) {
570
+ console.log(" CDN warmup: discovering paths from the staged Worker version...");
571
+ await discoverWarmPlan(targetUrl, headers);
572
+ remainingWarmPlan = prepareWarmPlan(remainingWarmPlan);
573
+ console.log(` CDN warmup: discovered ${remainingWarmPlan.paths.length} HTML, ${remainingWarmPlan.pagesDataPaths.length} Pages data, ${remainingWarmPlan.routeHandlerPaths?.length ?? 0} Route Handler, ${remainingWarmPlan.rscPaths.length} RSC, and ${remainingWarmPlan.loadingShellPaths.length} loading-shell request(s).`);
574
+ }
575
+ const stagedWarmPlan = {
576
+ loadingShellPaths: remainingWarmPlan.loadingShellPaths,
577
+ pagesDataPaths: remainingWarmPlan.pagesDataPaths,
578
+ paths: remainingWarmPlan.paths,
579
+ routeHandlerPaths: remainingWarmPlan.routeHandlerPaths,
580
+ rscPaths: remainingWarmPlan.rscPaths
581
+ };
582
+ const stagedWarmRequests = stagedWarmPlan.paths.length + stagedWarmPlan.pagesDataPaths.length + (stagedWarmPlan.routeHandlerPaths?.length ?? 0) + stagedWarmPlan.rscPaths.length + stagedWarmPlan.loadingShellPaths.length;
583
+ if (stagedWarmRequests > 0) {
584
+ console.log(" CDN warmup: waiting for the staged Worker version to become stable...");
585
+ const readiness = await waitForCdnWarmTargetReadiness({
374
586
  targetUrl,
375
- paths,
376
587
  headers,
377
- concurrency: options.warmCdnConcurrency,
378
- timeoutMs: options.warmCdnTimeout,
379
- retries: options.warmCdnRetries,
380
- strict: options.warmCdnStrict
588
+ plan: stagedWarmPlan,
589
+ prerenderSecret: options.prerenderSecret,
590
+ deploymentId,
591
+ expectedBuildId,
592
+ expectedRscBuildId,
593
+ phaseTimeoutMs: options.warmCdnReadinessTimeout,
594
+ probeIntervalMs: options.warmCdnReadinessProbeDelay,
595
+ requiredConsecutiveSuccesses: options.warmCdnReadinessProbes,
596
+ retries: options.warmCdnReadinessRetries ?? options.warmCdnRetries,
597
+ timeoutMs: options.warmCdnTimeout
381
598
  });
599
+ if (!readiness.ready) {
600
+ const message = `CDN warmup could not verify staged Worker readiness: ${readiness.error}.`;
601
+ const noPromoteNote = options.warmCdnPromote === false ? " CDN warmup cannot continue because promotion is disabled and the staged version was not warmed." : "";
602
+ if (!allowUnverifiedPromotion || options.warmCdnPromote === false) throw new Error(`${message}${noPromoteNote}`);
603
+ console.warn(` ${message} Promoting because the dangerous override is enabled.`);
604
+ } else {
605
+ console.log(" CDN warmup: staged Worker version is stable.");
606
+ const warmResult = await warmUploadedVersion(targetUrl, headers, true, stagedWarmPlan);
607
+ const optionalSkipped = options.optionalWarmTargetKeys ? warmResult.skippedTargets.filter((target) => options.optionalWarmTargetKeys.has(cdnWarmTargetKey(target))).length : 0;
608
+ if (hasPreparedWarmPlan && options.warmCdnCertify) {
609
+ if (warmResult.warmed + optionalSkipped !== stagedWarmRequests) throw new Error(`CDN warmup cannot certify the staged cache because only ${warmResult.warmed}/${stagedWarmRequests - optionalSkipped} cacheable entries completed their initial fill.`);
610
+ }
611
+ const requiredSkipped = warmResult.skipped - optionalSkipped;
612
+ if (hasPreparedWarmPlan && requiredSkipped > 0) {
613
+ const message = `Two-stage CDN warming could not fill ${requiredSkipped}/${warmResult.total} planned cache entries because Cloudflare refused cache admission.`;
614
+ if (!allowUnverifiedPromotion) throw new Error(message);
615
+ console.warn(` ${message} Promoting because the dangerous override is enabled.`);
616
+ }
617
+ if (optionalSkipped > 0) console.log(` CDN warmup: ${optionalSkipped} paired representation${optionalSkipped === 1 ? " remained" : "s remained"} private after ${optionalSkipped === 1 ? "its" : "their"} final render and will not be cached.`);
618
+ remainingWarmPlan = {
619
+ loadingShellPaths: warmResult.retryPlan.loadingShellPaths,
620
+ pagesDataPaths: warmResult.retryPlan.pagesDataPaths,
621
+ paths: warmResult.retryPlan.paths,
622
+ routeHandlerPaths: warmResult.retryPlan.routeHandlerPaths,
623
+ rscPaths: warmResult.retryPlan.rscPaths
624
+ };
625
+ if (hasPreparedWarmPlan && options.warmCdnCertify && warmResult.warmed > 0) {
626
+ console.log(` CDN warmup: certifying ${warmResult.warmed} staged cache entr${warmResult.warmed === 1 ? "y" : "ies"} before promotion...`);
627
+ const certification = await warmUploadedVersion(targetUrl, headers, true, warmResult.warmedPlan, true);
628
+ if (certification.warmed !== warmResult.warmed) throw new Error(`CDN warmup certified ${certification.warmed}/${warmResult.warmed} staged cache entries as reusable.`);
629
+ stagedCacheFilled = true;
630
+ } else stagedCacheFilled = warmResult.warmed > 0;
631
+ }
632
+ }
633
+ } catch (error) {
634
+ throw withStagedVersionCleanupNote(error);
635
+ }
636
+ else if (initialWarmRequests > 0) {
637
+ const message = "CDN warmup failed: pre-traffic warmup needs a production URL and Worker name for version overrides. Configure a route/custom domain and Worker name, or deploy without --experimental-warm-cdn-cache.";
638
+ if (!allowUnverifiedPromotion) throw new Error(`${message} ${getStagedVersionCleanupNote()}`);
639
+ console.warn(` ${message} Promoting because the dangerous override is enabled.`);
640
+ }
641
+ } else {
642
+ if (initialWarmRequests > 0) {
643
+ const message = "CDN warmup cannot stage the uploaded Worker at 0% because the current deployment is not exactly one version serving 100% traffic.";
644
+ if (!allowUnverifiedPromotion) throw new Error(`${message} No traffic or triggers were changed.`);
645
+ console.warn(` ${message} Promoting because the dangerous override is enabled.`);
646
+ }
647
+ console.warn(" CDN warmup: pre-traffic version override skipped because the current deployment is not one version serving 100% traffic.");
648
+ }
649
+ const countRemainingWarmRequests = () => remainingWarmPlan.paths.length + remainingWarmPlan.pagesDataPaths.length + (remainingWarmPlan.routeHandlerPaths?.length ?? 0) + remainingWarmPlan.rscPaths.length + remainingWarmPlan.loadingShellPaths.length;
650
+ if (options.warmCdnPromote === false) {
651
+ if (!staged) throw new Error("CDN warmup cannot skip promotion because the uploaded Worker version could not be staged at 0% traffic. The current deployment must have exactly one version serving 100% traffic.");
652
+ const remainingWarmRequests = countRemainingWarmRequests();
653
+ if (!hasPreparedWarmPlan && options.discoverWarmPlan && discoveredWarmRequests === 0) throw withStagedVersionCleanupNote(/* @__PURE__ */ new Error("CDN warmup cannot skip promotion because no build-discovered requests were found to warm."));
654
+ if (remainingWarmRequests > 0) throw withStagedVersionCleanupNote(/* @__PURE__ */ new Error(`CDN warmup cannot skip promotion because ${remainingWarmRequests} request(s) remain unwarmed.`));
655
+ if (hasPreparedWarmPlan && stagedDeploymentState) {
656
+ let currentDeployment;
657
+ try {
658
+ currentDeployment = runWranglerDeploymentStatus(root, options);
382
659
  } catch (error) {
383
- throw withStagedVersionCleanupNote(error);
660
+ const message = error instanceof Error ? error.message : String(error);
661
+ throw new Error(`${message} CDN warmup cannot confirm that the uploaded Worker remains staged at 0% traffic; production Worker triggers/routes remain applied. Inspect \`wrangler deployments status\` before continuing.`, { cause: error });
384
662
  }
385
- warmedBeforePromotion = true;
386
- } else if (options.warmCdnStrict) throw new Error("CDN warmup failed: pre-traffic warmup needs a production URL and Worker name for version overrides. Configure a route/custom domain and Worker name, or rerun without --warm-cdn-strict. " + getStagedVersionCleanupNote());
387
- } else console.warn(" CDN warmup: pre-traffic version override skipped because the current deployment is not a single 100% version.");
388
- const deployed = runWranglerVersionDeploy(root, [{
663
+ if (!deploymentStateEquals(currentDeployment, stagedDeploymentState)) throw new Error("Two-stage CDN warming stopped because Worker deployment traffic or deployment identity changed before the no-promote handoff. The uploaded Worker is not confirmed staged at 0% traffic; production Worker triggers/routes remain applied.");
664
+ }
665
+ console.log(" CDN warmup: promotion disabled; uploaded Worker version remains staged at 0% traffic and production Worker triggers/routes remain applied.");
666
+ return staged.deployedUrl ?? triggersDeployedUrl ?? upload.previewUrl ?? "(URL not detected in wrangler output)";
667
+ }
668
+ let deployed;
669
+ let prePromotionState = null;
670
+ const promotionTraffic = [{
389
671
  versionId: upload.versionId,
390
672
  percentage: 100
391
- }], options, warmedBeforePromotion ? "promote-warmed" : "promote-uploaded");
392
- if (!warmedBeforePromotion) {
393
- try {
394
- applyTriggers();
395
- } catch (error) {
396
- throw withPromotedVersionTriggerNote(error);
673
+ }];
674
+ let promotionAttempted = false;
675
+ try {
676
+ if (stagedCacheFilled) {
677
+ const promotionDelay = options.warmCdnPromotionDelay ?? 15e3;
678
+ if (promotionDelay > 0) {
679
+ console.log(` CDN warmup: waiting ${promotionDelay / 1e3} seconds for cache propagation before promotion...`);
680
+ await setTimeout(promotionDelay);
681
+ }
682
+ }
683
+ if (hasPreparedWarmPlan && stagingTraffic) {
684
+ prePromotionState = runWranglerDeploymentStatus(root, options);
685
+ if (!deploymentTrafficEquals(prePromotionState.versions, stagingTraffic) || stagedDeploymentState && !deploymentStateEquals(prePromotionState, stagedDeploymentState)) throw new Error("Two-stage CDN warming stopped because Worker deployment traffic or deployment identity changed before the final version could be promoted. No final version was promoted.");
397
686
  }
398
- const targetUrl = resolveCdnWarmupTargetUrl(root, deployed.deployedUrl ?? triggersDeployedUrl, options);
399
- if (targetUrl) await warmCdnCache({
400
- targetUrl,
401
- paths,
402
- concurrency: options.warmCdnConcurrency,
403
- timeoutMs: options.warmCdnTimeout,
404
- retries: options.warmCdnRetries,
405
- strict: options.warmCdnStrict
687
+ promotionAttempted = true;
688
+ deployed = runWranglerVersionDeploy(root, promotionTraffic, options, stagedCacheFilled ? "promote-warmed" : "promote-uploaded");
689
+ } catch (error) {
690
+ if (promotionAttempted) throw reconcileVersionDeployFailure(root, options, error, {
691
+ desiredTraffic: promotionTraffic,
692
+ desiredDescription: "The uploaded version is already promoted to 100%; Worker triggers/routes may already have changed.",
693
+ priorState: prePromotionState ?? (stagingTraffic ? {
694
+ deploymentId: null,
695
+ output: "",
696
+ versions: stagingTraffic
697
+ } : deploymentStatus),
698
+ priorDescription: "The uploaded version remains staged at 0% with the previous version still serving 100% traffic; Worker triggers/routes may already have changed."
406
699
  });
407
- else if (options.warmCdnStrict) throw new Error("CDN warmup failed: no production URL could be inferred from wrangler config or output. Configure a route/custom domain, ensure Wrangler prints a workers.dev URL, or rerun without --warm-cdn-strict.");
408
- else console.warn(" CDN warmup skipped: no production URL could be inferred from wrangler config or output.");
700
+ throw staged ? withStagedVersionCleanupNote(error) : error;
701
+ }
702
+ try {
703
+ applyTriggers();
704
+ } catch (error) {
705
+ throw withPromotedVersionTriggerNote(error);
706
+ }
707
+ let postPromotionTargetUrl = resolveCdnWarmupTargetUrl(root, triggersDeployedUrl, options) ?? deployed.deployedUrl;
708
+ if (!warmPlanDiscovered && postPromotionTargetUrl) try {
709
+ console.log(" CDN warmup: discovering paths from the promoted Worker version...");
710
+ await discoverWarmPlan(postPromotionTargetUrl);
711
+ remainingWarmPlan = prepareWarmPlan(remainingWarmPlan);
712
+ } catch (error) {
713
+ throw withPromotedVersionWarmupNote(error);
714
+ }
715
+ if (countRemainingWarmRequests() > 0) {
716
+ const targetUrl = postPromotionTargetUrl;
717
+ if (targetUrl) try {
718
+ await warmUploadedVersion(targetUrl, void 0, true, remainingWarmPlan);
719
+ } catch (error) {
720
+ throw withPromotedVersionWarmupNote(error);
721
+ }
722
+ else if (!allowUnverifiedPromotion) throw withPromotedVersionWarmupNote(/* @__PURE__ */ new Error("CDN warmup failed: no production URL could be inferred from wrangler config or output. Configure a route/custom domain, ensure Wrangler prints a workers.dev URL, or deploy without --experimental-warm-cdn-cache."));
723
+ else console.warn(" CDN warmup skipped: no production URL could be inferred after promotion; the dangerous override was enabled.");
409
724
  }
410
725
  return deployed.deployedUrl ?? triggersDeployedUrl ?? staged?.deployedUrl ?? upload.previewUrl ?? "(URL not detected in wrangler output)";
411
726
  }
412
- function resolveCdnWarmupTargetUrl(root, deployedUrl, options) {
413
- const config = parseWranglerConfig(root, options?.config);
414
- const env = getWranglerTargetEnv(options ?? {});
415
- const customDomain = (env ? config?.env?.[env]?.customDomain : void 0) ?? config?.customDomain;
416
- if (customDomain) return `https://${customDomain}`;
417
- return deployedUrl;
727
+ function deploymentTrafficEquals(actual, expected) {
728
+ const normalize = (traffic) => [...traffic].sort((a, b) => a.versionId.localeCompare(b.versionId));
729
+ const normalizedActual = normalize(actual);
730
+ const normalizedExpected = normalize(expected);
731
+ return normalizedActual.length === normalizedExpected.length && normalizedActual.every((version, index) => version.versionId === normalizedExpected[index]?.versionId && version.percentage === normalizedExpected[index]?.percentage);
732
+ }
733
+ function deploymentStateEquals(actual, expected) {
734
+ if (expected.deploymentId !== null && actual.deploymentId !== expected.deploymentId) return false;
735
+ return deploymentTrafficEquals(actual.versions, expected.versions);
418
736
  }
419
- function readWranglerDeploymentStatus(root, options) {
737
+ function reconcileVersionDeployFailure(root, options, error, expected) {
738
+ const message = error instanceof Error ? error.message : String(error);
739
+ let reconciliation;
420
740
  try {
421
- return runWranglerDeploymentStatus(root, options);
422
- } catch {
423
- return null;
741
+ const current = runWranglerDeploymentStatus(root, options);
742
+ if (deploymentTrafficEquals(current.versions, expected.desiredTraffic)) reconciliation = expected.desiredDescription;
743
+ else if (deploymentStateEquals(current, expected.priorState)) reconciliation = expected.priorDescription;
744
+ else reconciliation = "Worker deployment state differs from both the requested and prior state, so the deployment outcome is unknown or another deployment changed it.";
745
+ } catch (reconciliationError) {
746
+ reconciliation = `Worker deployment status could not be read after the command failed, so the deployment outcome is unknown (${reconciliationError instanceof Error ? reconciliationError.message : String(reconciliationError)}).`;
747
+ }
748
+ return new Error(`${message} ${reconciliation}`, { cause: error });
749
+ }
750
+ function assertDeploymentStateUnchanged(root, options, expected, message) {
751
+ if (!deploymentStateEquals(runWranglerDeploymentStatus(root, options), expected)) throw new Error(message);
752
+ }
753
+ async function deployWithCacheabilityProbe(root, options) {
754
+ if (!options.discoverWarmPlan) throw new Error("Two-stage CDN warming requires staged Worker route discovery before cacheability probing.");
755
+ const prerenderSecret = readPrerenderSecret(root);
756
+ const probeUpload = runWranglerVersionUpload(root, options);
757
+ const initialDeployment = runWranglerDeploymentStatus(root, options);
758
+ const probeTraffic = getZeroPercentStagingTraffic(initialDeployment, probeUpload.versionId);
759
+ if (!probeTraffic) throw new Error("Two-stage CDN warming cannot stage the probe Worker at 0% because the current deployment is not exactly one version serving 100% traffic. No traffic or triggers were changed.");
760
+ let stagedProbe;
761
+ try {
762
+ stagedProbe = runWranglerVersionDeploy(root, probeTraffic, options, "stage");
763
+ } catch (error) {
764
+ throw reconcileVersionDeployFailure(root, options, error, {
765
+ desiredTraffic: probeTraffic,
766
+ desiredDescription: "The probe version is staged at 0% with the previous version still serving 100% traffic; production Worker triggers/routes were not changed.",
767
+ priorState: initialDeployment,
768
+ priorDescription: "Worker deployment traffic was not changed and production Worker triggers/routes were not changed."
769
+ });
770
+ }
771
+ let stagedProbeDeployment;
772
+ try {
773
+ stagedProbeDeployment = runWranglerDeploymentStatus(root, options);
774
+ if (!deploymentTrafficEquals(stagedProbeDeployment.versions, probeTraffic)) throw new Error("Two-stage CDN warming stopped because Worker deployment traffic changed immediately after the probe version was staged.");
775
+ } catch (error) {
776
+ const message = error instanceof Error ? error.message : String(error);
777
+ throw new Error(`${message} The probe staging command completed, but its current deployment state could not be confirmed; production Worker triggers/routes were not changed. Inspect \`wrangler deployments status\` and remove the staged probe version if necessary.`, { cause: error });
778
+ }
779
+ let prepared;
780
+ try {
781
+ const targetUrl = resolveCdnWarmupTargetUrl(root, stagedProbe.deployedUrl ?? probeUpload.previewUrl, options);
782
+ const wranglerConfig = parseWranglerConfig(root, options.config);
783
+ const headers = buildVersionOverrideHeaders(options.name ?? probeUpload.workerName ?? resolveWorkerNameForVersionOverride(wranglerConfig, options), probeUpload.versionId);
784
+ if (!targetUrl || !headers) throw new Error("Two-stage CDN warming needs a production URL and Worker name for version-overridden cacheability probes.");
785
+ console.log(" CDN warmup: discovering paths from the staged probe Worker...");
786
+ const discovered = await options.discoverWarmPlan({
787
+ headers,
788
+ targetUrl
789
+ });
790
+ if (!discovered.buildId) throw new Error("Two-stage CDN warming requires the staged discovery result to match dist/server/BUILD_ID.");
791
+ if (!discovered.buildIdentity) throw new Error("Two-stage CDN warming requires a CDN adapter that exposes the application build identity.");
792
+ const plan = {
793
+ ...discovered,
794
+ appPaths: discovered.appPaths ? [...discovered.appPaths] : void 0,
795
+ fallbackRoutePatterns: discovered.fallbackRoutePatterns ? [...discovered.fallbackRoutePatterns] : void 0,
796
+ loadingShellPaths: [...discovered.loadingShellPaths],
797
+ pagesDataPaths: [...discovered.pagesDataPaths ?? []],
798
+ pagesPaths: discovered.pagesPaths ? [...discovered.pagesPaths] : void 0,
799
+ paths: [...discovered.paths],
800
+ routeHandlerPaths: [...discovered.routeHandlerPaths ?? []],
801
+ routePatterns: discovered.routePatterns ? { ...discovered.routePatterns } : void 0,
802
+ rscPaths: [...discovered.rscPaths]
803
+ };
804
+ if (!plan.appPaths && !plan.pagesPaths) throw new Error("Two-stage CDN warming requires staged discovery to report App or Pages route ownership.");
805
+ const ownedHtmlPaths = /* @__PURE__ */ new Set([...plan.appPaths ?? [], ...plan.pagesPaths ?? []]);
806
+ plan.paths = plan.paths.filter((pathname) => ownedHtmlPaths.has(pathname));
807
+ const targets = await createCdnWarmTargets({
808
+ deploymentId: plan.deploymentId,
809
+ headers,
810
+ loadingShellPaths: plan.loadingShellPaths,
811
+ pagesDataPaths: plan.pagesDataPaths,
812
+ paths: plan.paths,
813
+ routeHandlerPaths: plan.routeHandlerPaths,
814
+ routePatterns: plan.routePatterns,
815
+ rscPaths: plan.rscPaths
816
+ });
817
+ const routePatternCount = new Set(targets.flatMap((target) => target.route ? [`${target.route.kind}\0${target.route.pattern}`] : [])).size;
818
+ const concreteRoutePathCount = new Set(targets.flatMap((target) => target.route ? [`${target.route.kind}\0${target.route.pattern}\0${target.route.cacheabilityProbe?.concretePathname ?? cacheabilityRoutePathname(target.pathname, target.kind)}`] : [])).size;
819
+ if (targets.length > 0) {
820
+ console.log(" CDN warmup: waiting for the staged probe Worker to become stable...");
821
+ const readiness = await waitForCdnWarmTargetReadiness({
822
+ targetUrl,
823
+ headers,
824
+ plan,
825
+ prerenderSecret,
826
+ deploymentId: plan.deploymentId,
827
+ expectedBuildId: plan.buildIdentity,
828
+ expectedRscBuildId: plan.rscBuildId,
829
+ phaseTimeoutMs: options.warmCdnReadinessTimeout,
830
+ probeIntervalMs: options.warmCdnReadinessProbeDelay,
831
+ requiredConsecutiveSuccesses: options.warmCdnReadinessProbes,
832
+ retries: options.warmCdnReadinessRetries ?? options.warmCdnRetries,
833
+ timeoutMs: options.warmCdnTimeout
834
+ });
835
+ if (!readiness.ready) throw new Error(`Two-stage CDN warming could not verify staged probe Worker readiness: ${readiness.error}.`);
836
+ console.log(` CDN warmup: probing ${concreteRoutePathCount} concrete route path${concreteRoutePathCount === 1 ? "" : "s"} once across ${routePatternCount} pattern${routePatternCount === 1 ? "" : "s"}; filtering ${targets.length} candidate warm request identit${targets.length === 1 ? "y" : "ies"}...`);
837
+ } else {
838
+ const fallbackPatternCount = plan.fallbackRoutePatterns?.length ?? 0;
839
+ console.log(fallbackPatternCount > 0 ? ` CDN warmup: embedding ${fallbackPatternCount} on-demand static route pattern${fallbackPatternCount === 1 ? "" : "s"} without a speculative render.` : " CDN warmup: no page request identities were discovered; embedding an empty fail-closed cacheability manifest.");
840
+ }
841
+ const probeProgress = new CdnOperationProgress();
842
+ let probe;
843
+ try {
844
+ probe = await probeStagedWorkerCacheability({
845
+ buildId: discovered.buildId,
846
+ concurrency: options.warmCdnConcurrency,
847
+ expectedResponseBuildId: plan.buildIdentity,
848
+ fallbackRoutePatterns: plan.fallbackRoutePatterns,
849
+ phaseTimeoutMs: options.warmCdnProbeTimeout ?? 12e4,
850
+ retries: options.warmCdnProbeRetries ?? options.warmCdnRetries ?? 2,
851
+ retryDelayMs: DEFAULT_CACHEABILITY_PROBE_RETRY_DELAY_MS,
852
+ root,
853
+ targets,
854
+ targetUrl,
855
+ timeoutMs: options.warmCdnTimeout,
856
+ onProgress(progress) {
857
+ probeProgress.update(progress.completed, progress.total, `${progress.static} static, ${progress.dynamic} dynamic, ${progress.skipped} skipped`, "Probing route cacheability");
858
+ }
859
+ });
860
+ } finally {
861
+ probeProgress.finish();
862
+ }
863
+ console.log(` CDN warmup: classified ${probe.classified} route pattern${probe.classified === 1 ? "" : "s"} with ${probe.probed} render probe${probe.probed === 1 ? "" : "s"}; ${probe.dynamic} observed dynamic and ${probe.skipped} excluded by pattern-wide proof.`);
864
+ if (probe.failures.length > 0) throw new Error(`Two-stage CDN warming failed to classify ${probe.failures.length}/${concreteRoutePathCount} concrete route paths after ${probe.probed} render probe(s). First failure: ${probe.failures[0]}`);
865
+ const finalPlan = {
866
+ ...plan,
867
+ loadingShellPaths: probe.cacheableTargets.filter((target) => target.kind === "rsc-loading-shell").map((target) => target.sourcePathname),
868
+ pagesDataPaths: probe.cacheableTargets.filter((target) => target.kind === "pages-data").map((target) => target.sourcePathname),
869
+ paths: probe.cacheableTargets.filter((target) => target.kind === "html").map((target) => target.sourcePathname),
870
+ routeHandlerPaths: probe.cacheableTargets.filter((target) => target.kind === "app-route").map((target) => target.sourcePathname),
871
+ rscPaths: probe.cacheableTargets.filter((target) => target.kind === "rsc-full").map((target) => target.sourcePathname)
872
+ };
873
+ assertDeploymentStateUnchanged(root, options, stagedProbeDeployment, "Two-stage CDN warming stopped because Worker deployment traffic or deployment identity changed while cacheability was being probed. No final version was promoted.");
874
+ const finalUpload = runWranglerVersionUpload(root, {
875
+ config: writeCacheabilityManifestArtifact(root, options.config, probe.manifest),
876
+ env: options.env,
877
+ name: options.name,
878
+ preview: options.preview,
879
+ verbose: options.verbose
880
+ });
881
+ prepared = {
882
+ optionalWarmTargetKeys: new Set(probe.speculativeTargets.map(cdnWarmTargetKey)),
883
+ prerenderSecret,
884
+ plan: finalPlan,
885
+ upload: finalUpload
886
+ };
887
+ } catch (error) {
888
+ throw withStagedProbeVersionCleanupNote(error);
424
889
  }
890
+ return deployUploadedVersionWithCdnWarmup(root, prepared.plan.paths, {
891
+ ...options,
892
+ deploymentId: prepared.plan.deploymentId,
893
+ expectedBuildId: prepared.plan.buildIdentity,
894
+ expectedRscBuildId: prepared.plan.rscBuildId,
895
+ expectedDeploymentState: stagedProbeDeployment,
896
+ loadingShellPaths: prepared.plan.loadingShellPaths,
897
+ optionalWarmTargetKeys: prepared.optionalWarmTargetKeys,
898
+ pagesDataPaths: prepared.plan.pagesDataPaths,
899
+ prerenderSecret: prepared.prerenderSecret,
900
+ routeHandlerPaths: prepared.plan.routeHandlerPaths,
901
+ routePatterns: prepared.plan.routePatterns,
902
+ rscPaths: prepared.plan.rscPaths,
903
+ uploadedVersion: prepared.upload
904
+ });
905
+ }
906
+ function resolveCdnWarmupTargetUrl(_root, deployedUrl, options) {
907
+ return options?.warmCdnTarget ?? deployedUrl;
425
908
  }
426
909
  function getZeroPercentStagingTraffic(deployment, versionId) {
427
- const current = deployment?.versions ?? [];
428
- if (current.length !== 1 || current[0].percentage !== 100) return null;
429
- if (current[0].versionId === versionId) return null;
430
- return [current[0], {
910
+ const serving = (deployment?.versions ?? []).filter((version) => version.percentage > 0);
911
+ if (serving.length !== 1 || serving[0].percentage !== 100) return null;
912
+ if (serving[0].versionId === versionId) return null;
913
+ return [serving[0], {
431
914
  versionId,
432
915
  percentage: 0
433
916
  }];
@@ -447,20 +930,33 @@ function quoteStructuredHeaderString(value) {
447
930
  }
448
931
  function buildVersionOverrideHeaders(workerName, versionId) {
449
932
  if (!workerName) return void 0;
450
- return { "Cloudflare-Workers-Version-Overrides": `${workerName}=${quoteStructuredHeaderString(versionId)}` };
933
+ return {
934
+ "Cloudflare-Workers-Version-Overrides": `${workerName}=${quoteStructuredHeaderString(versionId)}`,
935
+ [VINEXT_EXPECTED_WORKER_VERSION_HEADER]: versionId
936
+ };
451
937
  }
452
938
  function withStagedVersionCleanupNote(error) {
453
939
  const message = error instanceof Error ? error.message : String(error);
454
940
  return new Error(`${message} ${getStagedVersionCleanupNote()}`, { cause: error });
455
941
  }
942
+ function withStagedProbeVersionCleanupNote(error) {
943
+ const message = error instanceof Error ? error.message : String(error);
944
+ return new Error(`${message} The probe version may remain staged at 0% with the previous version still serving 100% traffic; production Worker triggers/routes were not changed.`, { cause: error });
945
+ }
456
946
  function getStagedVersionCleanupNote() {
457
- return "The uploaded version may remain staged at 0% with the previous version still serving 100% traffic; rerun deploy to promote it or use `wrangler versions deploy` to choose the desired version split.";
947
+ return "The uploaded version may remain staged at 0% with the previous version still serving 100% traffic; Worker triggers/routes may also have changed because trigger deployment runs before warming. Rerun deploy to promote it or use `wrangler versions deploy` to choose the desired version split.";
458
948
  }
459
949
  function withPromotedVersionTriggerNote(error) {
460
950
  const message = error instanceof Error ? error.message : String(error);
461
951
  return new Error(`${message} The uploaded version may already be promoted to 100%, but Worker triggers/routes may not be updated; rerun deploy or \`wrangler triggers deploy\` after fixing the trigger error.`, { cause: error });
462
952
  }
953
+ function withPromotedVersionWarmupNote(error) {
954
+ const message = error instanceof Error ? error.message : String(error);
955
+ return new Error(`${message} The uploaded version is already promoted to 100% and its Worker triggers/routes were updated; rerun deploy to retry cache warming or roll back with \`wrangler versions deploy\`.`, { cause: error });
956
+ }
463
957
  async function deploy(options) {
958
+ if (options.warmCdnTarget !== void 0 && !options.warmCdnCache) throw new Error("--warm-cdn-target requires --experimental-warm-cdn-cache.");
959
+ const warmCdnTarget = options.warmCdnTarget === void 0 ? void 0 : validateCdnWarmTarget(options.warmCdnTarget);
464
960
  const deployEnv = validateWranglerEnvName(options.env || (options.preview ? "preview" : "production"));
465
961
  const root = path.resolve(options.root);
466
962
  loadDotenv({
@@ -495,6 +991,7 @@ async function deploy(options) {
495
991
  }
496
992
  const buildEnv = deployEnv === "production" && !options.env ? void 0 : deployEnv;
497
993
  const viteConfigMetadata = await withCloudflareEnv(buildEnv, () => loadDeployViteConfigMetadata(info.root));
994
+ const cdnAdapterConfig = resolveCdnAdapterConfig(viteConfigMetadata.cacheConfig);
498
995
  const nextConfig = await withCloudflareEnv(buildEnv, async () => {
499
996
  const inlineNextConfig = viteConfigMetadata.nextConfig;
500
997
  return resolveNextConfig(inlineNextConfig ? await resolveNextConfigInput(inlineNextConfig, PHASE_PRODUCTION_BUILD) : await loadNextConfig(info.root, PHASE_PRODUCTION_BUILD), info.root);
@@ -505,12 +1002,39 @@ async function deploy(options) {
505
1002
  vinextPrerenderConfig,
506
1003
  nextOutput: nextConfig.output
507
1004
  });
508
- const shouldEmitPrerenderPathManifest = options.warmCdnCache || !options.skipBuild && prerenderDecision;
1005
+ const hasStrictResponseVary = hasVerbatimResponseVary(viteConfigMetadata.cacheConfig);
1006
+ const hasBuildIdentityHeader = hasBuildIdentityResponseHeader(viteConfigMetadata.cacheConfig);
1007
+ const needsCacheabilityProbeManifest = projectRequiresRouteCacheabilityProbeManifest(info, viteConfigMetadata.cacheConfig);
1008
+ const shouldEmitPrerenderPathManifest = !options.skipBuild && prerenderDecision;
509
1009
  if (!options.skipBuild) await runBuild(info, buildEnv);
510
1010
  else console.log("\n Skipping build (--skip-build)");
1011
+ if (options.warmCdnCache && cdnAdapterConfig) {
1012
+ const wrangler = await loadProjectWranglerApi(info.root);
1013
+ const previousCwd = process.cwd();
1014
+ try {
1015
+ process.chdir(info.root);
1016
+ const config = wrangler.unstable_readConfig({
1017
+ config: options.config,
1018
+ env: buildEnv
1019
+ }, {
1020
+ hideWarnings: true,
1021
+ preserveOriginalMain: true,
1022
+ useRedirectIfAvailable: true
1023
+ });
1024
+ assertCdnVersionMetadataConfig({
1025
+ binding: cdnAdapterConfig.versionMetadataBinding,
1026
+ configuredBinding: config.version_metadata?.binding,
1027
+ configPath: config.configPath
1028
+ });
1029
+ } finally {
1030
+ process.chdir(previousCwd);
1031
+ }
1032
+ }
511
1033
  if (shouldEmitPrerenderPathManifest) await emitPrerenderPathManifest({
512
1034
  root: info.root,
513
1035
  nextConfig,
1036
+ buildIdentity: hasBuildIdentityHeader ? "response-header" : void 0,
1037
+ responseVary: hasStrictResponseVary ? "verbatim" : void 0,
514
1038
  routeRootConfig: viteConfigMetadata.routeRootConfig
515
1039
  });
516
1040
  let ranPrerender = false;
@@ -546,29 +1070,54 @@ async function deploy(options) {
546
1070
  const wranglerOptions = {
547
1071
  env: deployEnv === "production" && !options.env ? void 0 : deployEnv,
548
1072
  name: options.name,
549
- config: options.config
1073
+ config: options.config,
1074
+ verbose: options.verbose
550
1075
  };
551
1076
  let url;
552
- if (options.warmCdnCache) {
553
- const warmPaths = readPrerenderWarmPaths(root, {
554
- includeFallbackShells: options.warmCdnIncludeFallbacks,
555
- strict: options.warmCdnStrict
556
- });
557
- if (warmPaths.length > 0) url = await deployWithCdnWarmup(root, warmPaths, {
558
- ...wranglerOptions,
559
- warmCdnConcurrency: options.warmCdnConcurrency,
560
- warmCdnTimeout: options.warmCdnTimeout,
561
- warmCdnRetries: options.warmCdnRetries,
562
- warmCdnStrict: options.warmCdnStrict
563
- });
564
- else {
565
- console.log("\n CDN warmup skipped: no build-discovered paths found.");
566
- url = await runWranglerDeploy(root, wranglerOptions);
567
- }
568
- } else url = await runWranglerDeploy(root, wranglerOptions);
1077
+ if (options.warmCdnCache) url = await deployWithCdnWarmup(root, [], {
1078
+ ...wranglerOptions,
1079
+ cacheabilityProbe: needsCacheabilityProbeManifest,
1080
+ discoverWarmPlan: async ({ headers, targetUrl }) => {
1081
+ await emitPrerenderPathManifest({
1082
+ root: info.root,
1083
+ nextConfig,
1084
+ buildIdentity: hasBuildIdentityHeader ? "response-header" : void 0,
1085
+ responseVary: hasStrictResponseVary ? "verbatim" : void 0,
1086
+ routeRootConfig: viteConfigMetadata.routeRootConfig,
1087
+ pathDiscoveryTarget: {
1088
+ baseUrl: targetUrl,
1089
+ headers,
1090
+ phaseTimeoutMs: options.warmCdnDiscoveryTimeout ?? DEFAULT_REMOTE_PATH_DISCOVERY_PHASE_TIMEOUT_MS,
1091
+ retries: options.warmCdnDiscoveryRetries,
1092
+ retryDelayMs: DEFAULT_REMOTE_PATH_DISCOVERY_RETRY_DELAY_MS
1093
+ }
1094
+ });
1095
+ return readPrerenderWarmPlan(root, {
1096
+ includeFallbackShells: options.warmCdnIncludeFallbacks,
1097
+ strict: options.warmCdnCertify === true || !options.dangerouslyPromoteOnCdnWarmError
1098
+ });
1099
+ },
1100
+ warmCdnConcurrency: options.warmCdnConcurrency,
1101
+ warmCdnTarget,
1102
+ warmCdnTimeout: options.warmCdnTimeout,
1103
+ warmCdnRetries: options.warmCdnRetries,
1104
+ warmCdnDiscoveryTimeout: options.warmCdnDiscoveryTimeout,
1105
+ warmCdnDiscoveryRetries: options.warmCdnDiscoveryRetries,
1106
+ warmCdnProbeTimeout: options.warmCdnProbeTimeout,
1107
+ warmCdnProbeRetries: options.warmCdnProbeRetries,
1108
+ warmCdnCertify: options.warmCdnCertify,
1109
+ warmCdnReadinessTimeout: options.warmCdnReadinessTimeout,
1110
+ warmCdnReadinessRetries: options.warmCdnReadinessRetries,
1111
+ warmCdnReadinessProbes: options.warmCdnReadinessProbes,
1112
+ warmCdnReadinessProbeDelay: options.warmCdnReadinessProbeDelay,
1113
+ dangerouslyPromoteOnCdnWarmError: options.dangerouslyPromoteOnCdnWarmError,
1114
+ warmCdnPromote: options.warmCdnPromote,
1115
+ warmCdnPromotionDelay: options.warmCdnPromotionDelay
1116
+ });
1117
+ else url = await runWranglerDeploy(root, wranglerOptions);
569
1118
  console.log("\n ─────────────────────────────────────────");
570
1119
  console.log(` Deployed to: ${url}`);
571
1120
  console.log(" ─────────────────────────────────────────\n");
572
1121
  }
573
1122
  //#endregion
574
- export { buildNodeCliInvocation, buildVersionOverrideHeaders, buildWranglerDeployArgs, buildWranglerInvocation, buildWranglerKVBulkPutArgs, deploy, deployWithCdnWarmup, getZeroPercentStagingTraffic, parseDeployArgs, resolveCdnWarmupTargetUrl, resolveWorkerNameForVersionOverride, resolveWranglerBin, runWranglerDeploy, runWranglerKVBulkPut, validateWranglerEnvName, withCloudflareEnv };
1123
+ export { DEFAULT_CDN_WARM_PROMOTION_DELAY_MS, buildNodeCliInvocation, buildVersionOverrideHeaders, buildWranglerDeployArgs, buildWranglerInvocation, buildWranglerKVBulkPutArgs, deploy, deployWithCdnWarmup, getZeroPercentStagingTraffic, hasCdnWarmRequests, parseDeployArgs, projectRequiresRouteCacheabilityProbeManifest, resolveCdnWarmupTargetUrl, resolveWorkerNameForVersionOverride, resolveWranglerBin, runWranglerDeploy, runWranglerKVBulkPut, validateWranglerEnvName, withCloudflareEnv };