@vercel/container 27.0.0 → 29.0.0-snapshot-c9dfd83f2293

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.
Files changed (49) hide show
  1. package/dist/build-context.d.ts +7 -0
  2. package/dist/buildah-store-cache/cache.d.ts +30 -0
  3. package/dist/buildah-store-cache/cleanup.d.ts +2 -0
  4. package/dist/buildah-store-cache/command/index.d.ts +9 -0
  5. package/dist/buildah-store-cache/command/main.d.ts +1 -0
  6. package/dist/buildah-store-cache/command/operations.d.ts +13 -0
  7. package/dist/buildah-store-cache/command/types.d.ts +53 -0
  8. package/dist/buildah-store-cache/config.d.ts +5 -0
  9. package/dist/buildah-store-cache/lock.d.ts +17 -0
  10. package/dist/buildah-store-cache/state.d.ts +8 -0
  11. package/dist/buildah-store-cache/usage.d.ts +14 -0
  12. package/dist/buildah-store-command.js +2 -0
  13. package/dist/buildpacks/build.d.ts +14 -0
  14. package/dist/buildpacks/cache.d.ts +55 -0
  15. package/dist/buildpacks/distribution.d.ts +71 -0
  16. package/dist/buildpacks/go.d.ts +12 -0
  17. package/dist/buildpacks/lifecycle/build-user.d.ts +1 -0
  18. package/dist/buildpacks/lifecycle/buildah.d.ts +10 -0
  19. package/dist/buildpacks/lifecycle/docker.d.ts +19 -0
  20. package/dist/buildpacks/lifecycle/lifecycle.d.ts +161 -0
  21. package/dist/buildpacks/lifecycle/native.d.ts +58 -0
  22. package/dist/buildpacks/node-toolchain.d.ts +19 -0
  23. package/dist/buildpacks/registry.d.ts +54 -0
  24. package/dist/buildpacks/ruby.d.ts +25 -0
  25. package/dist/buildpacks/rust.d.ts +2 -0
  26. package/dist/buildpacks/version.d.ts +1 -0
  27. package/dist/clients/buildah.d.ts +31 -0
  28. package/dist/dev.d.ts +14 -0
  29. package/dist/diagnostics.d.ts +8 -0
  30. package/dist/engines/buildah.d.ts +10 -0
  31. package/dist/engines/docker.d.ts +2 -0
  32. package/dist/engines/index.d.ts +11 -0
  33. package/dist/engines/types.d.ts +84 -0
  34. package/dist/executable-image/index.d.ts +52 -0
  35. package/dist/image-source.d.ts +19 -0
  36. package/dist/index.d.ts +15 -0
  37. package/dist/index.js +1740 -405
  38. package/dist/oci-layout/index.d.ts +18 -0
  39. package/dist/oci-layout/layout.d.ts +40 -0
  40. package/dist/oci-layout/pull.d.ts +37 -0
  41. package/dist/oidc.d.ts +30 -0
  42. package/dist/prepare-cache.d.ts +7 -0
  43. package/dist/publish.d.ts +37 -0
  44. package/dist/registry.d.ts +27 -0
  45. package/dist/schedules-command-dispatcher +0 -0
  46. package/dist/schedules-command.d.ts +11 -0
  47. package/dist/storage-driver.d.ts +15 -0
  48. package/dist/util.d.ts +102 -0
  49. package/package.json +6 -5
package/dist/index.js CHANGED
@@ -31,6 +31,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
33
  CONTAINER_OUTPUT_PATH: () => CONTAINER_OUTPUT_PATH,
34
+ ExecutableImageBuilder: () => ExecutableImageBuilder,
34
35
  build: () => build,
35
36
  diagnostics: () => diagnostics,
36
37
  prepareCache: () => prepareCache,
@@ -38,7 +39,7 @@ __export(src_exports, {
38
39
  version: () => version
39
40
  });
40
41
  module.exports = __toCommonJS(src_exports);
41
- var import_build_utils9 = require("@vercel/build-utils");
42
+ var import_build_utils11 = require("@vercel/build-utils");
42
43
 
43
44
  // src/schedules-command.ts
44
45
  var import_promises = require("fs/promises");
