@vercel/container 27.0.0-snapshot-fdd4372a7e51 → 28.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) 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 +79 -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 +1190 -69
  38. package/dist/oci-layout/index.d.ts +18 -0
  39. package/dist/oci-layout/layout.d.ts +38 -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/registry.d.ts +27 -0
  44. package/dist/schedules-command-dispatcher +0 -0
  45. package/dist/schedules-command.d.ts +11 -0
  46. package/dist/storage-driver.d.ts +15 -0
  47. package/dist/util.d.ts +102 -0
  48. 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,7 @@ 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_node_path29 = __toESM(require("path"));
110
110
 
111
111
  // src/util.ts
112
112
  var import_build_utils2 = require("@vercel/build-utils");
@@ -164,6 +164,13 @@ function shortDigest(digest) {
164
164
  function delay(ms) {
165
165
  return new Promise((resolve5) => setTimeout(resolve5, ms));
166
166
  }
167
+ async function settleAll(tasks) {
168
+ for (const task of await Promise.allSettled(tasks)) {
169
+ if (task.status === "rejected") {
170
+ throw task.reason;
171
+ }
172
+ }
173
+ }
167
174
  async function withSpan(parent, name, attrs, fn) {
168
175
  if (!parent) {
169
176
  return fn(void 0);
@@ -200,6 +207,8 @@ function run(cmd, args, opts = {}) {
200
207
  const child = (0, import_node_child_process.spawn)(cmd, args, {
201
208
  cwd: opts.cwd,
202
209
  env: opts.env,
210
+ ...opts.uid !== void 0 && { uid: opts.uid },
211
+ ...opts.gid !== void 0 && { gid: opts.gid },
203
212
  stdio: [opts.input !== void 0 ? "pipe" : "ignore", "pipe", "pipe"]
204
213
  });
205
214
  let stdout = "";
@@ -271,6 +280,37 @@ function extractField(text, label) {
271
280
  function isBuildContainer() {
272
281
  return Boolean(readString(process.env.VERCEL_BUILD_IMAGE));
273
282
  }
283
+ var DEFAULT_API_URL = "https://api.vercel.com";
284
+ var DEFAULT_VCR_REGISTRY = "vcr.vercel.com";
285
+ function isVercelHostname(hostname) {
286
+ return hostname === "vercel.com" || hostname.endsWith(".vercel.com");
287
+ }
288
+ function resolveApiUrl() {
289
+ const configured = readString(process.env.VERCEL_API_URL);
290
+ if (!configured)
291
+ return DEFAULT_API_URL;
292
+ let url;
293
+ try {
294
+ url = new URL(configured);
295
+ } catch {
296
+ url = void 0;
297
+ }
298
+ if (url && url.protocol === "https:" && isVercelHostname(url.hostname)) {
299
+ return url.origin;
300
+ }
301
+ debug(`ignoring VERCEL_API_URL "${configured}"`);
302
+ return DEFAULT_API_URL;
303
+ }
304
+ function resolveVcrRegistry() {
305
+ const configured = readString(process.env.VERCEL_VCR_REGISTRY);
306
+ if (!configured)
307
+ return DEFAULT_VCR_REGISTRY;
308
+ if (/^[a-z0-9.-]+$/i.test(configured) && isVercelHostname(configured)) {
309
+ return configured;
310
+ }
311
+ debug(`ignoring VERCEL_VCR_REGISTRY "${configured}"`);
312
+ return DEFAULT_VCR_REGISTRY;
313
+ }
274
314
  function existingRegistryAuthFile() {
275
315
  const explicit = readString(process.env.REGISTRY_AUTH_FILE);
276
316
  if (explicit) {
@@ -534,7 +574,7 @@ function resolveProjectContext(token) {
534
574
  };
535
575
  }
536
576
  async function mintProjectOidcToken(params) {
537
- const apiUrl = (readString(process.env.VERCEL_API_URL) ?? "https://api.vercel.com").replace(/\/+$/, "");
577
+ const apiUrl = resolveApiUrl();
538
578
  const query = new URLSearchParams({ source: "vercel-container-build" });
539
579
  if (params.teamId) {
540
580
  query.set("teamId", params.teamId);
@@ -616,7 +656,7 @@ function formatVcrAuthError(registry, username, detail) {
616
656
  }
617
657
 
618
658
  // src/engines/types.ts
619
- var VCR_REGISTRY = process.env.VERCEL_VCR_REGISTRY || "vcr.vercel.com";
659
+ var VCR_REGISTRY = resolveVcrRegistry();
620
660
  var TARGET_PLATFORM = "linux/amd64";
621
661
  var DIGEST_RE = /^sha256:[a-f0-9]{64}$/;
622
662
  function buildArgFlags(params) {
@@ -753,7 +793,7 @@ async function ensureRepository(repository, token, claims, span) {
753
793
  return;
754
794
  }
755
795
  span?.setAttributes({ "team.id": teamId, "project.id": projectId });
756
- const apiUrl = (readString(process.env.VERCEL_API_URL) ?? "https://api.vercel.com").replace(/\/+$/, "");
796
+ const apiUrl = resolveApiUrl();
757
797
  const url = `${apiUrl}/v1/vcr/repository?teamId=${encodeURIComponent(teamId)}`;
758
798
  const body = JSON.stringify({ name: repository, projectId });
759
799
  step(`Ensuring registry repository "${repository}"`);
@@ -1678,6 +1718,11 @@ var distribution_default = {
1678
1718
  id: "vercel/rust",
1679
1719
  version: "0.5.0",
1680
1720
  sha256: "f0f038437829d45077c8ad31060cd2274b80c3c55acfbe00ca937ea7dddfad5c"
1721
+ },
1722
+ "prebuilt-static": {
1723
+ id: "vercel/prebuilt-static",
1724
+ version: "0.1.0",
1725
+ sha256: "edcc2674706ce7fdc69a2cedfa4aaba4743ede3bc930fffe5cdb9d4b1a53e81a"
1681
1726
  }
1682
1727
  },
1683
1728
  images: {
@@ -1815,23 +1860,48 @@ var BUILD_USER_ID = 1001;
1815
1860
  var BUILD_GROUP_ID = 1001;
1816
1861
  var BUILD_USER = `${BUILD_USER_ID}:${BUILD_GROUP_ID}`;
1817
1862
  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
- ];
1863
+ var CREATOR_KEYCHAIN_ENV = {
1864
+ CNB_REGISTRY_AUTH_KEYCHAIN_SKIP_AMAZON: "true",
1865
+ CNB_REGISTRY_AUTH_KEYCHAIN_SKIP_AZURE: "true"
1866
+ };
1867
+ var CREATOR_KEYCHAIN_ENV_ARGS = Object.entries(
1868
+ CREATOR_KEYCHAIN_ENV
1869
+ ).flatMap(([name, value]) => ["--env", `${name}=${value}`]);
1824
1870
  var ORDER_MOUNT_DIR = "/platform/order";
1825
1871
  var ORDER_FILE = `${ORDER_MOUNT_DIR}/order.toml`;
1826
1872
  var CACHE_MOUNT_DIR = "/cache";
1827
1873
  var ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
1828
- async function stageWorkspace({ files, workPath }, destinationDir) {
1874
+ async function stageWorkspace({
1875
+ files,
1876
+ workPath,
1877
+ repoRootPath
1878
+ }, destinationDir) {
1879
+ const repoRoot = (0, import_node_path8.resolve)(repoRootPath ?? workPath);
1880
+ const serviceRoot = (0, import_node_path8.resolve)(workPath);
1881
+ const serviceRelative = (0, import_node_path8.relative)(repoRoot, serviceRoot);
1882
+ if ((0, import_node_fs5.lstatSync)(serviceRoot).isSymbolicLink()) {
1883
+ throw new Error(
1884
+ "Buildpack service root must not be reached through a symbolic link."
1885
+ );
1886
+ }
1887
+ if (serviceRelative && serviceRelative !== "." && serviceRelative !== ".." && !serviceRelative.startsWith(`..${import_node_path8.sep}`) && !(0, import_node_path8.isAbsolute)(serviceRelative)) {
1888
+ let current = repoRoot;
1889
+ for (const part of serviceRelative.split(import_node_path8.sep)) {
1890
+ if (!part || part === ".")
1891
+ continue;
1892
+ current = (0, import_node_path8.join)(current, part);
1893
+ if ((0, import_node_fs5.lstatSync)(current).isSymbolicLink()) {
1894
+ throw new Error(
1895
+ "Buildpack service root must not be reached through a symbolic link."
1896
+ );
1897
+ }
1898
+ }
1899
+ }
1829
1900
  const staged = /* @__PURE__ */ Object.create(null);
1830
1901
  const symlinks = /* @__PURE__ */ new Set();
1831
1902
  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) {
1903
+ const normalized = import_node_path8.posix.normalize(name).replace(/\/$/, "");
1904
+ if (!normalized || normalized === "." || name.includes("\\") || import_node_path8.win32.isAbsolute(name) || import_node_path8.posix.isAbsolute(name) || name.split("/").includes("..") || normalized in staged) {
1835
1905
  throw new Error(`Invalid buildpack source path ${JSON.stringify(name)}.`);
1836
1906
  }
1837
1907
  staged[normalized] = file;
@@ -1851,7 +1921,13 @@ async function stageWorkspace({ files, workPath }, destinationDir) {
1851
1921
  `Buildpack source symlink ${name} has an absolute target.`
1852
1922
  );
1853
1923
  }
1854
- target = target.replace(/\\/g, "/");
1924
+ if (import_node_path8.sep === "\\") {
1925
+ target = target.replace(/\\/g, "/");
1926
+ } else if (target.includes("\\")) {
1927
+ throw new Error(
1928
+ `Buildpack source symlink ${name} has a target staging would reinterpret.`
1929
+ );
1930
+ }
1855
1931
  const resolved = import_node_path8.posix.join(import_node_path8.posix.dirname(normalized), target);
1856
1932
  if (resolved === ".." || resolved.startsWith("../")) {
1857
1933
  throw new Error(
@@ -1990,7 +2066,7 @@ function lifecycleFailure(error, context) {
1990
2066
  return Object.assign(
1991
2067
  new Error(
1992
2068
  [
1993
- `${context.buildpack.runtime} buildpack build failed via ${context.via} (${context.buildImage}).`,
2069
+ `${context.buildpack.runtime} buildpack build failed via ${context.via}${context.buildImage ? ` (${context.buildImage})` : ""}.`,
1994
2070
  ...hint ? [`The lifecycle exited with code ${exitCode}: ${hint}.`] : [],
1995
2071
  "",
1996
2072
  `Underlying error: ${error.message}`,
@@ -2024,6 +2100,24 @@ function cnbRegistryAuth(credentials) {
2024
2100
  const basic = Buffer.from(`${username}:${token}`).toString("base64");
2025
2101
  return JSON.stringify({ [registry]: `Basic ${basic}` });
2026
2102
  }
2103
+ function creatorExport(target) {
2104
+ if (target.kind === "oci-layout") {
2105
+ return {
2106
+ args: ["-layout", `-layout-dir=${target.layoutDir}`, target.imageRef],
2107
+ // lifecycle 0.21.18 guards `-layout` behind experimental mode and fails
2108
+ // when it is unset. `quiet` allows it without logging a warning into
2109
+ // every build.
2110
+ env: { CNB_EXPERIMENTAL_MODE: "quiet" }
2111
+ };
2112
+ }
2113
+ return {
2114
+ args: [target.imageRef],
2115
+ env: {
2116
+ CNB_REGISTRY_AUTH: cnbRegistryAuth(target.credentials),
2117
+ ...CREATOR_KEYCHAIN_ENV
2118
+ }
2119
+ };
2120
+ }
2027
2121
  function distributionUrls(buildpack) {
2028
2122
  return {
2029
2123
  lifecycle: LIFECYCLE.url,
@@ -3420,6 +3514,10 @@ function resolveImageSource(options, context) {
3420
3514
  "Buildpack builds are selected by Vercel from the project's framework or the service's runtime; `buildpack` is not a `builds` configuration option."
3421
3515
  );
3422
3516
  }
3517
+ const explicitImage = readString(config.handler);
3518
+ if (explicitImage && !(entrypointRef && isDockerfileRef(entrypointRef))) {
3519
+ return { kind: "prebuilt", imageRef: explicitImage };
3520
+ }
3423
3521
  if (buildpack && (config.daemon || readString(config.buildpackEntrypoint))) {
3424
3522
  return { kind: "buildpack", buildpack };
3425
3523
  }
@@ -3442,12 +3540,53 @@ function resolveImageSource(options, context) {
3442
3540
  );
3443
3541
  }
3444
3542
 
3445
- // src/buildah-store-cache/cache.ts
3543
+ // src/build-context.ts
3446
3544
  var import_build_utils7 = require("@vercel/build-utils");
3447
- var import_node_crypto8 = require("crypto");
3448
3545
  var import_promises7 = require("fs/promises");
3449
- var import_node_os11 = require("os");
3450
3546
  var import_node_path21 = require("path");
3547
+ async function resolveBuildContext({
3548
+ repoRootPath,
3549
+ workPath,
3550
+ contextDir,
3551
+ dockerfilePath
3552
+ }) {
3553
+ const [root, context, dockerfile] = await Promise.all([
3554
+ resolvePath(repoRootPath ?? workPath, "repository root"),
3555
+ resolvePath(contextDir, "container build context"),
3556
+ resolvePath(dockerfilePath, "Dockerfile")
3557
+ ]);
3558
+ for (const [label, target] of [
3559
+ ["Container build context", context],
3560
+ ["Dockerfile", dockerfile]
3561
+ ]) {
3562
+ const rel = (0, import_node_path21.relative)(root, target);
3563
+ if (rel === ".." || rel.startsWith(`..${import_node_path21.sep}`) || (0, import_node_path21.isAbsolute)(rel)) {
3564
+ throw new import_build_utils7.NowBuildError({
3565
+ code: "INVALID_CONTAINER_BUILD_CONTEXT",
3566
+ message: `${label} resolves outside the repository. Keep the build context and Dockerfile inside the repository, including symbolic link targets.`
3567
+ });
3568
+ }
3569
+ }
3570
+ return context;
3571
+ }
3572
+ async function resolvePath(path4, label) {
3573
+ try {
3574
+ return await (0, import_promises7.realpath)(path4);
3575
+ } catch (error) {
3576
+ const code = error.code;
3577
+ throw new import_build_utils7.NowBuildError({
3578
+ code: "INVALID_CONTAINER_BUILD_CONTEXT",
3579
+ message: `Cannot resolve ${label} "${path4}"${code ? ` (${code})` : ""}. Check that it exists and any symbolic links have accessible targets.`
3580
+ });
3581
+ }
3582
+ }
3583
+
3584
+ // src/buildah-store-cache/cache.ts
3585
+ var import_build_utils8 = require("@vercel/build-utils");
3586
+ var import_node_crypto8 = require("crypto");
3587
+ var import_promises8 = require("fs/promises");
3588
+ var import_node_os11 = require("os");
3589
+ var import_node_path22 = require("path");
3451
3590
  var BUILDAH_STORE_CACHE_DIR = ".vercel/cache/buildah-store";
3452
3591
  var STORE_PATHS = {
3453
3592
  graphRoot: BUILDAH_GRAPH_ROOT,
@@ -3461,7 +3600,7 @@ var BuildahStoreCache = class _BuildahStoreCache {
3461
3600
  }
3462
3601
  static forProject(options, client) {
3463
3602
  return new _BuildahStoreCache(
3464
- (0, import_node_path21.resolve)(options.repoRootPath || options.workPath),
3603
+ (0, import_node_path22.resolve)(options.repoRootPath || options.workPath),
3465
3604
  client
3466
3605
  );
3467
3606
  }
@@ -3537,8 +3676,8 @@ var BuildahStoreCache = class _BuildahStoreCache {
3537
3676
  if (!await isRegularFile(archive)) {
3538
3677
  return {};
3539
3678
  }
3540
- return await (0, import_build_utils7.glob)(
3541
- `${BUILDAH_STORE_CACHE_DIR}/${(0, import_node_path21.basename)(archive)}`,
3679
+ return await (0, import_build_utils8.glob)(
3680
+ `${BUILDAH_STORE_CACHE_DIR}/${(0, import_node_path22.basename)(archive)}`,
3542
3681
  this.repositoryRoot
3543
3682
  );
3544
3683
  } catch (error) {
@@ -3548,7 +3687,7 @@ var BuildahStoreCache = class _BuildahStoreCache {
3548
3687
  }
3549
3688
  async removeSnapshots() {
3550
3689
  try {
3551
- await (0, import_promises7.rm)(await this.snapshotDirectory({ create: false }), {
3690
+ await (0, import_promises8.rm)(await this.snapshotDirectory({ create: false }), {
3552
3691
  recursive: true,
3553
3692
  force: true
3554
3693
  });
@@ -3560,24 +3699,24 @@ var BuildahStoreCache = class _BuildahStoreCache {
3560
3699
  }
3561
3700
  async archivePath(options) {
3562
3701
  const key = await snapshotKey(this.client);
3563
- return (0, import_node_path21.join)(await this.snapshotDirectory(options), `store-${key}.tar.zst`);
3702
+ return (0, import_node_path22.join)(await this.snapshotDirectory(options), `store-${key}.tar.zst`);
3564
3703
  }
3565
3704
  async snapshotDirectory({
3566
3705
  create
3567
3706
  }) {
3568
- const root = await (0, import_promises7.realpath)(this.repositoryRoot);
3707
+ const root = await (0, import_promises8.realpath)(this.repositoryRoot);
3569
3708
  let directory = root;
3570
3709
  for (const part of BUILDAH_STORE_CACHE_DIR.split("/")) {
3571
- directory = (0, import_node_path21.join)(directory, part);
3710
+ directory = (0, import_node_path22.join)(directory, part);
3572
3711
  if (create) {
3573
- await (0, import_promises7.mkdir)(directory, { mode: 448 }).catch((error) => {
3712
+ await (0, import_promises8.mkdir)(directory, { mode: 448 }).catch((error) => {
3574
3713
  if (error.code !== "EEXIST")
3575
3714
  throw error;
3576
3715
  });
3577
3716
  }
3578
3717
  const stats = await lstatIfPresent(directory);
3579
3718
  if (!stats) {
3580
- return (0, import_node_path21.join)(root, BUILDAH_STORE_CACHE_DIR);
3719
+ return (0, import_node_path22.join)(root, BUILDAH_STORE_CACHE_DIR);
3581
3720
  }
3582
3721
  if (!stats.isDirectory()) {
3583
3722
  throw new Error(`${directory} is not a directory`);
@@ -3589,7 +3728,7 @@ var BuildahStoreCache = class _BuildahStoreCache {
3589
3728
  async function restoreStore(archive) {
3590
3729
  const storeLock = await requireStoreLock();
3591
3730
  const state = await createBuildahStoreStateDirectory();
3592
- const gate = new FileLock((0, import_node_path21.join)(state, "restore.lock"));
3731
+ const gate = new FileLock((0, import_node_path22.join)(state, "restore.lock"));
3593
3732
  return runStoreCommand(
3594
3733
  {
3595
3734
  action: "restore",
@@ -3597,7 +3736,7 @@ async function restoreStore(archive) {
3597
3736
  ...STORE_PATHS,
3598
3737
  archive,
3599
3738
  storeLock: storeLock.path,
3600
- marker: (0, import_node_path21.join)(state, "restored")
3739
+ marker: (0, import_node_path22.join)(state, "restored")
3601
3740
  }
3602
3741
  },
3603
3742
  gate
@@ -3628,7 +3767,7 @@ async function requireStoreLock() {
3628
3767
  }
3629
3768
  async function describeSave2(result, archive, start) {
3630
3769
  if (result.status === "saved") {
3631
- return `saved the Buildah store cache (${formatBytes((await (0, import_promises7.lstat)(archive)).size)}) in ${elapsed(start)}`;
3770
+ return `saved the Buildah store cache (${formatBytes((await (0, import_promises8.lstat)(archive)).size)}) in ${elapsed(start)}`;
3632
3771
  }
3633
3772
  if (result.status === "unused") {
3634
3773
  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 +3782,8 @@ async function snapshotKey(client) {
3643
3782
  [
3644
3783
  "/usr/share/containers/storage.conf",
3645
3784
  "/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"),
3785
+ (0, import_node_path22.join)(
3786
+ process.env.XDG_CONFIG_HOME || (0, import_node_path22.join)((0, import_node_os11.homedir)(), ".config"),
3648
3787
  "containers/storage.conf"
3649
3788
  ),
3650
3789
  process.env.CONTAINERS_STORAGE_CONF,
@@ -3669,7 +3808,7 @@ async function readOptionalFile(path4) {
3669
3808
  return "";
3670
3809
  }
3671
3810
  try {
3672
- return await (0, import_promises7.readFile)(path4, "utf8");
3811
+ return await (0, import_promises8.readFile)(path4, "utf8");
3673
3812
  } catch (error) {
3674
3813
  if (error.code === "ENOENT")
3675
3814
  return "";
@@ -3684,10 +3823,11 @@ function failureReason(error) {
3684
3823
  }
3685
3824
 
3686
3825
  // src/dev.ts
3826
+ var import_build_utils9 = require("@vercel/build-utils");
3687
3827
  var import_node_child_process4 = require("child_process");
3688
3828
  var import_node_fs16 = require("fs");
3689
3829
  var import_node_os12 = require("os");
3690
- var import_node_path22 = __toESM(require("path"));
3830
+ var import_node_path23 = __toESM(require("path"));
3691
3831
  var HOST_ONLY_ENV = /* @__PURE__ */ new Set([
3692
3832
  "TMPDIR",
3693
3833
  "TMP",
@@ -3717,8 +3857,8 @@ function isHostOnlyEnvVar(key) {
3717
3857
  return HOST_ONLY_ENV.has(key) || key.startsWith("__") || key.startsWith("XPC_") || key.startsWith("SSH_") || key.startsWith("Apple");
3718
3858
  }
3719
3859
  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");
3860
+ const dir = (0, import_node_fs16.mkdtempSync)(import_node_path23.default.join((0, import_node_os12.tmpdir)(), "vercel-container-dev-env-"));
3861
+ const file = import_node_path23.default.join(dir, "env");
3722
3862
  const lines = [];
3723
3863
  for (const [key, value] of Object.entries(env)) {
3724
3864
  if (value.includes("\n")) {
@@ -3801,14 +3941,62 @@ ${detail}` : "")
3801
3941
  });
3802
3942
  });
3803
3943
  }
3944
+ var PULL_AUTH_ERROR = /unauthorized|authentication required|no basic auth credentials|pull access denied|denied:|forbidden|\b40[13]\b/i;
3945
+ function prebuiltImagePullError(imageRef, detail) {
3946
+ if (imageRef.startsWith("vcr.vercel.com/") && PULL_AUTH_ERROR.test(detail)) {
3947
+ return new import_build_utils9.NowBuildError({
3948
+ code: "CONTAINER_IMAGE_PULL_UNAUTHORIZED",
3949
+ 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.
3950
+
3951
+ ${detail}`
3952
+ });
3953
+ }
3954
+ return new import_build_utils9.NowBuildError({
3955
+ code: "CONTAINER_IMAGE_PULL_FAILED",
3956
+ message: `Couldn't pull ${imageRef}.
3957
+
3958
+ ${detail}`
3959
+ });
3960
+ }
3961
+ async function hasLocalImage(imageRef, out) {
3962
+ try {
3963
+ await runForwarded(
3964
+ "docker",
3965
+ ["image", "inspect", "--format", "{{.Id}}", imageRef],
3966
+ out,
3967
+ { quiet: true }
3968
+ );
3969
+ return true;
3970
+ } catch {
3971
+ return false;
3972
+ }
3973
+ }
3974
+ async function pullPrebuiltImage(imageRef, out) {
3975
+ emit(out, `\u25B2 container vercel dev: pulling ${imageRef}`);
3976
+ try {
3977
+ await runForwarded("docker", ["pull", imageRef], out);
3978
+ } catch (err) {
3979
+ const error = prebuiltImagePullError(imageRef, err.message);
3980
+ if (!await hasLocalImage(imageRef, out)) {
3981
+ throw error;
3982
+ }
3983
+ const reason = error.code === "CONTAINER_IMAGE_PULL_UNAUTHORIZED" ? "the registry refused the pull; run `vercel vcr login docker` to get updates" : "the pull failed";
3984
+ emit(
3985
+ out,
3986
+ `\u25B2 container vercel dev: warning: couldn't pull ${imageRef} (${reason}). Using the local copy, which may be out of date.`
3987
+ );
3988
+ }
3989
+ }
3804
3990
  async function resolveDevImage(options, out, span) {
3805
3991
  const source = resolveImageSource(options, "dev");
3806
3992
  if (source.kind === "prebuilt") {
3993
+ await assertDockerAvailable(out);
3807
3994
  span?.setAttributes({ "container.dev_mode": "prebuilt" });
3808
3995
  emit(
3809
3996
  out,
3810
3997
  `\u25B2 container vercel dev: using prebuilt image ${source.imageRef}`
3811
3998
  );
3999
+ await pullPrebuiltImage(source.imageRef, out);
3812
4000
  return { image: source.imageRef };
3813
4001
  }
3814
4002
  if (source.kind === "buildpack") {
@@ -3817,14 +4005,15 @@ async function resolveDevImage(options, out, span) {
3817
4005
  );
3818
4006
  }
3819
4007
  const { dockerfilePath } = source;
3820
- if (!(0, import_node_fs16.existsSync)(dockerfilePath)) {
3821
- throw new Error(
3822
- `Dockerfile not found at "${dockerfilePath}" for container service.`
3823
- );
3824
- }
3825
4008
  const serviceName = options.service?.name ?? "service";
3826
4009
  const tag = devImageTag(serviceName);
3827
- const contextDir = options.service ? options.workPath : import_node_path22.default.dirname(dockerfilePath);
4010
+ const contextDir = await resolveBuildContext({
4011
+ repoRootPath: options.repoRootPath,
4012
+ workPath: options.workPath,
4013
+ contextDir: options.service ? options.workPath : import_node_path23.default.dirname(dockerfilePath),
4014
+ dockerfilePath
4015
+ });
4016
+ await assertDockerAvailable(out);
3828
4017
  const buildArgFlags2 = [];
3829
4018
  const buildEnv = options.meta?.buildEnv ?? {};
3830
4019
  for (const [key, value] of Object.entries(buildEnv)) {
@@ -3962,7 +4151,6 @@ async function startContainer(options, reuseKey) {
3962
4151
  async (span) => {
3963
4152
  const { config, meta, onStdout, onStderr } = options;
3964
4153
  const out = { onStdout, onStderr };
3965
- await assertDockerAvailable(out);
3966
4154
  const { image } = await withSpan(
3967
4155
  span,
3968
4156
  "container.dev.resolve_image",
@@ -3974,11 +4162,6 @@ async function startContainer(options, reuseKey) {
3974
4162
  options.service?.name ?? "service"
3975
4163
  );
3976
4164
  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
4165
  const metaEnv = meta?.env ?? {};
3983
4166
  for (const [key, value] of Object.entries(metaEnv)) {
3984
4167
  if (typeof value === "string" && !isHostOnlyEnvVar(key)) {
@@ -4042,7 +4225,7 @@ async function startContainer(options, reuseKey) {
4042
4225
  }
4043
4226
  });
4044
4227
  const cleanupEnvFile = () => {
4045
- (0, import_node_fs16.rmSync)(import_node_path22.default.dirname(envFilePath), { recursive: true, force: true });
4228
+ (0, import_node_fs16.rmSync)(import_node_path23.default.dirname(envFilePath), { recursive: true, force: true });
4046
4229
  };
4047
4230
  const shutdown = async () => {
4048
4231
  runningContainers.delete(reuseKey);
@@ -4118,10 +4301,10 @@ async function startContainer(options, reuseKey) {
4118
4301
  }
4119
4302
 
4120
4303
  // src/prepare-cache.ts
4121
- var import_build_utils8 = require("@vercel/build-utils");
4122
- var import_node_path23 = require("path");
4304
+ var import_build_utils10 = require("@vercel/build-utils");
4305
+ var import_node_path24 = require("path");
4123
4306
  async function prepareCache(options) {
4124
- const root = (0, import_node_path23.resolve)(options.repoRootPath || options.workPath);
4307
+ const root = (0, import_node_path24.resolve)(options.repoRootPath || options.workPath);
4125
4308
  const buildpackFiles = await collectBuildpackCache(root);
4126
4309
  const buildahStoreFiles = await BuildahStoreCache.forProject(
4127
4310
  options,
@@ -4131,7 +4314,7 @@ async function prepareCache(options) {
4131
4314
  }
4132
4315
  async function collectBuildpackCache(root) {
4133
4316
  const start = Date.now();
4134
- const files = await (0, import_build_utils8.glob)(`${BUILDPACK_CACHE_DIR}/**`, root);
4317
+ const files = await (0, import_build_utils10.glob)(`${BUILDPACK_CACHE_DIR}/**`, root);
4135
4318
  const count = Object.keys(files).length;
4136
4319
  if (count > 0) {
4137
4320
  info(
@@ -4143,6 +4326,943 @@ async function collectBuildpackCache(root) {
4143
4326
  return files;
4144
4327
  }
4145
4328
 
4329
+ // src/executable-image/index.ts
4330
+ var import_node_crypto11 = require("crypto");
4331
+ var import_promises12 = require("fs/promises");
4332
+ var import_node_path28 = require("path");
4333
+
4334
+ // src/buildpacks/lifecycle/native.ts
4335
+ var import_node_fs17 = require("fs");
4336
+ var import_promises9 = require("fs/promises");
4337
+ var import_node_path25 = require("path");
4338
+ var import_smol_toml4 = require("smol-toml");
4339
+ var PREBUILT_STATIC_GROUP = {
4340
+ runtime: "prebuilt-static",
4341
+ buildpacks: [vercelBuildpack("prebuilt-static")]
4342
+ };
4343
+ var HIVE_RUNTIME_MOUNTS = ["/tmp", "/opt/vercel"];
4344
+ function assertLinuxX64(platform = process.platform, arch = process.arch) {
4345
+ if (platform !== "linux" || arch !== "x64") {
4346
+ throw new Error(
4347
+ `Executable image builds require Linux x64 (current platform: ${platform}/${arch}).`
4348
+ );
4349
+ }
4350
+ }
4351
+ async function resolveNativeBuildUser(deps = {}) {
4352
+ const uid = (deps.getuid ?? process.getuid)?.();
4353
+ const gid = (deps.getgid ?? process.getgid)?.();
4354
+ if (uid === void 0 || gid === void 0) {
4355
+ throw new Error("The native CNB lifecycle requires Unix user IDs.");
4356
+ }
4357
+ if (uid !== 0 && gid !== 0) {
4358
+ return { uid, gid, switchUser: false };
4359
+ }
4360
+ if (uid !== 0) {
4361
+ throw new Error("The native CNB lifecycle cannot run with the root group.");
4362
+ }
4363
+ const passwd = await (deps.readPasswd ?? (() => (0, import_promises9.readFile)("/etc/passwd", "utf8")))();
4364
+ const nobody = passwd.split("\n").map((line) => line.split(":")).find(([name]) => name === "nobody");
4365
+ const unprivilegedUid = Number(nobody?.[2]);
4366
+ const unprivilegedGid = Number(nobody?.[3]);
4367
+ if (!Number.isInteger(unprivilegedUid) || !Number.isInteger(unprivilegedGid) || unprivilegedUid <= 0 || unprivilegedGid <= 0) {
4368
+ throw new Error(
4369
+ "The native CNB lifecycle requires a non-root nobody account."
4370
+ );
4371
+ }
4372
+ return { uid: unprivilegedUid, gid: unprivilegedGid, switchUser: true };
4373
+ }
4374
+ async function resolveStagingParent(resolveRealpath = import_promises9.realpath) {
4375
+ const parent = await resolveRealpath("/var/tmp");
4376
+ if (HIVE_RUNTIME_MOUNTS.some(
4377
+ (mount) => parent === mount || parent.startsWith(`${mount}/`)
4378
+ )) {
4379
+ throw new Error(
4380
+ `Cannot stage the native CNB image in ${parent}: Hive mounts over that path at runtime.`
4381
+ );
4382
+ }
4383
+ return parent;
4384
+ }
4385
+ async function chownRecursive(rootPath, uid, gid) {
4386
+ const stats = await (0, import_promises9.lstat)(rootPath);
4387
+ if (stats.isDirectory()) {
4388
+ for (const entry of await (0, import_promises9.readdir)(rootPath)) {
4389
+ await chownRecursive((0, import_node_path25.join)(rootPath, entry), uid, gid);
4390
+ }
4391
+ }
4392
+ await (0, import_promises9.lchown)(rootPath, uid, gid);
4393
+ }
4394
+ async function verifyLaunchCommand(layersDir, executablePath) {
4395
+ const metadata = (0, import_smol_toml4.parse)(
4396
+ await (0, import_promises9.readFile)((0, import_node_path25.join)(layersDir, "config", "metadata.toml"), "utf8")
4397
+ );
4398
+ const valid = metadata.processes?.some(
4399
+ (proc) => proc.type === "web" && proc.direct === true && proc.command?.length === 1 && (proc.command[0] === executablePath || proc.command[0] === "./user-server")
4400
+ );
4401
+ if (!valid) {
4402
+ throw new Error(
4403
+ "The prebuilt-static buildpack did not declare the staged user-server as its direct web process."
4404
+ );
4405
+ }
4406
+ }
4407
+ var NativeLifecycleRunner = class {
4408
+ constructor(options) {
4409
+ this.options = options;
4410
+ this.runCommand = options.runCommand ?? run;
4411
+ }
4412
+ async runPush(params) {
4413
+ return this.execute(
4414
+ params.executablePath,
4415
+ {
4416
+ kind: "registry",
4417
+ imageRef: params.imageRef,
4418
+ credentials: params.credentials
4419
+ },
4420
+ async (reportFile) => {
4421
+ const digest = readReportDigest(await (0, import_promises9.readFile)(reportFile, "utf8"));
4422
+ if (!digest) {
4423
+ throw new Error("The CNB lifecycle did not report an image digest.");
4424
+ }
4425
+ return digest;
4426
+ },
4427
+ params.span
4428
+ );
4429
+ }
4430
+ async runLayout(params) {
4431
+ await this.execute(
4432
+ params.executablePath,
4433
+ {
4434
+ kind: "oci-layout",
4435
+ imageRef: params.outputImageRef,
4436
+ layoutDir: params.layoutRoot
4437
+ },
4438
+ async () => void 0,
4439
+ params.span
4440
+ );
4441
+ }
4442
+ /**
4443
+ * Runs the creator, then `readResult` while the creator's report still
4444
+ * exists, so a failure in either is reported as a lifecycle failure.
4445
+ */
4446
+ async execute(executablePath, target, readResult, span) {
4447
+ const executableStats = await (0, import_promises9.lstat)(executablePath);
4448
+ if (!executableStats.isFile() || executableStats.size === 0) {
4449
+ throw new Error(
4450
+ "The prebuilt executable must be a nonempty regular file."
4451
+ );
4452
+ }
4453
+ const { user, stagingParent, cnbDir, platformDir, orderFile, runImage } = this.options;
4454
+ const runRoot = await (0, import_promises9.mkdtemp)((0, import_node_path25.join)(stagingParent, "vercel-cnb-native-"));
4455
+ try {
4456
+ if (user.switchUser) {
4457
+ await (0, import_promises9.chmod)(runRoot, 493);
4458
+ }
4459
+ const workPath = (0, import_node_path25.join)(runRoot, "workspace");
4460
+ const layers = (0, import_node_path25.join)(runRoot, "layers");
4461
+ const reportDir = (0, import_node_path25.join)(runRoot, "report");
4462
+ const home = (0, import_node_path25.join)(runRoot, "home");
4463
+ const temp = (0, import_node_path25.join)(runRoot, "tmp");
4464
+ const dirs = [workPath, layers, reportDir, home, temp];
4465
+ for (const dir of dirs) {
4466
+ await (0, import_promises9.mkdir)(dir, { mode: 448 });
4467
+ }
4468
+ const executable = (0, import_node_path25.join)(workPath, "user-server");
4469
+ await (0, import_promises9.copyFile)(executablePath, executable, import_node_fs17.constants.COPYFILE_EXCL);
4470
+ const handle = await (0, import_promises9.open)(
4471
+ executable,
4472
+ import_node_fs17.constants.O_RDONLY | import_node_fs17.constants.O_NOFOLLOW
4473
+ );
4474
+ try {
4475
+ await handle.chmod(493);
4476
+ if (user.switchUser) {
4477
+ await handle.chown(user.uid, user.gid);
4478
+ }
4479
+ } finally {
4480
+ await handle.close();
4481
+ }
4482
+ if (user.switchUser) {
4483
+ for (const dir of dirs) {
4484
+ await (0, import_promises9.chown)(dir, user.uid, user.gid);
4485
+ }
4486
+ }
4487
+ const lifecycleDir = (0, import_node_path25.join)(cnbDir, "lifecycle");
4488
+ const reportFile = (0, import_node_path25.join)(reportDir, "report.toml");
4489
+ const { args: exportArgs, env: exportEnv } = creatorExport(target);
4490
+ const args = [
4491
+ `-app=${workPath}`,
4492
+ `-layers=${layers}`,
4493
+ `-buildpacks=${(0, import_node_path25.join)(cnbDir, "buildpacks")}`,
4494
+ `-platform=${platformDir}`,
4495
+ `-order=${orderFile}`,
4496
+ `-launcher=${(0, import_node_path25.join)(lifecycleDir, "launcher")}`,
4497
+ `-launcher-sbom=${lifecycleDir}`,
4498
+ `-uid=${user.uid}`,
4499
+ `-gid=${user.gid}`,
4500
+ `-run-image=${runImage}`,
4501
+ `-report=${reportFile}`,
4502
+ "-skip-restore",
4503
+ ...exportArgs
4504
+ ];
4505
+ const env = {
4506
+ PATH: "/usr/bin:/bin",
4507
+ HOME: home,
4508
+ TMPDIR: temp,
4509
+ ...target.kind === "registry" && { DOCKER_CONFIG: home },
4510
+ CNB_PLATFORM_API,
4511
+ ...exportEnv
4512
+ };
4513
+ try {
4514
+ await this.runCommand((0, import_node_path25.join)(lifecycleDir, "creator"), args, {
4515
+ cwd: workPath,
4516
+ ...user.switchUser && { uid: user.uid, gid: user.gid },
4517
+ env
4518
+ });
4519
+ await verifyLaunchCommand(layers, executable);
4520
+ return await readResult(reportFile);
4521
+ } catch (error) {
4522
+ throw lifecycleFailure(error, {
4523
+ buildpack: this.options.buildpack,
4524
+ via: "native lifecycle",
4525
+ workPath,
4526
+ span
4527
+ });
4528
+ }
4529
+ } finally {
4530
+ await (0, import_promises9.rm)(runRoot, { recursive: true, force: true });
4531
+ }
4532
+ }
4533
+ };
4534
+
4535
+ // src/oci-layout/layout.ts
4536
+ var import_node_crypto9 = require("crypto");
4537
+ var import_promises10 = require("fs/promises");
4538
+ var import_node_path26 = require("path");
4539
+ var OCI_LAYOUT_VERSION = "1.0.0";
4540
+ var OCI_INDEX_MEDIA_TYPE = "application/vnd.oci.image.index.v1+json";
4541
+ var OCI_MANIFEST_MEDIA_TYPE = "application/vnd.oci.image.manifest.v1+json";
4542
+ var DOCKER_MANIFEST_MEDIA_TYPE = "application/vnd.docker.distribution.manifest.v2+json";
4543
+ var SINGLE_MANIFEST_MEDIA_TYPES = /* @__PURE__ */ new Set([
4544
+ OCI_MANIFEST_MEDIA_TYPE,
4545
+ DOCKER_MANIFEST_MEDIA_TYPE
4546
+ ]);
4547
+ function isRecord(value) {
4548
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4549
+ }
4550
+ function sha256Digest(bytes) {
4551
+ const view = bytes instanceof Uint8Array && !Buffer.isBuffer(bytes) ? bytes : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
4552
+ return `sha256:${(0, import_node_crypto9.createHash)("sha256").update(view).digest("hex")}`;
4553
+ }
4554
+ function parseSha256Hex(digest) {
4555
+ if (!DIGEST_RE.test(digest)) {
4556
+ throw new Error(`Unsupported OCI digest ${JSON.stringify(digest)}.`);
4557
+ }
4558
+ return digest.slice("sha256:".length);
4559
+ }
4560
+ function blobPath2(layoutDir, digest) {
4561
+ return (0, import_node_path26.join)(layoutDir, "blobs", "sha256", parseSha256Hex(digest));
4562
+ }
4563
+ function assertSafePathSegment(segment, imageRef) {
4564
+ if (!segment || segment === "." || segment === ".." || segment.includes("/") || segment.includes("\\")) {
4565
+ throw new Error(`Invalid image reference for OCI layout: "${imageRef}".`);
4566
+ }
4567
+ }
4568
+ function layoutRefPath(layoutDir, imageRef) {
4569
+ const firstSlash = imageRef.indexOf("/");
4570
+ if (firstSlash <= 0 || firstSlash === imageRef.length - 1) {
4571
+ throw new Error(`Invalid image reference for OCI layout: "${imageRef}".`);
4572
+ }
4573
+ const registry = imageRef.slice(0, firstSlash);
4574
+ assertSafePathSegment(registry, imageRef);
4575
+ const remainder = imageRef.slice(firstSlash + 1);
4576
+ const atIndex = remainder.indexOf("@");
4577
+ if (atIndex !== -1) {
4578
+ const repository2 = remainder.slice(0, atIndex);
4579
+ const digest = remainder.slice(atIndex + 1);
4580
+ const repoParts2 = repository2.split("/");
4581
+ for (const part of repoParts2) {
4582
+ assertSafePathSegment(part, imageRef);
4583
+ }
4584
+ const hex = parseSha256Hex(digest);
4585
+ return (0, import_node_path26.join)(layoutDir, registry, ...repoParts2, "sha256", hex);
4586
+ }
4587
+ const colonIndex = remainder.lastIndexOf(":");
4588
+ if (colonIndex <= remainder.lastIndexOf("/") || colonIndex === remainder.length - 1) {
4589
+ throw new Error(`Invalid image reference for OCI layout: "${imageRef}".`);
4590
+ }
4591
+ const repository = remainder.slice(0, colonIndex);
4592
+ const tag = remainder.slice(colonIndex + 1);
4593
+ const repoParts = repository.split("/");
4594
+ for (const part of repoParts) {
4595
+ assertSafePathSegment(part, imageRef);
4596
+ }
4597
+ assertSafePathSegment(tag, imageRef);
4598
+ return (0, import_node_path26.join)(layoutDir, registry, ...repoParts, tag);
4599
+ }
4600
+ function parseDescriptor(value, label) {
4601
+ if (!isRecord(value)) {
4602
+ throw new Error(`Invalid OCI ${label} descriptor.`);
4603
+ }
4604
+ const { mediaType, digest, size } = value;
4605
+ if (typeof digest !== "string" || !DIGEST_RE.test(digest)) {
4606
+ throw new Error(`Invalid OCI ${label} digest: ${JSON.stringify(digest)}.`);
4607
+ }
4608
+ if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
4609
+ throw new Error(`Invalid OCI ${label} size: ${JSON.stringify(size)}.`);
4610
+ }
4611
+ if (mediaType !== void 0 && typeof mediaType !== "string") {
4612
+ throw new Error(`Invalid OCI ${label} mediaType.`);
4613
+ }
4614
+ return { mediaType, digest, size };
4615
+ }
4616
+ async function readRegularJson(path4, label) {
4617
+ const stats = await (0, import_promises10.lstat)(path4).catch((error) => {
4618
+ if (error.code === "ENOENT") {
4619
+ throw new Error(`OCI layout is missing ${label}.`);
4620
+ }
4621
+ throw error;
4622
+ });
4623
+ if (!stats.isFile()) {
4624
+ throw new Error(`OCI layout ${label} must be a regular file.`);
4625
+ }
4626
+ try {
4627
+ return JSON.parse(await (0, import_promises10.readFile)(path4, "utf8"));
4628
+ } catch {
4629
+ throw new Error(`OCI layout ${label} is not valid JSON.`);
4630
+ }
4631
+ }
4632
+ async function readVerifiedBlob(layoutDir, descriptor, label) {
4633
+ const path4 = blobPath2(layoutDir, descriptor.digest);
4634
+ const stats = await (0, import_promises10.lstat)(path4).catch((error) => {
4635
+ if (error.code === "ENOENT") {
4636
+ throw new Error(
4637
+ `OCI layout is missing ${label} blob ${descriptor.digest}.`
4638
+ );
4639
+ }
4640
+ throw error;
4641
+ });
4642
+ if (!stats.isFile()) {
4643
+ throw new Error(
4644
+ `OCI layout ${label} blob ${descriptor.digest} must be a regular file.`
4645
+ );
4646
+ }
4647
+ if (stats.size !== descriptor.size) {
4648
+ throw new Error(
4649
+ `OCI layout ${label} blob ${descriptor.digest} has size ${stats.size}, expected ${descriptor.size}.`
4650
+ );
4651
+ }
4652
+ const content = await (0, import_promises10.readFile)(path4);
4653
+ if (content.length !== descriptor.size) {
4654
+ throw new Error(
4655
+ `OCI layout ${label} blob ${descriptor.digest} has size ${content.length}, expected ${descriptor.size}.`
4656
+ );
4657
+ }
4658
+ const actual = sha256Digest(content);
4659
+ if (actual !== descriptor.digest) {
4660
+ throw new Error(
4661
+ `OCI layout ${label} blob ${descriptor.digest} hashes to ${actual}.`
4662
+ );
4663
+ }
4664
+ return content;
4665
+ }
4666
+ async function verifyBlobSize(layoutDir, descriptor, label) {
4667
+ const path4 = blobPath2(layoutDir, descriptor.digest);
4668
+ const stats = await (0, import_promises10.lstat)(path4).catch((error) => {
4669
+ if (error.code === "ENOENT") {
4670
+ throw new Error(
4671
+ `OCI layout is missing ${label} blob ${descriptor.digest}.`
4672
+ );
4673
+ }
4674
+ throw error;
4675
+ });
4676
+ if (!stats.isFile()) {
4677
+ throw new Error(
4678
+ `OCI layout ${label} blob ${descriptor.digest} must be a regular file.`
4679
+ );
4680
+ }
4681
+ if (stats.size !== descriptor.size) {
4682
+ throw new Error(
4683
+ `OCI layout ${label} blob ${descriptor.digest} has size ${stats.size}, expected ${descriptor.size}.`
4684
+ );
4685
+ }
4686
+ }
4687
+ async function verifyOciLayout(layoutDir) {
4688
+ const marker = await readRegularJson(
4689
+ (0, import_node_path26.join)(layoutDir, "oci-layout"),
4690
+ "oci-layout"
4691
+ );
4692
+ if (!isRecord(marker) || marker.imageLayoutVersion !== OCI_LAYOUT_VERSION) {
4693
+ throw new Error(
4694
+ `Unsupported OCI layout version in "${layoutDir}". Expected "${OCI_LAYOUT_VERSION}".`
4695
+ );
4696
+ }
4697
+ const index = await readRegularJson(
4698
+ (0, import_node_path26.join)(layoutDir, "index.json"),
4699
+ "index.json"
4700
+ );
4701
+ if (!isRecord(index) || !Array.isArray(index.manifests)) {
4702
+ throw new Error("OCI layout index.json has no manifests list.");
4703
+ }
4704
+ if (index.manifests.length !== 1) {
4705
+ throw new Error(
4706
+ `OCI layout index.json must contain exactly 1 manifest, found ${index.manifests.length}.`
4707
+ );
4708
+ }
4709
+ const manifestDescriptor = parseDescriptor(index.manifests[0], "manifest");
4710
+ if (!manifestDescriptor.mediaType || !SINGLE_MANIFEST_MEDIA_TYPES.has(manifestDescriptor.mediaType)) {
4711
+ throw new Error(
4712
+ `OCI layout index.json must reference a single image manifest, found mediaType ${JSON.stringify(manifestDescriptor.mediaType)}.`
4713
+ );
4714
+ }
4715
+ const manifestBytes = await readVerifiedBlob(
4716
+ layoutDir,
4717
+ manifestDescriptor,
4718
+ "manifest"
4719
+ );
4720
+ let manifest;
4721
+ try {
4722
+ manifest = JSON.parse(manifestBytes.toString("utf8"));
4723
+ } catch {
4724
+ throw new Error("OCI layout image manifest is not valid JSON.");
4725
+ }
4726
+ if (!isRecord(manifest) || !Array.isArray(manifest.layers)) {
4727
+ throw new Error("OCI layout image manifest is missing layers.");
4728
+ }
4729
+ if (manifest.layers.length === 0) {
4730
+ throw new Error("OCI layout image manifest has no layers.");
4731
+ }
4732
+ const configDescriptor = parseDescriptor(manifest.config, "config");
4733
+ const configBytes = await readVerifiedBlob(
4734
+ layoutDir,
4735
+ configDescriptor,
4736
+ "config"
4737
+ );
4738
+ let config;
4739
+ try {
4740
+ config = JSON.parse(configBytes.toString("utf8"));
4741
+ } catch {
4742
+ throw new Error("OCI layout image config is not valid JSON.");
4743
+ }
4744
+ if (!isRecord(config) || config.os !== "linux" || config.architecture !== "amd64") {
4745
+ throw new Error(
4746
+ `OCI layout image must target linux/amd64, found ${JSON.stringify(
4747
+ isRecord(config) ? `${config.os}/${config.architecture}` : config
4748
+ )}.`
4749
+ );
4750
+ }
4751
+ for (let i = 0; i < manifest.layers.length; i++) {
4752
+ const layerDescriptor = parseDescriptor(manifest.layers[i], `layer[${i}]`);
4753
+ await verifyBlobSize(layoutDir, layerDescriptor, `layer[${i}]`);
4754
+ }
4755
+ return { manifestDigest: manifestDescriptor.digest };
4756
+ }
4757
+ async function moveDirectory(sourceDir, destinationDir) {
4758
+ const parentDir = (0, import_node_path26.dirname)(destinationDir);
4759
+ await (0, import_promises10.mkdir)(parentDir, { recursive: true });
4760
+ try {
4761
+ await (0, import_promises10.rename)(sourceDir, destinationDir);
4762
+ return;
4763
+ } catch (error) {
4764
+ if (error.code !== "EXDEV") {
4765
+ throw error;
4766
+ }
4767
+ }
4768
+ const tempDir = await (0, import_promises10.mkdtemp)((0, import_node_path26.join)(parentDir, ".oci-layout-"));
4769
+ try {
4770
+ await (0, import_promises10.cp)(sourceDir, tempDir, { recursive: true });
4771
+ await (0, import_promises10.rename)(tempDir, destinationDir);
4772
+ } catch (error) {
4773
+ await (0, import_promises10.rm)(tempDir, { recursive: true, force: true });
4774
+ throw error;
4775
+ }
4776
+ await (0, import_promises10.rm)(sourceDir, { recursive: true, force: true });
4777
+ }
4778
+
4779
+ // src/oci-layout/pull.ts
4780
+ var import_node_crypto10 = require("crypto");
4781
+ var import_promises11 = require("fs/promises");
4782
+ var import_node_path27 = require("path");
4783
+ var MANIFEST_ACCEPT_HEADER = [
4784
+ OCI_MANIFEST_MEDIA_TYPE,
4785
+ DOCKER_MANIFEST_MEDIA_TYPE,
4786
+ OCI_INDEX_MEDIA_TYPE,
4787
+ "application/vnd.docker.distribution.manifest.list.v2+json"
4788
+ ].join(", ");
4789
+ var PULL_ATTEMPTS = 3;
4790
+ var PULL_TIMEOUT_MS = 3e4;
4791
+ var MAX_REDIRECTS = 5;
4792
+ function parseDigestImageRef(imageRef) {
4793
+ const atIndex = imageRef.indexOf("@");
4794
+ if (atIndex === -1) {
4795
+ throw new Error(
4796
+ `Expected a digest-pinned image reference, got "${imageRef}".`
4797
+ );
4798
+ }
4799
+ const namePart = imageRef.slice(0, atIndex);
4800
+ const digest = imageRef.slice(atIndex + 1);
4801
+ if (!DIGEST_RE.test(digest)) {
4802
+ throw new Error(
4803
+ `Expected a sha256 digest in image reference "${imageRef}".`
4804
+ );
4805
+ }
4806
+ const firstSlash = namePart.indexOf("/");
4807
+ if (firstSlash <= 0 || firstSlash === namePart.length - 1) {
4808
+ throw new Error(
4809
+ `Expected "<registry>/<repository>@sha256:..." image reference, got "${imageRef}".`
4810
+ );
4811
+ }
4812
+ const registry = namePart.slice(0, firstSlash);
4813
+ const repository = namePart.slice(firstSlash + 1);
4814
+ if (repository.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
4815
+ throw new Error(`Invalid repository in image reference "${imageRef}".`);
4816
+ }
4817
+ return { registry, repository, digest };
4818
+ }
4819
+ function describeFetchError2(error) {
4820
+ const err = error;
4821
+ const cause = err.cause?.message;
4822
+ return cause ? `${err.message} (${cause})` : err.message;
4823
+ }
4824
+ var OciRegistryPuller = class {
4825
+ constructor(options) {
4826
+ this.options = options;
4827
+ this.fetchImpl = options.fetchImpl ?? fetch;
4828
+ this.retryDelayMs = options.retryDelayMs ?? 500;
4829
+ }
4830
+ async pullToLayout(imageRef, destinationDir) {
4831
+ const parsed = parseDigestImageRef(imageRef);
4832
+ if (parsed.registry !== this.options.credentials.registry) {
4833
+ throw new Error(
4834
+ `Registry credentials for ${this.options.credentials.registry} cannot be used to pull from ${parsed.registry}.`
4835
+ );
4836
+ }
4837
+ const baseUrl = (this.options.baseUrl ?? `https://${parsed.registry}`).replace(/\/+$/, "");
4838
+ const baseOrigin = new URL(baseUrl).origin;
4839
+ const requireHttps = new URL(baseUrl).protocol === "https:";
4840
+ const authorization = `Basic ${Buffer.from(
4841
+ `${this.options.credentials.username}:${this.options.credentials.token}`
4842
+ ).toString("base64")}`;
4843
+ const manifestUrl = `${baseUrl}/v2/${parsed.repository}/manifests/${parsed.digest}`;
4844
+ const manifestBytes = await this.fetchBytes({
4845
+ url: manifestUrl,
4846
+ baseOrigin,
4847
+ requireHttps,
4848
+ authorization,
4849
+ accept: MANIFEST_ACCEPT_HEADER,
4850
+ registry: parsed.registry,
4851
+ label: `manifest ${imageRef}`
4852
+ });
4853
+ const actualManifestDigest = sha256Digest(manifestBytes);
4854
+ if (actualManifestDigest !== parsed.digest) {
4855
+ throw new Error(
4856
+ `Manifest digest mismatch for ${imageRef}: expected ${parsed.digest}, received ${actualManifestDigest}.`
4857
+ );
4858
+ }
4859
+ let manifest;
4860
+ try {
4861
+ manifest = JSON.parse(new TextDecoder().decode(manifestBytes));
4862
+ } catch {
4863
+ throw new Error(`Manifest for ${imageRef} is not valid JSON.`);
4864
+ }
4865
+ if (!isRecord(manifest)) {
4866
+ throw new Error(`Manifest for ${imageRef} must be a JSON object.`);
4867
+ }
4868
+ if (Array.isArray(manifest.manifests) && (!manifest.config || !Array.isArray(manifest.layers))) {
4869
+ throw new Error(
4870
+ `Expected ${imageRef} to resolve to a single linux/amd64 image manifest, not an image index.`
4871
+ );
4872
+ }
4873
+ if (!Array.isArray(manifest.layers) || manifest.layers.length === 0) {
4874
+ throw new Error(`Manifest for ${imageRef} has no layers.`);
4875
+ }
4876
+ const configDescriptor = parseDescriptor(manifest.config, "config");
4877
+ const layerDescriptors = manifest.layers.map(
4878
+ (layer, index) => parseDescriptor(layer, `layer[${index}]`)
4879
+ );
4880
+ const blobsDir = (0, import_node_path27.join)(destinationDir, "blobs", "sha256");
4881
+ await (0, import_promises11.mkdir)(blobsDir, { recursive: true, mode: 493 });
4882
+ try {
4883
+ await (0, import_promises11.writeFile)(
4884
+ (0, import_node_path27.join)(blobsDir, parseSha256Hex(parsed.digest)),
4885
+ manifestBytes
4886
+ );
4887
+ const fetchBlob = async (descriptor, label) => {
4888
+ const written = await this.fetchToFile(
4889
+ {
4890
+ url: `${baseUrl}/v2/${parsed.repository}/blobs/${descriptor.digest}`,
4891
+ baseOrigin,
4892
+ requireHttps,
4893
+ authorization,
4894
+ registry: parsed.registry,
4895
+ label: `${label} ${descriptor.digest}`
4896
+ },
4897
+ blobPath2(destinationDir, descriptor.digest)
4898
+ );
4899
+ if (written.size !== descriptor.size) {
4900
+ throw new Error(
4901
+ `Blob size mismatch for ${label} ${descriptor.digest}: expected ${descriptor.size}, received ${written.size}.`
4902
+ );
4903
+ }
4904
+ if (written.digest !== descriptor.digest) {
4905
+ throw new Error(
4906
+ `Blob digest mismatch for ${label} ${descriptor.digest}: received ${written.digest}.`
4907
+ );
4908
+ }
4909
+ };
4910
+ const uniqueLayers = /* @__PURE__ */ new Map();
4911
+ for (const layer of layerDescriptors) {
4912
+ if (!uniqueLayers.has(layer.digest)) {
4913
+ uniqueLayers.set(layer.digest, layer);
4914
+ }
4915
+ }
4916
+ await settleAll([
4917
+ fetchBlob(configDescriptor, "config"),
4918
+ ...[...uniqueLayers.values()].map(
4919
+ (layer, index) => fetchBlob(layer, `layer[${index}]`)
4920
+ )
4921
+ ]);
4922
+ let config;
4923
+ try {
4924
+ config = JSON.parse(
4925
+ await (0, import_promises11.readFile)(
4926
+ blobPath2(destinationDir, configDescriptor.digest),
4927
+ "utf8"
4928
+ )
4929
+ );
4930
+ } catch {
4931
+ throw new Error(`Config blob for ${imageRef} is not valid JSON.`);
4932
+ }
4933
+ if (!isRecord(config) || config.os !== "linux" || config.architecture !== "amd64") {
4934
+ throw new Error(
4935
+ `Run image ${imageRef} must target linux/amd64, found ${JSON.stringify(
4936
+ isRecord(config) ? `${config.os}/${config.architecture}` : config
4937
+ )}.`
4938
+ );
4939
+ }
4940
+ const manifestMediaType = typeof manifest.mediaType === "string" ? manifest.mediaType : OCI_MANIFEST_MEDIA_TYPE;
4941
+ await (0, import_promises11.writeFile)(
4942
+ (0, import_node_path27.join)(destinationDir, "oci-layout"),
4943
+ JSON.stringify({ imageLayoutVersion: OCI_LAYOUT_VERSION })
4944
+ );
4945
+ await (0, import_promises11.writeFile)(
4946
+ (0, import_node_path27.join)(destinationDir, "index.json"),
4947
+ JSON.stringify({
4948
+ schemaVersion: 2,
4949
+ mediaType: OCI_INDEX_MEDIA_TYPE,
4950
+ manifests: [
4951
+ {
4952
+ mediaType: manifestMediaType,
4953
+ digest: parsed.digest,
4954
+ size: manifestBytes.byteLength
4955
+ }
4956
+ ]
4957
+ })
4958
+ );
4959
+ return { manifestDigest: parsed.digest };
4960
+ } catch (error) {
4961
+ await (0, import_promises11.rm)(destinationDir, { recursive: true, force: true });
4962
+ throw error;
4963
+ }
4964
+ }
4965
+ fetchBytes(request) {
4966
+ return this.fetchWithRetries(
4967
+ request,
4968
+ async (response) => new Uint8Array(await response.arrayBuffer())
4969
+ );
4970
+ }
4971
+ /** Streams a blob into `path`, hashing it on the way, and returns its size and digest. */
4972
+ fetchToFile(request, path4) {
4973
+ return this.fetchWithRetries(request, async (response) => {
4974
+ const hash = (0, import_node_crypto10.createHash)("sha256");
4975
+ let size = 0;
4976
+ const file = await (0, import_promises11.open)(path4, "w");
4977
+ try {
4978
+ if (response.body) {
4979
+ for await (const chunk of response.body) {
4980
+ hash.update(chunk);
4981
+ size += chunk.byteLength;
4982
+ await file.write(chunk);
4983
+ }
4984
+ }
4985
+ } finally {
4986
+ await file.close();
4987
+ }
4988
+ return { size, digest: `sha256:${hash.digest("hex")}` };
4989
+ });
4990
+ }
4991
+ /**
4992
+ * GETs `request.url`, retrying network errors, 429 and 5xx responses.
4993
+ * `readBody` runs inside the retry, so a connection that drops while the
4994
+ * body streams is retried like one that drops before the headers arrive.
4995
+ */
4996
+ async fetchWithRetries(request, readBody) {
4997
+ let lastError = `Failed to pull ${request.label}.`;
4998
+ for (let attempt = 1; attempt <= PULL_ATTEMPTS; attempt++) {
4999
+ debug(`registry pull (${attempt}/${PULL_ATTEMPTS}): GET ${request.url}`);
5000
+ try {
5001
+ const response = await this.fetchFollowingRedirects(
5002
+ request.url,
5003
+ request.baseOrigin,
5004
+ request.requireHttps,
5005
+ request.authorization,
5006
+ request.accept
5007
+ );
5008
+ if (response.ok) {
5009
+ return await readBody(response);
5010
+ }
5011
+ if (response.status === 401 || response.status === 403) {
5012
+ throw new NonRetryablePullError(
5013
+ request.registry === VCR_REGISTRY ? formatVcrAuthError(
5014
+ request.registry,
5015
+ this.options.credentials.username,
5016
+ `HTTP ${response.status} pulling ${request.label}.`
5017
+ ) : `Registry authentication failed pulling ${request.label}: HTTP ${response.status}.`
5018
+ );
5019
+ }
5020
+ lastError = `Failed to pull ${request.label}: HTTP ${response.status}.`;
5021
+ if (response.status !== 429 && response.status < 500) {
5022
+ throw new NonRetryablePullError(lastError);
5023
+ }
5024
+ } catch (error) {
5025
+ if (error instanceof NonRetryablePullError) {
5026
+ throw error;
5027
+ }
5028
+ lastError = `Failed to pull ${request.label}: ${describeFetchError2(error)}`;
5029
+ }
5030
+ if (attempt < PULL_ATTEMPTS) {
5031
+ await delay(this.retryDelayMs * 2 ** (attempt - 1));
5032
+ }
5033
+ }
5034
+ throw new Error(lastError);
5035
+ }
5036
+ async fetchFollowingRedirects(initialUrl, baseOrigin, requireHttps, authorization, accept) {
5037
+ let currentUrl = new URL(initialUrl);
5038
+ for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects++) {
5039
+ const headers = {};
5040
+ if (currentUrl.origin === baseOrigin) {
5041
+ headers.authorization = authorization;
5042
+ }
5043
+ if (accept) {
5044
+ headers.accept = accept;
5045
+ }
5046
+ const response = await this.fetchImpl(currentUrl.href, {
5047
+ method: "GET",
5048
+ headers,
5049
+ redirect: "manual",
5050
+ signal: AbortSignal.timeout(PULL_TIMEOUT_MS)
5051
+ });
5052
+ if (response.status < 300 || response.status >= 400) {
5053
+ return response;
5054
+ }
5055
+ const location = response.headers.get("location");
5056
+ if (!location) {
5057
+ return response;
5058
+ }
5059
+ if (redirects === MAX_REDIRECTS) {
5060
+ throw new NonRetryablePullError(
5061
+ `Too many redirects pulling ${initialUrl}.`
5062
+ );
5063
+ }
5064
+ const nextUrl = new URL(location, currentUrl);
5065
+ if (requireHttps && nextUrl.protocol !== "https:") {
5066
+ throw new NonRetryablePullError(
5067
+ `Refusing insecure redirect to ${nextUrl.protocol} while pulling from HTTPS registry.`
5068
+ );
5069
+ }
5070
+ currentUrl = nextUrl;
5071
+ }
5072
+ throw new NonRetryablePullError(
5073
+ `Too many redirects pulling ${initialUrl}.`
5074
+ );
5075
+ }
5076
+ };
5077
+ var NonRetryablePullError = class extends Error {
5078
+ };
5079
+
5080
+ // src/oci-layout/index.ts
5081
+ var CONTAINER_OCI_LAYOUT_ENV = "VERCEL_CONTAINER_OCI_LAYOUT";
5082
+ function ociLayoutRequested(env = process.env) {
5083
+ return env[CONTAINER_OCI_LAYOUT_ENV] === "1";
5084
+ }
5085
+
5086
+ // src/executable-image/index.ts
5087
+ var ExecutableImageBuilder = class _ExecutableImageBuilder {
5088
+ constructor(sharedRoot, runner, mode, span) {
5089
+ this.sharedRoot = sharedRoot;
5090
+ this.runner = runner;
5091
+ this.mode = mode;
5092
+ this.span = span;
5093
+ this.closed = false;
5094
+ }
5095
+ /** Fetches the lifecycle and buildpack, and in layout mode pulls run-static. */
5096
+ static async create(options, deps = {}) {
5097
+ assertLinuxX64(deps.platform, deps.arch);
5098
+ const env = options.env ?? process.env;
5099
+ const layoutMode = ociLayoutRequested(env);
5100
+ const user = await (deps.resolveBuildUser ?? resolveNativeBuildUser)();
5101
+ const stagingParent = await (deps.resolveStagingParent ?? resolveStagingParent)();
5102
+ const registry = deps.registry ?? VCR_REGISTRY;
5103
+ const runImage = deps.runImage ?? BUILDPACK_IMAGES.runStatic;
5104
+ const fetchDist = deps.fetchDistribution ?? fetchDistribution;
5105
+ const resolveTarget = deps.resolveRegistryTarget ?? resolveRegistryTarget;
5106
+ const ensureRepo = deps.ensureRepository ?? ensureRepository;
5107
+ const sharedRoot = await (0, import_promises12.mkdtemp)(
5108
+ (0, import_node_path28.join)(stagingParent, "vercel-cnb-executable-")
5109
+ );
5110
+ try {
5111
+ if (user.switchUser) {
5112
+ await (0, import_promises12.chmod)(sharedRoot, 493);
5113
+ }
5114
+ const cnbDir = (0, import_node_path28.join)(sharedRoot, "cnb");
5115
+ const platformDir = (0, import_node_path28.join)(sharedRoot, "platform");
5116
+ await (0, import_promises12.mkdir)(cnbDir, { mode: 493 });
5117
+ await (0, import_promises12.mkdir)(platformDir, { mode: 493 });
5118
+ if (user.switchUser) {
5119
+ await (0, import_promises12.chmod)(cnbDir, 493);
5120
+ await (0, import_promises12.chmod)(platformDir, 493);
5121
+ }
5122
+ const orderFile = (0, import_node_path28.join)(
5123
+ writeOrderDir(PREBUILT_STATIC_GROUP, sharedRoot),
5124
+ "order.toml"
5125
+ );
5126
+ const target = await resolveTarget({
5127
+ repository: options.repository,
5128
+ tag: "build",
5129
+ span: options.span
5130
+ });
5131
+ const runner = new NativeLifecycleRunner({
5132
+ stagingParent,
5133
+ user,
5134
+ buildpack: PREBUILT_STATIC_GROUP,
5135
+ cnbDir,
5136
+ platformDir,
5137
+ orderFile,
5138
+ runImage,
5139
+ runCommand: deps.runCommand
5140
+ });
5141
+ if (layoutMode) {
5142
+ const layoutRoot = (0, import_node_path28.join)(sharedRoot, "layout");
5143
+ await (0, import_promises12.mkdir)(layoutRoot, { mode: 448 });
5144
+ const runImageLayoutDir = layoutRefPath(layoutRoot, runImage);
5145
+ const puller = new OciRegistryPuller({
5146
+ credentials: {
5147
+ registry,
5148
+ username: target.username,
5149
+ token: target.token
5150
+ },
5151
+ baseUrl: deps.registryBaseUrl,
5152
+ fetchImpl: deps.fetchImpl
5153
+ });
5154
+ step("Fetching the CNB lifecycle, buildpacks, and run image");
5155
+ await settleAll([
5156
+ fetchDist(PREBUILT_STATIC_GROUP, cnbDir),
5157
+ puller.pullToLayout(runImage, runImageLayoutDir)
5158
+ ]);
5159
+ if (user.switchUser) {
5160
+ await chownRecursive(layoutRoot, user.uid, user.gid);
5161
+ }
5162
+ done("fetched the CNB lifecycle, buildpacks, and run image");
5163
+ return new _ExecutableImageBuilder(
5164
+ sharedRoot,
5165
+ runner,
5166
+ { kind: "oci-layout", layoutRoot },
5167
+ options.span
5168
+ );
5169
+ }
5170
+ step("Fetching the CNB lifecycle and buildpacks");
5171
+ await settleAll([
5172
+ fetchDist(PREBUILT_STATIC_GROUP, cnbDir),
5173
+ ensureRepo(
5174
+ options.repository,
5175
+ target.token,
5176
+ target.claims,
5177
+ options.span
5178
+ )
5179
+ ]);
5180
+ done("fetched the CNB lifecycle and buildpacks");
5181
+ return new _ExecutableImageBuilder(
5182
+ sharedRoot,
5183
+ runner,
5184
+ {
5185
+ kind: "registry",
5186
+ registry,
5187
+ token: target.token,
5188
+ username: target.username,
5189
+ fullRepository: target.fullRepository
5190
+ },
5191
+ options.span
5192
+ );
5193
+ } catch (error) {
5194
+ await (0, import_promises12.rm)(sharedRoot, { recursive: true, force: true });
5195
+ throw error;
5196
+ }
5197
+ }
5198
+ /** Packages one static linux/amd64 executable as an image. */
5199
+ async build(executable) {
5200
+ if (this.closed) {
5201
+ throw new Error("ExecutableImageBuilder has already been closed.");
5202
+ }
5203
+ const tag = `build-${(0, import_node_crypto11.randomUUID)()}`;
5204
+ const mode = this.mode;
5205
+ return withSpan(
5206
+ this.span,
5207
+ "container.executable_image.build",
5208
+ {
5209
+ "buildpack.runtime": PREBUILT_STATIC_GROUP.runtime,
5210
+ "container.engine": "native",
5211
+ "container.mode": mode.kind
5212
+ },
5213
+ (span) => mode.kind === "oci-layout" ? this.exportLayout(mode, tag, executable, span) : this.push(mode, tag, executable, span)
5214
+ );
5215
+ }
5216
+ async close() {
5217
+ if (this.closed)
5218
+ return;
5219
+ this.closed = true;
5220
+ await (0, import_promises12.rm)(this.sharedRoot, { recursive: true, force: true });
5221
+ }
5222
+ async exportLayout(mode, tag, executable, span) {
5223
+ const outputImageRef = `oci.local/executable:${tag}`;
5224
+ const exportedDir = layoutRefPath(mode.layoutRoot, outputImageRef);
5225
+ try {
5226
+ step(`Exporting ${executable.layoutDir} directly with the CNB lifecycle`);
5227
+ await this.runner.runLayout({
5228
+ executablePath: executable.executablePath,
5229
+ outputImageRef,
5230
+ layoutRoot: mode.layoutRoot,
5231
+ span
5232
+ });
5233
+ const { manifestDigest } = await verifyOciLayout(exportedDir);
5234
+ await moveDirectory(exportedDir, executable.layoutDir);
5235
+ span?.setAttributes({ "image.digest": manifestDigest });
5236
+ info(`Image layout ${executable.layoutDir} (${manifestDigest})`);
5237
+ return {
5238
+ kind: "oci-layout",
5239
+ directory: executable.layoutDir,
5240
+ manifestDigest
5241
+ };
5242
+ } finally {
5243
+ await (0, import_promises12.rm)(exportedDir, { recursive: true, force: true });
5244
+ }
5245
+ }
5246
+ async push(mode, tag, executable, span) {
5247
+ const { registry, fullRepository, username, token } = mode;
5248
+ const imageRef = `${registry}/${fullRepository}:${tag}`;
5249
+ step(`Publishing ${imageRef} directly with the CNB lifecycle`);
5250
+ const digest = await this.runner.runPush({
5251
+ executablePath: executable.executablePath,
5252
+ imageRef,
5253
+ credentials: { registry, username, token },
5254
+ span
5255
+ });
5256
+ const reference = `${registry}/${fullRepository}@${digest}`;
5257
+ span?.setAttributes({
5258
+ "image.digest": digest,
5259
+ "image.resolved_ref": reference
5260
+ });
5261
+ info(`Image reference ${reference}`);
5262
+ return { kind: "registry", reference };
5263
+ }
5264
+ };
5265
+
4146
5266
  // src/index.ts
4147
5267
  var version = 2;
4148
5268
  var CONTAINER_OUTPUT_PATH = "container";
@@ -4348,7 +5468,7 @@ async function resolveImageHandler(options, source, buildahClient, span, schedul
4348
5468
  });
4349
5469
  return tag3;
4350
5470
  }
4351
- const repository2 = daemon ? (0, import_build_utils9.getDaemonImageRepository)(daemon.name) : sanitizeRepository(options.service?.name ?? buildpack.runtime);
5471
+ const repository2 = daemon ? (0, import_build_utils11.getDaemonImageRepository)(daemon.name) : sanitizeRepository(options.service?.name ?? buildpack.runtime);
4352
5472
  const tag2 = resolveImageTag();
4353
5473
  span?.setAttributes({
4354
5474
  "container.mode": "buildpack-build-and-push",
@@ -4387,22 +5507,22 @@ async function resolveImageHandler(options, source, buildahClient, span, schedul
4387
5507
  if (meta?.isDev) {
4388
5508
  const serviceName = options.service?.name;
4389
5509
  const tag2 = devImageTag(
4390
- serviceName ?? import_node_path24.default.basename(dockerfileRel).split(".")[0]
5510
+ serviceName ?? import_node_path29.default.basename(dockerfileRel).split(".")[0]
4391
5511
  );
4392
5512
  span?.setAttributes({ "container.mode": "dev", "image.tag": tag2 });
4393
5513
  return tag2;
4394
5514
  }
4395
- if (!(0, import_node_fs17.existsSync)(dockerfilePath)) {
4396
- throw new Error(
4397
- `Dockerfile not found at "${dockerfilePath}" for container service.`
4398
- );
4399
- }
4400
- const repository = daemon ? (0, import_build_utils9.getDaemonImageRepository)(daemon.name) : sanitizeRepository(
4401
- options.service?.name ?? import_node_path24.default.basename(dockerfileRel).split(".")[0]
5515
+ const repository = daemon ? (0, import_build_utils11.getDaemonImageRepository)(daemon.name) : sanitizeRepository(
5516
+ options.service?.name ?? import_node_path29.default.basename(dockerfileRel).split(".")[0]
4402
5517
  );
4403
5518
  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)) === ".";
5519
+ const contextDir = await resolveBuildContext({
5520
+ repoRootPath: options.repoRootPath,
5521
+ workPath: options.workPath,
5522
+ contextDir: daemon || schedulesCommand || options.service ? options.workPath : import_node_path29.default.dirname(dockerfilePath),
5523
+ dockerfilePath
5524
+ });
5525
+ const contextIsRoot = Boolean(daemon || schedulesCommand || options.service) || import_node_path29.default.dirname(import_node_path29.default.normalize(dockerfileRel)) === ".";
4406
5526
  const buildArgs = buildArgsFromEnv(meta?.buildEnv);
4407
5527
  span?.setAttributes({
4408
5528
  "container.mode": "build_and_push",
@@ -4491,7 +5611,7 @@ async function build(options) {
4491
5611
  }
4492
5612
  };
4493
5613
  }
4494
- const lambdaOptions = await (0, import_build_utils9.getLambdaOptionsFromFunction)({
5614
+ const lambdaOptions = await (0, import_build_utils11.getLambdaOptionsFromFunction)({
4495
5615
  sourceFile: resolveFunctionSourceFile(options),
4496
5616
  config: options.config,
4497
5617
  isScheduleEntrypoint: schedulesCommand !== void 0
@@ -4500,7 +5620,7 @@ async function build(options) {
4500
5620
  await generateProjectManifest({
4501
5621
  workPath: options.workPath,
4502
5622
  framework: options.diagnosticsValues?.framework,
4503
- serviceType: options.service ? (0, import_build_utils9.getReportedServiceType)(options.service) : void 0
5623
+ serviceType: options.service ? (0, import_build_utils11.getReportedServiceType)(options.service) : void 0
4504
5624
  });
4505
5625
  const routes = [
4506
5626
  { handle: "filesystem" },
@@ -4543,6 +5663,7 @@ async function build(options) {
4543
5663
  // Annotate the CommonJS export names for ESM import in node:
4544
5664
  0 && (module.exports = {
4545
5665
  CONTAINER_OUTPUT_PATH,
5666
+ ExecutableImageBuilder,
4546
5667
  build,
4547
5668
  diagnostics,
4548
5669
  prepareCache,