@cloudflare/deploy-helpers 0.12.2 → 0.14.0

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/index.mjs CHANGED
@@ -10,8 +10,8 @@ import path__default, { resolve, isAbsolute, sep, extname } from 'node:path';
10
10
  import url2, { URLSearchParams as URLSearchParams$1 } from 'node:url';
11
11
  import * as cli from '@cloudflare/cli-shared-helpers';
12
12
  import { updateStatus, cancel } from '@cloudflare/cli-shared-helpers';
13
- import { SchedulingPolicy, ApplicationsService, ApiError, listDurableObjects, resolveImageName, pushImageIfChanged, ContainerImagePreparationsService, ContainerImagePreparationStatus, createDurableObjectNamespaceResolver, initContainersSharedContext, pushBuiltContainerImage, deployContainers, verifyDockerInstalled } from '@cloudflare/containers-shared';
14
- import { INHERIT_SYMBOL, APIError, UserError, getEnvironmentVariableFactory, isNonInteractiveOrCI, getHostFromRoute, retryOnAPIFailure, ParseError, getComplianceRegionSubdomain, configFileName, formatTime, getSubdomainMixedStateCheckDisabled, LOGGER_LEVELS, CONTAINER_IMAGES_BINDING, getResolvedDurableObjectContainerApps, isDurableObjectContainerApp, getDockerPath, validateDurableObjectContainerApplications, getDurableObjectClassNameToUseSQLiteMap, SERVICE_TAG_PREFIX, ENVIRONMENT_TAG_PREFIX, getDurableObjectExports, partitionExports, getWranglerTmpDir, parsePackageJSON, getInstalledPackageVersion, FatalError, readFileSync as readFileSync$1, parseJSON, printBindings, experimental_readRawConfig, experimental_patchConfig, PatchConfigError, COMPLIANCE_REGION_CONFIG_UNKNOWN, constructWranglerConfig, getCIMatchTag, formatConfigSnippet, DEFAULT_COMPAT_DATE, writeOutput, getDurableObjectContainerApps, getBindings, hasDurableObjectExports, parseNonHyphenedUuid, getWorkersCIBranchName, getCIOverrideName, getBindingTypeFriendlyName } from '@cloudflare/workers-utils';
13
+ import { SchedulingPolicy, ApplicationsService, listDurableObjects, ApiError, resolveImageName, pushImageIfChanged, ContainerImagePreparationsService, ContainerImagePreparationStatus, createDurableObjectNamespaceResolver, initContainersSharedContext, pushBuiltContainerImage, deployContainers, verifyDockerInstalled } from '@cloudflare/containers-shared';
14
+ import { INHERIT_SYMBOL, APIError, UserError, getEnvironmentVariableFactory, isNonInteractiveOrCI, getHostFromRoute, retryOnAPIFailure, ParseError, getComplianceRegionSubdomain, configFileName, formatTime, getSubdomainMixedStateCheckDisabled, LOGGER_LEVELS, getResolvedDurableObjectContainerApps, isDurableObjectContainerApp, getDockerPath, validateDurableObjectContainerApplications, getDurableObjectClassNameToUseSQLiteMap, SERVICE_TAG_PREFIX, ENVIRONMENT_TAG_PREFIX, getDurableObjectExports, partitionExports, getWranglerTmpDir, parsePackageJSON, getInstalledPackageVersion, FatalError, readFileSync as readFileSync$1, parseJSON, printBindings, experimental_readRawConfig, experimental_patchConfig, PatchConfigError, COMPLIANCE_REGION_CONFIG_UNKNOWN, constructWranglerConfig, getCIMatchTag, formatConfigSnippet, DEFAULT_COMPAT_DATE, writeOutput, getDurableObjectContainerApps, getBindings, hasDurableObjectExports, parseNonHyphenedUuid, getWorkersCIBranchName, getCIOverrideName, getBindingTypeFriendlyName, defaultWranglerConfig } from '@cloudflare/workers-utils';
15
15
  import { Response, FormData } from 'undici';
16
16
  import chalk6 from 'chalk';
17
17
  import PQueue from 'p-queue';
@@ -29,6 +29,7 @@ import { parse as parse$1 } from 'dotenv';
29
29
  import { getFreshSourceMapSupport, getNodeCompat } from 'miniflare';
30
30
  import { execSync } from 'node:child_process';
31
31
  import { createHash } from 'node:crypto';
32
+ import { convertToWranglerConfig } from '@cloudflare/config';
32
33
 
33
34
  // ../../node_modules/.pnpm/ignore@5.3.1/node_modules/ignore/index.js
34
35
  var require_ignore = __commonJS({
@@ -6522,59 +6523,6 @@ function formatVersions(versions, traffic) {
6522
6523
  }).join("\n\n");
6523
6524
  }
6524
6525
  __name(formatVersions, "formatVersions");