@@ -105,8 +106,8 @@ async function generateProjectManifest({
105
106
  var diagnostics = (options) => (0, import_build_utils.createDiagnostics)(manifestSlot(options.config?.daemon?.name))(options);
106
107
 
107
108
  // src/index.ts
108
- var import_node_fs17 = require("fs");
109
- var import_node_path24 = __toESM(require("path"));
109
+ var import_promises14 = require("fs/promises");
110
+ var import_node_path30 = __toESM(require("path"));
110
111
 
111
112
  // src/util.ts
112
113
  var import_build_utils2 = require("@vercel/build-utils");
@@ -164,6 +165,13 @@ function shortDigest(digest) {
164
165
  function delay(ms) {
165
166
  return new Promise((resolve5) => setTimeout(resolve5, ms));
166
167
  }
168
+ async function settleAll(tasks) {
169
+ for (const task of await Promise.allSettled(tasks)) {
170
+ if (task.status === "rejected") {
171
+ throw task.reason;
172
+ }
173
+ }
174
+ }
167
175
  async function withSpan(parent, name, attrs, fn) {
168
176
  if (!parent) {
169
177
  return fn(void 0);
@@ -200,6 +208,8 @@ function run(cmd, args, opts = {}) {
200
208
  const child = (0, import_node_child_process.spawn)(cmd, args, {
201
209
  cwd: opts.cwd,
202
210
  env: opts.env,
211
+ ...opts.uid !== void 0 && { uid: opts.uid },
212
+ ...opts.gid !== void 0 && { gid: opts.gid },
203
213
  stdio: [opts.input !== void 0 ? "pipe" : "ignore", "pipe", "pipe"]
204
214
  });
205
215
  let stdout = "";
@@ -271,6 +281,37 @@ function extractField(text, label) {
271
281
  function isBuildContainer() {
272
282
  return Boolean(readString(process.env.VERCEL_BUILD_IMAGE));
273
283
  }
284
+ var DEFAULT_API_URL = "https://api.vercel.com";
285
+ var DEFAULT_VCR_REGISTRY = "vcr.vercel.com";
286
+ function isVercelHostname(hostname) {
287
+ return hostname === "vercel.com" || hostname.endsWith(".vercel.com");
288
+ }
289
+ function resolveApiUrl() {
290
+ const configured = readString(process.env.VERCEL_API_URL);
291
+ if (!configured)
292
+ return DEFAULT_API_URL;
293
+ let url;
294
+ try {
295
+ url = new URL(configured);
296
+ } catch {
297
+ url = void 0;
298
+ }
299
+ if (url && url.protocol === "https:" && isVercelHostname(url.hostname)) {
300
+ return url.origin;
301
+ }
302
+ debug(`ignoring VERCEL_API_URL "${configured}"`);
303
+ return DEFAULT_API_URL;
304
+ }
305
+ function resolveVcrRegistry() {
306
+ const configured = readString(process.env.VERCEL_VCR_REGISTRY);
307
+ if (!configured)
308
+ return DEFAULT_VCR_REGISTRY;
309
+ if (/^[a-z0-9.-]+$/i.test(configured) && isVercelHostname(configured)) {
310
+ return configured;
311
+ }
312
+ debug(`ignoring VERCEL_VCR_REGISTRY "${configured}"`);
313
+ return DEFAULT_VCR_REGISTRY;
314
+ }
274
315
  function existingRegistryAuthFile() {
275
316
  const explicit = readString(process.env.REGISTRY_AUTH_FILE);
276
317
  if (explicit) {
@@ -534,7 +575,7 @@ function resolveProjectContext(token) {
534
575
  };
535
576
  }
536
577
  async function mintProjectOidcToken(params) {
537
- const apiUrl = (readString(process.env.VERCEL_API_URL) ?? "https://api.vercel.com").replace(/\/+$/, "");
578
+ const apiUrl = resolveApiUrl();
538
579
  const query = new URLSearchParams({ source: "vercel-container-build" });
539
580
  if (params.teamId) {
540
581
  query.set("teamId", params.teamId);
@@ -616,7 +657,7 @@ function formatVcrAuthError(registry, username, detail) {
616
657
  }
617
658
 
618
659
  // src/engines/types.ts
619
- var VCR_REGISTRY = process.env.VERCEL_VCR_REGISTRY || "vcr.vercel.com";
660
+ var VCR_REGISTRY = resolveVcrRegistry();
620
661
  var TARGET_PLATFORM = "linux/amd64";
621
662
  var DIGEST_RE = /^sha256:[a-f0-9]{64}$/;
622
663
  function buildArgFlags(params) {
@@ -629,6 +670,9 @@ function buildArgFlags(params) {
629
670
  function buildTargetFlags(params) {
630
671
  return params.buildTarget ? ["--target", params.buildTarget] : [];
631
672
  }
673
+ function exportsLayouts(engine) {
674
+ return engine.exportLayout !== void 0;
675
+ }
632
676
 
633
677
  // src/registry.ts
634
678
  async function resolveRegistryTarget(params) {
@@ -753,7 +797,7 @@ async function ensureRepository(repository, token, claims, span) {
753
797
  return;
754
798
  }
755
799
  span?.setAttributes({ "team.id": teamId, "project.id": projectId });
756
- const apiUrl = (readString(process.env.VERCEL_API_URL) ?? "https://api.vercel.com").replace(/\/+$/, "");
800
+ const apiUrl = resolveApiUrl();
757
801
  const url = `${apiUrl}/v1/vcr/repository?teamId=${encodeURIComponent(teamId)}`;
758
802
  const body = JSON.stringify({ name: repository, projectId });
759
803
  step(`Ensuring registry repository "${repository}"`);
@@ -786,6 +830,15 @@ async function ensureRepository(repository, token, claims, span) {
786
830
  }
787
831
 
788
832
  // src/engines/buildah.ts
833
+ var ZSTD_OCI_ARGS = [
834
+ "--compression-format",
835
+ "zstd",
836
+ "--compression-level",
837
+ "3",
838
+ "--force-compression",
839
+ "--format",
840
+ "oci"
841
+ ];
789
842
  function localImageRef(params) {
790
843
  const { imageRef } = params;
791
844
  if (!params.useBuildahStoreCache) {
@@ -992,15 +1045,7 @@ ${stderr}`)
992
1045
  const digestDir = (0, import_node_fs3.mkdtempSync)((0, import_node_path6.join)((0, import_node_os5.tmpdir)(), "vercel-container-digest-"));
993
1046
  const digestFile = (0, import_node_path6.join)(digestDir, "digest");
994
1047
  const zstdEnabled = !readString(process.env.VERCEL_VCR_DISABLE_ZSTD);
995
- const zstdArgs = zstdEnabled ? [
996
- "--compression-format",
997
- "zstd",
998
- "--compression-level",
999
- "3",
1000
- "--force-compression",
1001
- "--format",
1002
- "oci"
1003
- ] : [];
1048
+ const zstdArgs = zstdEnabled ? ZSTD_OCI_ARGS : [];
1004
1049
  info(
1005
1050
  `pushing ${params.imageRef} ` + (zstdEnabled ? "with zstd compression (level=3, force, oci)" : "with default compression (zstd disabled)")
1006
1051
  );
@@ -1044,6 +1089,14 @@ ${stderr}`)
1044
1089
  `--digestfile did not contain a digest (${JSON.stringify(digest)}) \u2014 resolving registry manifest`
1045
1090
  );
1046
1091
  return resolvePushedImageDigest(params);
1092
+ },
1093
+ async exportLayout(params, directory) {
1094
+ await client.run([
1095
+ "push",
1096
+ ...ZSTD_OCI_ARGS,
1097
+ localImageRef(params),
1098
+ `oci:${directory}`
1099
+ ]);
1047
1100
  }
1048
1101
  };
1049
1102
  }
@@ -1678,6 +1731,11 @@ var distribution_default = {
1678
1731
  id: "vercel/rust",
1679
1732
  version: "0.5.0",
1680
1733
  sha256: "f0f038437829d45077c8ad31060cd2274b80c3c55acfbe00ca937ea7dddfad5c"
1734
+ },
1735
+ "prebuilt-static": {
1736
+ id: "vercel/prebuilt-static",
1737
+ version: "0.1.0",
1738
+ sha256: "edcc2674706ce7fdc69a2cedfa4aaba4743ede3bc930fffe5cdb9d4b1a53e81a"
1681
1739
  }
1682
1740
  },
1683
1741
  images: {
@@ -1815,23 +1873,48 @@ var BUILD_USER_ID = 1001;
1815
1873
  var BUILD_GROUP_ID = 1001;
1816
1874
  var BUILD_USER = `${BUILD_USER_ID}:${BUILD_GROUP_ID}`;
1817
1875
  var CNB_PLATFORM_API = "0.15";
1818
- var CREATOR_KEYCHAIN_ENV_ARGS = [
1819
- "--env",
1820
- "CNB_REGISTRY_AUTH_KEYCHAIN_SKIP_AMAZON=true",
1821
- "--env",
1822
- "CNB_REGISTRY_AUTH_KEYCHAIN_SKIP_AZURE=true"
1823
- ];
1876
+ var CREATOR_KEYCHAIN_ENV = {
1877
+ CNB_REGISTRY_AUTH_KEYCHAIN_SKIP_AMAZON: "true",
1878
+ CNB_REGISTRY_AUTH_KEYCHAIN_SKIP_AZURE: "true"
1879
+ };
1880
+ var CREATOR_KEYCHAIN_ENV_ARGS = Object.entries(
1881
+ CREATOR_KEYCHAIN_ENV
1882
+ ).flatMap(([name, value]) => ["--env", `${name}=${value}`]);
1824
1883
  var ORDER_MOUNT_DIR = "/platform/order";
1825
1884
  var ORDER_FILE = `${ORDER_MOUNT_DIR}/order.toml`;
1826
1885
  var CACHE_MOUNT_DIR = "/cache";
1827
1886
  var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
1828
- async function stageWorkspace({ files, workPath }, destinationDir) {
1887
+ async function stageWorkspace({
1888
+ files,
1889
+ workPath,
1890
+ repoRootPath
1891
+ }, destinationDir) {
1892
+ const repoRoot = (0, import_node_path8.resolve)(repoRootPath ?? workPath);
1893
+ const serviceRoot = (0, import_node_path8.resolve)(workPath);
1894
+ const serviceRelative = (0, import_node_path8.relative)(repoRoot, serviceRoot);
1895
+ if ((0, import_node_fs5.lstatSync)(serviceRoot).isSymbolicLink()) {
1896
+ throw new Error(
1897
+ "Buildpack service root must not be reached through a symbolic link."
1898
+ );
1899
+ }
1900
+ if (serviceRelative && serviceRelative !== "." && serviceRelative !== ".." && !serviceRelative.startsWith(`..${import_node_path8.sep}`) && !(0, import_node_path8.isAbsolute)(serviceRelative)) {
1901
+ let current = repoRoot;
1902
+ for (const part of serviceRelative.split(import_node_path8.sep)) {
1903
+ if (!part || part === ".")
1904
+ continue;
1905
+ current = (0, import_node_path8.join)(current, part);
1906
+ if ((0, import_node_fs5.lstatSync)(current).isSymbolicLink()) {
1907
+ throw new Error(
1908
+ "Buildpack service root must not be reached through a symbolic link."
1909
+ );
1910
+ }
1911
+ }
1912
+ }
1829
1913
  const staged = /* @__PURE__ */ Object.create(null);
1830
1914
  const symlinks = /* @__PURE__ */ new Set();
1831
1915
  for (const [name, file] of Object.entries(files)) {
1832
- const portable = name.replace(/\\/g, "/");
1833
- const normalized = import_node_path8.posix.normalize(portable).replace(/\/$/, "");
1834
- if (!normalized || normalized === "." || import_node_path8.win32.isAbsolute(name) || import_node_path8.posix.isAbsolute(portable) || portable.split("/").includes("..") || normalized in staged) {
1916
+ const normalized = import_node_path8.posix.normalize(name).replace(/\/$/, "");
1917
+ if (!normalized || normalized === "." || name.includes("\\") || import_node_path8.win32.isAbsolute(name) || import_node_path8.posix.isAbsolute(name) || name.split("/").includes("..") || normalized in staged) {
1835
1918
  throw new Error(`Invalid buildpack source path ${JSON.stringify(name)}.`);
1836
1919
  }
1837
1920
  staged[normalized] = file;
@@ -1851,7 +1934,13 @@ async function stageWorkspace({ files, workPath }, destinationDir) {
1851
1934
  `Buildpack source symlink ${name} has an absolute target.`
1852
1935
  );
1853
1936
  }
1854
- target = target.replace(/\\/g, "/");
1937
+ if (import_node_path8.sep === "\\") {
1938
+ target = target.replace(/\\/g, "/");
1939
+ } else if (target.includes("\\")) {
1940
+ throw new Error(
1941
+ `Buildpack source symlink ${name} has a target staging would reinterpret.`
1942
+ );
1943
+ }
1855
1944
  const resolved = import_node_path8.posix.join(import_node_path8.posix.dirname(normalized), target);
1856
1945
  if (resolved === ".." || resolved.startsWith("../")) {
1857
1946
  throw new Error(
@@ -1990,7 +2079,7 @@ function lifecycleFailure(error, context) {
1990
2079
  return Object.assign(
1991
2080
  new Error(
1992
2081
  [
1993
- `${context.buildpack.runtime} buildpack build failed via ${context.via} (${context.buildImage}).`,
2082
+ `${context.buildpack.runtime} buildpack build failed via ${context.via}${context.buildImage ? ` (${context.buildImage})` : ""}.`,
1994
2083
  ...hint ? [`The lifecycle exited with code ${exitCode}: ${hint}.`] : [],
1995
2084
  "",
1996
2085
  `Underlying error: ${error.message}`,
@@ -2024,6 +2113,24 @@ function cnbRegistryAuth(credentials) {
2024
2113
  const basic = Buffer.from(`${username}:${token}`).toString("base64");
2025
2114
  return JSON.stringify({ [registry]: `Basic ${basic}` });
2026
2115
  }
2116
+ function creatorExport(target) {
2117
+ if (target.kind === "oci-layout") {
2118
+ return {
2119
+ args: ["-layout", `-layout-dir=${target.layoutDir}`, target.imageRef],
2120
+ // lifecycle 0.21.18 guards `-layout` behind experimental mode and fails
2121
+ // when it is unset. `quiet` allows it without logging a warning into
2122
+ // every build.
2123
+ env: { CNB_EXPERIMENTAL_MODE: "quiet" }
2124
+ };
2125
+ }
2126
+ return {
2127
+ args: [target.imageRef],
2128
+ env: {
2129
+ CNB_REGISTRY_AUTH: cnbRegistryAuth(target.credentials),
2130
+ ...CREATOR_KEYCHAIN_ENV
2131
+ }
2132
+ };
2133
+ }
2027
2134
  function distributionUrls(buildpack) {
2028
2135
  return {
2029
2136
  lifecycle: LIFECYCLE.url,
@@ -2732,14 +2839,14 @@ var import_node_crypto7 = require("crypto");
2732
2839
  var import_node_fs8 = require("fs");
2733
2840
  var import_node_os9 = require("os");
2734
2841
  var import_node_path13 = require("path");
2735
- function localBuildImageDockerfile(buildImage, nodeMajor) {
2842
+ function localBuildImageDockerfile(buildImage2, nodeMajor) {
2736
2843
  const lines = [];
2737
2844
  if (nodeMajor !== void 0) {
2738
2845
  lines.push(
2739
2846
  `FROM docker.io/library/node:${nodeMajor}-bookworm-slim AS node`
2740
2847
  );
2741
2848
  }
2742
- lines.push(`FROM ${buildImage}`, "USER 0:0");
2849
+ lines.push(`FROM ${buildImage2}`, "USER 0:0");
2743
2850
  if (nodeMajor !== void 0) {
2744
2851
  lines.push(`COPY --from=node /usr/local /node${nodeMajor}`);
2745
2852
  }
@@ -3410,6 +3517,15 @@ async function buildAndPushBuildpack(params) {
3410
3517
  var import_node_fs15 = require("fs");
3411
3518
  var import_node_path20 = __toESM(require("path"));
3412
3519
  var DETECT_SENTINEL = "<detect>";
3520
+ var IMAGE_REFERENCE_PATTERN = /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*(?::[0-9]+)?\/)?[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*)*(?::[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127})?(?:@[a-zA-Z][a-zA-Z0-9]*(?:[-_.+][a-zA-Z][a-zA-Z0-9]*)*:[0-9a-fA-F]{32,})?$/;
3521
+ function assertValidImageReference(imageRef) {
3522
+ if (!IMAGE_REFERENCE_PATTERN.test(imageRef)) {
3523
+ throw new Error(
3524
+ `Prebuilt image reference "${imageRef}" is not a valid Docker image reference, e.g. "docker.io/library/nginx:1.27".`
3525
+ );
3526
+ }
3527
+ return imageRef;
3528
+ }
3413
3529
  function resolveImageSource(options, context) {
3414
3530
  const { config, workPath, entrypoint } = options;
3415
3531
  const entrypointRef = readString(entrypoint);
@@ -3420,6 +3536,13 @@ function resolveImageSource(options, context) {
3420
3536
  "Buildpack builds are selected by Vercel from the project's framework or the service's runtime; `buildpack` is not a `builds` configuration option."
3421
3537
  );
3422
3538
  }
3539
+ const explicitImage = readString(config.handler);
3540
+ if (explicitImage && !(entrypointRef && isDockerfileRef(entrypointRef))) {
3541
+ return {
3542
+ kind: "prebuilt",
3543
+ imageRef: assertValidImageReference(explicitImage)
3544
+ };
3545
+ }
3423
3546
  if (buildpack && (config.daemon || readString(config.buildpackEntrypoint))) {
3424
3547
  return { kind: "buildpack", buildpack };
3425
3548
  }
@@ -3432,7 +3555,10 @@ function resolveImageSource(options, context) {
3432
3555
  }
3433
3556
  const prebuiltImage = readString(config.handler) ?? (isDetectSentinel ? void 0 : entrypointRef);
3434
3557
  if (prebuiltImage) {
3435
- return { kind: "prebuilt", imageRef: prebuiltImage };
3558
+ return {
3559
+ kind: "prebuilt",
3560
+ imageRef: assertValidImageReference(prebuiltImage)
3561
+ };
3436
3562
  }
3437
3563
  if (buildpack) {
3438
3564
  return { kind: "buildpack", buildpack };
@@ -3442,12 +3568,53 @@ function resolveImageSource(options, context) {
3442
3568
  );
3443
3569
  }
3444
3570
 
3445
- // src/buildah-store-cache/cache.ts
3571
+ // src/build-context.ts
3446
3572
  var import_build_utils7 = require("@vercel/build-utils");
3447
- var import_node_crypto8 = require("crypto");
3448
3573
  var import_promises7 = require("fs/promises");
3449
- var import_node_os11 = require("os");
3450
3574
  var import_node_path21 = require("path");
3575
+ async function resolveBuildContext({
3576
+ repoRootPath,
3577
+ workPath,
3578
+ contextDir,
3579
+ dockerfilePath
3580
+ }) {
3581
+ const [root, context, dockerfile] = await Promise.all([
3582
+ resolvePath(repoRootPath ?? workPath, "repository root"),
3583
+ resolvePath(contextDir, "container build context"),
3584
+ resolvePath(dockerfilePath, "Dockerfile")
3585
+ ]);
3586
+ for (const [label, target] of [
3587
+ ["Container build context", context],
3588
+ ["Dockerfile", dockerfile]
3589
+ ]) {
3590
+ const rel = (0, import_node_path21.relative)(root, target);
3591
+ if (rel === ".." || rel.startsWith(`..${import_node_path21.sep}`) || (0, import_node_path21.isAbsolute)(rel)) {
3592
+ throw new import_build_utils7.NowBuildError({
3593
+ code: "INVALID_CONTAINER_BUILD_CONTEXT",
3594
+ message: `${label} resolves outside the repository. Keep the build context and Dockerfile inside the repository, including symbolic link targets.`
3595
+ });
3596
+ }
3597
+ }
3598
+ return context;
3599
+ }
3600
+ async function resolvePath(path4, label) {
3601
+ try {
3602
+ return await (0, import_promises7.realpath)(path4);
3603
+ } catch (error) {
3604
+ const code = error.code;
3605
+ throw new import_build_utils7.NowBuildError({
3606
+ code: "INVALID_CONTAINER_BUILD_CONTEXT",
3607
+ message: `Cannot resolve ${label} "${path4}"${code ? ` (${code})` : ""}. Check that it exists and any symbolic links have accessible targets.`
3608
+ });
3609
+ }
3610
+ }
3611
+
3612
+ // src/buildah-store-cache/cache.ts
3613
+ var import_build_utils8 = require("@vercel/build-utils");
3614
+ var import_node_crypto8 = require("crypto");
3615
+ var import_promises8 = require("fs/promises");
3616
+ var import_node_os11 = require("os");
3617
+ var import_node_path22 = require("path");
3451
3618
  var BUILDAH_STORE_CACHE_DIR = ".vercel/cache/buildah-store";
3452
3619
  var STORE_PATHS = {
3453
3620
  graphRoot: BUILDAH_GRAPH_ROOT,
@@ -3461,7 +3628,7 @@ var BuildahStoreCache = class _BuildahStoreCache {
3461
3628
  }
3462
3629
  static forProject(options, client) {
3463
3630
  return new _BuildahStoreCache(
3464
- (0, import_node_path21.resolve)(options.repoRootPath || options.workPath),
3631
+ (0, import_node_path22.resolve)(options.repoRootPath || options.workPath),
3465
3632
  client
3466
3633
  );
3467
3634
  }
@@ -3537,8 +3704,8 @@ var BuildahStoreCache = class _BuildahStoreCache {
3537
3704
  if (!await isRegularFile(archive)) {
3538
3705
  return {};
3539
3706
  }
3540
- return await (0, import_build_utils7.glob)(
3541
- `${BUILDAH_STORE_CACHE_DIR}/${(0, import_node_path21.basename)(archive)}`,
3707
+ return await (0, import_build_utils8.glob)(
3708
+ `${BUILDAH_STORE_CACHE_DIR}/${(0, import_node_path22.basename)(archive)}`,
3542
3709
  this.repositoryRoot
3543
3710
  );
3544
3711
  } catch (error) {
@@ -3548,7 +3715,7 @@ var BuildahStoreCache = class _BuildahStoreCache {
3548
3715
  }
3549
3716
  async removeSnapshots() {
3550
3717
  try {
3551
- await (0, import_promises7.rm)(await this.snapshotDirectory({ create: false }), {
3718
+ await (0, import_promises8.rm)(await this.snapshotDirectory({ create: false }), {
3552
3719
  recursive: true,
3553
3720
  force: true
3554
3721
  });
@@ -3560,24 +3727,24 @@ var BuildahStoreCache = class _BuildahStoreCache {
3560
3727
  }
3561
3728
  async archivePath(options) {
3562
3729
  const key = await snapshotKey(this.client);
3563
- return (0, import_node_path21.join)(await this.snapshotDirectory(options), `store-${key}.tar.zst`);
3730
+ return (0, import_node_path22.join)(await this.snapshotDirectory(options), `store-${key}.tar.zst`);
3564
3731
  }
3565
3732
  async snapshotDirectory({
3566
3733
  create
3567
3734
  }) {
3568
- const root = await (0, import_promises7.realpath)(this.repositoryRoot);
3735
+ const root = await (0, import_promises8.realpath)(this.repositoryRoot);
3569
3736
  let directory = root;
3570
3737
  for (const part of BUILDAH_STORE_CACHE_DIR.split("/")) {
3571
- directory = (0, import_node_path21.join)(directory, part);
3738
+ directory = (0, import_node_path22.join)(directory, part);
3572
3739
  if (create) {
3573
- await (0, import_promises7.mkdir)(directory, { mode: 448 }).catch((error) => {
3740
+ await (0, import_promises8.mkdir)(directory, { mode: 448 }).catch((error) => {
3574
3741
  if (error.code !== "EEXIST")
3575
3742
  throw error;
3576
3743
  });
3577
3744
  }
3578
3745
  const stats = await lstatIfPresent(directory);
3579
3746
  if (!stats) {
3580
- return (0, import_node_path21.join)(root, BUILDAH_STORE_CACHE_DIR);
3747
+ return (0, import_node_path22.join)(root, BUILDAH_STORE_CACHE_DIR);
3581
3748
  }
3582
3749
  if (!stats.isDirectory()) {
3583
3750
  throw new Error(`${directory} is not a directory`);
@@ -3589,7 +3756,7 @@ var BuildahStoreCache = class _BuildahStoreCache {
3589
3756
  async function restoreStore(archive) {
3590
3757
  const storeLock = await requireStoreLock();
3591
3758
  const state = await createBuildahStoreStateDirectory();
3592
- const gate = new FileLock((0, import_node_path21.join)(state, "restore.lock"));
3759
+ const gate = new FileLock((0, import_node_path22.join)(state, "restore.lock"));
3593
3760
  return runStoreCommand(
3594
3761
  {
3595
3762
  action: "restore",
@@ -3597,7 +3764,7 @@ async function restoreStore(archive) {
3597
3764
  ...STORE_PATHS,
3598
3765
  archive,
3599
3766
  storeLock: storeLock.path,
3600
- marker: (0, import_node_path21.join)(state, "restored")
3767
+ marker: (0, import_node_path22.join)(state, "restored")
3601
3768
  }
3602
3769
  },
3603
3770
  gate
@@ -3628,7 +3795,7 @@ async function requireStoreLock() {
3628
3795
  }
3629
3796
  async function describeSave2(result, archive, start) {
3630
3797
  if (result.status === "saved") {
3631
- return `saved the Buildah store cache (${formatBytes((await (0, import_promises7.lstat)(archive)).size)}) in ${elapsed(start)}`;
3798
+ return `saved the Buildah store cache (${formatBytes((await (0, import_promises8.lstat)(archive)).size)}) in ${elapsed(start)}`;
3632
3799
  }
3633
3800
  if (result.status === "unused") {
3634
3801
  return await isRegularFile(archive) ? "kept the previous Buildah store cache: no service built with Buildah" : "no Buildah store cache to keep: no service recorded Buildah image usage";
@@ -3643,8 +3810,8 @@ async function snapshotKey(client) {
3643
3810
  [
3644
3811
  "/usr/share/containers/storage.conf",
3645
3812
  "/etc/containers/storage.conf",
3646
- (0, import_node_path21.join)(
3647
- process.env.XDG_CONFIG_HOME || (0, import_node_path21.join)((0, import_node_os11.homedir)(), ".config"),
3813
+ (0, import_node_path22.join)(
3814
+ process.env.XDG_CONFIG_HOME || (0, import_node_path22.join)((0, import_node_os11.homedir)(), ".config"),
3648
3815
  "containers/storage.conf"
3649
3816
  ),
3650
3817
  process.env.CONTAINERS_STORAGE_CONF,
@@ -3669,7 +3836,7 @@ async function readOptionalFile(path4) {
3669
3836
  return "";
3670
3837
  }
3671
3838
  try {
3672
- return await (0, import_promises7.readFile)(path4, "utf8");
3839
+ return await (0, import_promises8.readFile)(path4, "utf8");
3673
3840
  } catch (error) {
3674
3841
  if (error.code === "ENOENT")
3675
3842
  return "";
@@ -3683,183 +3850,1001 @@ function failureReason(error) {
3683
3850
  return String(error?.message ?? error).trim().split("\n").at(-1) ?? "";
3684
3851
  }
3685
3852
 
3686
- // src/dev.ts
3687
- var import_node_child_process4 = require("child_process");
3688
- var import_node_fs16 = require("fs");
3689
- var import_node_os12 = require("os");
3690
- var import_node_path22 = __toESM(require("path"));
3691
- var HOST_ONLY_ENV = /* @__PURE__ */ new Set([
3692
- "TMPDIR",
3693
- "TMP",
3694
- "TEMP",
3695
- "HOME",
3696
- "PATH",
3697
- "PWD",
3698
- "OLDPWD",
3699
- "SHELL",
3700
- "SHLVL",
3701
- "USER",
3702
- "LOGNAME",
3703
- "TERM",
3704
- "TERM_PROGRAM",
3705
- "TERM_PROGRAM_VERSION",
3706
- "TERM_SESSION_ID",
3707
- "COLORTERM",
3708
- "LANG",
3709
- "LC_ALL",
3710
- "LC_CTYPE",
3711
- "COMMAND_MODE",
3712
- "SECURITYSESSIONID",
3713
- "__CF_USER_TEXT_ENCODING",
3714
- "__CFBundleIdentifier"
3853
+ // src/oci-layout/layout.ts
3854
+ var import_node_crypto9 = require("crypto");
3855
+ var import_promises9 = require("fs/promises");
3856
+ var import_node_path23 = require("path");
3857
+ var OCI_LAYOUT_VERSION = "1.0.0";
3858
+ var OCI_INDEX_MEDIA_TYPE = "application/vnd.oci.image.index.v1+json";
3859
+ var OCI_MANIFEST_MEDIA_TYPE = "application/vnd.oci.image.manifest.v1+json";
3860
+ var DOCKER_MANIFEST_MEDIA_TYPE = "application/vnd.docker.distribution.manifest.v2+json";
3861
+ var DOCKER_MANIFEST_LIST_MEDIA_TYPE = "application/vnd.docker.distribution.manifest.list.v2+json";
3862
+ var OCI_CONFIG_MEDIA_TYPE = "application/vnd.oci.image.config.v1+json";
3863
+ var DOCKER_CONFIG_MEDIA_TYPE = "application/vnd.docker.container.image.v1+json";
3864
+ var MANIFEST_MEDIA_TYPES2 = /* @__PURE__ */ new Set([
3865
+ OCI_MANIFEST_MEDIA_TYPE,
3866
+ DOCKER_MANIFEST_MEDIA_TYPE
3715
3867
  ]);
3716
- function isHostOnlyEnvVar(key) {
3717
- return HOST_ONLY_ENV.has(key) || key.startsWith("__") || key.startsWith("XPC_") || key.startsWith("SSH_") || key.startsWith("Apple");
3868
+ var INDEX_MEDIA_TYPES = /* @__PURE__ */ new Set([
3869
+ OCI_INDEX_MEDIA_TYPE,
3870
+ DOCKER_MANIFEST_LIST_MEDIA_TYPE
3871
+ ]);
3872
+ var IMAGE_CONFIG_MEDIA_TYPES = /* @__PURE__ */ new Set([
3873
+ OCI_CONFIG_MEDIA_TYPE,
3874
+ DOCKER_CONFIG_MEDIA_TYPE
3875
+ ]);
3876
+ function isRecord(value) {
3877
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3718
3878
  }
3719
- function writeEnvFile(env) {
3720
- const dir = (0, import_node_fs16.mkdtempSync)(import_node_path22.default.join((0, import_node_os12.tmpdir)(), "vercel-container-dev-env-"));
3721
- const file = import_node_path22.default.join(dir, "env");
3722
- const lines = [];
3723
- for (const [key, value] of Object.entries(env)) {
3724
- if (value.includes("\n")) {
3725
- continue;
3879
+ function sha256Digest(bytes) {
3880
+ const view = bytes instanceof Uint8Array && !Buffer.isBuffer(bytes) ? bytes : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
3881
+ return `sha256:${(0, import_node_crypto9.createHash)("sha256").update(view).digest("hex")}`;
3882
+ }
3883
+ function parseSha256Hex(digest) {
3884
+ if (!DIGEST_RE.test(digest)) {
3885
+ throw new Error(`Unsupported OCI digest ${JSON.stringify(digest)}.`);
3886
+ }
3887
+ return digest.slice("sha256:".length);
3888
+ }
3889
+ function blobPath2(layoutDir, digest) {
3890
+ return (0, import_node_path23.join)(layoutDir, "blobs", "sha256", parseSha256Hex(digest));
3891
+ }
3892
+ function assertSafePathSegment(segment, imageRef) {
3893
+ if (!segment || segment === "." || segment === ".." || segment.includes("/") || segment.includes("\\")) {
3894
+ throw new Error(`Invalid image reference for OCI layout: "${imageRef}".`);
3895
+ }
3896
+ }
3897
+ function layoutRefPath(layoutDir, imageRef) {
3898
+ const firstSlash = imageRef.indexOf("/");
3899
+ if (firstSlash <= 0 || firstSlash === imageRef.length - 1) {
3900
+ throw new Error(`Invalid image reference for OCI layout: "${imageRef}".`);
3901
+ }
3902
+ const registry = imageRef.slice(0, firstSlash);
3903
+ assertSafePathSegment(registry, imageRef);
3904
+ const remainder = imageRef.slice(firstSlash + 1);
3905
+ const atIndex = remainder.indexOf("@");
3906
+ if (atIndex !== -1) {
3907
+ const repository2 = remainder.slice(0, atIndex);
3908
+ const digest = remainder.slice(atIndex + 1);
3909
+ const repoParts2 = repository2.split("/");
3910
+ for (const part of repoParts2) {
3911
+ assertSafePathSegment(part, imageRef);
3726
3912
  }
3727
- lines.push(`${key}=${value}`);
3913
+ const hex = parseSha256Hex(digest);
3914
+ return (0, import_node_path23.join)(layoutDir, registry, ...repoParts2, "sha256", hex);
3728
3915
  }
3729
- (0, import_node_fs16.writeFileSync)(file, `${lines.join("\n")}
3730
- `);
3731
- return file;
3916
+ const colonIndex = remainder.lastIndexOf(":");
3917
+ if (colonIndex <= remainder.lastIndexOf("/") || colonIndex === remainder.length - 1) {
3918
+ throw new Error(`Invalid image reference for OCI layout: "${imageRef}".`);
3919
+ }
3920
+ const repository = remainder.slice(0, colonIndex);
3921
+ const tag = remainder.slice(colonIndex + 1);
3922
+ const repoParts = repository.split("/");
3923
+ for (const part of repoParts) {
3924
+ assertSafePathSegment(part, imageRef);
3925
+ }
3926
+ assertSafePathSegment(tag, imageRef);
3927
+ return (0, import_node_path23.join)(layoutDir, registry, ...repoParts, tag);
3732
3928
  }
3733
- function useContainerHost(endpoint) {
3929
+ function parseDescriptor(value, label) {
3930
+ if (!isRecord(value)) {
3931
+ throw new Error(`Invalid OCI ${label} descriptor.`);
3932
+ }
3933
+ const { mediaType, digest, size } = value;
3934
+ if (typeof digest !== "string" || !DIGEST_RE.test(digest)) {
3935
+ throw new Error(`Invalid OCI ${label} digest: ${JSON.stringify(digest)}.`);
3936
+ }
3937
+ if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
3938
+ throw new Error(`Invalid OCI ${label} size: ${JSON.stringify(size)}.`);
3939
+ }
3940
+ if (mediaType !== void 0 && typeof mediaType !== "string") {
3941
+ throw new Error(`Invalid OCI ${label} mediaType.`);
3942
+ }
3943
+ return { mediaType, digest, size };
3944
+ }
3945
+ function parseJson(text, label) {
3734
3946
  try {
3735
- const url = new URL(endpoint);
3736
- if (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]") {
3737
- url.hostname = "host.docker.internal";
3738
- return url.toString();
3739
- }
3947
+ return JSON.parse(text);
3740
3948
  } catch {
3949
+ throw new Error(`OCI layout ${label} is not valid JSON.`);
3741
3950
  }
3742
- return endpoint;
3743
3951
  }
3744
- function emit(out, line) {
3745
- if (out.onStderr) {
3746
- out.onStderr(Buffer.from(`${line}
3747
- `));
3748
- } else {
3749
- process.stderr.write(`${line}
3750
- `);
3952
+ async function readRegularJson(path4, label) {
3953
+ const stats = await (0, import_promises9.lstat)(path4).catch((error) => {
3954
+ if (error.code === "ENOENT") {
3955
+ throw new Error(`OCI layout is missing ${label}.`);
3956
+ }
3957
+ throw error;
3958
+ });
3959
+ if (!stats.isFile()) {
3960
+ throw new Error(`OCI layout ${label} must be a regular file.`);
3751
3961
  }
3962
+ return parseJson(await (0, import_promises9.readFile)(path4, "utf8"), label);
3752
3963
  }
3753
- function runForwarded(cmd, args, out, opts = {}) {
3754
- return new Promise((resolve5, reject) => {
3755
- const child = (0, import_node_child_process4.spawn)(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
3756
- let stdout = "";
3757
- let stderr = "";
3758
- child.stdout?.on("data", (chunk) => {
3759
- stdout += chunk.toString();
3760
- if (!opts.quiet) {
3761
- if (out.onStdout) {
3762
- out.onStdout(chunk);
3763
- } else {
3764
- process.stderr.write(chunk.toString());
3765
- }
3766
- }
3767
- });
3768
- child.stderr?.on("data", (chunk) => {
3769
- stderr += chunk.toString();
3770
- if (!opts.quiet) {
3771
- if (out.onStderr) {
3772
- out.onStderr(chunk);
3773
- } else {
3774
- process.stderr.write(chunk.toString());
3775
- }
3776
- }
3777
- });
3778
- child.on("error", (err) => {
3779
- if (err.code === "ENOENT") {
3780
- reject(
3781
- new Error(
3782
- `Command not found: \`${cmd}\`. Ensure \`${cmd}\` is installed and on your PATH (Docker is required for \`vercel dev\` with container services).`
3783
- )
3784
- );
3785
- return;
3786
- }
3787
- reject(err);
3788
- });
3789
- child.on("close", (code) => {
3790
- if (code === 0) {
3791
- resolve5({ stdout });
3792
- } else {
3793
- const detail = stderr.trim().split("\n").slice(-5).join("\n");
3794
- reject(
3795
- new Error(
3796
- `\`${cmd} ${args.join(" ")}\` exited with code ${code}` + (detail ? `
3797
- ${detail}` : "")
3798
- )
3799
- );
3800
- }
3801
- });
3964
+ async function readVerifiedBlob(layoutDir, descriptor, label) {
3965
+ const path4 = blobPath2(layoutDir, descriptor.digest);
3966
+ const stats = await (0, import_promises9.lstat)(path4).catch((error) => {
3967
+ if (error.code === "ENOENT") {
3968
+ throw new Error(
3969
+ `OCI layout is missing ${label} blob ${descriptor.digest}.`
3970
+ );
3971
+ }
3972
+ throw error;
3802
3973
  });
3803
- }
3804
- async function resolveDevImage(options, out, span) {
3805
- const source = resolveImageSource(options, "dev");
3806
- if (source.kind === "prebuilt") {
3807
- span?.setAttributes({ "container.dev_mode": "prebuilt" });
3808
- emit(
3809
- out,
3810
- `\u25B2 container vercel dev: using prebuilt image ${source.imageRef}`
3974
+ if (!stats.isFile()) {
3975
+ throw new Error(
3976
+ `OCI layout ${label} blob ${descriptor.digest} must be a regular file.`
3811
3977
  );
3812
- return { image: source.imageRef };
3813
3978
  }
3814
- if (source.kind === "buildpack") {
3979
+ if (stats.size !== descriptor.size) {
3815
3980
  throw new Error(
3816
- `Unexpected buildpack image source in \`vercel dev\` for "${options.workPath}".`
3981
+ `OCI layout ${label} blob ${descriptor.digest} has size ${stats.size}, expected ${descriptor.size}.`
3817
3982
  );
3818
3983
  }
3819
- const { dockerfilePath } = source;
3820
- if (!(0, import_node_fs16.existsSync)(dockerfilePath)) {
3984
+ const content = await (0, import_promises9.readFile)(path4);
3985
+ if (content.length !== descriptor.size) {
3821
3986
  throw new Error(
3822
- `Dockerfile not found at "${dockerfilePath}" for container service.`
3987
+ `OCI layout ${label} blob ${descriptor.digest} has size ${content.length}, expected ${descriptor.size}.`
3823
3988
  );
3824
3989
  }
3825
- const serviceName = options.service?.name ?? "service";
3826
- const tag = devImageTag(serviceName);
3827
- const contextDir = options.service ? options.workPath : import_node_path22.default.dirname(dockerfilePath);
3828
- const buildArgFlags2 = [];
3829
- const buildEnv = options.meta?.buildEnv ?? {};
3830
- for (const [key, value] of Object.entries(buildEnv)) {
3831
- if (typeof value === "string") {
3832
- buildArgFlags2.push("--build-arg", `${key}=${value}`);
3990
+ const actual = sha256Digest(content);
3991
+ if (actual !== descriptor.digest) {
3992
+ throw new Error(
3993
+ `OCI layout ${label} blob ${descriptor.digest} hashes to ${actual}.`
3994
+ );
3995
+ }
3996
+ return content;
3997
+ }
3998
+ async function verifyBlobSize(layoutDir, descriptor, label) {
3999
+ const path4 = blobPath2(layoutDir, descriptor.digest);
4000
+ const stats = await (0, import_promises9.lstat)(path4).catch((error) => {
4001
+ if (error.code === "ENOENT") {
4002
+ throw new Error(
4003
+ `OCI layout is missing ${label} blob ${descriptor.digest}.`
4004
+ );
3833
4005
  }
4006
+ throw error;
4007
+ });
4008
+ if (!stats.isFile()) {
4009
+ throw new Error(
4010
+ `OCI layout ${label} blob ${descriptor.digest} must be a regular file.`
4011
+ );
4012
+ }
4013
+ if (stats.size !== descriptor.size) {
4014
+ throw new Error(
4015
+ `OCI layout ${label} blob ${descriptor.digest} has size ${stats.size}, expected ${descriptor.size}.`
4016
+ );
3834
4017
  }
3835
- const buildTarget = resolveBuildTarget(options.config);
3836
- span?.setAttributes({ "container.dev_mode": "build", "image.tag": tag });
3837
- emit(
3838
- out,
3839
- `\u25B2 container vercel dev: building ${tag} (docker, host platform${buildTarget ? `, target ${buildTarget}` : ""})`
3840
- );
3841
- await runForwarded(
3842
- "docker",
3843
- [
3844
- "build",
3845
- ...buildArgFlags2,
3846
- ...buildTargetFlags({ buildTarget }),
3847
- "-t",
3848
- tag,
3849
- "-f",
3850
- dockerfilePath,
3851
- contextDir
3852
- ],
3853
- out
3854
- );
3855
- emit(out, `\u25B2 container built ${tag}`);
3856
- return { image: tag };
4018
+ }
4019
+ async function readVerifiedJson(layoutDir, descriptor, label) {
4020
+ const bytes = await readVerifiedBlob(layoutDir, descriptor, label);
4021
+ return parseJson(bytes.toString("utf8"), `image ${label}`);
4022
+ }
4023
+ function manifestsOf(index, label) {
4024
+ if (!isRecord(index) || !Array.isArray(index.manifests)) {
4025
+ throw new Error(`OCI layout ${label} has no manifests list.`);
4026
+ }
4027
+ return index.manifests;
4028
+ }
4029
+ function platformOf(value) {
4030
+ if (!isRecord(value)) {
4031
+ return void 0;
4032
+ }
4033
+ const { os, architecture } = value;
4034
+ return typeof os === "string" && typeof architecture === "string" ? `${os}/${architecture}` : void 0;
4035
+ }
4036
+ async function collectTargetImages(search, manifests) {
4037
+ for (const entry of manifests) {
4038
+ const descriptor = parseDescriptor(entry, "manifest");
4039
+ const declared = platformOf(entry.platform);
4040
+ if (declared && declared !== TARGET_PLATFORM) {
4041
+ search.otherPlatforms.add(declared);
4042
+ continue;
4043
+ }
4044
+ const mediaType = descriptor.mediaType ?? "";
4045
+ if (INDEX_MEDIA_TYPES.has(mediaType)) {
4046
+ const index = await readVerifiedJson(
4047
+ search.layoutDir,
4048
+ descriptor,
4049
+ "index"
4050
+ );
4051
+ await collectTargetImages(search, manifestsOf(index, "image index"));
4052
+ } else if (MANIFEST_MEDIA_TYPES2.has(mediaType)) {
4053
+ await collectTargetImage(search, descriptor);
4054
+ }
4055
+ }
4056
+ }
4057
+ async function collectTargetImage(search, descriptor) {
4058
+ if (search.matches.has(descriptor.digest)) {
4059
+ return;
4060
+ }
4061
+ const manifest = await readVerifiedJson(
4062
+ search.layoutDir,
4063
+ descriptor,
4064
+ "manifest"
4065
+ );
4066
+ if (!isRecord(manifest)) {
4067
+ throw new Error("OCI layout image manifest must be a JSON object.");
4068
+ }
4069
+ const configDescriptor = parseDescriptor(manifest.config, "config");
4070
+ if (configDescriptor.mediaType && !IMAGE_CONFIG_MEDIA_TYPES.has(configDescriptor.mediaType)) {
4071
+ return;
4072
+ }
4073
+ const platform = platformOf(
4074
+ await readVerifiedJson(search.layoutDir, configDescriptor, "config")
4075
+ );
4076
+ if (platform !== TARGET_PLATFORM) {
4077
+ if (platform) {
4078
+ search.otherPlatforms.add(platform);
4079
+ }
4080
+ return;
4081
+ }
4082
+ if (!Array.isArray(manifest.layers)) {
4083
+ throw new Error("OCI layout image manifest is missing layers.");
4084
+ }
4085
+ search.matches.set(descriptor.digest, {
4086
+ descriptor,
4087
+ layers: manifest.layers
4088
+ });
4089
+ }
4090
+ async function verifyOciLayout(layoutDir) {
4091
+ const marker = await readRegularJson(
4092
+ (0, import_node_path23.join)(layoutDir, "oci-layout"),
4093
+ "oci-layout"
4094
+ );
4095
+ if (!isRecord(marker) || marker.imageLayoutVersion !== OCI_LAYOUT_VERSION) {
4096
+ throw new Error(
4097
+ `Unsupported OCI layout version in "${layoutDir}". Expected "${OCI_LAYOUT_VERSION}".`
4098
+ );
4099
+ }
4100
+ const index = await readRegularJson(
4101
+ (0, import_node_path23.join)(layoutDir, "index.json"),
4102
+ "index.json"
4103
+ );
4104
+ const search = {
4105
+ layoutDir,
4106
+ matches: /* @__PURE__ */ new Map(),
4107
+ otherPlatforms: /* @__PURE__ */ new Set()
4108
+ };
4109
+ await collectTargetImages(search, manifestsOf(index, "index.json"));
4110
+ const images = [...search.matches.values()];
4111
+ if (images.length === 0) {
4112
+ const others = [...search.otherPlatforms].filter(
4113
+ (platform) => platform !== "unknown/unknown"
4114
+ );
4115
+ throw new Error(
4116
+ `OCI layout has no ${TARGET_PLATFORM} image${others.length > 0 ? `; found ${others.join(", ")}` : ""}.`
4117
+ );
4118
+ }
4119
+ if (images.length > 1) {
4120
+ throw new Error(
4121
+ `OCI layout has ${images.length} ${TARGET_PLATFORM} images; expected one.`
4122
+ );
4123
+ }
4124
+ const [{ descriptor, layers }] = images;
4125
+ if (layers.length === 0) {
4126
+ throw new Error("OCI layout image manifest has no layers.");
4127
+ }
4128
+ for (let i = 0; i < layers.length; i++) {
4129
+ const layerDescriptor = parseDescriptor(layers[i], `layer[${i}]`);
4130
+ await verifyBlobSize(layoutDir, layerDescriptor, `layer[${i}]`);
4131
+ }
4132
+ return { manifestDigest: descriptor.digest };
4133
+ }
4134
+ async function moveDirectory(sourceDir, destinationDir) {
4135
+ const parentDir = (0, import_node_path23.dirname)(destinationDir);
4136
+ await (0, import_promises9.mkdir)(parentDir, { recursive: true });
4137
+ try {
4138
+ await (0, import_promises9.rename)(sourceDir, destinationDir);
4139
+ return;
4140
+ } catch (error) {
4141
+ if (error.code !== "EXDEV") {
4142
+ throw error;
4143
+ }
4144
+ }
4145
+ const tempDir = await (0, import_promises9.mkdtemp)((0, import_node_path23.join)(parentDir, ".oci-layout-"));
4146
+ try {
4147
+ await (0, import_promises9.cp)(sourceDir, tempDir, { recursive: true });
4148
+ await (0, import_promises9.rename)(tempDir, destinationDir);
4149
+ } catch (error) {
4150
+ await (0, import_promises9.rm)(tempDir, { recursive: true, force: true });
4151
+ throw error;
4152
+ }
4153
+ await (0, import_promises9.rm)(sourceDir, { recursive: true, force: true });
4154
+ }
4155
+
4156
+ // src/oci-layout/pull.ts
4157
+ var import_node_crypto10 = require("crypto");
4158
+ var import_promises10 = require("fs/promises");
4159
+ var import_node_path24 = require("path");
4160
+ var MANIFEST_ACCEPT_HEADER = [
4161
+ OCI_MANIFEST_MEDIA_TYPE,
4162
+ DOCKER_MANIFEST_MEDIA_TYPE,
4163
+ OCI_INDEX_MEDIA_TYPE,
4164
+ DOCKER_MANIFEST_LIST_MEDIA_TYPE
4165
+ ].join(", ");
4166
+ var PULL_ATTEMPTS = 3;
4167
+ var PULL_TIMEOUT_MS = 3e4;
4168
+ var MAX_REDIRECTS = 5;
4169
+ function parseDigestImageRef(imageRef) {
4170
+ const atIndex = imageRef.indexOf("@");
4171
+ if (atIndex === -1) {
4172
+ throw new Error(
4173
+ `Expected a digest-pinned image reference, got "${imageRef}".`
4174
+ );
4175
+ }
4176
+ const namePart = imageRef.slice(0, atIndex);
4177
+ const digest = imageRef.slice(atIndex + 1);
4178
+ if (!DIGEST_RE.test(digest)) {
4179
+ throw new Error(
4180
+ `Expected a sha256 digest in image reference "${imageRef}".`
4181
+ );
4182
+ }
4183
+ const firstSlash = namePart.indexOf("/");
4184
+ if (firstSlash <= 0 || firstSlash === namePart.length - 1) {
4185
+ throw new Error(
4186
+ `Expected "<registry>/<repository>@sha256:..." image reference, got "${imageRef}".`
4187
+ );
4188
+ }
4189
+ const registry = namePart.slice(0, firstSlash);
4190
+ const repository = namePart.slice(firstSlash + 1);
4191
+ if (repository.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
4192
+ throw new Error(`Invalid repository in image reference "${imageRef}".`);
4193
+ }
4194
+ return { registry, repository, digest };
4195
+ }
4196
+ function describeFetchError2(error) {
4197
+ const err = error;
4198
+ const cause = err.cause?.message;
4199
+ return cause ? `${err.message} (${cause})` : err.message;
4200
+ }
4201
+ var OciRegistryPuller = class {
4202
+ constructor(options) {
4203
+ this.options = options;
4204
+ this.fetchImpl = options.fetchImpl ?? fetch;
4205
+ this.retryDelayMs = options.retryDelayMs ?? 500;
4206
+ }
4207
+ async pullToLayout(imageRef, destinationDir) {
4208
+ const parsed = parseDigestImageRef(imageRef);
4209
+ if (parsed.registry !== this.options.credentials.registry) {
4210
+ throw new Error(
4211
+ `Registry credentials for ${this.options.credentials.registry} cannot be used to pull from ${parsed.registry}.`
4212
+ );
4213
+ }
4214
+ const baseUrl = (this.options.baseUrl ?? `https://${parsed.registry}`).replace(/\/+$/, "");
4215
+ const baseOrigin = new URL(baseUrl).origin;
4216
+ const requireHttps = new URL(baseUrl).protocol === "https:";
4217
+ const authorization = `Basic ${Buffer.from(
4218
+ `${this.options.credentials.username}:${this.options.credentials.token}`
4219
+ ).toString("base64")}`;
4220
+ const manifestUrl = `${baseUrl}/v2/${parsed.repository}/manifests/${parsed.digest}`;
4221
+ const manifestBytes = await this.fetchBytes({
4222
+ url: manifestUrl,
4223
+ baseOrigin,
4224
+ requireHttps,
4225
+ authorization,
4226
+ accept: MANIFEST_ACCEPT_HEADER,
4227
+ registry: parsed.registry,
4228
+ label: `manifest ${imageRef}`
4229
+ });
4230
+ const actualManifestDigest = sha256Digest(manifestBytes);
4231
+ if (actualManifestDigest !== parsed.digest) {
4232
+ throw new Error(
4233
+ `Manifest digest mismatch for ${imageRef}: expected ${parsed.digest}, received ${actualManifestDigest}.`
4234
+ );
4235
+ }
4236
+ let manifest;
4237
+ try {
4238
+ manifest = JSON.parse(new TextDecoder().decode(manifestBytes));
4239
+ } catch {
4240
+ throw new Error(`Manifest for ${imageRef} is not valid JSON.`);
4241
+ }
4242
+ if (!isRecord(manifest)) {
4243
+ throw new Error(`Manifest for ${imageRef} must be a JSON object.`);
4244
+ }
4245
+ if (Array.isArray(manifest.manifests) && (!manifest.config || !Array.isArray(manifest.layers))) {
4246
+ throw new Error(
4247
+ `Expected ${imageRef} to resolve to a single linux/amd64 image manifest, not an image index.`
4248
+ );
4249
+ }
4250
+ if (!Array.isArray(manifest.layers) || manifest.layers.length === 0) {
4251
+ throw new Error(`Manifest for ${imageRef} has no layers.`);
4252
+ }
4253
+ const configDescriptor = parseDescriptor(manifest.config, "config");
4254
+ const layerDescriptors = manifest.layers.map(
4255
+ (layer, index) => parseDescriptor(layer, `layer[${index}]`)
4256
+ );
4257
+ const blobsDir = (0, import_node_path24.join)(destinationDir, "blobs", "sha256");
4258
+ await (0, import_promises10.mkdir)(blobsDir, { recursive: true, mode: 493 });
4259
+ try {
4260
+ await (0, import_promises10.writeFile)(
4261
+ (0, import_node_path24.join)(blobsDir, parseSha256Hex(parsed.digest)),
4262
+ manifestBytes
4263
+ );
4264
+ const fetchBlob = async (descriptor, label) => {
4265
+ const written = await this.fetchToFile(
4266
+ {
4267
+ url: `${baseUrl}/v2/${parsed.repository}/blobs/${descriptor.digest}`,
4268
+ baseOrigin,
4269
+ requireHttps,
4270
+ authorization,
4271
+ registry: parsed.registry,
4272
+ label: `${label} ${descriptor.digest}`
4273
+ },
4274
+ blobPath2(destinationDir, descriptor.digest)
4275
+ );
4276
+ if (written.size !== descriptor.size) {
4277
+ throw new Error(
4278
+ `Blob size mismatch for ${label} ${descriptor.digest}: expected ${descriptor.size}, received ${written.size}.`
4279
+ );
4280
+ }
4281
+ if (written.digest !== descriptor.digest) {
4282
+ throw new Error(
4283
+ `Blob digest mismatch for ${label} ${descriptor.digest}: received ${written.digest}.`
4284
+ );
4285
+ }
4286
+ };
4287
+ const uniqueLayers = /* @__PURE__ */ new Map();
4288
+ for (const layer of layerDescriptors) {
4289
+ if (!uniqueLayers.has(layer.digest)) {
4290
+ uniqueLayers.set(layer.digest, layer);
4291
+ }
4292
+ }
4293
+ await settleAll([
4294
+ fetchBlob(configDescriptor, "config"),
4295
+ ...[...uniqueLayers.values()].map(
4296
+ (layer, index) => fetchBlob(layer, `layer[${index}]`)
4297
+ )
4298
+ ]);
4299
+ let config;
4300
+ try {
4301
+ config = JSON.parse(
4302
+ await (0, import_promises10.readFile)(
4303
+ blobPath2(destinationDir, configDescriptor.digest),
4304
+ "utf8"
4305
+ )
4306
+ );
4307
+ } catch {
4308
+ throw new Error(`Config blob for ${imageRef} is not valid JSON.`);
4309
+ }
4310
+ if (!isRecord(config) || config.os !== "linux" || config.architecture !== "amd64") {
4311
+ throw new Error(
4312
+ `Run image ${imageRef} must target linux/amd64, found ${JSON.stringify(
4313
+ isRecord(config) ? `${config.os}/${config.architecture}` : config
4314
+ )}.`
4315
+ );
4316
+ }
4317
+ const manifestMediaType = typeof manifest.mediaType === "string" ? manifest.mediaType : OCI_MANIFEST_MEDIA_TYPE;
4318
+ await (0, import_promises10.writeFile)(
4319
+ (0, import_node_path24.join)(destinationDir, "oci-layout"),
4320
+ JSON.stringify({ imageLayoutVersion: OCI_LAYOUT_VERSION })
4321
+ );
4322
+ await (0, import_promises10.writeFile)(
4323
+ (0, import_node_path24.join)(destinationDir, "index.json"),
4324
+ JSON.stringify({
4325
+ schemaVersion: 2,
4326
+ mediaType: OCI_INDEX_MEDIA_TYPE,
4327
+ manifests: [
4328
+ {
4329
+ mediaType: manifestMediaType,
4330
+ digest: parsed.digest,
4331
+ size: manifestBytes.byteLength
4332
+ }
4333
+ ]
4334
+ })
4335
+ );
4336
+ return { manifestDigest: parsed.digest };
4337
+ } catch (error) {
4338
+ await (0, import_promises10.rm)(destinationDir, { recursive: true, force: true });
4339
+ throw error;
4340
+ }
4341
+ }
4342
+ fetchBytes(request) {
4343
+ return this.fetchWithRetries(
4344
+ request,
4345
+ async (response) => new Uint8Array(await response.arrayBuffer())
4346
+ );
4347
+ }
4348
+ /** Streams a blob into `path`, hashing it on the way, and returns its size and digest. */
4349
+ fetchToFile(request, path4) {
4350
+ return this.fetchWithRetries(request, async (response) => {
4351
+ const hash = (0, import_node_crypto10.createHash)("sha256");
4352
+ let size = 0;
4353
+ const file = await (0, import_promises10.open)(path4, "w");
4354
+ try {
4355
+ if (response.body) {
4356
+ for await (const chunk of response.body) {
4357
+ hash.update(chunk);
4358
+ size += chunk.byteLength;
4359
+ await file.write(chunk);
4360
+ }
4361
+ }
4362
+ } finally {
4363
+ await file.close();
4364
+ }
4365
+ return { size, digest: `sha256:${hash.digest("hex")}` };
4366
+ });
4367
+ }
4368
+ /**
4369
+ * GETs `request.url`, retrying network errors, 429 and 5xx responses.
4370
+ * `readBody` runs inside the retry, so a connection that drops while the
4371
+ * body streams is retried like one that drops before the headers arrive.
4372
+ */
4373
+ async fetchWithRetries(request, readBody) {
4374
+ let lastError = `Failed to pull ${request.label}.`;
4375
+ for (let attempt = 1; attempt <= PULL_ATTEMPTS; attempt++) {
4376
+ debug(`registry pull (${attempt}/${PULL_ATTEMPTS}): GET ${request.url}`);
4377
+ try {
4378
+ const response = await this.fetchFollowingRedirects(
4379
+ request.url,
4380
+ request.baseOrigin,
4381
+ request.requireHttps,
4382
+ request.authorization,
4383
+ request.accept
4384
+ );
4385
+ if (response.ok) {
4386
+ return await readBody(response);
4387
+ }
4388
+ if (response.status === 401 || response.status === 403) {
4389
+ throw new NonRetryablePullError(
4390
+ request.registry === VCR_REGISTRY ? formatVcrAuthError(
4391
+ request.registry,
4392
+ this.options.credentials.username,
4393
+ `HTTP ${response.status} pulling ${request.label}.`
4394
+ ) : `Registry authentication failed pulling ${request.label}: HTTP ${response.status}.`
4395
+ );
4396
+ }
4397
+ lastError = `Failed to pull ${request.label}: HTTP ${response.status}.`;
4398
+ if (response.status !== 429 && response.status < 500) {
4399
+ throw new NonRetryablePullError(lastError);
4400
+ }
4401
+ } catch (error) {
4402
+ if (error instanceof NonRetryablePullError) {
4403
+ throw error;
4404
+ }
4405
+ lastError = `Failed to pull ${request.label}: ${describeFetchError2(error)}`;
4406
+ }
4407
+ if (attempt < PULL_ATTEMPTS) {
4408
+ await delay(this.retryDelayMs * 2 ** (attempt - 1));
4409
+ }
4410
+ }
4411
+ throw new Error(lastError);
4412
+ }
4413
+ async fetchFollowingRedirects(initialUrl, baseOrigin, requireHttps, authorization, accept) {
4414
+ let currentUrl = new URL(initialUrl);
4415
+ for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects++) {
4416
+ const headers = {};
4417
+ if (currentUrl.origin === baseOrigin) {
4418
+ headers.authorization = authorization;
4419
+ }
4420
+ if (accept) {
4421
+ headers.accept = accept;
4422
+ }
4423
+ const response = await this.fetchImpl(currentUrl.href, {
4424
+ method: "GET",
4425
+ headers,
4426
+ redirect: "manual",
4427
+ signal: AbortSignal.timeout(PULL_TIMEOUT_MS)
4428
+ });
4429
+ if (response.status < 300 || response.status >= 400) {
4430
+ return response;
4431
+ }
4432
+ const location = response.headers.get("location");
4433
+ if (!location) {
4434
+ return response;
4435
+ }
4436
+ if (redirects === MAX_REDIRECTS) {
4437
+ throw new NonRetryablePullError(
4438
+ `Too many redirects pulling ${initialUrl}.`
4439
+ );
4440
+ }
4441
+ const nextUrl = new URL(location, currentUrl);
4442
+ if (requireHttps && nextUrl.protocol !== "https:") {
4443
+ throw new NonRetryablePullError(
4444
+ `Refusing insecure redirect to ${nextUrl.protocol} while pulling from HTTPS registry.`
4445
+ );
4446
+ }
4447
+ currentUrl = nextUrl;
4448
+ }
4449
+ throw new NonRetryablePullError(
4450
+ `Too many redirects pulling ${initialUrl}.`
4451
+ );
4452
+ }
4453
+ };
4454
+ var NonRetryablePullError = class extends Error {
4455
+ };
4456
+
4457
+ // src/oci-layout/index.ts
4458
+ var CONTAINER_OCI_LAYOUT_ENV = "VERCEL_CONTAINER_OCI_LAYOUT";
4459
+ function ociLayoutRequested(env = process.env) {
4460
+ return env[CONTAINER_OCI_LAYOUT_ENV] === "1";
4461
+ }
4462
+
4463
+ // src/publish.ts
4464
+ var import_promises11 = require("fs/promises");
4465
+ var import_node_os12 = require("os");
4466
+ var import_node_path25 = require("path");
4467
+ function createImagePublisher(params) {
4468
+ const { build: build2, engine, exportLayout } = params;
4469
+ if (!exportLayout) {
4470
+ return new VcrPublisher(engine, build2);
4471
+ }
4472
+ if (!exportsLayouts(engine)) {
4473
+ throw new Error(
4474
+ `${CONTAINER_OCI_LAYOUT_ENV}=1 needs Buildah to write the image as an OCI image layout, but this build uses ${engine.name}.`
4475
+ );
4476
+ }
4477
+ return new OciLayoutPublisher(engine, build2);
4478
+ }
4479
+ var VcrPublisher = class {
4480
+ constructor(engine, build2) {
4481
+ this.engine = engine;
4482
+ this.build = build2;
4483
+ this.mode = "build_and_push";
4484
+ this.spanAttributes = { "container.registry": VCR_REGISTRY };
4485
+ }
4486
+ async resolve(span) {
4487
+ const { repository, tag } = this.build;
4488
+ const target = await resolveRegistryTarget({ repository, tag, span });
4489
+ span?.setAttributes({
4490
+ "container.repository": target.fullRepository,
4491
+ "image.tag": tag,
4492
+ "image.ref": target.imageRef,
4493
+ "registry.username": target.username
4494
+ });
4495
+ return {
4496
+ imageRef: target.imageRef,
4497
+ connect: (connectSpan) => this.connect(target, connectSpan),
4498
+ publish: (params, pushSpan) => this.push(target, params, pushSpan)
4499
+ };
4500
+ }
4501
+ async connect(target, span) {
4502
+ await authenticateRegistry(this.engine, this.credentials(target), span);
4503
+ await withSpan(
4504
+ span,
4505
+ "container.ensure_repository",
4506
+ { "container.repository": this.build.repository },
4507
+ (s) => ensureRepository(this.build.repository, target.token, target.claims, s)
4508
+ );
4509
+ }
4510
+ async push(target, params, span) {
4511
+ const { imageRef } = params;
4512
+ const pushStart = Date.now();
4513
+ step(`Pushing ${imageRef}`);
4514
+ const digest = await withSpan(
4515
+ span,
4516
+ "container.push",
4517
+ { "image.ref": imageRef },
4518
+ () => this.engine.push({
4519
+ ...params,
4520
+ ...this.credentials(target),
4521
+ repository: this.build.repository
4522
+ })
4523
+ );
4524
+ done(`pushed ${shortDigest(digest)} in ${elapsed(pushStart)}`);
4525
+ const reference = `${VCR_REGISTRY}/${target.fullRepository}@${digest}`;
4526
+ span?.setAttributes({
4527
+ "image.digest": digest,
4528
+ "image.resolved_ref": reference
4529
+ });
4530
+ info(`Image reference ${reference}`);
4531
+ return { kind: "registry", reference };
4532
+ }
4533
+ credentials(target) {
4534
+ return {
4535
+ registry: VCR_REGISTRY,
4536
+ username: target.username,
4537
+ token: target.token
4538
+ };
4539
+ }
4540
+ };
4541
+ var OciLayoutPublisher = class {
4542
+ constructor(engine, build2) {
4543
+ this.engine = engine;
4544
+ this.build = build2;
4545
+ this.mode = "build_and_export";
4546
+ this.spanAttributes = {};
4547
+ }
4548
+ async resolve(span) {
4549
+ const imageRef = `localhost/${this.build.repository}:${this.build.tag}`;
4550
+ span?.setAttributes({ "image.tag": this.build.tag, "image.ref": imageRef });
4551
+ return {
4552
+ imageRef,
4553
+ publish: (params, exportSpan) => this.exportLayout(params, exportSpan)
4554
+ };
4555
+ }
4556
+ async exportLayout(params, span) {
4557
+ const { imageRef } = params;
4558
+ const exportStart = Date.now();
4559
+ step("Saving image");
4560
+ const directory = await createStagingDirectory();
4561
+ debug(`exporting ${imageRef} as an OCI image layout to ${directory}`);
4562
+ try {
4563
+ const { manifestDigest } = await withSpan(
4564
+ span,
4565
+ "container.export_layout",
4566
+ { "image.ref": imageRef },
4567
+ async () => {
4568
+ await this.engine.exportLayout(params, directory);
4569
+ return verifyOciLayout(directory);
4570
+ }
4571
+ );
4572
+ done(`saved ${shortDigest(manifestDigest)} in ${elapsed(exportStart)}`);
4573
+ span?.setAttributes({ "image.digest": manifestDigest });
4574
+ return { kind: "oci-layout", directory, manifestDigest };
4575
+ } catch (error) {
4576
+ await (0, import_promises11.rm)(directory, { recursive: true, force: true });
4577
+ throw error;
4578
+ }
4579
+ }
4580
+ };
4581
+ async function createStagingDirectory() {
4582
+ const parent = isBuildContainer() ? (0, import_node_path25.join)((0, import_node_path25.dirname)(BUILDAH_GRAPH_ROOT), "oci-layouts") : (0, import_node_os12.tmpdir)();
4583
+ await (0, import_promises11.mkdir)(parent, { recursive: true });
4584
+ return (0, import_promises11.mkdtemp)((0, import_node_path25.join)(parent, "vercel-container-layout-"));
4585
+ }
4586
+ async function authenticateRegistry(engine, credentials, span) {
4587
+ const forceLogin = readString(process.env.VERCEL_VCR_FORCE_LOGIN) === "1";
4588
+ const authFile = forceLogin ? void 0 : existingRegistryAuthFile();
4589
+ if (authFile) {
4590
+ debug(`registry auth file present: ${authFile}`);
4591
+ step(`Using registry credentials from ${authFile}`);
4592
+ span?.setAttributes({
4593
+ "container.registry": VCR_REGISTRY,
4594
+ "registry.username": credentials.username,
4595
+ "registry.auth_file": authFile,
4596
+ "registry.login_skipped": toTag(true)
4597
+ });
4598
+ done("authenticated via provisioned credentials");
4599
+ return;
4600
+ }
4601
+ step(`Authenticating to ${VCR_REGISTRY} as ${credentials.username}`);
4602
+ await withSpan(
4603
+ span,
4604
+ "container.registry_login",
4605
+ {
4606
+ "container.registry": VCR_REGISTRY,
4607
+ "registry.username": credentials.username
4608
+ },
4609
+ () => engine.login(credentials)
4610
+ );
4611
+ done("authenticated");
4612
+ }
4613
+
4614
+ // src/dev.ts
4615
+ var import_build_utils9 = require("@vercel/build-utils");
4616
+ var import_node_child_process4 = require("child_process");
4617
+ var import_node_fs16 = require("fs");
4618
+ var import_node_os13 = require("os");
4619
+ var import_node_path26 = __toESM(require("path"));
4620
+ var HOST_ONLY_ENV = /* @__PURE__ */ new Set([
4621
+ "TMPDIR",
4622
+ "TMP",
4623
+ "TEMP",
4624
+ "HOME",
4625
+ "PATH",
4626
+ "PWD",
4627
+ "OLDPWD",
4628
+ "SHELL",
4629
+ "SHLVL",
4630
+ "USER",
4631
+ "LOGNAME",
4632
+ "TERM",
4633
+ "TERM_PROGRAM",
4634
+ "TERM_PROGRAM_VERSION",
4635
+ "TERM_SESSION_ID",
4636
+ "COLORTERM",
4637
+ "LANG",
4638
+ "LC_ALL",
4639
+ "LC_CTYPE",
4640
+ "COMMAND_MODE",
4641
+ "SECURITYSESSIONID",
4642
+ "__CF_USER_TEXT_ENCODING",
4643
+ "__CFBundleIdentifier"
4644
+ ]);
4645
+ function isHostOnlyEnvVar(key) {
4646
+ return HOST_ONLY_ENV.has(key) || key.startsWith("__") || key.startsWith("XPC_") || key.startsWith("SSH_") || key.startsWith("Apple");
4647
+ }
4648
+ function writeEnvFile(env) {
4649
+ const dir = (0, import_node_fs16.mkdtempSync)(import_node_path26.default.join((0, import_node_os13.tmpdir)(), "vercel-container-dev-env-"));
4650
+ const file = import_node_path26.default.join(dir, "env");
4651
+ const lines = [];
4652
+ for (const [key, value] of Object.entries(env)) {
4653
+ if (value.includes("\n")) {
4654
+ continue;
4655
+ }
4656
+ lines.push(`${key}=${value}`);
4657
+ }
4658
+ (0, import_node_fs16.writeFileSync)(file, `${lines.join("\n")}
4659
+ `);
4660
+ return file;
4661
+ }
4662
+ function useContainerHost(endpoint) {
4663
+ try {
4664
+ const url = new URL(endpoint);
4665
+ if (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]") {
4666
+ url.hostname = "host.docker.internal";
4667
+ return url.toString();
4668
+ }
4669
+ } catch {
4670
+ }
4671
+ return endpoint;
4672
+ }
4673
+ function emit(out, line) {
4674
+ if (out.onStderr) {
4675
+ out.onStderr(Buffer.from(`${line}
4676
+ `));
4677
+ } else {
4678
+ process.stderr.write(`${line}
4679
+ `);
4680
+ }
4681
+ }
4682
+ function runForwarded(cmd, args, out, opts = {}) {
4683
+ return new Promise((resolve5, reject) => {
4684
+ const child = (0, import_node_child_process4.spawn)(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
4685
+ let stdout = "";
4686
+ let stderr = "";
4687
+ child.stdout?.on("data", (chunk) => {
4688
+ stdout += chunk.toString();
4689
+ if (!opts.quiet) {
4690
+ if (out.onStdout) {
4691
+ out.onStdout(chunk);
4692
+ } else {
4693
+ process.stderr.write(chunk.toString());
4694
+ }
4695
+ }
4696
+ });
4697
+ child.stderr?.on("data", (chunk) => {
4698
+ stderr += chunk.toString();
4699
+ if (!opts.quiet) {
4700
+ if (out.onStderr) {
4701
+ out.onStderr(chunk);
4702
+ } else {
4703
+ process.stderr.write(chunk.toString());
4704
+ }
4705
+ }
4706
+ });
4707
+ child.on("error", (err) => {
4708
+ if (err.code === "ENOENT") {
4709
+ reject(
4710
+ new Error(
4711
+ `Command not found: \`${cmd}\`. Ensure \`${cmd}\` is installed and on your PATH (Docker is required for \`vercel dev\` with container services).`
4712
+ )
4713
+ );
4714
+ return;
4715
+ }
4716
+ reject(err);
4717
+ });
4718
+ child.on("close", (code) => {
4719
+ if (code === 0) {
4720
+ resolve5({ stdout });
4721
+ } else {
4722
+ const detail = stderr.trim().split("\n").slice(-5).join("\n");
4723
+ reject(
4724
+ new Error(
4725
+ `\`${cmd} ${args.join(" ")}\` exited with code ${code}` + (detail ? `
4726
+ ${detail}` : "")
4727
+ )
4728
+ );
4729
+ }
4730
+ });
4731
+ });
4732
+ }
4733
+ var PULL_AUTH_ERROR = /unauthorized|authentication required|no basic auth credentials|pull access denied|denied:|forbidden|\b40[13]\b/i;
4734
+ function prebuiltImagePullError(imageRef, detail) {
4735
+ if (imageRef.startsWith("vcr.vercel.com/") && PULL_AUTH_ERROR.test(detail)) {
4736
+ return new import_build_utils9.NowBuildError({
4737
+ code: "CONTAINER_IMAGE_PULL_UNAUTHORIZED",
4738
+ message: `Couldn't pull ${imageRef} from Vercel Container Registry. Log Docker in with \`vercel vcr login docker\`, check that this project can read the image, and run \`vercel dev\` again.
4739
+
4740
+ ${detail}`
4741
+ });
4742
+ }
4743
+ return new import_build_utils9.NowBuildError({
4744
+ code: "CONTAINER_IMAGE_PULL_FAILED",
4745
+ message: `Couldn't pull ${imageRef}.
4746
+
4747
+ ${detail}`
4748
+ });
4749
+ }
4750
+ async function hasLocalImage(imageRef, out) {
4751
+ try {
4752
+ await runForwarded(
4753
+ "docker",
4754
+ ["image", "inspect", "--format", "{{.Id}}", imageRef],
4755
+ out,
4756
+ { quiet: true }
4757
+ );
4758
+ return true;
4759
+ } catch {
4760
+ return false;
4761
+ }
4762
+ }
4763
+ async function pullPrebuiltImage(imageRef, out) {
4764
+ emit(out, `\u25B2 container vercel dev: pulling ${imageRef}`);
4765
+ try {
4766
+ await runForwarded("docker", ["pull", imageRef], out);
4767
+ } catch (err) {
4768
+ const error = prebuiltImagePullError(imageRef, err.message);
4769
+ if (!await hasLocalImage(imageRef, out)) {
4770
+ throw error;
4771
+ }
4772
+ const reason = error.code === "CONTAINER_IMAGE_PULL_UNAUTHORIZED" ? "the registry refused the pull; run `vercel vcr login docker` to get updates" : "the pull failed";
4773
+ emit(
4774
+ out,
4775
+ `\u25B2 container vercel dev: warning: couldn't pull ${imageRef} (${reason}). Using the local copy, which may be out of date.`
4776
+ );
4777
+ }
4778
+ }
4779
+ async function resolveDevImage(options, out, span) {
4780
+ const source = resolveImageSource(options, "dev");
4781
+ if (source.kind === "prebuilt") {
4782
+ await assertDockerAvailable(out);
4783
+ span?.setAttributes({ "container.dev_mode": "prebuilt" });
4784
+ emit(
4785
+ out,
4786
+ `\u25B2 container vercel dev: using prebuilt image ${source.imageRef}`
4787
+ );
4788
+ await pullPrebuiltImage(source.imageRef, out);
4789
+ return { image: source.imageRef };
4790
+ }
4791
+ if (source.kind === "buildpack") {
4792
+ throw new Error(
4793
+ `Unexpected buildpack image source in \`vercel dev\` for "${options.workPath}".`
4794
+ );
4795
+ }
4796
+ const { dockerfilePath } = source;
4797
+ const serviceName = options.service?.name ?? "service";
4798
+ const tag = devImageTag(serviceName);
4799
+ const contextDir = await resolveBuildContext({
4800
+ repoRootPath: options.repoRootPath,
4801
+ workPath: options.workPath,
4802
+ contextDir: options.service ? options.workPath : import_node_path26.default.dirname(dockerfilePath),
4803
+ dockerfilePath
4804
+ });
4805
+ await assertDockerAvailable(out);
4806
+ const buildArgFlags2 = [];
4807
+ const buildEnv = options.meta?.buildEnv ?? {};
4808
+ for (const [key, value] of Object.entries(buildEnv)) {
4809
+ if (typeof value === "string") {
4810
+ buildArgFlags2.push("--build-arg", `${key}=${value}`);
4811
+ }
4812
+ }
4813
+ const buildTarget = resolveBuildTarget(options.config);
4814
+ span?.setAttributes({ "container.dev_mode": "build", "image.tag": tag });
4815
+ emit(
4816
+ out,
4817
+ `\u25B2 container vercel dev: building ${tag} (docker, host platform${buildTarget ? `, target ${buildTarget}` : ""})`
4818
+ );
4819
+ await runForwarded(
4820
+ "docker",
4821
+ [
4822
+ "build",
4823
+ ...buildArgFlags2,
4824
+ ...buildTargetFlags({ buildTarget }),
4825
+ "-t",
4826
+ tag,
4827
+ "-f",
4828
+ dockerfilePath,
4829
+ contextDir
4830
+ ],
4831
+ out
4832
+ );
4833
+ emit(out, `\u25B2 container built ${tag}`);
4834
+ return { image: tag };
3857
4835
  }
3858
4836
  async function resolveContainerPort(image, out) {
3859
4837
  try {
3860
4838
  const { stdout } = await runForwarded(
3861
4839
  "docker",
3862
- ["image", "inspect", "--format", "{{json .Config.ExposedPorts}}", image],
4840
+ [
4841
+ "image",
4842
+ "inspect",
4843
+ "--format",
4844
+ "{{json .Config.ExposedPorts}}",
4845
+ "--",
4846
+ image
4847
+ ],
3863
4848
  out,
3864
4849
  { quiet: true }
3865
4850
  );
@@ -3962,7 +4947,6 @@ async function startContainer(options, reuseKey) {
3962
4947
  async (span) => {
3963
4948
  const { config, meta, onStdout, onStderr } = options;
3964
4949
  const out = { onStdout, onStderr };
3965
- await assertDockerAvailable(out);
3966
4950
  const { image } = await withSpan(
3967
4951
  span,
3968
4952
  "container.dev.resolve_image",
@@ -3974,11 +4958,6 @@ async function startContainer(options, reuseKey) {
3974
4958
  options.service?.name ?? "service"
3975
4959
  );
3976
4960
  const mergedEnv = {};
3977
- for (const [key, value] of Object.entries(process.env)) {
3978
- if (typeof value === "string" && !isHostOnlyEnvVar(key)) {
3979
- mergedEnv[key] = value;
3980
- }
3981
- }
3982
4961
  const metaEnv = meta?.env ?? {};
3983
4962
  for (const [key, value] of Object.entries(metaEnv)) {
3984
4963
  if (typeof value === "string" && !isHostOnlyEnvVar(key)) {
@@ -4022,6 +5001,7 @@ async function startContainer(options, reuseKey) {
4022
5001
  ...needsHostGateway ? ["--add-host", "host.docker.internal:host-gateway"] : [],
4023
5002
  "--env-file",
4024
5003
  envFilePath,
5004
+ "--",
4025
5005
  image,
4026
5006
  ...command ?? []
4027
5007
  ];
@@ -4042,7 +5022,7 @@ async function startContainer(options, reuseKey) {
4042
5022
  }
4043
5023
  });
4044
5024
  const cleanupEnvFile = () => {
4045
- (0, import_node_fs16.rmSync)(import_node_path22.default.dirname(envFilePath), { recursive: true, force: true });
5025
+ (0, import_node_fs16.rmSync)(import_node_path26.default.dirname(envFilePath), { recursive: true, force: true });
4046
5026
  };
4047
5027
  const shutdown = async () => {
4048
5028
  runningContainers.delete(reuseKey);
@@ -4118,10 +5098,10 @@ async function startContainer(options, reuseKey) {
4118
5098
  }
4119
5099
 
4120
5100
  // src/prepare-cache.ts
4121
- var import_build_utils8 = require("@vercel/build-utils");
4122
- var import_node_path23 = require("path");
5101
+ var import_build_utils10 = require("@vercel/build-utils");
5102
+ var import_node_path27 = require("path");
4123
5103
  async function prepareCache(options) {
4124
- const root = (0, import_node_path23.resolve)(options.repoRootPath || options.workPath);
5104
+ const root = (0, import_node_path27.resolve)(options.repoRootPath || options.workPath);
4125
5105
  const buildpackFiles = await collectBuildpackCache(root);
4126
5106
  const buildahStoreFiles = await BuildahStoreCache.forProject(
4127
5107
  options,
@@ -4131,7 +5111,7 @@ async function prepareCache(options) {
4131
5111
  }
4132
5112
  async function collectBuildpackCache(root) {
4133
5113
  const start = Date.now();
4134
- const files = await (0, import_build_utils8.glob)(`${BUILDPACK_CACHE_DIR}/**`, root);
5114
+ const files = await (0, import_build_utils10.glob)(`${BUILDPACK_CACHE_DIR}/**`, root);
4135
5115
  const count = Object.keys(files).length;
4136
5116
  if (count > 0) {
4137
5117
  info(
@@ -4143,6 +5123,392 @@ async function collectBuildpackCache(root) {
4143
5123
  return files;
4144
5124
  }
4145
5125
 
5126
+ // src/executable-image/index.ts
5127
+ var import_node_crypto11 = require("crypto");
5128
+ var import_promises13 = require("fs/promises");
5129
+ var import_node_path29 = require("path");
5130
+
5131
+ // src/buildpacks/lifecycle/native.ts
5132
+ var import_node_fs17 = require("fs");
5133
+ var import_promises12 = require("fs/promises");
5134
+ var import_node_path28 = require("path");
5135
+ var import_smol_toml4 = require("smol-toml");
5136
+ var PREBUILT_STATIC_GROUP = {
5137
+ runtime: "prebuilt-static",
5138
+ buildpacks: [vercelBuildpack("prebuilt-static")]
5139
+ };
5140
+ var HIVE_RUNTIME_MOUNTS = ["/tmp", "/opt/vercel"];
5141
+ function assertLinuxX64(platform = process.platform, arch = process.arch) {
5142
+ if (platform !== "linux" || arch !== "x64") {
5143
+ throw new Error(
5144
+ `Executable image builds require Linux x64 (current platform: ${platform}/${arch}).`
5145
+ );
5146
+ }
5147
+ }
5148
+ async function resolveNativeBuildUser(deps = {}) {
5149
+ const uid = (deps.getuid ?? process.getuid)?.();
5150
+ const gid = (deps.getgid ?? process.getgid)?.();
5151
+ if (uid === void 0 || gid === void 0) {
5152
+ throw new Error("The native CNB lifecycle requires Unix user IDs.");
5153
+ }
5154
+ if (uid !== 0 && gid !== 0) {
5155
+ return { uid, gid, switchUser: false };
5156
+ }
5157
+ if (uid !== 0) {
5158
+ throw new Error("The native CNB lifecycle cannot run with the root group.");
5159
+ }
5160
+ const passwd = await (deps.readPasswd ?? (() => (0, import_promises12.readFile)("/etc/passwd", "utf8")))();
5161
+ const nobody = passwd.split("\n").map((line) => line.split(":")).find(([name]) => name === "nobody");
5162
+ const unprivilegedUid = Number(nobody?.[2]);
5163
+ const unprivilegedGid = Number(nobody?.[3]);
5164
+ if (!Number.isInteger(unprivilegedUid) || !Number.isInteger(unprivilegedGid) || unprivilegedUid <= 0 || unprivilegedGid <= 0) {
5165
+ throw new Error(
5166
+ "The native CNB lifecycle requires a non-root nobody account."
5167
+ );
5168
+ }
5169
+ return { uid: unprivilegedUid, gid: unprivilegedGid, switchUser: true };
5170
+ }
5171
+ async function resolveStagingParent(resolveRealpath = import_promises12.realpath) {
5172
+ const parent = await resolveRealpath("/var/tmp");
5173
+ if (HIVE_RUNTIME_MOUNTS.some(
5174
+ (mount) => parent === mount || parent.startsWith(`${mount}/`)
5175
+ )) {
5176
+ throw new Error(
5177
+ `Cannot stage the native CNB image in ${parent}: Hive mounts over that path at runtime.`
5178
+ );
5179
+ }
5180
+ return parent;
5181
+ }
5182
+ async function chownRecursive(rootPath, uid, gid) {
5183
+ const stats = await (0, import_promises12.lstat)(rootPath);
5184
+ if (stats.isDirectory()) {
5185
+ for (const entry of await (0, import_promises12.readdir)(rootPath)) {
5186
+ await chownRecursive((0, import_node_path28.join)(rootPath, entry), uid, gid);
5187
+ }
5188
+ }
5189
+ await (0, import_promises12.lchown)(rootPath, uid, gid);
5190
+ }
5191
+ async function verifyLaunchCommand(layersDir, executablePath) {
5192
+ const metadata = (0, import_smol_toml4.parse)(
5193
+ await (0, import_promises12.readFile)((0, import_node_path28.join)(layersDir, "config", "metadata.toml"), "utf8")
5194
+ );
5195
+ const valid = metadata.processes?.some(
5196
+ (proc) => proc.type === "web" && proc.direct === true && proc.command?.length === 1 && (proc.command[0] === executablePath || proc.command[0] === "./user-server")
5197
+ );
5198
+ if (!valid) {
5199
+ throw new Error(
5200
+ "The prebuilt-static buildpack did not declare the staged user-server as its direct web process."
5201
+ );
5202
+ }
5203
+ }
5204
+ var NativeLifecycleRunner = class {
5205
+ constructor(options) {
5206
+ this.options = options;
5207
+ this.runCommand = options.runCommand ?? run;
5208
+ }
5209
+ async runPush(params) {
5210
+ return this.execute(
5211
+ params.executablePath,
5212
+ {
5213
+ kind: "registry",
5214
+ imageRef: params.imageRef,
5215
+ credentials: params.credentials
5216
+ },
5217
+ async (reportFile) => {
5218
+ const digest = readReportDigest(await (0, import_promises12.readFile)(reportFile, "utf8"));
5219
+ if (!digest) {
5220
+ throw new Error("The CNB lifecycle did not report an image digest.");
5221
+ }
5222
+ return digest;
5223
+ },
5224
+ params.span
5225
+ );
5226
+ }
5227
+ async runLayout(params) {
5228
+ await this.execute(
5229
+ params.executablePath,
5230
+ {
5231
+ kind: "oci-layout",
5232
+ imageRef: params.outputImageRef,
5233
+ layoutDir: params.layoutRoot
5234
+ },
5235
+ async () => void 0,
5236
+ params.span
5237
+ );
5238
+ }
5239
+ /**
5240
+ * Runs the creator, then `readResult` while the creator's report still
5241
+ * exists, so a failure in either is reported as a lifecycle failure.
5242
+ */
5243
+ async execute(executablePath, target, readResult, span) {
5244
+ const executableStats = await (0, import_promises12.lstat)(executablePath);
5245
+ if (!executableStats.isFile() || executableStats.size === 0) {
5246
+ throw new Error(
5247
+ "The prebuilt executable must be a nonempty regular file."
5248
+ );
5249
+ }
5250
+ const { user, stagingParent, cnbDir, platformDir, orderFile, runImage } = this.options;
5251
+ const runRoot = await (0, import_promises12.mkdtemp)((0, import_node_path28.join)(stagingParent, "vercel-cnb-native-"));
5252
+ try {
5253
+ if (user.switchUser) {
5254
+ await (0, import_promises12.chmod)(runRoot, 493);
5255
+ }
5256
+ const workPath = (0, import_node_path28.join)(runRoot, "workspace");
5257
+ const layers = (0, import_node_path28.join)(runRoot, "layers");
5258
+ const reportDir = (0, import_node_path28.join)(runRoot, "report");
5259
+ const home = (0, import_node_path28.join)(runRoot, "home");
5260
+ const temp = (0, import_node_path28.join)(runRoot, "tmp");
5261
+ const dirs = [workPath, layers, reportDir, home, temp];
5262
+ for (const dir of dirs) {
5263
+ await (0, import_promises12.mkdir)(dir, { mode: 448 });
5264
+ }
5265
+ const executable = (0, import_node_path28.join)(workPath, "user-server");
5266
+ await (0, import_promises12.copyFile)(executablePath, executable, import_node_fs17.constants.COPYFILE_EXCL);
5267
+ const handle = await (0, import_promises12.open)(
5268
+ executable,
5269
+ import_node_fs17.constants.O_RDONLY | import_node_fs17.constants.O_NOFOLLOW
5270
+ );
5271
+ try {
5272
+ await handle.chmod(493);
5273
+ if (user.switchUser) {
5274
+ await handle.chown(user.uid, user.gid);
5275
+ }
5276
+ } finally {
5277
+ await handle.close();
5278
+ }
5279
+ if (user.switchUser) {
5280
+ for (const dir of dirs) {
5281
+ await (0, import_promises12.chown)(dir, user.uid, user.gid);
5282
+ }
5283
+ }
5284
+ const lifecycleDir = (0, import_node_path28.join)(cnbDir, "lifecycle");
5285
+ const reportFile = (0, import_node_path28.join)(reportDir, "report.toml");
5286
+ const { args: exportArgs, env: exportEnv } = creatorExport(target);
5287
+ const args = [
5288
+ `-app=${workPath}`,
5289
+ `-layers=${layers}`,
5290
+ `-buildpacks=${(0, import_node_path28.join)(cnbDir, "buildpacks")}`,
5291
+ `-platform=${platformDir}`,
5292
+ `-order=${orderFile}`,
5293
+ `-launcher=${(0, import_node_path28.join)(lifecycleDir, "launcher")}`,
5294
+ `-launcher-sbom=${lifecycleDir}`,
5295
+ `-uid=${user.uid}`,
5296
+ `-gid=${user.gid}`,
5297
+ `-run-image=${runImage}`,
5298
+ `-report=${reportFile}`,
5299
+ "-skip-restore",
5300
+ ...exportArgs
5301
+ ];
5302
+ const env = {
5303
+ PATH: "/usr/bin:/bin",
5304
+ HOME: home,
5305
+ TMPDIR: temp,
5306
+ ...target.kind === "registry" && { DOCKER_CONFIG: home },
5307
+ CNB_PLATFORM_API,
5308
+ ...exportEnv
5309
+ };
5310
+ try {
5311
+ await this.runCommand((0, import_node_path28.join)(lifecycleDir, "creator"), args, {
5312
+ cwd: workPath,
5313
+ ...user.switchUser && { uid: user.uid, gid: user.gid },
5314
+ env
5315
+ });
5316
+ await verifyLaunchCommand(layers, executable);
5317
+ return await readResult(reportFile);
5318
+ } catch (error) {
5319
+ throw lifecycleFailure(error, {
5320
+ buildpack: this.options.buildpack,
5321
+ via: "native lifecycle",
5322
+ workPath,
5323
+ span
5324
+ });
5325
+ }
5326
+ } finally {
5327
+ await (0, import_promises12.rm)(runRoot, { recursive: true, force: true });
5328
+ }
5329
+ }
5330
+ };
5331
+
5332
+ // src/executable-image/index.ts
5333
+ var ExecutableImageBuilder = class _ExecutableImageBuilder {
5334
+ constructor(sharedRoot, runner, mode, span) {
5335
+ this.sharedRoot = sharedRoot;
5336
+ this.runner = runner;
5337
+ this.mode = mode;
5338
+ this.span = span;
5339
+ this.closed = false;
5340
+ }
5341
+ /** Fetches the lifecycle and buildpack, and in layout mode pulls run-static. */
5342
+ static async create(options, deps = {}) {
5343
+ assertLinuxX64(deps.platform, deps.arch);
5344
+ const env = options.env ?? process.env;
5345
+ const layoutMode = ociLayoutRequested(env);
5346
+ const user = await (deps.resolveBuildUser ?? resolveNativeBuildUser)();
5347
+ const stagingParent = await (deps.resolveStagingParent ?? resolveStagingParent)();
5348
+ const registry = deps.registry ?? VCR_REGISTRY;
5349
+ const runImage = deps.runImage ?? BUILDPACK_IMAGES.runStatic;
5350
+ const fetchDist = deps.fetchDistribution ?? fetchDistribution;
5351
+ const resolveTarget = deps.resolveRegistryTarget ?? resolveRegistryTarget;
5352
+ const ensureRepo = deps.ensureRepository ?? ensureRepository;
5353
+ const sharedRoot = await (0, import_promises13.mkdtemp)(
5354
+ (0, import_node_path29.join)(stagingParent, "vercel-cnb-executable-")
5355
+ );
5356
+ try {
5357
+ if (user.switchUser) {
5358
+ await (0, import_promises13.chmod)(sharedRoot, 493);
5359
+ }
5360
+ const cnbDir = (0, import_node_path29.join)(sharedRoot, "cnb");
5361
+ const platformDir = (0, import_node_path29.join)(sharedRoot, "platform");
5362
+ await (0, import_promises13.mkdir)(cnbDir, { mode: 493 });
5363
+ await (0, import_promises13.mkdir)(platformDir, { mode: 493 });
5364
+ if (user.switchUser) {
5365
+ await (0, import_promises13.chmod)(cnbDir, 493);
5366
+ await (0, import_promises13.chmod)(platformDir, 493);
5367
+ }
5368
+ const orderFile = (0, import_node_path29.join)(
5369
+ writeOrderDir(PREBUILT_STATIC_GROUP, sharedRoot),
5370
+ "order.toml"
5371
+ );
5372
+ const target = await resolveTarget({
5373
+ repository: options.repository,
5374
+ tag: "build",
5375
+ span: options.span
5376
+ });
5377
+ const runner = new NativeLifecycleRunner({
5378
+ stagingParent,
5379
+ user,
5380
+ buildpack: PREBUILT_STATIC_GROUP,
5381
+ cnbDir,
5382
+ platformDir,
5383
+ orderFile,
5384
+ runImage,
5385
+ runCommand: deps.runCommand
5386
+ });
5387
+ if (layoutMode) {
5388
+ const layoutRoot = (0, import_node_path29.join)(sharedRoot, "layout");
5389
+ await (0, import_promises13.mkdir)(layoutRoot, { mode: 448 });
5390
+ const runImageLayoutDir = layoutRefPath(layoutRoot, runImage);
5391
+ const puller = new OciRegistryPuller({
5392
+ credentials: {
5393
+ registry,
5394
+ username: target.username,
5395
+ token: target.token
5396
+ },
5397
+ baseUrl: deps.registryBaseUrl,
5398
+ fetchImpl: deps.fetchImpl
5399
+ });
5400
+ step("Fetching the CNB lifecycle, buildpacks, and run image");
5401
+ await settleAll([
5402
+ fetchDist(PREBUILT_STATIC_GROUP, cnbDir),
5403
+ puller.pullToLayout(runImage, runImageLayoutDir)
5404
+ ]);
5405
+ if (user.switchUser) {
5406
+ await chownRecursive(layoutRoot, user.uid, user.gid);
5407
+ }
5408
+ done("fetched the CNB lifecycle, buildpacks, and run image");
5409
+ return new _ExecutableImageBuilder(
5410
+ sharedRoot,
5411
+ runner,
5412
+ { kind: "oci-layout", layoutRoot },
5413
+ options.span
5414
+ );
5415
+ }
5416
+ step("Fetching the CNB lifecycle and buildpacks");
5417
+ await settleAll([
5418
+ fetchDist(PREBUILT_STATIC_GROUP, cnbDir),
5419
+ ensureRepo(
5420
+ options.repository,
5421
+ target.token,
5422
+ target.claims,
5423
+ options.span
5424
+ )
5425
+ ]);
5426
+ done("fetched the CNB lifecycle and buildpacks");
5427
+ return new _ExecutableImageBuilder(
5428
+ sharedRoot,
5429
+ runner,
5430
+ {
5431
+ kind: "registry",
5432
+ registry,
5433
+ token: target.token,
5434
+ username: target.username,
5435
+ fullRepository: target.fullRepository
5436
+ },
5437
+ options.span
5438
+ );
5439
+ } catch (error) {
5440
+ await (0, import_promises13.rm)(sharedRoot, { recursive: true, force: true });
5441
+ throw error;
5442
+ }
5443
+ }
5444
+ /** Packages one static linux/amd64 executable as an image. */
5445
+ async build(executable) {
5446
+ if (this.closed) {
5447
+ throw new Error("ExecutableImageBuilder has already been closed.");
5448
+ }
5449
+ const tag = `build-${(0, import_node_crypto11.randomUUID)()}`;
5450
+ const mode = this.mode;
5451
+ return withSpan(
5452
+ this.span,
5453
+ "container.executable_image.build",
5454
+ {
5455
+ "buildpack.runtime": PREBUILT_STATIC_GROUP.runtime,
5456
+ "container.engine": "native",
5457
+ "container.mode": mode.kind
5458
+ },
5459
+ (span) => mode.kind === "oci-layout" ? this.exportLayout(mode, tag, executable, span) : this.push(mode, tag, executable, span)
5460
+ );
5461
+ }
5462
+ async close() {
5463
+ if (this.closed)
5464
+ return;
5465
+ this.closed = true;
5466
+ await (0, import_promises13.rm)(this.sharedRoot, { recursive: true, force: true });
5467
+ }
5468
+ async exportLayout(mode, tag, executable, span) {
5469
+ const outputImageRef = `oci.local/executable:${tag}`;
5470
+ const exportedDir = layoutRefPath(mode.layoutRoot, outputImageRef);
5471
+ try {
5472
+ step(`Exporting ${executable.layoutDir} directly with the CNB lifecycle`);
5473
+ await this.runner.runLayout({
5474
+ executablePath: executable.executablePath,
5475
+ outputImageRef,
5476
+ layoutRoot: mode.layoutRoot,
5477
+ span
5478
+ });
5479
+ const { manifestDigest } = await verifyOciLayout(exportedDir);
5480
+ await moveDirectory(exportedDir, executable.layoutDir);
5481
+ span?.setAttributes({ "image.digest": manifestDigest });
5482
+ info(`Image layout ${executable.layoutDir} (${manifestDigest})`);
5483
+ return {
5484
+ kind: "oci-layout",
5485
+ directory: executable.layoutDir,
5486
+ manifestDigest
5487
+ };
5488
+ } finally {
5489
+ await (0, import_promises13.rm)(exportedDir, { recursive: true, force: true });
5490
+ }
5491
+ }
5492
+ async push(mode, tag, executable, span) {
5493
+ const { registry, fullRepository, username, token } = mode;
5494
+ const imageRef = `${registry}/${fullRepository}:${tag}`;
5495
+ step(`Publishing ${imageRef} directly with the CNB lifecycle`);
5496
+ const digest = await this.runner.runPush({
5497
+ executablePath: executable.executablePath,
5498
+ imageRef,
5499
+ credentials: { registry, username, token },
5500
+ span
5501
+ });
5502
+ const reference = `${registry}/${fullRepository}@${digest}`;
5503
+ span?.setAttributes({
5504
+ "image.digest": digest,
5505
+ "image.resolved_ref": reference
5506
+ });
5507
+ info(`Image reference ${reference}`);
5508
+ return { kind: "registry", reference };
5509
+ }
5510
+ };
5511
+
4146
5512
  // src/index.ts
4147
5513
  var version = 2;
4148
5514
  var CONTAINER_OUTPUT_PATH = "container";
@@ -4168,164 +5534,122 @@ function resolveImageTag() {
4168
5534
  }
4169
5535
  return `build-${Date.now().toString(36)}`;
4170
5536
  }
4171
- async function authenticateRegistry(engine, buildParams, span) {
4172
- const forceLogin = readString(process.env.VERCEL_VCR_FORCE_LOGIN) === "1";
4173
- const authFile = forceLogin ? void 0 : existingRegistryAuthFile();
4174
- if (authFile) {
4175
- debug(`registry auth file present: ${authFile}`);
4176
- step(`Using registry credentials from ${authFile}`);
4177
- span?.setAttributes({
4178
- "container.registry": VCR_REGISTRY,
4179
- "registry.username": buildParams.username,
4180
- "registry.auth_file": authFile,
4181
- "registry.login_skipped": toTag(true)
4182
- });
4183
- done("authenticated via provisioned credentials");
4184
- return;
4185
- }
4186
- step(`Authenticating to ${VCR_REGISTRY} as ${buildParams.username}`);
5537
+ async function prepareToolchain(engine, span) {
4187
5538
  await withSpan(
4188
5539
  span,
4189
- "container.registry_login",
5540
+ "container.ensure_toolchain_ready",
5541
+ { "container.engine": engine.name },
5542
+ (s) => engine.ensureReady(s)
5543
+ );
5544
+ await withSpan(
5545
+ span,
5546
+ "container.toolchain_diagnostics",
5547
+ { "container.engine": engine.name },
5548
+ (s) => engine.logDiagnostics(s)
5549
+ );
5550
+ await withSpan(
5551
+ span,
5552
+ "container.verify_storage",
5553
+ { "container.engine": engine.name },
5554
+ (s) => engine.verifyStorage?.(s) ?? Promise.resolve()
5555
+ );
5556
+ }
5557
+ async function buildImage(engine, buildParams, schedulesCommand, span) {
5558
+ const { imageRef, dockerfilePath, contextDir, buildArgs, buildTarget } = buildParams;
5559
+ debug(`dockerfile: ${dockerfilePath}`);
5560
+ debug(`context: ${contextDir}`);
5561
+ debug(`platform: ${TARGET_PLATFORM}`);
5562
+ debug(`target: ${buildTarget ?? "(last stage)"}`);
5563
+ debug(
5564
+ `build args: ${buildArgs ? Object.keys(buildArgs).length : 0} (from project build env)`
5565
+ );
5566
+ const buildStart = Date.now();
5567
+ step(
5568
+ `${engine.name} build (${TARGET_PLATFORM}${buildTarget ? `, target ${buildTarget}` : ""})`
5569
+ );
5570
+ await withSpan(
5571
+ span,
5572
+ "container.image_build",
4190
5573
  {
4191
- "container.registry": VCR_REGISTRY,
4192
- "registry.username": buildParams.username
5574
+ "image.ref": imageRef,
5575
+ "image.platform": TARGET_PLATFORM,
5576
+ "image.build_target": buildTarget
4193
5577
  },
4194
- () => engine.login(buildParams)
5578
+ async () => {
5579
+ if (schedulesCommand) {
5580
+ await buildSchedulesCommandImage(engine, buildParams);
5581
+ } else {
5582
+ await engine.build(buildParams);
5583
+ }
5584
+ }
5585
+ );
5586
+ done(`built in ${elapsed(buildStart)}`);
5587
+ }
5588
+ function reportStorage(engine, span) {
5589
+ return withSpan(
5590
+ span,
5591
+ "container.report_storage",
5592
+ { "container.engine": engine.name },
5593
+ (s) => engine.reportStorage?.(s) ?? Promise.resolve()
4195
5594
  );
4196
- done("authenticated");
4197
5595
  }
4198
- async function buildAndPushImage(params) {
4199
- const {
4200
- contextDir,
4201
- dockerfilePath,
4202
- repository,
4203
- tag,
4204
- buildArgs,
4205
- buildTarget,
4206
- buildahClient,
4207
- parentSpan
4208
- } = params;
4209
- const engine = selectContainerEngine(buildahClient);
5596
+ async function buildAndPublishImage(build2, exportLayout) {
5597
+ const engine = selectContainerEngine(build2.buildahClient);
5598
+ const publisher = createImagePublisher({ build: build2, engine, exportLayout });
5599
+ build2.parentSpan?.setAttributes({ "container.mode": publisher.mode });
4210
5600
  return withSpan(
4211
- parentSpan,
4212
- "container.build_and_push",
5601
+ build2.parentSpan,
5602
+ `container.${publisher.mode}`,
4213
5603
  {
4214
5604
  "container.engine": engine.name,
4215
- "container.registry": VCR_REGISTRY,
4216
- "container.repository": repository
5605
+ "container.repository": build2.repository,
5606
+ ...publisher.spanAttributes
4217
5607
  },
4218
5608
  async (buildSpan) => {
4219
- const target = await resolveRegistryTarget({
4220
- repository,
4221
- tag,
5609
+ const publication = await publisher.resolve(buildSpan);
5610
+ const { imageRef } = publication;
5611
+ const buildParams = {
5612
+ contextDir: build2.contextDir,
5613
+ dockerfilePath: build2.dockerfilePath,
5614
+ imageRef,
5615
+ buildArgs: build2.buildArgs,
5616
+ buildTarget: build2.buildTarget,
5617
+ useBuildahStoreCache: buildahStoreCacheEnabled(),
4222
5618
  span: buildSpan
4223
- });
4224
- const { token, claims, username, fullRepository, imageRef } = target;
4225
- buildSpan?.setAttributes({
4226
- "container.repository": fullRepository,
4227
- "image.tag": tag,
4228
- "image.ref": imageRef,
4229
- "registry.username": username
4230
- });
5619
+ };
4231
5620
  return engine.withRuntime(buildSpan, async () => {
4232
- await withSpan(
4233
- buildSpan,
4234
- "container.ensure_toolchain_ready",
4235
- { "container.engine": engine.name },
4236
- (s) => engine.ensureReady(s)
4237
- );
4238
- await withSpan(
4239
- buildSpan,
4240
- "container.toolchain_diagnostics",
4241
- { "container.engine": engine.name },
4242
- (s) => engine.logDiagnostics(s)
4243
- );
4244
- await withSpan(
4245
- buildSpan,
4246
- "container.verify_storage",
4247
- { "container.engine": engine.name },
4248
- (s) => engine.verifyStorage?.(s) ?? Promise.resolve()
4249
- );
4250
- const buildParams = {
4251
- contextDir,
4252
- dockerfilePath,
4253
- imageRef,
4254
- registry: VCR_REGISTRY,
4255
- username,
4256
- token,
4257
- repository,
4258
- buildArgs,
4259
- buildTarget,
4260
- useBuildahStoreCache: buildahStoreCacheEnabled(),
4261
- span: buildSpan
4262
- };
4263
- await authenticateRegistry(engine, buildParams, buildSpan);
4264
- await withSpan(
4265
- buildSpan,
4266
- "container.ensure_repository",
4267
- { "container.repository": repository },
4268
- (s) => ensureRepository(repository, token, claims, s)
4269
- );
4270
- info(`Building image ${imageRef} (${engine.name})`);
4271
- debug(`dockerfile: ${dockerfilePath}`);
4272
- debug(`context: ${contextDir}`);
4273
- debug(`platform: ${TARGET_PLATFORM}`);
4274
- debug(`target: ${buildTarget ?? "(last stage)"}`);
4275
- debug(
4276
- `build args: ${buildArgs ? Object.keys(buildArgs).length : 0} (from project build env)`
4277
- );
5621
+ await prepareToolchain(engine, buildSpan);
5622
+ await publication.connect?.(buildSpan);
5623
+ const imageName = exportLayout ? build2.repository : imageRef;
5624
+ info(`Building image ${imageName} (${engine.name})`);
4278
5625
  const buildStart = Date.now();
4279
- step(
4280
- `${engine.name} build (${TARGET_PLATFORM}${buildTarget ? `, target ${buildTarget}` : ""})`
4281
- );
4282
- await withSpan(
4283
- buildSpan,
4284
- "container.image_build",
4285
- {
4286
- "image.ref": imageRef,
4287
- "image.platform": TARGET_PLATFORM,
4288
- "image.build_target": buildTarget
4289
- },
4290
- async () => {
4291
- if (params.schedulesCommand) {
4292
- await buildSchedulesCommandImage(engine, buildParams);
4293
- } else {
4294
- await engine.build(buildParams);
4295
- }
4296
- }
4297
- );
4298
- done(`built in ${elapsed(buildStart)}`);
4299
- const pushStart = Date.now();
4300
- step(`Pushing ${imageRef}`);
4301
- const digest = await withSpan(
4302
- buildSpan,
4303
- "container.push",
4304
- { "image.ref": imageRef },
4305
- () => engine.push(buildParams)
5626
+ await buildImage(
5627
+ engine,
5628
+ buildParams,
5629
+ build2.schedulesCommand,
5630
+ buildSpan
4306
5631
  );
4307
- done(`pushed ${shortDigest(digest)} in ${elapsed(pushStart)}`);
4308
- await withSpan(
4309
- buildSpan,
4310
- "container.report_storage",
4311
- { "container.engine": engine.name },
4312
- (s) => engine.reportStorage?.(s) ?? Promise.resolve()
4313
- );
4314
- const resolvedRef = `${VCR_REGISTRY}/${fullRepository}@${digest}`;
4315
- buildSpan?.setAttributes({
4316
- "image.digest": digest,
4317
- "image.resolved_ref": resolvedRef
4318
- });
4319
- info(`Image reference ${resolvedRef}`);
5632
+ const image = await publication.publish(buildParams, buildSpan);
5633
+ await reportStorage(engine, buildSpan);
4320
5634
  debug(
4321
- `container build_and_push total: ${elapsed(buildStart)} (build + push + storage report)`
5635
+ `container ${publisher.mode} total: ${elapsed(buildStart)} (build + publish + storage report)`
4322
5636
  );
4323
- return resolvedRef;
5637
+ return image;
4324
5638
  });
4325
5639
  }
4326
5640
  );
4327
5641
  }
4328
- async function resolveImageHandler(options, source, buildahClient, span, schedulesCommand) {
5642
+ async function containerImageFields(image) {
5643
+ if (image.kind === "registry") {
5644
+ return { files: {}, handler: image.reference };
5645
+ }
5646
+ return {
5647
+ files: await (0, import_build_utils11.glob)("**", image.directory),
5648
+ handler: image.manifestDigest,
5649
+ image: { type: "oci-layout", path: "image" }
5650
+ };
5651
+ }
5652
+ async function resolveImageOutput(options, source, buildahClient, span, schedulesCommand) {
4329
5653
  const { config, meta } = options;
4330
5654
  const { daemon } = config;
4331
5655
  span?.setAttributes({
@@ -4335,7 +5659,7 @@ async function resolveImageHandler(options, source, buildahClient, span, schedul
4335
5659
  if (source.kind === "prebuilt") {
4336
5660
  span?.setAttributes({ "container.mode": "prebuilt" });
4337
5661
  info(`Using prebuilt image ${source.imageRef}`);
4338
- return source.imageRef;
5662
+ return { kind: "registry", reference: source.imageRef };
4339
5663
  }
4340
5664
  if (source.kind === "buildpack") {
4341
5665
  const { buildpack } = source;
@@ -4346,9 +5670,9 @@ async function resolveImageHandler(options, source, buildahClient, span, schedul
4346
5670
  "buildpack.runtime": buildpack.runtime,
4347
5671
  "image.tag": tag3
4348
5672
  });
4349
- return tag3;
5673
+ return { kind: "registry", reference: tag3 };
4350
5674
  }
4351
- const repository2 = daemon ? (0, import_build_utils9.getDaemonImageRepository)(daemon.name) : sanitizeRepository(options.service?.name ?? buildpack.runtime);
5675
+ const repository2 = daemon ? (0, import_build_utils11.getDaemonImageRepository)(daemon.name) : sanitizeRepository(options.service?.name ?? buildpack.runtime);
4352
5676
  const tag2 = resolveImageTag();
4353
5677
  span?.setAttributes({
4354
5678
  "container.mode": "buildpack-build-and-push",
@@ -4360,20 +5684,23 @@ async function resolveImageHandler(options, source, buildahClient, span, schedul
4360
5684
  meta?.buildEnv ?? (buildpack.runtime === "go" ? { CGO_ENABLED: process.env.CGO_ENABLED } : void 0)
4361
5685
  );
4362
5686
  try {
4363
- return await buildAndPushBuildpack({
4364
- buildpack,
4365
- files: options.files,
4366
- workPath: options.workPath,
4367
- repoRootPath: options.repoRootPath,
4368
- service: options.service,
4369
- repository: repository2,
4370
- tag: tag2,
4371
- config,
4372
- meta,
4373
- buildEnv,
4374
- buildahClient,
4375
- parentSpan: span
4376
- });
5687
+ return {
5688
+ kind: "registry",
5689
+ reference: await buildAndPushBuildpack({
5690
+ buildpack,
5691
+ files: options.files,
5692
+ workPath: options.workPath,
5693
+ repoRootPath: options.repoRootPath,
5694
+ service: options.service,
5695
+ repository: repository2,
5696
+ tag: tag2,
5697
+ config,
5698
+ meta,
5699
+ buildEnv,
5700
+ buildahClient,
5701
+ parentSpan: span
5702
+ })
5703
+ };
4377
5704
  } catch (error) {
4378
5705
  if (daemon && error.exitCode === BUILDPACK_FAILED_EXIT_CODE) {
4379
5706
  throw new Error(
@@ -4387,40 +5714,43 @@ async function resolveImageHandler(options, source, buildahClient, span, schedul
4387
5714
  if (meta?.isDev) {
4388
5715
  const serviceName = options.service?.name;
4389
5716
  const tag2 = devImageTag(
4390
- serviceName ?? import_node_path24.default.basename(dockerfileRel).split(".")[0]
5717
+ serviceName ?? import_node_path30.default.basename(dockerfileRel).split(".")[0]
4391
5718
  );
4392
5719
  span?.setAttributes({ "container.mode": "dev", "image.tag": tag2 });
4393
- return tag2;
4394
- }
4395
- if (!(0, import_node_fs17.existsSync)(dockerfilePath)) {
4396
- throw new Error(
4397
- `Dockerfile not found at "${dockerfilePath}" for container service.`
4398
- );
5720
+ return { kind: "registry", reference: tag2 };
4399
5721
  }
4400
- const repository = daemon ? (0, import_build_utils9.getDaemonImageRepository)(daemon.name) : sanitizeRepository(
4401
- options.service?.name ?? import_node_path24.default.basename(dockerfileRel).split(".")[0]
5722
+ const repository = daemon ? (0, import_build_utils11.getDaemonImageRepository)(daemon.name) : sanitizeRepository(
5723
+ options.service?.name ?? import_node_path30.default.basename(dockerfileRel).split(".")[0]
4402
5724
  );
4403
5725
  const tag = resolveImageTag();
4404
- const contextDir = daemon || schedulesCommand || options.service ? options.workPath : import_node_path24.default.dirname(dockerfilePath);
4405
- const contextIsRoot = Boolean(daemon || schedulesCommand || options.service) || import_node_path24.default.dirname(import_node_path24.default.normalize(dockerfileRel)) === ".";
5726
+ const contextDir = await resolveBuildContext({
5727
+ repoRootPath: options.repoRootPath,
5728
+ workPath: options.workPath,
5729
+ contextDir: daemon || schedulesCommand || options.service ? options.workPath : import_node_path30.default.dirname(dockerfilePath),
5730
+ dockerfilePath
5731
+ });
5732
+ const contextIsRoot = Boolean(daemon || schedulesCommand || options.service) || import_node_path30.default.dirname(import_node_path30.default.normalize(dockerfileRel)) === ".";
4406
5733
  const buildArgs = buildArgsFromEnv(meta?.buildEnv);
5734
+ const shouldExportLayout = ociLayoutRequested() && !daemon;
4407
5735
  span?.setAttributes({
4408
- "container.mode": "build_and_push",
4409
5736
  "container.repository": repository,
4410
5737
  "container.context_is_root": toTag(contextIsRoot),
4411
5738
  "image.tag": tag
4412
5739
  });
4413
- return buildAndPushImage({
4414
- contextDir,
4415
- dockerfilePath,
4416
- repository,
4417
- tag,
4418
- buildArgs,
4419
- buildTarget: resolveBuildTarget(options.config),
4420
- buildahClient,
4421
- parentSpan: span,
4422
- schedulesCommand
4423
- });
5740
+ return buildAndPublishImage(
5741
+ {
5742
+ contextDir,
5743
+ dockerfilePath,
5744
+ repository,
5745
+ tag,
5746
+ buildArgs,
5747
+ buildTarget: resolveBuildTarget(options.config),
5748
+ buildahClient,
5749
+ parentSpan: span,
5750
+ schedulesCommand
5751
+ },
5752
+ shouldExportLayout
5753
+ );
4424
5754
  }
4425
5755
  function buildArgsFromEnv(env) {
4426
5756
  if (!env) {
@@ -4437,7 +5767,6 @@ function buildArgsFromEnv(env) {
4437
5767
  async function build(options) {
4438
5768
  const source = resolveImageSource(options, "build");
4439
5769
  const schedulesCommand = options.config.schedulesCommand;
4440
- const { daemon } = options.config;
4441
5770
  const buildahClient = new BuildahClient(sharedBuildahStoreLock);
4442
5771
  if (!options.meta?.isDev && selectContainerEngine(buildahClient).name === "buildah") {
4443
5772
  await BuildahStoreCache.forProject(options, buildahClient).beforeBuild({
@@ -4449,15 +5778,25 @@ async function build(options) {
4449
5778
  options.span,
4450
5779
  "container.resolve_image",
4451
5780
  { "service.name": options.service?.name },
4452
- (span) => resolveImageHandler(
4453
- options,
4454
- source,
4455
- buildahClient,
4456
- span,
4457
- schedulesCommand
4458
- )
5781
+ (span) => resolveImageOutput(options, source, buildahClient, span, schedulesCommand)
4459
5782
  );
5783
+ try {
5784
+ return await createBuildResult(options, source, schedulesCommand, image);
5785
+ } catch (error) {
5786
+ if (image.kind === "oci-layout") {
5787
+ await (0, import_promises14.rm)(image.directory, { recursive: true, force: true });
5788
+ }
5789
+ throw error;
5790
+ }
5791
+ }
5792
+ async function createBuildResult(options, source, schedulesCommand, image) {
5793
+ const { daemon } = options.config;
4460
5794
  if (daemon) {
5795
+ if (image.kind !== "registry") {
5796
+ throw new Error(
5797
+ `Daemon "${daemon.name}" was built as an OCI image layout, but daemons run from the registry.`
5798
+ );
5799
+ }
4461
5800
  await generateProjectManifest({
4462
5801
  workPath: options.workPath,
4463
5802
  framework: options.diagnosticsValues?.framework,
@@ -4468,7 +5807,7 @@ async function build(options) {
4468
5807
  daemons: {
4469
5808
  [daemon.name]: {
4470
5809
  runtime: "container",
4471
- image,
5810
+ image: image.reference,
4472
5811
  // Checked by vercel.json validation: a daemon sets one of them.
4473
5812
  instances: daemon.instances ?? daemon.replicas,
4474
5813
  // A command replaces the image's entrypoint, which for a buildpack
@@ -4491,7 +5830,7 @@ async function build(options) {
4491
5830
  }
4492
5831
  };
4493
5832
  }
4494
- const lambdaOptions = await (0, import_build_utils9.getLambdaOptionsFromFunction)({
5833
+ const lambdaOptions = await (0, import_build_utils11.getLambdaOptionsFromFunction)({
4495
5834
  sourceFile: resolveFunctionSourceFile(options),
4496
5835
  config: options.config,
4497
5836
  isScheduleEntrypoint: schedulesCommand !== void 0
@@ -4500,7 +5839,7 @@ async function build(options) {
4500
5839
  await generateProjectManifest({
4501
5840
  workPath: options.workPath,
4502
5841
  framework: options.diagnosticsValues?.framework,
4503
- serviceType: options.service ? (0, import_build_utils9.getReportedServiceType)(options.service) : void 0
5842
+ serviceType: options.service ? (0, import_build_utils11.getReportedServiceType)(options.service) : void 0
4504
5843
  });
4505
5844
  const routes = [
4506
5845
  { handle: "filesystem" },
@@ -4523,26 +5862,22 @@ async function build(options) {
4523
5862
  return {
4524
5863
  routes: schedulesCommand ? [] : routes,
4525
5864
  output: {
4526
- [outputPath]: {
4527
- type: "Lambda",
4528
- files: {},
4529
- // For `runtime: 'container'` the OCI image reference is carried in
4530
- // `handler`; the platform surfaces it as the container image downstream
4531
- // (vercel/api#76729).
4532
- handler: image,
5865
+ [outputPath]: new import_build_utils11.ContainerImage({
5866
+ ...await containerImageFields(image),
4533
5867
  runtime: "container",
4534
5868
  environment: schedulesCommand ? {
4535
5869
  [SCHEDULES_COMMAND_ENV]: JSON.stringify(schedulesCommand.command)
4536
5870
  } : {},
4537
5871
  ...command ? { command } : {},
4538
5872
  ...lambdaOptions
4539
- }
5873
+ })
4540
5874
  }
4541
5875
  };
4542
5876
  }
4543
5877
  // Annotate the CommonJS export names for ESM import in node:
4544
5878
  0 && (module.exports = {
4545
5879
  CONTAINER_OUTPUT_PATH,
5880
+ ExecutableImageBuilder,
4546
5881
  build,
4547
5882
  diagnostics,
4548
5883
  prepareCache,