6525
- async function clearRemovedContainerImagesBindings(config2, durableObjectContainerConfig, bindings, workerUrl) {
6526
- if (durableObjectContainerConfig.length > 0) {
6527
- return;
6528
- }
6529
- const settings = await fetchResult(
6530
- config2,
6531
- `${workerUrl}/settings`
6532
- );
6533
- if (settings.bindings.some(({ name }) => name === CONTAINER_IMAGES_BINDING)) {
6534
- bindings[CONTAINER_IMAGES_BINDING] ??= { type: "json", value: {} };
6535
- }
6536
- }
6537
- __name(clearRemovedContainerImagesBindings, "clearRemovedContainerImagesBindings");
6538
- function addContainerImagesBinding(durableObjectContainerConfig, bindings, preparedContainerImages, options = {}) {
6539
- const shouldInheritExisting = options.preserveExisting && options.workerExists && options.hasExistingBinding;
6540
- if (options.preserveExisting && !shouldInheritExisting) {
6541
- return;
6542
- }
6543
- if (durableObjectContainerConfig.length === 0 && !shouldInheritExisting) {
6544
- return;
6545
- }
6546
- if (bindings[CONTAINER_IMAGES_BINDING] !== void 0) {
6547
- throw new UserError(
6548
- `The binding name "${CONTAINER_IMAGES_BINDING}" is reserved for Durable Object-managed Container images.`,
6549
- {
6550
- telemetryMessage: "durable object container images binding name conflict"
6551
- }
6552
- );
6553
- }
6554
- if (options.preserveExisting) {
6555
- bindings[CONTAINER_IMAGES_BINDING] = { type: "inherit" };
6556
- return;
6557
- }
6558
- bindings[CONTAINER_IMAGES_BINDING] = {
6559
- type: "json",
6560
- value: Object.fromEntries(
6561
- getResolvedDurableObjectContainerApps(
6562
- durableObjectContainerConfig,
6563
- options.exports
6564
- ).map((container) => {
6565
- const configuredImages = Object.keys(container.images ?? {});
6566
- const preparedImages = preparedContainerImages[container.class_name];
6567
- if (configuredImages.length > 0 && preparedImages === void 0) {
6568
- throw new Error(
6569
- `Container images for Durable Object class "${container.class_name}" were not prepared before upload.`
6570
- );
6571
- }
6572
- return [container.class_name, preparedImages ?? {}];
6573
- })
6574
- )
6575
- };
6576
- }
6577
- __name(addContainerImagesBinding, "addContainerImagesBinding");
6578
6526
  function getContainerMetadata(containers, preparedContainerImages = {}, options = {}) {
6579
6527
  const managedClasses = new Map(
6580
6528
  getResolvedDurableObjectContainerApps(containers, options.exports).map(
@@ -6624,8 +6572,7 @@ async function getContainerMetadataForRolloutSkip(config2, containers, {
6624
6572
  allowUnprepared: true,
6625
6573
  exports: config2.exports
6626
6574
  }
6627
- ),
6628
- hasExistingContainerImagesBinding: false
6575
+ )
6629
6576
  };
6630
6577
  }
6631
6578
  if (dispatchNamespace !== void 0) {
@@ -6651,22 +6598,6 @@ async function getContainerMetadataForRolloutSkip(config2, containers, {
6651
6598
  void 0,
6652
6599
  latestDeployment.versions.map(({ version_id }) => version_id)
6653
6600
  );
6654
- const containerImagesBindingByVersion = versions.map(
6655
- (version2) => version2.resources.bindings.some(
6656
- (binding) => binding.name === CONTAINER_IMAGES_BINDING
6657
- )
6658
- );
6659
- const hasExistingContainerImagesBinding = containerImagesBindingByVersion[0] ?? false;
6660
- if (containerImagesBindingByVersion.some(
6661
- (hasBinding) => hasBinding !== hasExistingContainerImagesBinding
6662
- )) {
6663
- throw new UserError(
6664
- `All currently deployed Worker Versions must have identical ${CONTAINER_IMAGES_BINDING} binding presence when using --containers-rollout=none.`,
6665
- {
6666
- telemetryMessage: "rollout none inconsistent durable object container image binding"
6667
- }
6668
- );
6669
- }
6670
6601
  const containerMetadataByVersion = versions.map(
6671
6602
  (version2) => version2.resources?.script_runtime?.containers
6672
6603
  );
@@ -6675,8 +6606,7 @@ async function getContainerMetadataForRolloutSkip(config2, containers, {
6675
6606
  );
6676
6607
  if (existingMetadata.length === 0) {
6677
6608
  return {
6678
- containers: void 0,
6679
- hasExistingContainerImagesBinding
6609
+ containers: void 0
6680
6610
  };
6681
6611
  }
6682
6612
  const expectedMetadata = existingMetadata[0];
@@ -6691,8 +6621,7 @@ async function getContainerMetadataForRolloutSkip(config2, containers, {
6691
6621
  );
6692
6622
  }
6693
6623
  return {
6694
- containers: existingMetadata[0],
6695
- hasExistingContainerImagesBinding
6624
+ containers: existingMetadata[0]
6696
6625
  };
6697
6626
  }
6698
6627
  __name(getContainerMetadataForRolloutSkip, "getContainerMetadataForRolloutSkip");
@@ -6744,24 +6673,6 @@ async function createDurableObjectContainerApplication(application, namespaceId)
6744
6673
  );
6745
6674
  }
6746
6675
  __name(createDurableObjectContainerApplication, "createDurableObjectContainerApplication");
6747
- function getContainerImageClasses(version2) {
6748
- const binding = version2.resources.bindings.find(
6749
- (candidate) => candidate.name === CONTAINER_IMAGES_BINDING
6750
- );
6751
- if (binding === void 0) {
6752
- return void 0;
6753
- }
6754
- if (binding.type !== "json" || typeof binding.json !== "object" || binding.json === null || Array.isArray(binding.json)) {
6755
- throw new UserError(
6756
- `Worker Version ${version2.id} has invalid ${CONTAINER_IMAGES_BINDING} metadata.`,
6757
- {
6758
- telemetryMessage: "versions deploy invalid durable object container image binding"
6759
- }
6760
- );
6761
- }
6762
- return new Set(Object.keys(binding.json));
6763
- }
6764
- __name(getContainerImageClasses, "getContainerImageClasses");
6765
6676
  function getNamespaceId(version2, scriptName, className) {
6766
6677
  const binding = version2.resources.bindings.find(
6767
6678
  (candidate) => candidate.type === "durable_object_namespace" && candidate.class_name === className && (candidate.script_name === void 0 || candidate.script_name === scriptName)
@@ -6769,18 +6680,17 @@ function getNamespaceId(version2, scriptName, className) {
6769
6680
  return binding?.type === "durable_object_namespace" ? binding.namespace_id : void 0;
6770
6681
  }
6771
6682
  __name(getNamespaceId, "getNamespaceId");
6772
- function getDurableObjectContainerApplicationsFromVersion(version2, scriptName) {
6773
- const containerClasses = getContainerImageClasses(version2);
6774
- if (containerClasses === void 0) {
6775
- return [];
6776
- }
6683
+ function getDurableObjectContainerApplicationsFromVersion(version2, scriptName, containerClasses) {
6777
6684
  const containers = version2.resources.script_runtime.containers ?? [];
6778
- return [...containerClasses].sort().map((className) => {
6685
+ return [...containerClasses].sort().flatMap((className) => {
6779
6686
  const matchingContainers = containers.filter(
6780
6687
  (container2) => container2.class_name === className
6781
6688
  );
6689
+ if (matchingContainers.length === 0) {
6690
+ return [];
6691
+ }
6782
6692
  const [container] = matchingContainers;
6783
- if (matchingContainers.length !== 1 || container?.name === void 0) {
6693
+ if (typeof className !== "string" || className.length === 0 || matchingContainers.length !== 1 || !container?.name) {
6784
6694
  throw new UserError(
6785
6695
  `Worker Version ${version2.id} has invalid Durable Object-managed Container metadata for class "${className}".`,
6786
6696
  {
@@ -6797,8 +6707,17 @@ function getDurableObjectContainerApplicationsFromVersion(version2, scriptName)
6797
6707
  }
6798
6708
  __name(getDurableObjectContainerApplicationsFromVersion, "getDurableObjectContainerApplicationsFromVersion");
6799
6709
  function getVersionedDurableObjectContainerApplications(versions, scriptName) {
6710
+ const containerClasses = new Set(
6711
+ versions.flatMap(
6712
+ (version2) => (version2.resources.script_runtime.containers ?? []).filter((container) => Object.keys(container.images ?? {}).length > 0).map((container) => container.class_name)
6713
+ )
6714
+ );
6800
6715
  const applicationsByVersion = versions.map(
6801
- (version2) => getDurableObjectContainerApplicationsFromVersion(version2, scriptName)
6716
+ (version2) => getDurableObjectContainerApplicationsFromVersion(
6717
+ version2,
6718
+ scriptName,
6719
+ containerClasses
6720
+ )
6802
6721
  );
6803
6722
  const [firstApplications = []] = applicationsByVersion;
6804
6723
  const expectedDefinition = JSON.stringify(
@@ -6837,6 +6756,52 @@ function getVersionedDurableObjectContainerApplications(versions, scriptName) {
6837
6756
  });
6838
6757
  }
6839
6758
  __name(getVersionedDurableObjectContainerApplications, "getVersionedDurableObjectContainerApplications");
6759
+ function validateApplicationIdentity(application, namespaceId, existing) {
6760
+ if (existing.id !== namespaceId || existing.durable_objects?.namespace_id !== namespaceId || existing.scheduling_policy !== SchedulingPolicy.DURABLE_OBJECT || existing.name !== application.name) {
6761
+ throw new UserError(
6762
+ `The application for Durable Object namespace "${namespaceId}" does not match Container "${application.name}". The existing name, namespace, and scheduling policy must match before its settings can be applied.`,
6763
+ {
6764
+ telemetryMessage: "durable object container application identity mismatch"
6765
+ }
6766
+ );
6767
+ }
6768
+ }
6769
+ __name(validateApplicationIdentity, "validateApplicationIdentity");
6770
+ async function validateImageLessContainerApplicationsForUpload(config2, containers, { accountId, scriptName }) {
6771
+ const imageLessContainers = getResolvedDurableObjectContainerApps(
6772
+ containers,
6773
+ config2.exports
6774
+ ).filter((container) => Object.keys(container.images ?? {}).length === 0);
6775
+ if (imageLessContainers.length === 0) {
6776
+ return;
6777
+ }
6778
+ const namespaces = await listDurableObjects(config2, accountId);
6779
+ for (const container of imageLessContainers) {
6780
+ const namespace = namespaces.find(
6781
+ (candidate) => candidate.class === container.class_name && candidate.script === scriptName && candidate.preview === void 0 && candidate.dispatch_namespace === void 0
6782
+ );
6783
+ let existing;
6784
+ if (namespace !== void 0) {
6785
+ try {
6786
+ existing = await ApplicationsService.getApplication(namespace.id);
6787
+ } catch (error51) {
6788
+ if (!(error51 instanceof ApiError) || error51.status !== 404) {
6789
+ throw error51;
6790
+ }
6791
+ }
6792
+ }
6793
+ if (namespace === void 0 || existing === void 0) {
6794
+ throw new UserError(
6795
+ `Container "${container.name}" has no named images and has not been provisioned. Run \`wrangler deploy\` to create its Durable Object-managed application before using \`wrangler versions upload\`, or configure at least one named image.`,
6796
+ {
6797
+ telemetryMessage: "versions upload image less container application missing"
6798
+ }
6799
+ );
6800
+ }
6801
+ validateApplicationIdentity(container, namespace.id, existing);
6802
+ }
6803
+ }
6804
+ __name(validateImageLessContainerApplicationsForUpload, "validateImageLessContainerApplicationsForUpload");
6840
6805
  async function applyApplication(application, namespaceId, settings = {}, updateExisting = false) {
6841
6806
  let existing;
6842
6807
  try {
@@ -6850,14 +6815,7 @@ async function applyApplication(application, namespaceId, settings = {}, updateE
6850
6815
  );
6851
6816
  return;
6852
6817
  }
6853
- if (existing.id !== namespaceId || existing.durable_objects?.namespace_id !== namespaceId || existing.scheduling_policy !== SchedulingPolicy.DURABLE_OBJECT || existing.name !== application.name) {
6854
- throw new UserError(
6855
- `The application for Durable Object namespace "${namespaceId}" does not match Container "${application.name}". The existing name, namespace, and scheduling policy must match before its settings can be applied.`,
6856
- {
6857
- telemetryMessage: "durable object container application identity mismatch"
6858
- }
6859
- );
6860
- }
6818
+ validateApplicationIdentity(application, namespaceId, existing);
6861
6819
  if (!updateExisting) {
6862
6820
  return;
6863
6821
  }
@@ -7012,7 +6970,8 @@ async function prepareDurableObjectContainerApplications(config2, durableObjectC
7012
6970
  accountId,
7013
6971
  dryRun,
7014
6972
  scriptName,
7015
- dispatchNamespace
6973
+ dispatchNamespace,
6974
+ requireExistingImageLessApplications = false
7016
6975
  }) {
7017
6976
  validateDurableObjectContainerApplications(
7018
6977
  config2,
@@ -7047,6 +7006,14 @@ async function prepareDurableObjectContainerApplications(config2, durableObjectC
7047
7006
  }
7048
7007
  }
7049
7008
  }
7009
+ if (!dryRun && requireExistingImageLessApplications) {
7010
+ assert6(accountId);
7011
+ await validateImageLessContainerApplicationsForUpload(
7012
+ config2,
7013
+ durableObjectContainerConfig,
7014
+ { accountId, scriptName }
7015
+ );
7016
+ }
7050
7017
  const containers = managedContainers.filter(
7051
7018
  (container) => Object.keys(container.images ?? {}).length > 0
7052
7019
  );
@@ -25492,25 +25459,6 @@ async function deployWorker(props, config2, buildResult, callbacks) {
25492
25459
  type: "deploy",
25493
25460
  workerExists
25494
25461
  });
25495
- if (!skipContainerChanges && keepVars && !isDryRun && workerExists) {
25496
- await clearRemovedContainerImagesBindings(
25497
- config2,
25498
- durableObjectContainerConfig,
25499
- bindings,
25500
- workerUrl
25501
- );
25502
- }
25503
- addContainerImagesBinding(
25504
- durableObjectContainerConfig,
25505
- bindings,
25506
- preparedContainerImages ?? {},
25507
- {
25508
- preserveExisting: skipContainerChanges,
25509
- exports: config2.exports,
25510
- workerExists,
25511
- hasExistingBinding: rolloutSkipContainerState?.hasExistingContainerImagesBinding
25512
- }
25513
- );
25514
25462
  if (workersSitesAssets.manifest) {
25515
25463
  modules.push({
25516
25464
  name: "__STATIC_CONTENT_MANIFEST",
@@ -25947,10 +25895,7 @@ async function uploadWorkerVersion(props, config2, buildResult, callbacks) {
25947
25895
  const { entry, compatibilityDate, compatibilityFlags, keepVars, accountId } = props;
25948
25896
  const assetsOptions = resolveAssetOptions(props, config2);
25949
25897
  const { name } = validateWorkerProps(props, config2);
25950
- const { workerTag, tags, workerExists, aborted: aborted2 } = await preUploadApiChecks(
25951
- props,
25952
- config2
25953
- );
25898
+ const { workerTag, tags, aborted: aborted2 } = await preUploadApiChecks(props, config2);
25954
25899
  if (aborted2) {
25955
25900
  return { versionId: null, workerTag };
25956
25901
  }
@@ -26000,7 +25945,8 @@ async function uploadWorkerVersion(props, config2, buildResult, callbacks) {
26000
25945
  {
26001
25946
  accountId,
26002
25947
  dryRun: Boolean(props.dryRun),
26003
- scriptName
25948
+ scriptName,
25949
+ requireExistingImageLessApplications: true
26004
25950
  }
26005
25951
  );
26006
25952
  const assetsUploadResult = assetsOptions && !props.dryRun ? await syncAssets(config2, accountId, assetsOptions.directory, scriptName) : void 0;
@@ -26019,20 +25965,6 @@ async function uploadWorkerVersion(props, config2, buildResult, callbacks) {
26019
25965
  }
26020
25966
  }
26021
25967
  addRequiredSecretsInheritBindings(config2, bindings, { type: "upload" });
26022
- if (keepVars && !props.dryRun && workerExists) {
26023
- await clearRemovedContainerImagesBindings(
26024
- config2,
26025
- durableObjectContainerConfig,
26026
- bindings,
26027
- workerUrl
26028
- );
26029
- }
26030
- addContainerImagesBinding(
26031
- durableObjectContainerConfig,
26032
- bindings,
26033
- preparedContainerImages ?? {},
26034
- { exports: config2.exports }
26035
- );
26036
25968
  const placement = parseConfigPlacement(config2.placement);
26037
25969
  const entryPointName = path__default.basename(resolvedEntryPointPath);
26038
25970
  const main = {
@@ -26220,7 +26152,9 @@ async function uploadWorkerVersion(props, config2, buildResult, callbacks) {
26220
26152
  assert6(versionId);
26221
26153
  await deployDurableObjectContainerApplications(
26222
26154
  config2,
26223
- durableObjectContainerConfig,
26155
+ durableObjectContainerConfig.filter(
26156
+ (container) => Object.keys(container.images ?? {}).length > 0
26157
+ ),
26224
26158
  {
26225
26159
  versionId,
26226
26160
  accountId,
@@ -26765,17 +26699,22 @@ function getBindingValue(binding) {
26765
26699
  }
26766
26700
  }
26767
26701
  __name(getBindingValue, "getBindingValue");
26768
- function extractConfigBindings(config2) {
26769
- const previews = config2.previews;
26702
+ function extractBindings(previews, assets, omitIdentifierlessBindings = false) {
26770
26703
  const env = {};
26771
26704
  const vars = previews?.vars ?? {};
26772
26705
  for (const [name, value] of Object.entries(vars)) {
26773
26706
  env[name] = typeof value === "string" ? { type: "plain_text", text: value } : { type: "json", json: value };
26774
26707
  }
26775
26708
  for (const kv of previews?.kv_namespaces ?? []) {
26709
+ if (omitIdentifierlessBindings && kv.id === void 0) {
26710
+ continue;
26711
+ }
26776
26712
  env[kv.binding] = { type: "kv_namespace", namespace_id: kv.id };
26777
26713
  }
26778
26714
  for (const d1 of previews?.d1_databases ?? []) {
26715
+ if (omitIdentifierlessBindings && d1.database_id === void 0) {
26716
+ continue;
26717
+ }
26779
26718
  env[d1.binding] = {
26780
26719
  type: "d1",
26781
26720
  database_id: d1.database_id,
@@ -26783,6 +26722,9 @@ function extractConfigBindings(config2) {
26783
26722
  };
26784
26723
  }
26785
26724
  for (const r2 of previews?.r2_buckets ?? []) {
26725
+ if (omitIdentifierlessBindings && r2.bucket_name === void 0) {
26726
+ continue;
26727
+ }
26786
26728
  env[r2.binding] = {
26787
26729
  type: "r2_bucket",
26788
26730
  bucket_name: r2.bucket_name,
@@ -26796,11 +26738,33 @@ function extractConfigBindings(config2) {
26796
26738
  service: service.service,
26797
26739
  environment,
26798
26740
  entrypoint: service.entrypoint,
26741
+ props: service.props,
26799
26742
  ...crossAccountGrant !== void 0 && {
26800
26743
  cross_account_grant: crossAccountGrant
26801
26744
  }
26802
26745
  };
26803
26746
  }
26747
+ for (const memory of previews?.agent_memory ?? []) {
26748
+ env[memory.binding] = {
26749
+ type: "agent_memory",
26750
+ namespace: memory.namespace
26751
+ };
26752
+ }
26753
+ for (const vpc of previews?.vpc_networks ?? []) {
26754
+ const binding = { type: "vpc_network" };
26755
+ if ("tunnel_id" in vpc) {
26756
+ binding.tunnel_id = vpc.tunnel_id;
26757
+ } else {
26758
+ binding.network_id = vpc.network_id;
26759
+ }
26760
+ env[vpc.binding] = binding;
26761
+ }
26762
+ for (const binding of previews?.logfwdr?.bindings ?? []) {
26763
+ env[binding.name] = {
26764
+ type: "logfwdr",
26765
+ destination: binding.destination
26766
+ };
26767
+ }
26804
26768
  for (const doBinding of previews?.durable_objects?.bindings ?? []) {
26805
26769
  env[doBinding.name] = {
26806
26770
  type: "durable_object_namespace",
@@ -26938,8 +26902,8 @@ function extractConfigBindings(config2) {
26938
26902
  if (previews?.version_metadata) {
26939
26903
  env[previews.version_metadata.binding] = { type: "version_metadata" };
26940
26904
  }
26941
- if (config2.assets?.binding) {
26942
- env[config2.assets.binding] = { type: "assets" };
26905
+ if (assets?.binding) {
26906
+ env[assets.binding] = { type: "assets" };
26943
26907
  }
26944
26908
  for (const binding of previews?.unsafe?.bindings ?? []) {
26945
26909
  const { name, type, ...rest } = binding;
@@ -26947,7 +26911,15 @@ function extractConfigBindings(config2) {
26947
26911
  }
26948
26912
  return env;
26949
26913
  }
26914
+ __name(extractBindings, "extractBindings");
26915
+ function extractConfigBindings(config2) {
26916
+ return extractBindings(config2.previews, config2.assets);
26917
+ }
26950
26918
  __name(extractConfigBindings, "extractConfigBindings");
26919
+ function extractBuildOutputBindings(config2) {
26920
+ return extractBindings(config2, config2.assets, true);
26921
+ }
26922
+ __name(extractBuildOutputBindings, "extractBuildOutputBindings");
26951
26923
  function getDeclaredDOClassNames(config2) {
26952
26924
  const declared = /* @__PURE__ */ new Set();
26953
26925
  for (const migration of config2.migrations ?? []) {
@@ -27017,6 +26989,14 @@ function assemblePreviewScriptSettings(config2) {
27017
26989
  return result;
27018
26990
  }
27019
26991
  __name(assemblePreviewScriptSettings, "assemblePreviewScriptSettings");
26992
+ function assertPreviewBuildOutputRootConfig(rootConfig) {
26993
+ if (rootConfig?.buildContext.isPreview !== true) {
26994
+ throw new UserError("Build Output was not created by a Preview build.", {
26995
+ telemetryMessage: "preview build output missing preview intent"
26996
+ });
26997
+ }
26998
+ }
26999
+ __name(assertPreviewBuildOutputRootConfig, "assertPreviewBuildOutputRootConfig");
27020
27000
  function buildPreviewContainerConfig(config2, parentWorkerName, previewSlug, previewContainers) {
27021
27001
  const previews = config2.previews;
27022
27002
  const previewDOBindings = previews?.durable_objects?.bindings ?? [];
@@ -27247,24 +27227,24 @@ function getPreviewMigrationsToUpload(workerName, config2, currentMigrationTag)
27247
27227
  }
27248
27228
  __name(getPreviewMigrationsToUpload, "getPreviewMigrationsToUpload");
27249
27229
  function buildResultToDeploymentModules(buildResult, assetFiles) {
27250
- const mainModuleName = path__default.basename(buildResult.resolvedEntryPointPath);
27251
- const mainContentType = moduleTypeMimeType[buildResult.bundleType] ?? "application/octet-stream";
27252
- const deploymentModules = [
27253
- {
27254
- name: mainModuleName,
27255
- content_type: mainContentType,
27256
- content: buildResult.content
27257
- },
27258
- ...buildResult.modules.map((mod) => {
27259
- const contentType = moduleTypeMimeType[mod.type ?? "text"] ?? "application/octet-stream";
27260
- return {
27230
+ let mainModuleName;
27231
+ const deploymentModules = [];
27232
+ if (buildResult) {
27233
+ mainModuleName = buildResult.mainModuleName ?? path__default.basename(buildResult.resolvedEntryPointPath);
27234
+ deploymentModules.push(
27235
+ {
27236
+ name: mainModuleName,
27237
+ content_type: moduleTypeMimeType[buildResult.bundleType] ?? "application/octet-stream",
27238
+ content: buildResult.content
27239
+ },
27240
+ ...buildResult.modules.map((mod) => ({
27261
27241
  name: mod.name,
27262
- content_type: contentType,
27242
+ content_type: moduleTypeMimeType[mod.type ?? "text"] ?? "application/octet-stream",
27263
27243
  content: mod.content
27264
- };
27265
- })
27266
- ];
27267
- if (buildResult.sourceMaps) {
27244
+ }))
27245
+ );
27246
+ }
27247
+ if (buildResult?.sourceMaps) {
27268
27248
  deploymentModules.push(
27269
27249
  ...buildResult.sourceMaps.map((sourceMap) => ({
27270
27250
  name: sourceMap.name,
@@ -27297,8 +27277,12 @@ async function assemblePreviewDeploymentSettings(config2, buildResult, accountId
27297
27277
  _headers: options.assetsOptions?._headers,
27298
27278
  _redirects: options.assetsOptions?._redirects
27299
27279
  });
27300
- request.main_module = deploymentModules.main_module;
27301
- request.modules = deploymentModules.modules;
27280
+ if (deploymentModules.main_module !== void 0) {
27281
+ request.main_module = deploymentModules.main_module;
27282
+ }
27283
+ if (deploymentModules.modules.length > 0) {
27284
+ request.modules = deploymentModules.modules;
27285
+ }
27302
27286
  if (options.assetsOptions) {
27303
27287
  const assetsUploadResult = await syncAssets(
27304
27288
  config2,
@@ -27491,8 +27475,7 @@ async function provisionParentWorker(config2, accountId, workerName, json2) {
27491
27475
  );
27492
27476
  }
27493
27477
  __name(provisionParentWorker, "provisionParentWorker");
27494
- async function preview(accountId, args, config2, buildResult, assetsOptions, callbacks) {
27495
- const workerName = resolveWorkerName(args, config2);
27478
+ async function runPreview(accountId, args, config2, buildResult, assetsOptions, callbacks, workerName, replaceTailConsumersAfterCreate = false) {
27496
27479
  let secrets;
27497
27480
  if (args.secretsFile) {
27498
27481
  secrets = (await parseBulkInputToObject(args.secretsFile))?.content;
@@ -27535,17 +27518,26 @@ async function preview(accountId, args, config2, buildResult, assetsOptions, cal
27535
27518
  }
27536
27519
  }
27537
27520
  const isNewPreview = !existingPreview;
27521
+ const previewRequest = assemblePreviewScriptSettings(config2);
27538
27522
  let previewResource;
27539
27523
  if (isNewPreview) {
27540
27524
  previewResource = await createPreview(
27541
27525
  config2,
27542
27526
  accountId,
27543
27527
  workerName,
27544
- { name: previewName, ...assemblePreviewScriptSettings(config2) },
27528
+ { name: previewName, ...previewRequest },
27545
27529
  { ignoreBaseConfig }
27546
27530
  );
27531
+ if (replaceTailConsumersAfterCreate && previewRequest.tail_consumers !== void 0) {
27532
+ previewResource = await editPreview(
27533
+ config2,
27534
+ accountId,
27535
+ workerName,
27536
+ previewIdentifier,
27537
+ { tail_consumers: previewRequest.tail_consumers }
27538
+ );
27539
+ }
27547
27540
  } else {
27548
- const previewRequest = assemblePreviewScriptSettings(config2);
27549
27541
  if (Object.keys(previewRequest).length > 0) {
27550
27542
  previewResource = await editPreview(
27551
27543
  config2,
@@ -27639,7 +27631,127 @@ async function preview(accountId, args, config2, buildResult, assetsOptions, cal
27639
27631
  }
27640
27632
  return { preview: previewResource, deployment, isNewPreview };
27641
27633
  }
27634
+ __name(runPreview, "runPreview");
27635
+ async function preview(accountId, args, config2, buildResult, assetsOptions, callbacks) {
27636
+ return runPreview(
27637
+ accountId,
27638
+ args,
27639
+ config2,
27640
+ buildResult,
27641
+ assetsOptions,
27642
+ callbacks,
27643
+ resolveWorkerName(args, config2)
27644
+ );
27645
+ }
27642
27646
  __name(preview, "preview");
27647
+ async function previewBuildOutput(accountId, args, buildOutput) {
27648
+ const { workerConfig, rootConfig, buildResult, assets } = buildOutput;
27649
+ assertPreviewBuildOutputRootConfig(rootConfig);
27650
+ if (workerConfig.domains?.length) {
27651
+ throw new UserError(
27652
+ "Preview uploads from Build Output don't support the `domains` field.",
27653
+ {
27654
+ telemetryMessage: "preview build output custom domains not supported"
27655
+ }
27656
+ );
27657
+ }
27658
+ if (workerConfig.triggers?.length) {
27659
+ throw new UserError(
27660
+ "Preview uploads from Build Output don't support the `triggers` field.",
27661
+ {
27662
+ telemetryMessage: "preview build output triggers not supported"
27663
+ }
27664
+ );
27665
+ }
27666
+ if (workerConfig.tailConsumers?.some((consumer) => consumer.streaming)) {
27667
+ throw new UserError(
27668
+ "Preview uploads from Build Output don't support streaming tail consumers.",
27669
+ {
27670
+ telemetryMessage: "preview build output streaming tail consumer not supported"
27671
+ }
27672
+ );
27673
+ }
27674
+ if (Object.values(workerConfig.exports ?? {}).some(
27675
+ (configExport) => "container" in configExport && configExport.container !== void 0
27676
+ )) {
27677
+ throw new UserError(
27678
+ "Preview uploads from Build Output don't support Container-backed Durable Objects.",
27679
+ {
27680
+ telemetryMessage: "preview build output containers not supported"
27681
+ }
27682
+ );
27683
+ }
27684
+ if (workerConfig.unsafe?.capnp !== void 0 || Object.keys(workerConfig.unsafe?.metadata ?? {}).length > 0) {
27685
+ throw new UserError(
27686
+ "Preview uploads from Build Output don't support unsafe metadata or Cap'n Proto schemas.",
27687
+ {
27688
+ telemetryMessage: "preview build output unsafe settings not supported"
27689
+ }
27690
+ );
27691
+ }
27692
+ const { buildContext: _buildContext, ...settings } = rootConfig;
27693
+ const { manifest: _manifest, ...worker } = workerConfig;
27694
+ const convertedConfig = convertToWranglerConfig({
27695
+ ...settings,
27696
+ worker,
27697
+ // TODO: Add support for Containers in Preview uploads from Build Output.
27698
+ containers: []
27699
+ });
27700
+ const previewBuildResult = buildResult && {
27701
+ ...buildResult,
27702
+ mainModuleName: workerConfig.manifest?.mainModule
27703
+ };
27704
+ const bindings = extractBuildOutputBindings(convertedConfig);
27705
+ const previewConfig = {
27706
+ ...defaultWranglerConfig,
27707
+ compliance_region: convertedConfig.compliance_region,
27708
+ name: workerConfig.name,
27709
+ compatibility_date: convertedConfig.compatibility_date,
27710
+ compatibility_flags: convertedConfig.compatibility_flags ?? [],
27711
+ exports: convertedConfig.exports ?? {},
27712
+ limits: convertedConfig.limits,
27713
+ cache: convertedConfig.cache,
27714
+ placement: convertedConfig.placement,
27715
+ observability: convertedConfig.observability,
27716
+ logpush: convertedConfig.logpush,
27717
+ workers_dev: false,
27718
+ preview_urls: true,
27719
+ previews: {
27720
+ tail_consumers: convertedConfig.tail_consumers ?? (workerConfig.tailConsumers === void 0 ? void 0 : []),
27721
+ unsafe: {
27722
+ bindings: Object.entries(bindings).map(([name, binding]) => ({
27723
+ name,
27724
+ ...binding
27725
+ }))
27726
+ }
27727
+ },
27728
+ assets: convertedConfig.assets
27729
+ };
27730
+ const assetsOptions = assets && {
27731
+ ...assets,
27732
+ _headers: assets._headers ?? maybeGetFile(path__default.join(assets.directory, "_headers")),
27733
+ _redirects: assets._redirects ?? maybeGetFile(path__default.join(assets.directory, "_redirects")),
27734
+ assetConfig: {
27735
+ html_handling: convertedConfig.assets?.html_handling,
27736
+ not_found_handling: convertedConfig.assets?.not_found_handling
27737
+ },
27738
+ run_worker_first: convertedConfig.assets?.run_worker_first
27739
+ };
27740
+ return runPreview(
27741
+ accountId,
27742
+ { ...args, ignoreBaseConfig: false },
27743
+ previewConfig,
27744
+ previewBuildResult,
27745
+ assetsOptions,
27746
+ {
27747
+ getNormalizedContainerOptions: void 0,
27748
+ deployPreviewContainers: void 0
27749
+ },
27750
+ workerConfig.name,
27751
+ true
27752
+ );
27753
+ }
27754
+ __name(previewBuildOutput, "previewBuildOutput");
27643
27755
  async function previewDelete(accountId, args, config2) {
27644
27756
  const workerName = resolveWorkerName(args, config2);
27645
27757
  let previewName = args.name;
@@ -27819,4 +27931,4 @@ __name(formatBindings, "formatBindings");
27819
27931
  * THE SOFTWARE.
27820
27932
  */
27821
27933
 
27822
- export { ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE, EXPORTS_RECONCILIATION_ERROR_CODE, INCONSISTENT_EXPORTS_ACROSS_VERSIONS_CODE, INVALID_INHERIT_BINDING_CODE, NO_ACTIVE_PREVIEW_URLS_MESSAGE, NoInputError, PREVIEW_DOMAIN_PROVISIONING_NOTE, WORKER_LEGACY_ENVIRONMENT_NOT_FOUND_ERR_CODE, WORKER_NOT_FOUND_ERR_CODE, WORKFLOW_CRON_REQUIRES_PAID_PLAN_CODE, WORKFLOW_NOT_FOUND_CODE, addRequiredSecretsInheritBindings, addWorkersSitesBindings, applyServiceAndEnvironmentTags, assemblePreviewScriptSettings, buildAssetManifest, checkRemoteSecretsOverride, checkWorkflowConflicts, collectPackageDependencies, confirmLatestDeploymentOverwrite, createDeployment, createDurableObjectContainerApplication, createPreview, createPreviewDeployment, createPreviewDeploymentForm, createPreviewParentWorker, createTruncatedAlias, decodeJwtPayload, deletePreview, deletePullConsumer, deleteWorkerConsumer, deploy, deployDurableObjectContainerApplications, deployVersionedDurableObjectContainerApplications, deployWfpUserWorker, diagnoseScriptSizeError, diagnoseStartupError, diffJsonObjects, downloadWorkerConfig, drawBox, drawConnectedChildBox, editPreview, ensureQueuesExistByConfig, extractConfigBindings, fetchDeployableVersions, fetchDeploymentVersions, fetchLatestDeployment, fetchLatestDeployments, fetchSecrets, fetchVersion, fetchVersions, fetchWorkerConfig, formatAlignedRows, formatBindings, formatNoActivePreviewUrlsMessage, generatePreviewAlias, getBindingValue, getBranchName2 as getBranchName, getCommitSha, getConfigPatch, getDeployConfirmFunction, getEdgeKvUploadConcurrency, getHeadCommitMessage, getHeadCommitRef, getMigrationsToUpload, getPreview, getPreviewBaseConfig, getPreviewDeployment, getPreviewOwnedContainerClassNames, getPullRequestMetadata, getQueue, getRemoteConfigDiff, getRepositoryUrl, getSettings, getSize, getSourceMappedStack, getSourceMappedString, getSubdomainValues, getSubdomainValuesAPIMock, getVersionedDurableObjectContainerApplications, getWorkersDevSubdomain, getZoneForRoute, getZoneIdFromHost, handleMissingSecretsError, hasDefinedEnvironments, hashFile, helpIfErrorIsSizeOrScriptStartup, isExportsReconciliationErrorDetails, isJwtExpired, isModifiedDiffValue, isNonDestructive, isWorkerNotFoundError, listConsumers, listQueues, maybeRetrieveFileSourceMap, padToVisibleWidth, parseBulkInputToObject, parseConfigPlacement, patchNonVersionedScriptSettings, patchPreviewBaseConfig, patchPreviewDeployment, postConsumer, prepareDurableObjectContainerApplications, preview, previewContainerAppName, previewDelete, printBundleSize, printVersions, provisionBindings, publishCustomDomains, publishRoutes, putConsumer, putConsumerById, renderBindingDependsOnExportError, renderExportsReconciliationError, renderExportsReconciliationSuccess, renderInconsistentExportsAcrossVersionsError, renderRoute, resolveAssetOptions, resolveDoLifecyclePayload, resolveExportsUploadPayload, resolveVersionedDurableObjectContainerApplications, resolveWorkerName, sanitizeBranchName, shouldUseCIMetadataFallback, stripAnsi, syncAssets, tagsAreEqual, triggersDeploy, updateQueueConsumers, validateEventTriggerTargets, validateFileSecrets, validateNodeCompatMode, validateRoutes, verifyWorkerMatchesCITag, versionsUpload, visibleLength, warnOnErrorUpdatingServiceAndEnvironmentTags, workerNotFoundErrorMessage };
27934
+ export { ACTOR_BINDING_DEPENDS_ON_EXPORT_CODE, EXPORTS_RECONCILIATION_ERROR_CODE, INCONSISTENT_EXPORTS_ACROSS_VERSIONS_CODE, INVALID_INHERIT_BINDING_CODE, NO_ACTIVE_PREVIEW_URLS_MESSAGE, NoInputError, PREVIEW_DOMAIN_PROVISIONING_NOTE, WORKER_LEGACY_ENVIRONMENT_NOT_FOUND_ERR_CODE, WORKER_NOT_FOUND_ERR_CODE, WORKFLOW_CRON_REQUIRES_PAID_PLAN_CODE, WORKFLOW_NOT_FOUND_CODE, addRequiredSecretsInheritBindings, addWorkersSitesBindings, applyServiceAndEnvironmentTags, assemblePreviewScriptSettings, assertPreviewBuildOutputRootConfig, buildAssetManifest, checkRemoteSecretsOverride, checkWorkflowConflicts, collectPackageDependencies, confirmLatestDeploymentOverwrite, createDeployment, createDurableObjectContainerApplication, createPreview, createPreviewDeployment, createPreviewDeploymentForm, createPreviewParentWorker, createTruncatedAlias, decodeJwtPayload, deletePreview, deletePullConsumer, deleteWorkerConsumer, deploy, deployDurableObjectContainerApplications, deployVersionedDurableObjectContainerApplications, deployWfpUserWorker, diagnoseScriptSizeError, diagnoseStartupError, diffJsonObjects, downloadWorkerConfig, drawBox, drawConnectedChildBox, editPreview, ensureQueuesExistByConfig, extractBuildOutputBindings, extractConfigBindings, fetchDeployableVersions, fetchDeploymentVersions, fetchLatestDeployment, fetchLatestDeployments, fetchSecrets, fetchVersion, fetchVersions, fetchWorkerConfig, formatAlignedRows, formatBindings, formatNoActivePreviewUrlsMessage, generatePreviewAlias, getBindingValue, getBranchName2 as getBranchName, getCommitSha, getConfigPatch, getDeployConfirmFunction, getEdgeKvUploadConcurrency, getHeadCommitMessage, getHeadCommitRef, getMigrationsToUpload, getPreview, getPreviewBaseConfig, getPreviewDeployment, getPreviewOwnedContainerClassNames, getPullRequestMetadata, getQueue, getRemoteConfigDiff, getRepositoryUrl, getSettings, getSize, getSourceMappedStack, getSourceMappedString, getSubdomainValues, getSubdomainValuesAPIMock, getVersionedDurableObjectContainerApplications, getWorkersDevSubdomain, getZoneForRoute, getZoneIdFromHost, handleMissingSecretsError, hasDefinedEnvironments, hashFile, helpIfErrorIsSizeOrScriptStartup, isExportsReconciliationErrorDetails, isJwtExpired, isModifiedDiffValue, isNonDestructive, isWorkerNotFoundError, listConsumers, listQueues, maybeRetrieveFileSourceMap, padToVisibleWidth, parseBulkInputToObject, parseConfigPlacement, patchNonVersionedScriptSettings, patchPreviewBaseConfig, patchPreviewDeployment, postConsumer, prepareDurableObjectContainerApplications, preview, previewBuildOutput, previewContainerAppName, previewDelete, printBundleSize, printVersions, provisionBindings, publishCustomDomains, publishRoutes, putConsumer, putConsumerById, renderBindingDependsOnExportError, renderExportsReconciliationError, renderExportsReconciliationSuccess, renderInconsistentExportsAcrossVersionsError, renderRoute, resolveAssetOptions, resolveDoLifecyclePayload, resolveExportsUploadPayload, resolveVersionedDurableObjectContainerApplications, resolveWorkerName, sanitizeBranchName, shouldUseCIMetadataFallback, stripAnsi, syncAssets, tagsAreEqual, triggersDeploy, updateQueueConsumers, validateEventTriggerTargets, validateFileSecrets, validateImageLessContainerApplicationsForUpload, validateNodeCompatMode, validateRoutes, verifyWorkerMatchesCITag, versionsUpload, visibleLength, warnOnErrorUpdatingServiceAndEnvironmentTags, workerNotFoundErrorMessage };