@vercel/container 0.0.0 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/dist/index.js +1680 -0
- package/package.json +26 -1
package/dist/index.js
ADDED
|
@@ -0,0 +1,1680 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var src_exports = {};
|
|
32
|
+
__export(src_exports, {
|
|
33
|
+
build: () => build,
|
|
34
|
+
prepareCache: () => prepareCache,
|
|
35
|
+
startDevServer: () => startDevServer,
|
|
36
|
+
version: () => version
|
|
37
|
+
});
|
|
38
|
+
module.exports = __toCommonJS(src_exports);
|
|
39
|
+
var import_node_fs6 = require("fs");
|
|
40
|
+
var import_node_path6 = __toESM(require("path"));
|
|
41
|
+
|
|
42
|
+
// src/util.ts
|
|
43
|
+
var import_build_utils = require("@vercel/build-utils");
|
|
44
|
+
var import_node_child_process = require("child_process");
|
|
45
|
+
var import_node_crypto = require("crypto");
|
|
46
|
+
var import_node_fs = require("fs");
|
|
47
|
+
var import_node_os = require("os");
|
|
48
|
+
var import_node_path = require("path");
|
|
49
|
+
var DEBUG = Boolean((0, import_build_utils.getPlatformEnv)("BUILDER_DEBUG"));
|
|
50
|
+
function write(line) {
|
|
51
|
+
process.stderr.write(`${line}
|
|
52
|
+
`);
|
|
53
|
+
}
|
|
54
|
+
function info(message) {
|
|
55
|
+
write(`\u25B2 container ${message}`);
|
|
56
|
+
}
|
|
57
|
+
function step(message) {
|
|
58
|
+
write(` \u2192 ${message}`);
|
|
59
|
+
}
|
|
60
|
+
function done(message) {
|
|
61
|
+
write(` \u2713 ${message}`);
|
|
62
|
+
}
|
|
63
|
+
function debug(message) {
|
|
64
|
+
if (DEBUG) {
|
|
65
|
+
write(` \xB7 ${message}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function elapsed(since) {
|
|
69
|
+
return `${((Date.now() - since) / 1e3).toFixed(1)}s`;
|
|
70
|
+
}
|
|
71
|
+
function shortDigest(digest) {
|
|
72
|
+
return digest.startsWith("sha256:") ? `${digest.slice(0, 19)}\u2026` : digest;
|
|
73
|
+
}
|
|
74
|
+
async function withSpan(parent, name, attrs, fn) {
|
|
75
|
+
if (!parent) {
|
|
76
|
+
return fn(void 0);
|
|
77
|
+
}
|
|
78
|
+
return parent.child(name, attrs).trace((span) => fn(span));
|
|
79
|
+
}
|
|
80
|
+
function toTag(value) {
|
|
81
|
+
return String(value);
|
|
82
|
+
}
|
|
83
|
+
function readString(value) {
|
|
84
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
85
|
+
}
|
|
86
|
+
function run(cmd, args, opts = {}) {
|
|
87
|
+
return new Promise((resolve, reject) => {
|
|
88
|
+
const child = (0, import_node_child_process.spawn)(cmd, args, {
|
|
89
|
+
cwd: opts.cwd,
|
|
90
|
+
stdio: [opts.input !== void 0 ? "pipe" : "ignore", "pipe", "pipe"]
|
|
91
|
+
});
|
|
92
|
+
let stdout = "";
|
|
93
|
+
let stderr = "";
|
|
94
|
+
child.stdout?.on("data", (chunk) => {
|
|
95
|
+
const text = chunk.toString();
|
|
96
|
+
stdout += text;
|
|
97
|
+
if (!opts.quiet) {
|
|
98
|
+
process.stderr.write(text);
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
child.stderr?.on("data", (chunk) => {
|
|
102
|
+
const text = chunk.toString();
|
|
103
|
+
stderr += text;
|
|
104
|
+
if (!opts.quiet) {
|
|
105
|
+
process.stderr.write(text);
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
child.on("error", (err) => {
|
|
109
|
+
if (err.code === "ENOENT") {
|
|
110
|
+
reject(
|
|
111
|
+
new Error(
|
|
112
|
+
`Command not found: \`${cmd}\`. Ensure \`${cmd}\` is installed and on your PATH.`
|
|
113
|
+
)
|
|
114
|
+
);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
reject(err);
|
|
118
|
+
});
|
|
119
|
+
child.on("close", (code) => {
|
|
120
|
+
if (code === 0) {
|
|
121
|
+
resolve({ stdout, stderr });
|
|
122
|
+
} else {
|
|
123
|
+
const detail = stderr.trim().split("\n").slice(-5).join("\n");
|
|
124
|
+
reject(
|
|
125
|
+
new Error(
|
|
126
|
+
`\`${cmd} ${args.join(" ")}\` exited with code ${code}` + (detail ? `
|
|
127
|
+
${detail}` : "")
|
|
128
|
+
)
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
if (opts.input !== void 0) {
|
|
133
|
+
child.stdin?.end(opts.input);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
function extractField(text, label) {
|
|
138
|
+
const match = text.match(new RegExp(`^\\s*${label}:\\s*(.+)$`, "m"));
|
|
139
|
+
return match?.[1]?.trim();
|
|
140
|
+
}
|
|
141
|
+
function tokenFingerprint(token) {
|
|
142
|
+
if (!token)
|
|
143
|
+
return "absent";
|
|
144
|
+
const sha = (0, import_node_crypto.createHash)("sha256").update(token).digest("hex").slice(0, 8);
|
|
145
|
+
return `present(len=${token.length}, sha256=${sha})`;
|
|
146
|
+
}
|
|
147
|
+
function debugTokenClaims(label, token) {
|
|
148
|
+
if (!DEBUG)
|
|
149
|
+
return;
|
|
150
|
+
if (!token) {
|
|
151
|
+
debug(`${label}: <absent>`);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
try {
|
|
155
|
+
const payload = token.split(".")[1];
|
|
156
|
+
if (!payload) {
|
|
157
|
+
debug(`${label}: <not a JWT>`);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
const claims = JSON.parse(
|
|
161
|
+
Buffer.from(payload, "base64url").toString("utf8")
|
|
162
|
+
);
|
|
163
|
+
const safe = {
|
|
164
|
+
iss: claims.iss,
|
|
165
|
+
aud: claims.aud,
|
|
166
|
+
sub: claims.sub,
|
|
167
|
+
scope: claims.scope,
|
|
168
|
+
owner: claims.owner,
|
|
169
|
+
owner_id: claims.owner_id,
|
|
170
|
+
project: claims.project,
|
|
171
|
+
project_id: claims.project_id,
|
|
172
|
+
exp: typeof claims.exp === "number" ? `${new Date(claims.exp * 1e3).toISOString()} (in ${Math.round(
|
|
173
|
+
(claims.exp * 1e3 - Date.now()) / 1e3
|
|
174
|
+
)}s)` : claims.exp
|
|
175
|
+
};
|
|
176
|
+
debug(`${label}: ${JSON.stringify(safe)}`);
|
|
177
|
+
} catch (err) {
|
|
178
|
+
debug(`${label}: <unparseable claims> (${err.message})`);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function decodeOidcClaims(token) {
|
|
182
|
+
if (!token)
|
|
183
|
+
return {};
|
|
184
|
+
try {
|
|
185
|
+
const payload = token.split(".")[1];
|
|
186
|
+
if (!payload)
|
|
187
|
+
return {};
|
|
188
|
+
const json = Buffer.from(payload, "base64url").toString("utf8");
|
|
189
|
+
return JSON.parse(json);
|
|
190
|
+
} catch {
|
|
191
|
+
return {};
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function isBuildContainer() {
|
|
195
|
+
return Boolean(readString(process.env.VERCEL_BUILD_IMAGE));
|
|
196
|
+
}
|
|
197
|
+
function existingRegistryAuthFile() {
|
|
198
|
+
const explicit = readString(process.env.REGISTRY_AUTH_FILE);
|
|
199
|
+
if (explicit) {
|
|
200
|
+
return (0, import_node_fs.existsSync)(explicit) ? explicit : void 0;
|
|
201
|
+
}
|
|
202
|
+
const fromXdg = readString(process.env.XDG_CONFIG_HOME);
|
|
203
|
+
const configHome = fromXdg || (0, import_node_path.join)((0, import_node_os.homedir)(), ".config");
|
|
204
|
+
const defaultPath = (0, import_node_path.join)(configHome, "containers", "auth.json");
|
|
205
|
+
return (0, import_node_fs.existsSync)(defaultPath) ? defaultPath : void 0;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// src/engines/buildah.ts
|
|
209
|
+
var import_node_fs3 = require("fs");
|
|
210
|
+
var import_node_os3 = require("os");
|
|
211
|
+
var import_node_path3 = require("path");
|
|
212
|
+
|
|
213
|
+
// src/storage-driver.ts
|
|
214
|
+
var import_node_fs2 = require("fs");
|
|
215
|
+
var import_node_os2 = require("os");
|
|
216
|
+
var import_node_path2 = require("path");
|
|
217
|
+
var BUILDAH_GRAPH_ROOT = "/vercel/.containers/storage";
|
|
218
|
+
var BUILDAH_RUN_ROOT = "/run/containers/storage";
|
|
219
|
+
var REQUIRED_BUILD_CONTAINER_DRIVER = "overlay";
|
|
220
|
+
async function hasBinary(name) {
|
|
221
|
+
try {
|
|
222
|
+
await run("which", [name], { quiet: true });
|
|
223
|
+
return true;
|
|
224
|
+
} catch {
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
var cachedStorageDriver;
|
|
229
|
+
function selectStorageDriver() {
|
|
230
|
+
if (!cachedStorageDriver) {
|
|
231
|
+
cachedStorageDriver = (async () => {
|
|
232
|
+
const override = readString(process.env.VERCEL_VCR_DOCKER_STORAGE_DRIVER);
|
|
233
|
+
if (override) {
|
|
234
|
+
return override;
|
|
235
|
+
}
|
|
236
|
+
if (isBuildContainer()) {
|
|
237
|
+
return void 0;
|
|
238
|
+
}
|
|
239
|
+
if (await hasBinary("fuse-overlayfs") && (0, import_node_fs2.existsSync)("/dev/fuse")) {
|
|
240
|
+
return "fuse-overlayfs";
|
|
241
|
+
}
|
|
242
|
+
return "vfs";
|
|
243
|
+
})();
|
|
244
|
+
}
|
|
245
|
+
return cachedStorageDriver;
|
|
246
|
+
}
|
|
247
|
+
var BUILDAH_REGISTRIES_CONF = `unqualified-search-registries = ["docker.io"]
|
|
248
|
+
short-name-mode = "permissive"
|
|
249
|
+
`;
|
|
250
|
+
var cachedRegistriesConfPath;
|
|
251
|
+
function buildahRegistriesConfPath() {
|
|
252
|
+
if (!cachedRegistriesConfPath) {
|
|
253
|
+
const dir = (0, import_node_fs2.mkdtempSync)((0, import_node_path2.join)((0, import_node_os2.tmpdir)(), "vercel-container-registries-"));
|
|
254
|
+
cachedRegistriesConfPath = (0, import_node_path2.join)(dir, "registries.conf");
|
|
255
|
+
(0, import_node_fs2.writeFileSync)(cachedRegistriesConfPath, BUILDAH_REGISTRIES_CONF);
|
|
256
|
+
}
|
|
257
|
+
return cachedRegistriesConfPath;
|
|
258
|
+
}
|
|
259
|
+
async function buildahStorageArgs() {
|
|
260
|
+
const driver = await selectStorageDriver();
|
|
261
|
+
const rootArgs = isBuildContainer() ? ["--root", BUILDAH_GRAPH_ROOT, "--runroot", BUILDAH_RUN_ROOT] : [];
|
|
262
|
+
const registriesArgs = [
|
|
263
|
+
"--registries-conf",
|
|
264
|
+
buildahRegistriesConfPath()
|
|
265
|
+
];
|
|
266
|
+
if (!driver) {
|
|
267
|
+
return [...rootArgs, ...registriesArgs];
|
|
268
|
+
}
|
|
269
|
+
if (driver === "fuse-overlayfs") {
|
|
270
|
+
return [
|
|
271
|
+
...rootArgs,
|
|
272
|
+
...registriesArgs,
|
|
273
|
+
"--storage-driver",
|
|
274
|
+
"overlay",
|
|
275
|
+
"--storage-opt",
|
|
276
|
+
"overlay.mount_program=/usr/bin/fuse-overlayfs"
|
|
277
|
+
];
|
|
278
|
+
}
|
|
279
|
+
return [...rootArgs, ...registriesArgs, "--storage-driver", driver];
|
|
280
|
+
}
|
|
281
|
+
async function readBuildahStoreInfo() {
|
|
282
|
+
const args = await buildahStorageArgs();
|
|
283
|
+
const { stdout } = await run("buildah", [...args, "info"], { quiet: true });
|
|
284
|
+
const store = JSON.parse(stdout).store;
|
|
285
|
+
if (!store) {
|
|
286
|
+
return void 0;
|
|
287
|
+
}
|
|
288
|
+
const graphStatus = store.GraphStatus;
|
|
289
|
+
return {
|
|
290
|
+
graphRoot: String(store.GraphRoot ?? ""),
|
|
291
|
+
runRoot: String(store.RunRoot ?? ""),
|
|
292
|
+
driver: String(store.GraphDriverName ?? ""),
|
|
293
|
+
backingFs: String(
|
|
294
|
+
graphStatus?.["Backing Filesystem"] ?? graphStatus?.["Backing filesystem"] ?? ""
|
|
295
|
+
)
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
async function assertBuildContainerStorage(log = () => {
|
|
299
|
+
}) {
|
|
300
|
+
if (!isBuildContainer()) {
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
if (readString(process.env.VERCEL_VCR_DOCKER_STORAGE_DRIVER)) {
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
const strict = Boolean(readString(process.env.VERCEL_VCR_STRICT_STORAGE));
|
|
307
|
+
let storeInfo;
|
|
308
|
+
try {
|
|
309
|
+
storeInfo = await readBuildahStoreInfo();
|
|
310
|
+
} catch (err) {
|
|
311
|
+
const message = `Could not verify buildah storage via \`buildah info\`: ${err.message}`;
|
|
312
|
+
if (strict) {
|
|
313
|
+
throw new Error(message);
|
|
314
|
+
}
|
|
315
|
+
log(message);
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
if (!storeInfo) {
|
|
319
|
+
const message = "Could not verify buildah storage: `buildah info` returned no store data.";
|
|
320
|
+
if (strict) {
|
|
321
|
+
throw new Error(message);
|
|
322
|
+
}
|
|
323
|
+
log(message);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
const problems = [];
|
|
327
|
+
if (storeInfo.driver !== REQUIRED_BUILD_CONTAINER_DRIVER) {
|
|
328
|
+
problems.push(
|
|
329
|
+
`storage driver is "${storeInfo.driver}", expected "${REQUIRED_BUILD_CONTAINER_DRIVER}"`
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
if (storeInfo.graphRoot !== BUILDAH_GRAPH_ROOT) {
|
|
333
|
+
problems.push(
|
|
334
|
+
`graphRoot is "${storeInfo.graphRoot}", expected the mounted volume "${BUILDAH_GRAPH_ROOT}"`
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
if (storeInfo.backingFs && storeInfo.backingFs === "overlayfs") {
|
|
338
|
+
problems.push(
|
|
339
|
+
`backing filesystem is "${storeInfo.backingFs}" (the overlay rootfs), not the mounted volume`
|
|
340
|
+
);
|
|
341
|
+
}
|
|
342
|
+
const summary = `buildah storage: driver=${storeInfo.driver} graphRoot=${storeInfo.graphRoot} runRoot=${storeInfo.runRoot} backingFs=${storeInfo.backingFs || "?"}`;
|
|
343
|
+
if (problems.length === 0) {
|
|
344
|
+
log(`${summary} \u2014 verified`);
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
const detail = `${summary}
|
|
348
|
+
Problems: ${problems.join("; ")}.
|
|
349
|
+
Expected the native overlay driver with the graphroot under the XFS \`/vercel\` cell volume (requires vercel/hive#2310 capabilities + the storage.conf from vercel/api#76567).`;
|
|
350
|
+
if (strict) {
|
|
351
|
+
throw new Error(
|
|
352
|
+
`Container build storage is not configured as intended.
|
|
353
|
+
${detail}`
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
log(
|
|
357
|
+
`${detail}
|
|
358
|
+
Continuing (set VERCEL_VCR_STRICT_STORAGE=1 to fail builds).`
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// src/oidc.ts
|
|
363
|
+
function parseOidcToken(token) {
|
|
364
|
+
const parts = token.split(".");
|
|
365
|
+
if (parts.length !== 3) {
|
|
366
|
+
throw new Error(
|
|
367
|
+
"VERCEL_OIDC_TOKEN is not a valid JWT (expected 3 dot-separated segments)."
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
try {
|
|
371
|
+
const json = Buffer.from(parts[1], "base64url").toString("utf8");
|
|
372
|
+
return JSON.parse(json);
|
|
373
|
+
} catch {
|
|
374
|
+
throw new Error("VERCEL_OIDC_TOKEN has an unreadable JWT payload.");
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
function resolveProjectContext(token) {
|
|
378
|
+
const claims = parseOidcToken(token);
|
|
379
|
+
return {
|
|
380
|
+
projectId: readString(process.env.VERCEL_PROJECT_ID) ?? claims.project_id,
|
|
381
|
+
teamId: readString(process.env.VERCEL_TEAM_ID) ?? readString(process.env.VERCEL_ORG_ID) ?? claims.owner_id
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
async function mintProjectOidcToken(params) {
|
|
385
|
+
const apiUrl = (readString(process.env.VERCEL_API_URL) ?? "https://api.vercel.com").replace(/\/+$/, "");
|
|
386
|
+
const query = new URLSearchParams({ source: "vercel-container-build" });
|
|
387
|
+
if (params.teamId) {
|
|
388
|
+
query.set("teamId", params.teamId);
|
|
389
|
+
}
|
|
390
|
+
const url = `${apiUrl}/v1/projects/${encodeURIComponent(params.projectId)}/token?${query}`;
|
|
391
|
+
debug(`OIDC mint: POST ${url}`);
|
|
392
|
+
const res = await fetch(url, {
|
|
393
|
+
method: "POST",
|
|
394
|
+
headers: {
|
|
395
|
+
authorization: `Bearer ${params.authToken}`,
|
|
396
|
+
"content-type": "application/json"
|
|
397
|
+
}
|
|
398
|
+
});
|
|
399
|
+
if (!res.ok) {
|
|
400
|
+
const body = (await res.text()).trim();
|
|
401
|
+
throw new Error(
|
|
402
|
+
`Failed to mint OIDC token: HTTP ${res.status}` + (body ? ` \u2014 ${body.split("\n").slice(-3).join("\n")}` : "")
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
const payload = await res.json();
|
|
406
|
+
if (!payload.token) {
|
|
407
|
+
throw new Error("Failed to mint OIDC token: response missing `token`.");
|
|
408
|
+
}
|
|
409
|
+
return payload.token;
|
|
410
|
+
}
|
|
411
|
+
async function resolveOidcTokenForBuild(span) {
|
|
412
|
+
const existing = readString(process.env.VERCEL_OIDC_TOKEN);
|
|
413
|
+
if (!existing) {
|
|
414
|
+
throw new Error(
|
|
415
|
+
"Missing VERCEL_OIDC_TOKEN for the container registry (set by the platform or `vercel pull`)."
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
const authToken = readString(process.env.VERCEL_TOKEN);
|
|
419
|
+
if (!authToken) {
|
|
420
|
+
debug(
|
|
421
|
+
"No VERCEL_TOKEN available to mint; using existing VERCEL_OIDC_TOKEN"
|
|
422
|
+
);
|
|
423
|
+
span?.setAttributes({ "oidc.mint_result": "reused_existing" });
|
|
424
|
+
debug(`registry token: ${tokenFingerprint(existing)}`);
|
|
425
|
+
return existing;
|
|
426
|
+
}
|
|
427
|
+
const { projectId, teamId } = resolveProjectContext(existing);
|
|
428
|
+
if (!projectId) {
|
|
429
|
+
debug("No project id available to mint; using existing VERCEL_OIDC_TOKEN");
|
|
430
|
+
span?.setAttributes({ "oidc.mint_result": "reused_existing" });
|
|
431
|
+
return existing;
|
|
432
|
+
}
|
|
433
|
+
step("Minting fresh OIDC token for container registry");
|
|
434
|
+
let token;
|
|
435
|
+
try {
|
|
436
|
+
token = await mintProjectOidcToken({
|
|
437
|
+
projectId,
|
|
438
|
+
teamId,
|
|
439
|
+
authToken
|
|
440
|
+
});
|
|
441
|
+
} catch (err) {
|
|
442
|
+
debug(`OIDC mint failed, using existing token: ${err.message}`);
|
|
443
|
+
span?.setAttributes({ "oidc.mint_result": "failed_reused_existing" });
|
|
444
|
+
return existing;
|
|
445
|
+
}
|
|
446
|
+
process.env.VERCEL_OIDC_TOKEN = token;
|
|
447
|
+
span?.setAttributes({
|
|
448
|
+
"oidc.mint_result": "minted",
|
|
449
|
+
"project.id": projectId,
|
|
450
|
+
...teamId ? { "team.id": teamId } : {}
|
|
451
|
+
});
|
|
452
|
+
done("OIDC token minted");
|
|
453
|
+
debug(`registry token: ${tokenFingerprint(token)}`);
|
|
454
|
+
return token;
|
|
455
|
+
}
|
|
456
|
+
function formatVcrAuthError(registry, username, detail) {
|
|
457
|
+
return [
|
|
458
|
+
`Authentication to ${registry} as "${username}" was rejected.`,
|
|
459
|
+
"",
|
|
460
|
+
`Make sure your team ("${username}") is enrolled in the`,
|
|
461
|
+
"`vercel-enable-vcr` flag and that the OIDC token is valid for it.",
|
|
462
|
+
...detail ? ["", detail] : []
|
|
463
|
+
].join("\n");
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// src/engines/types.ts
|
|
467
|
+
var VCR_REGISTRY = process.env.VERCEL_VCR_REGISTRY || "vcr.vercel.com";
|
|
468
|
+
var TARGET_PLATFORM = "linux/amd64";
|
|
469
|
+
function buildArgFlags(params) {
|
|
470
|
+
const flags = [];
|
|
471
|
+
for (const [key, value] of Object.entries(params.buildArgs ?? {})) {
|
|
472
|
+
flags.push("--build-arg", `${key}=${value}`);
|
|
473
|
+
}
|
|
474
|
+
return flags;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// src/engines/buildah.ts
|
|
478
|
+
async function runBuildah(args, opts = {}) {
|
|
479
|
+
const storageArgs = await buildahStorageArgs();
|
|
480
|
+
const fullArgs = [...storageArgs, ...args];
|
|
481
|
+
debug(`exec: buildah ${fullArgs.join(" ")}`);
|
|
482
|
+
return run("buildah", fullArgs, opts);
|
|
483
|
+
}
|
|
484
|
+
function logLayerCacheSummary(output) {
|
|
485
|
+
const steps = (output.match(/^STEP\s+\d+\/\d+:/gm) || []).length;
|
|
486
|
+
const cached = (output.match(/-->\s+Using cache\b/gi) || []).length;
|
|
487
|
+
if (steps === 0) {
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
const built = Math.max(steps - cached, 0);
|
|
491
|
+
info(`layer cache: ${cached}/${steps} steps reused, ${built} rebuilt`);
|
|
492
|
+
}
|
|
493
|
+
var buildahEngine = {
|
|
494
|
+
name: "buildah",
|
|
495
|
+
async ensureReady(span) {
|
|
496
|
+
try {
|
|
497
|
+
const storageDriver = await selectStorageDriver();
|
|
498
|
+
const { stdout } = await runBuildah(["--version"], { quiet: true });
|
|
499
|
+
span?.setAttributes({
|
|
500
|
+
"buildah.version": stdout.trim().split("\n")[0],
|
|
501
|
+
"buildah.storage_driver": storageDriver ?? "storage.conf"
|
|
502
|
+
});
|
|
503
|
+
} catch (err) {
|
|
504
|
+
const message = err.message;
|
|
505
|
+
if (/Command not found/i.test(message)) {
|
|
506
|
+
throw new Error(
|
|
507
|
+
isBuildContainer() ? "The `buildah` CLI is not available in this build container. Install buildah (via SPAL) in the build image." : "Buildah was not found on your PATH. Install buildah or run the build on Vercel where the build container provides it."
|
|
508
|
+
);
|
|
509
|
+
}
|
|
510
|
+
throw err;
|
|
511
|
+
}
|
|
512
|
+
},
|
|
513
|
+
async logDiagnostics(span) {
|
|
514
|
+
try {
|
|
515
|
+
const storageDriver = await selectStorageDriver();
|
|
516
|
+
const version2 = (await runBuildah(["--version"], { quiet: true })).stdout.trim();
|
|
517
|
+
info(
|
|
518
|
+
`buildah: ${version2.split("\n")[0] ?? version2} (storage-driver=${storageDriver ?? "storage.conf"})`
|
|
519
|
+
);
|
|
520
|
+
span?.setAttributes({
|
|
521
|
+
"container.engine": "buildah",
|
|
522
|
+
"buildah.version": toTag(version2.split("\n")[0]),
|
|
523
|
+
"buildah.storage_driver": toTag(storageDriver ?? "storage.conf")
|
|
524
|
+
});
|
|
525
|
+
} catch (err) {
|
|
526
|
+
debug(`buildah diagnostics unavailable: ${err.message}`);
|
|
527
|
+
}
|
|
528
|
+
},
|
|
529
|
+
async withRuntime(_span, fn) {
|
|
530
|
+
return fn();
|
|
531
|
+
},
|
|
532
|
+
async build(params) {
|
|
533
|
+
try {
|
|
534
|
+
const { stdout: stdout2 } = await runBuildah(["images", "--quiet"], {
|
|
535
|
+
quiet: true
|
|
536
|
+
});
|
|
537
|
+
const imageCount = stdout2.trim() ? stdout2.trim().split("\n").length : 0;
|
|
538
|
+
info(
|
|
539
|
+
imageCount > 0 ? `layer store: warm (${imageCount} image(s) present before build)` : "layer store: cold (no cached images; first build or cache miss)"
|
|
540
|
+
);
|
|
541
|
+
} catch (err) {
|
|
542
|
+
debug(`could not read store warmth: ${err.message}`);
|
|
543
|
+
}
|
|
544
|
+
const { stdout, stderr } = await runBuildah([
|
|
545
|
+
"build",
|
|
546
|
+
"--platform",
|
|
547
|
+
TARGET_PLATFORM,
|
|
548
|
+
// Commit and cache a layer per Dockerfile instruction so unchanged steps
|
|
549
|
+
// (base image, dependency installs, etc.) can be reused on later builds
|
|
550
|
+
// when the image store is warm. Without this buildah squashes the build
|
|
551
|
+
// and no per-step caching happens.
|
|
552
|
+
"--layers",
|
|
553
|
+
// Use the host network namespace for RUN steps. The build runs inside a
|
|
554
|
+
// restricted Hive cell that cannot program iptables, so buildah's default
|
|
555
|
+
// rootless networking (netavark) fails with
|
|
556
|
+
// "netavark: iptables ... Could not fetch rule set generation id".
|
|
557
|
+
// Host networking skips per-container network setup and reuses the cell's
|
|
558
|
+
// existing egress.
|
|
559
|
+
"--network",
|
|
560
|
+
"host",
|
|
561
|
+
...buildArgFlags(params),
|
|
562
|
+
"-t",
|
|
563
|
+
params.imageRef,
|
|
564
|
+
"-f",
|
|
565
|
+
params.dockerfilePath,
|
|
566
|
+
params.contextDir
|
|
567
|
+
]);
|
|
568
|
+
logLayerCacheSummary(`${stdout}
|
|
569
|
+
${stderr}`);
|
|
570
|
+
},
|
|
571
|
+
async login(params) {
|
|
572
|
+
try {
|
|
573
|
+
await runBuildah(
|
|
574
|
+
[
|
|
575
|
+
"login",
|
|
576
|
+
params.registry,
|
|
577
|
+
"--username",
|
|
578
|
+
params.username,
|
|
579
|
+
"--password-stdin"
|
|
580
|
+
],
|
|
581
|
+
{ input: params.token, quiet: !DEBUG }
|
|
582
|
+
);
|
|
583
|
+
} catch (err) {
|
|
584
|
+
const message = err.message;
|
|
585
|
+
if (/denied|forbidden|unauthorized|401|403/i.test(message)) {
|
|
586
|
+
throw new Error(
|
|
587
|
+
formatVcrAuthError(
|
|
588
|
+
params.registry,
|
|
589
|
+
params.username,
|
|
590
|
+
`Underlying error: ${message}`
|
|
591
|
+
)
|
|
592
|
+
);
|
|
593
|
+
}
|
|
594
|
+
throw err;
|
|
595
|
+
}
|
|
596
|
+
},
|
|
597
|
+
async verifyStorage(span) {
|
|
598
|
+
await assertBuildContainerStorage((message) => {
|
|
599
|
+
info(message);
|
|
600
|
+
const info0 = message.split("\n")[0];
|
|
601
|
+
span?.setAttributes({ "buildah.storage.verify": info0 });
|
|
602
|
+
});
|
|
603
|
+
},
|
|
604
|
+
async reportStorage(span) {
|
|
605
|
+
if (!DEBUG) {
|
|
606
|
+
return;
|
|
607
|
+
}
|
|
608
|
+
try {
|
|
609
|
+
const storeInfo = await readBuildahStoreInfo();
|
|
610
|
+
if (!storeInfo) {
|
|
611
|
+
debug("buildah info: no `store` field in output");
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
info(
|
|
615
|
+
`buildah storage: graphRoot=${storeInfo.graphRoot} runRoot=${storeInfo.runRoot} driver=${storeInfo.driver} backingFs=${storeInfo.backingFs || "?"}`
|
|
616
|
+
);
|
|
617
|
+
span?.setAttributes({
|
|
618
|
+
"buildah.storage.graph_root": storeInfo.graphRoot,
|
|
619
|
+
"buildah.storage.run_root": storeInfo.runRoot,
|
|
620
|
+
"buildah.storage.driver": storeInfo.driver,
|
|
621
|
+
"buildah.storage.backing_fs": storeInfo.backingFs
|
|
622
|
+
});
|
|
623
|
+
} catch (err) {
|
|
624
|
+
debug(`buildah storage report unavailable: ${err.message}`);
|
|
625
|
+
}
|
|
626
|
+
},
|
|
627
|
+
async push(params) {
|
|
628
|
+
const digestDir = (0, import_node_fs3.mkdtempSync)((0, import_node_path3.join)((0, import_node_os3.tmpdir)(), "vercel-container-digest-"));
|
|
629
|
+
const digestFile = (0, import_node_path3.join)(digestDir, "digest");
|
|
630
|
+
const zstdEnabled = !readString(process.env.VERCEL_VCR_DISABLE_ZSTD);
|
|
631
|
+
const zstdArgs = zstdEnabled ? [
|
|
632
|
+
"--compression-format",
|
|
633
|
+
"zstd",
|
|
634
|
+
"--compression-level",
|
|
635
|
+
"3",
|
|
636
|
+
"--force-compression",
|
|
637
|
+
"--format",
|
|
638
|
+
"oci"
|
|
639
|
+
] : [];
|
|
640
|
+
info(
|
|
641
|
+
`pushing ${params.imageRef} ` + (zstdEnabled ? "with zstd compression (level=3, force, oci)" : "with default compression (zstd disabled)")
|
|
642
|
+
);
|
|
643
|
+
const pushStart = Date.now();
|
|
644
|
+
try {
|
|
645
|
+
await runBuildah([
|
|
646
|
+
"push",
|
|
647
|
+
...zstdArgs,
|
|
648
|
+
"--digestfile",
|
|
649
|
+
digestFile,
|
|
650
|
+
params.imageRef
|
|
651
|
+
]);
|
|
652
|
+
const digest = (0, import_node_fs3.readFileSync)(digestFile, "utf8").trim();
|
|
653
|
+
const resolved = digest.match(/sha256:[a-f0-9]{64}/)?.[0] ?? (digest || void 0);
|
|
654
|
+
debug(
|
|
655
|
+
`push completed in ${Date.now() - pushStart}ms` + (resolved ? ` (digest ${resolved})` : "")
|
|
656
|
+
);
|
|
657
|
+
return resolved;
|
|
658
|
+
} catch (err) {
|
|
659
|
+
const message = err.message;
|
|
660
|
+
if (/denied|forbidden|unauthorized|not found|401|403|404/i.test(message)) {
|
|
661
|
+
throw new Error(
|
|
662
|
+
[
|
|
663
|
+
`Pushing ${params.imageRef} was denied.`,
|
|
664
|
+
"",
|
|
665
|
+
`The build tried to ensure the "${params.repository}" repository exists, but`,
|
|
666
|
+
"the push was still rejected. Verify access (or create the repository under",
|
|
667
|
+
"your project's Sandboxes \u2192 Container Registry tab), then re-run the build.",
|
|
668
|
+
"",
|
|
669
|
+
`Underlying error: ${message}`
|
|
670
|
+
].join("\n")
|
|
671
|
+
);
|
|
672
|
+
}
|
|
673
|
+
throw err;
|
|
674
|
+
} finally {
|
|
675
|
+
(0, import_node_fs3.rmSync)(digestDir, { recursive: true, force: true });
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
|
|
680
|
+
// src/engines/docker.ts
|
|
681
|
+
var import_node_child_process2 = require("child_process");
|
|
682
|
+
function runDocker(args, opts = {}) {
|
|
683
|
+
debug(`exec: docker ${args.join(" ")}`);
|
|
684
|
+
return run("docker", args, opts);
|
|
685
|
+
}
|
|
686
|
+
async function hasBinary2(name) {
|
|
687
|
+
try {
|
|
688
|
+
await run("which", [name], { quiet: true });
|
|
689
|
+
return true;
|
|
690
|
+
} catch {
|
|
691
|
+
return false;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
async function isDockerDaemonReachable() {
|
|
695
|
+
try {
|
|
696
|
+
await run("docker", ["version", "--format", "{{.Server.Version}}"], {
|
|
697
|
+
quiet: true
|
|
698
|
+
});
|
|
699
|
+
return true;
|
|
700
|
+
} catch {
|
|
701
|
+
return false;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
function tail(text, n = 12) {
|
|
705
|
+
return text.trim().split("\n").slice(-n).join("\n");
|
|
706
|
+
}
|
|
707
|
+
async function startDockerDaemon(span) {
|
|
708
|
+
const driver = await selectStorageDriver() ?? "vfs";
|
|
709
|
+
const args = ["--storage-driver", driver];
|
|
710
|
+
const extra = readString(process.env.VERCEL_VCR_DOCKERD_ARGS);
|
|
711
|
+
if (extra) {
|
|
712
|
+
args.push(...extra.split(" ").filter(Boolean));
|
|
713
|
+
}
|
|
714
|
+
span?.setAttributes({ "docker.storage_driver": driver });
|
|
715
|
+
step(`Starting Docker daemon (storage-driver=${driver})`);
|
|
716
|
+
debug(`exec: dockerd ${args.join(" ")}`);
|
|
717
|
+
const child = (0, import_node_child_process2.spawn)("dockerd", args, {
|
|
718
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
719
|
+
});
|
|
720
|
+
let log = "";
|
|
721
|
+
const capture = (chunk) => {
|
|
722
|
+
const text = chunk.toString();
|
|
723
|
+
log += text;
|
|
724
|
+
if (DEBUG) {
|
|
725
|
+
process.stderr.write(text);
|
|
726
|
+
}
|
|
727
|
+
};
|
|
728
|
+
child.stdout?.on("data", capture);
|
|
729
|
+
child.stderr?.on("data", capture);
|
|
730
|
+
let exitInfo;
|
|
731
|
+
child.on("exit", (code, signal) => {
|
|
732
|
+
exitInfo = `code=${code ?? "null"} signal=${signal ?? "null"}`;
|
|
733
|
+
});
|
|
734
|
+
const timeoutMs = Number(process.env.VERCEL_VCR_DOCKERD_TIMEOUT_MS) || 3e4;
|
|
735
|
+
const deadline = Date.now() + timeoutMs;
|
|
736
|
+
for (; ; ) {
|
|
737
|
+
if (exitInfo !== void 0) {
|
|
738
|
+
throw new Error(
|
|
739
|
+
[
|
|
740
|
+
`The Docker daemon exited before becoming ready (${exitInfo}).`,
|
|
741
|
+
"In a build container this usually means the environment is missing the",
|
|
742
|
+
`kernel capabilities dockerd needs, or the "${driver}" storage driver`,
|
|
743
|
+
"is unavailable. Override the storage driver with",
|
|
744
|
+
"VERCEL_VCR_DOCKER_STORAGE_DRIVER, or pass extra daemon flags with",
|
|
745
|
+
'VERCEL_VCR_DOCKERD_ARGS (e.g. "--iptables=false") for networking issues.',
|
|
746
|
+
"",
|
|
747
|
+
tail(log)
|
|
748
|
+
].join("\n")
|
|
749
|
+
);
|
|
750
|
+
}
|
|
751
|
+
if (await isDockerDaemonReachable()) {
|
|
752
|
+
done("Docker daemon ready");
|
|
753
|
+
return { child, logTail: () => log };
|
|
754
|
+
}
|
|
755
|
+
if (Date.now() >= deadline) {
|
|
756
|
+
child.kill("SIGKILL");
|
|
757
|
+
throw new Error(
|
|
758
|
+
[
|
|
759
|
+
`The Docker daemon did not become ready within ${Math.round(
|
|
760
|
+
timeoutMs / 1e3
|
|
761
|
+
)}s.`,
|
|
762
|
+
"In a build container this usually means the environment is missing the",
|
|
763
|
+
`kernel capabilities dockerd needs, or the "${driver}" storage driver`,
|
|
764
|
+
"is unavailable. Override it with VERCEL_VCR_DOCKER_STORAGE_DRIVER.",
|
|
765
|
+
"",
|
|
766
|
+
tail(log)
|
|
767
|
+
].join("\n")
|
|
768
|
+
);
|
|
769
|
+
}
|
|
770
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
async function stopDockerDaemon(daemon, span) {
|
|
774
|
+
const { child } = daemon;
|
|
775
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
778
|
+
step("Stopping Docker daemon");
|
|
779
|
+
const stopTimeoutMs = Number(process.env.VERCEL_VCR_DOCKERD_STOP_TIMEOUT_MS) || 1e4;
|
|
780
|
+
await new Promise((resolve) => {
|
|
781
|
+
let settled = false;
|
|
782
|
+
const finish = () => {
|
|
783
|
+
if (!settled) {
|
|
784
|
+
settled = true;
|
|
785
|
+
resolve();
|
|
786
|
+
}
|
|
787
|
+
};
|
|
788
|
+
child.once("exit", finish);
|
|
789
|
+
child.kill("SIGTERM");
|
|
790
|
+
setTimeout(() => {
|
|
791
|
+
try {
|
|
792
|
+
child.kill("SIGKILL");
|
|
793
|
+
} catch {
|
|
794
|
+
}
|
|
795
|
+
finish();
|
|
796
|
+
}, stopTimeoutMs).unref?.();
|
|
797
|
+
});
|
|
798
|
+
span?.setAttributes({ "docker.daemon_stopped": "true" });
|
|
799
|
+
done("Docker daemon stopped");
|
|
800
|
+
}
|
|
801
|
+
function detachDaemon(daemon) {
|
|
802
|
+
const { child } = daemon;
|
|
803
|
+
child.stdout?.removeAllListeners("data");
|
|
804
|
+
child.stderr?.removeAllListeners("data");
|
|
805
|
+
child.stdout?.destroy();
|
|
806
|
+
child.stderr?.destroy();
|
|
807
|
+
child.unref();
|
|
808
|
+
}
|
|
809
|
+
async function withManagedDaemon(span, fn) {
|
|
810
|
+
if (await isDockerDaemonReachable()) {
|
|
811
|
+
return fn();
|
|
812
|
+
}
|
|
813
|
+
if (!await hasBinary2("dockerd")) {
|
|
814
|
+
return fn();
|
|
815
|
+
}
|
|
816
|
+
const daemon = await withSpan(
|
|
817
|
+
span,
|
|
818
|
+
"container.start_daemon",
|
|
819
|
+
void 0,
|
|
820
|
+
(s) => startDockerDaemon(s)
|
|
821
|
+
);
|
|
822
|
+
try {
|
|
823
|
+
return await fn();
|
|
824
|
+
} finally {
|
|
825
|
+
if (isBuildContainer()) {
|
|
826
|
+
detachDaemon(daemon);
|
|
827
|
+
} else {
|
|
828
|
+
await withSpan(
|
|
829
|
+
span,
|
|
830
|
+
"container.stop_daemon",
|
|
831
|
+
void 0,
|
|
832
|
+
(s) => stopDockerDaemon(daemon, s)
|
|
833
|
+
);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
var dockerEngine = {
|
|
838
|
+
name: "docker",
|
|
839
|
+
async ensureReady(span) {
|
|
840
|
+
try {
|
|
841
|
+
const { stdout } = await run(
|
|
842
|
+
"docker",
|
|
843
|
+
["version", "--format", "{{.Server.Version}}"],
|
|
844
|
+
{ quiet: true }
|
|
845
|
+
);
|
|
846
|
+
span?.setAttributes({ "docker.server_version": stdout.trim() });
|
|
847
|
+
} catch (err) {
|
|
848
|
+
const message = err.message;
|
|
849
|
+
const onVercel = isBuildContainer();
|
|
850
|
+
if (/Command not found/i.test(message)) {
|
|
851
|
+
throw new Error(
|
|
852
|
+
onVercel ? "The `docker` CLI is not available in this build container." : "Docker CLI was not found on your PATH. Install Docker and make sure the `docker` command is available so the container image can be built."
|
|
853
|
+
);
|
|
854
|
+
}
|
|
855
|
+
throw new Error(
|
|
856
|
+
(onVercel ? [
|
|
857
|
+
"The Docker daemon is not available in this build container.",
|
|
858
|
+
"",
|
|
859
|
+
"Container builds start and manage their own dockerd; not being able",
|
|
860
|
+
"to reach it points at a missing Docker install or insufficient kernel",
|
|
861
|
+
"capabilities in the build image rather than anything in your project."
|
|
862
|
+
] : [
|
|
863
|
+
"Cannot connect to the Docker daemon \u2014 is Docker running?",
|
|
864
|
+
"",
|
|
865
|
+
"Start Docker (Docker Desktop, Colima, or OrbStack) and verify it with",
|
|
866
|
+
"`docker info`, then re-run the build."
|
|
867
|
+
]).concat(["", `Underlying error: ${message}`]).join("\n")
|
|
868
|
+
);
|
|
869
|
+
}
|
|
870
|
+
},
|
|
871
|
+
async logDiagnostics(span) {
|
|
872
|
+
try {
|
|
873
|
+
const [version2, dockerInfo] = await Promise.all([
|
|
874
|
+
run("docker", ["version"], { quiet: true }).then((r) => r.stdout).catch(() => ""),
|
|
875
|
+
run("docker", ["info"], { quiet: true }).then((r) => r.stdout).catch(() => "")
|
|
876
|
+
]);
|
|
877
|
+
const clientVersion = extractField(
|
|
878
|
+
version2.split(/^Server:/m)[0] ?? version2,
|
|
879
|
+
"Version"
|
|
880
|
+
);
|
|
881
|
+
const serverBlock = version2.split(/^Server:/m)[1] ?? "";
|
|
882
|
+
const serverVersion = extractField(serverBlock, "Version") ?? extractField(dockerInfo, "Server Version");
|
|
883
|
+
const storageDriver = extractField(dockerInfo, "Storage Driver");
|
|
884
|
+
info(
|
|
885
|
+
`docker: client=${clientVersion ?? "?"} server=${serverVersion ?? "?"} storage-driver=${storageDriver ?? "?"}`
|
|
886
|
+
);
|
|
887
|
+
debug(`--- docker version ---
|
|
888
|
+
${version2.trim()}`);
|
|
889
|
+
span?.setAttributes({
|
|
890
|
+
"container.engine": "docker",
|
|
891
|
+
"docker.client_version": toTag(clientVersion),
|
|
892
|
+
"docker.server_version": toTag(serverVersion),
|
|
893
|
+
"docker.storage_driver": toTag(storageDriver)
|
|
894
|
+
});
|
|
895
|
+
} catch (err) {
|
|
896
|
+
debug(`docker diagnostics unavailable: ${err.message}`);
|
|
897
|
+
}
|
|
898
|
+
},
|
|
899
|
+
withRuntime: withManagedDaemon,
|
|
900
|
+
async build(params) {
|
|
901
|
+
await runDocker([
|
|
902
|
+
"build",
|
|
903
|
+
"--platform",
|
|
904
|
+
TARGET_PLATFORM,
|
|
905
|
+
...buildArgFlags(params),
|
|
906
|
+
"-t",
|
|
907
|
+
params.imageRef,
|
|
908
|
+
"-f",
|
|
909
|
+
params.dockerfilePath,
|
|
910
|
+
params.contextDir
|
|
911
|
+
]);
|
|
912
|
+
},
|
|
913
|
+
async login(params) {
|
|
914
|
+
try {
|
|
915
|
+
await runDocker(
|
|
916
|
+
[
|
|
917
|
+
"login",
|
|
918
|
+
params.registry,
|
|
919
|
+
"--username",
|
|
920
|
+
params.username,
|
|
921
|
+
"--password-stdin"
|
|
922
|
+
],
|
|
923
|
+
{ input: params.token, quiet: !DEBUG }
|
|
924
|
+
);
|
|
925
|
+
} catch (err) {
|
|
926
|
+
const message = err.message;
|
|
927
|
+
if (/denied|forbidden|unauthorized|401|403/i.test(message)) {
|
|
928
|
+
throw new Error(
|
|
929
|
+
formatVcrAuthError(
|
|
930
|
+
params.registry,
|
|
931
|
+
params.username,
|
|
932
|
+
`Underlying error: ${message}`
|
|
933
|
+
)
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
throw err;
|
|
937
|
+
}
|
|
938
|
+
},
|
|
939
|
+
async push(params) {
|
|
940
|
+
try {
|
|
941
|
+
info(`pushing ${params.imageRef}`);
|
|
942
|
+
const pushStart = Date.now();
|
|
943
|
+
const { stdout } = await runDocker(["push", params.imageRef]);
|
|
944
|
+
debug(`push completed in ${Date.now() - pushStart}ms`);
|
|
945
|
+
let resolvedDigest = stdout.match(/sha256:[a-f0-9]{64}/)?.[0];
|
|
946
|
+
if (!resolvedDigest) {
|
|
947
|
+
debug("digest not found in push output \u2014 inspecting RepoDigests");
|
|
948
|
+
const inspect = await run(
|
|
949
|
+
"docker",
|
|
950
|
+
["inspect", "--format", "{{index .RepoDigests 0}}", params.imageRef],
|
|
951
|
+
{ quiet: true }
|
|
952
|
+
);
|
|
953
|
+
resolvedDigest = inspect.stdout.match(/sha256:[a-f0-9]{64}/)?.[0];
|
|
954
|
+
}
|
|
955
|
+
return resolvedDigest;
|
|
956
|
+
} catch (err) {
|
|
957
|
+
const message = err.message;
|
|
958
|
+
if (/denied|forbidden|unauthorized|not found|401|403|404/i.test(message)) {
|
|
959
|
+
throw new Error(
|
|
960
|
+
[
|
|
961
|
+
`Pushing ${params.imageRef} was denied.`,
|
|
962
|
+
"",
|
|
963
|
+
`The build tried to ensure the "${params.repository}" repository exists, but`,
|
|
964
|
+
"the push was still rejected. Verify access (or create the repository under",
|
|
965
|
+
"your project's Sandboxes \u2192 Container Registry tab), then re-run the build.",
|
|
966
|
+
"",
|
|
967
|
+
`Underlying error: ${message}`
|
|
968
|
+
].join("\n")
|
|
969
|
+
);
|
|
970
|
+
}
|
|
971
|
+
throw err;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
};
|
|
975
|
+
|
|
976
|
+
// src/engines/index.ts
|
|
977
|
+
function selectContainerEngine() {
|
|
978
|
+
const override = readString(
|
|
979
|
+
process.env.VERCEL_CONTAINER_ENGINE
|
|
980
|
+
)?.toLowerCase();
|
|
981
|
+
if (override === "buildah")
|
|
982
|
+
return buildahEngine;
|
|
983
|
+
if (override === "docker")
|
|
984
|
+
return dockerEngine;
|
|
985
|
+
return isBuildContainer() ? buildahEngine : dockerEngine;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
// src/registry.ts
|
|
989
|
+
async function ensureRepository(repository, token, claims, span) {
|
|
990
|
+
if (repository.includes("/")) {
|
|
991
|
+
debug(`skipping repository auto-create (fully-qualified "${repository}")`);
|
|
992
|
+
span?.setAttributes({ "repository.create_result": "skipped_qualified" });
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
const teamId = claims.owner_id;
|
|
996
|
+
const projectId = claims.project_id;
|
|
997
|
+
if (!teamId || !projectId) {
|
|
998
|
+
debug(
|
|
999
|
+
`skipping repository auto-create (missing ${!teamId ? "team id" : "project id"})`
|
|
1000
|
+
);
|
|
1001
|
+
span?.setAttributes({
|
|
1002
|
+
"repository.create_result": "skipped_missing_ids"
|
|
1003
|
+
});
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
span?.setAttributes({ "team.id": teamId, "project.id": projectId });
|
|
1007
|
+
const apiUrl = (readString(process.env.VERCEL_API_URL) ?? "https://api.vercel.com").replace(/\/+$/, "");
|
|
1008
|
+
const url = `${apiUrl}/v1/vcr/repository?teamId=${encodeURIComponent(teamId)}`;
|
|
1009
|
+
const body = JSON.stringify({ name: repository, projectId });
|
|
1010
|
+
step(`Ensuring registry repository "${repository}"`);
|
|
1011
|
+
debug(`repository create: POST ${url}`);
|
|
1012
|
+
try {
|
|
1013
|
+
const res = await fetch(url, {
|
|
1014
|
+
method: "POST",
|
|
1015
|
+
headers: {
|
|
1016
|
+
authorization: `Bearer ${token}`,
|
|
1017
|
+
"content-type": "application/json"
|
|
1018
|
+
},
|
|
1019
|
+
body
|
|
1020
|
+
});
|
|
1021
|
+
span?.setAttributes({ "repository.create_status": toTag(res.status) });
|
|
1022
|
+
if (res.ok) {
|
|
1023
|
+
span?.setAttributes({ "repository.create_result": "created" });
|
|
1024
|
+
done(`created repository "${repository}"`);
|
|
1025
|
+
} else if (res.status === 409) {
|
|
1026
|
+
span?.setAttributes({ "repository.create_result": "already_exists" });
|
|
1027
|
+
done(`repository "${repository}" already exists`);
|
|
1028
|
+
} else {
|
|
1029
|
+
span?.setAttributes({ "repository.create_result": "unexpected_status" });
|
|
1030
|
+
done("continuing \u2014 push will validate the repository");
|
|
1031
|
+
}
|
|
1032
|
+
} catch (err) {
|
|
1033
|
+
debug(`repository auto-create failed: ${err.message}`);
|
|
1034
|
+
span?.setAttributes({ "repository.create_result": "error" });
|
|
1035
|
+
done("continuing \u2014 push will validate the repository");
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
// src/dev.ts
|
|
1040
|
+
var import_node_child_process3 = require("child_process");
|
|
1041
|
+
var import_node_fs4 = require("fs");
|
|
1042
|
+
var import_node_os4 = require("os");
|
|
1043
|
+
var import_node_path4 = __toESM(require("path"));
|
|
1044
|
+
var HOST_ONLY_ENV = /* @__PURE__ */ new Set([
|
|
1045
|
+
"TMPDIR",
|
|
1046
|
+
"TMP",
|
|
1047
|
+
"TEMP",
|
|
1048
|
+
"HOME",
|
|
1049
|
+
"PATH",
|
|
1050
|
+
"PWD",
|
|
1051
|
+
"OLDPWD",
|
|
1052
|
+
"SHELL",
|
|
1053
|
+
"SHLVL",
|
|
1054
|
+
"USER",
|
|
1055
|
+
"LOGNAME",
|
|
1056
|
+
"TERM",
|
|
1057
|
+
"TERM_PROGRAM",
|
|
1058
|
+
"TERM_PROGRAM_VERSION",
|
|
1059
|
+
"TERM_SESSION_ID",
|
|
1060
|
+
"COLORTERM",
|
|
1061
|
+
"LANG",
|
|
1062
|
+
"LC_ALL",
|
|
1063
|
+
"LC_CTYPE",
|
|
1064
|
+
"COMMAND_MODE",
|
|
1065
|
+
"SECURITYSESSIONID",
|
|
1066
|
+
"__CF_USER_TEXT_ENCODING",
|
|
1067
|
+
"__CFBundleIdentifier"
|
|
1068
|
+
]);
|
|
1069
|
+
function isHostOnlyEnvVar(key) {
|
|
1070
|
+
return HOST_ONLY_ENV.has(key) || key.startsWith("__") || key.startsWith("XPC_") || key.startsWith("SSH_") || key.startsWith("Apple");
|
|
1071
|
+
}
|
|
1072
|
+
function writeEnvFile(env) {
|
|
1073
|
+
const dir = (0, import_node_fs4.mkdtempSync)(import_node_path4.default.join((0, import_node_os4.tmpdir)(), "vercel-container-dev-env-"));
|
|
1074
|
+
const file = import_node_path4.default.join(dir, "env");
|
|
1075
|
+
const lines = [];
|
|
1076
|
+
for (const [key, value] of Object.entries(env)) {
|
|
1077
|
+
if (value.includes("\n")) {
|
|
1078
|
+
continue;
|
|
1079
|
+
}
|
|
1080
|
+
lines.push(`${key}=${value}`);
|
|
1081
|
+
}
|
|
1082
|
+
(0, import_node_fs4.writeFileSync)(file, `${lines.join("\n")}
|
|
1083
|
+
`);
|
|
1084
|
+
return file;
|
|
1085
|
+
}
|
|
1086
|
+
function emit(out, line) {
|
|
1087
|
+
if (out.onStderr) {
|
|
1088
|
+
out.onStderr(Buffer.from(`${line}
|
|
1089
|
+
`));
|
|
1090
|
+
} else {
|
|
1091
|
+
process.stderr.write(`${line}
|
|
1092
|
+
`);
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
function runForwarded(cmd, args, out, opts = {}) {
|
|
1096
|
+
return new Promise((resolve, reject) => {
|
|
1097
|
+
const child = (0, import_node_child_process3.spawn)(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
1098
|
+
let stdout = "";
|
|
1099
|
+
let stderr = "";
|
|
1100
|
+
child.stdout?.on("data", (chunk) => {
|
|
1101
|
+
stdout += chunk.toString();
|
|
1102
|
+
if (!opts.quiet) {
|
|
1103
|
+
if (out.onStdout) {
|
|
1104
|
+
out.onStdout(chunk);
|
|
1105
|
+
} else {
|
|
1106
|
+
process.stderr.write(chunk.toString());
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
});
|
|
1110
|
+
child.stderr?.on("data", (chunk) => {
|
|
1111
|
+
stderr += chunk.toString();
|
|
1112
|
+
if (!opts.quiet) {
|
|
1113
|
+
if (out.onStderr) {
|
|
1114
|
+
out.onStderr(chunk);
|
|
1115
|
+
} else {
|
|
1116
|
+
process.stderr.write(chunk.toString());
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
});
|
|
1120
|
+
child.on("error", (err) => {
|
|
1121
|
+
if (err.code === "ENOENT") {
|
|
1122
|
+
reject(
|
|
1123
|
+
new Error(
|
|
1124
|
+
`Command not found: \`${cmd}\`. Ensure \`${cmd}\` is installed and on your PATH (Docker is required for \`vercel dev\` with container services).`
|
|
1125
|
+
)
|
|
1126
|
+
);
|
|
1127
|
+
return;
|
|
1128
|
+
}
|
|
1129
|
+
reject(err);
|
|
1130
|
+
});
|
|
1131
|
+
child.on("close", (code) => {
|
|
1132
|
+
if (code === 0) {
|
|
1133
|
+
resolve({ stdout });
|
|
1134
|
+
} else {
|
|
1135
|
+
const detail = stderr.trim().split("\n").slice(-5).join("\n");
|
|
1136
|
+
reject(
|
|
1137
|
+
new Error(
|
|
1138
|
+
`\`${cmd} ${args.join(" ")}\` exited with code ${code}` + (detail ? `
|
|
1139
|
+
${detail}` : "")
|
|
1140
|
+
)
|
|
1141
|
+
);
|
|
1142
|
+
}
|
|
1143
|
+
});
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
1146
|
+
function devImageTag(serviceName) {
|
|
1147
|
+
const safe = serviceName.toLowerCase().replace(/[^a-z0-9-_.]/g, "-");
|
|
1148
|
+
return `vercel-dev/${safe || "service"}:dev`;
|
|
1149
|
+
}
|
|
1150
|
+
function isDockerfileRef(ref) {
|
|
1151
|
+
const base = import_node_path4.default.basename(ref).toLowerCase();
|
|
1152
|
+
return base === "dockerfile" || base === "containerfile" || base.endsWith(".dockerfile");
|
|
1153
|
+
}
|
|
1154
|
+
function normalizeCommand(command) {
|
|
1155
|
+
if (typeof command === "string") {
|
|
1156
|
+
return [command];
|
|
1157
|
+
}
|
|
1158
|
+
if (Array.isArray(command) && command.every((item) => typeof item === "string")) {
|
|
1159
|
+
return command;
|
|
1160
|
+
}
|
|
1161
|
+
return void 0;
|
|
1162
|
+
}
|
|
1163
|
+
async function resolveDevImage(options, out, span) {
|
|
1164
|
+
const { config, workPath, entrypoint } = options;
|
|
1165
|
+
const entrypointRef = readString(entrypoint);
|
|
1166
|
+
const dockerfileConfigured = entrypointRef && isDockerfileRef(entrypointRef) ? entrypointRef : void 0;
|
|
1167
|
+
const dockerfileRel = dockerfileConfigured ?? "Dockerfile";
|
|
1168
|
+
const dockerfilePath = import_node_path4.default.join(workPath, dockerfileRel);
|
|
1169
|
+
const hasDockerfile = dockerfileConfigured !== void 0 || (0, import_node_fs4.existsSync)(dockerfilePath);
|
|
1170
|
+
const prebuiltImage = readString(config.handler) ?? (hasDockerfile ? void 0 : entrypointRef);
|
|
1171
|
+
if (!hasDockerfile) {
|
|
1172
|
+
if (!prebuiltImage) {
|
|
1173
|
+
throw new Error(
|
|
1174
|
+
"Container service must specify an entrypoint: a prebuilt OCI image reference, or a Dockerfile path to run with `vercel dev`."
|
|
1175
|
+
);
|
|
1176
|
+
}
|
|
1177
|
+
span?.setAttributes({ "container.dev_mode": "prebuilt" });
|
|
1178
|
+
emit(out, `\u25B2 container vercel dev: using prebuilt image ${prebuiltImage}`);
|
|
1179
|
+
return prebuiltImage;
|
|
1180
|
+
}
|
|
1181
|
+
if (!(0, import_node_fs4.existsSync)(dockerfilePath)) {
|
|
1182
|
+
throw new Error(
|
|
1183
|
+
`Dockerfile not found at "${dockerfilePath}" for container service.`
|
|
1184
|
+
);
|
|
1185
|
+
}
|
|
1186
|
+
const serviceName = options.service?.name ?? "service";
|
|
1187
|
+
const tag = devImageTag(serviceName);
|
|
1188
|
+
const contextDir = import_node_path4.default.dirname(dockerfilePath);
|
|
1189
|
+
const buildArgFlags2 = [];
|
|
1190
|
+
const buildEnv = options.meta?.buildEnv ?? {};
|
|
1191
|
+
for (const [key, value] of Object.entries(buildEnv)) {
|
|
1192
|
+
if (typeof value === "string") {
|
|
1193
|
+
buildArgFlags2.push("--build-arg", `${key}=${value}`);
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
span?.setAttributes({ "container.dev_mode": "build", "image.tag": tag });
|
|
1197
|
+
emit(out, `\u25B2 container vercel dev: building ${tag} (docker, host platform)`);
|
|
1198
|
+
await runForwarded(
|
|
1199
|
+
"docker",
|
|
1200
|
+
["build", ...buildArgFlags2, "-t", tag, "-f", dockerfilePath, contextDir],
|
|
1201
|
+
out
|
|
1202
|
+
);
|
|
1203
|
+
emit(out, `\u25B2 container built ${tag}`);
|
|
1204
|
+
return tag;
|
|
1205
|
+
}
|
|
1206
|
+
async function resolveContainerPort(image, out) {
|
|
1207
|
+
try {
|
|
1208
|
+
const { stdout } = await runForwarded(
|
|
1209
|
+
"docker",
|
|
1210
|
+
["image", "inspect", "--format", "{{json .Config.ExposedPorts}}", image],
|
|
1211
|
+
out,
|
|
1212
|
+
{ quiet: true }
|
|
1213
|
+
);
|
|
1214
|
+
const exposed = JSON.parse(stdout.trim() || "null");
|
|
1215
|
+
if (exposed) {
|
|
1216
|
+
const ports = Object.keys(exposed).map((key) => Number(key.split("/")[0])).filter((n) => Number.isFinite(n)).sort((a, b) => a - b);
|
|
1217
|
+
if (ports.length > 0) {
|
|
1218
|
+
return ports[0];
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
} catch (err) {
|
|
1222
|
+
debug(`could not inspect EXPOSE for ${image}: ${err.message}`);
|
|
1223
|
+
}
|
|
1224
|
+
return 3e3;
|
|
1225
|
+
}
|
|
1226
|
+
async function readMappedHostPort(containerName, containerPort, out) {
|
|
1227
|
+
const { stdout } = await runForwarded(
|
|
1228
|
+
"docker",
|
|
1229
|
+
["port", containerName, `${containerPort}/tcp`],
|
|
1230
|
+
out,
|
|
1231
|
+
{ quiet: true }
|
|
1232
|
+
);
|
|
1233
|
+
const match = stdout.match(/:(\d+)\s*$/m);
|
|
1234
|
+
if (!match) {
|
|
1235
|
+
throw new Error(
|
|
1236
|
+
`Could not determine mapped host port for ${containerName} (${containerPort}/tcp). Got: ${stdout.trim()}`
|
|
1237
|
+
);
|
|
1238
|
+
}
|
|
1239
|
+
return Number(match[1]);
|
|
1240
|
+
}
|
|
1241
|
+
function uniqueContainerName(serviceName) {
|
|
1242
|
+
const safe = serviceName.toLowerCase().replace(/[^a-z0-9-_.]/g, "-");
|
|
1243
|
+
return `vercel-dev-${safe || "service"}-${process.pid}-${Date.now().toString(36)}`;
|
|
1244
|
+
}
|
|
1245
|
+
async function startDevServer(options) {
|
|
1246
|
+
return withSpan(
|
|
1247
|
+
options.span,
|
|
1248
|
+
"container.dev.start",
|
|
1249
|
+
{ "service.name": options.service?.name },
|
|
1250
|
+
async (span) => {
|
|
1251
|
+
const { config, meta, onStdout, onStderr } = options;
|
|
1252
|
+
const out = { onStdout, onStderr };
|
|
1253
|
+
const image = await withSpan(
|
|
1254
|
+
span,
|
|
1255
|
+
"container.dev.resolve_image",
|
|
1256
|
+
{},
|
|
1257
|
+
(s) => resolveDevImage(options, out, s)
|
|
1258
|
+
);
|
|
1259
|
+
const containerPort = await resolveContainerPort(image, out);
|
|
1260
|
+
const containerName = uniqueContainerName(
|
|
1261
|
+
options.service?.name ?? "service"
|
|
1262
|
+
);
|
|
1263
|
+
const mergedEnv = {};
|
|
1264
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
1265
|
+
if (typeof value === "string" && !isHostOnlyEnvVar(key)) {
|
|
1266
|
+
mergedEnv[key] = value;
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
const metaEnv = meta?.env ?? {};
|
|
1270
|
+
for (const [key, value] of Object.entries(metaEnv)) {
|
|
1271
|
+
if (typeof value === "string" && !isHostOnlyEnvVar(key)) {
|
|
1272
|
+
mergedEnv[key] = value;
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
mergedEnv.PORT = String(containerPort);
|
|
1276
|
+
const envFilePath = writeEnvFile(mergedEnv);
|
|
1277
|
+
const command = normalizeCommand(
|
|
1278
|
+
config.command
|
|
1279
|
+
);
|
|
1280
|
+
const requestedHostPort = typeof meta?.port === "number" ? meta.port : 0;
|
|
1281
|
+
const args = [
|
|
1282
|
+
"run",
|
|
1283
|
+
"--rm",
|
|
1284
|
+
"--name",
|
|
1285
|
+
containerName,
|
|
1286
|
+
// Publish the container port to the orchestrator-provided host port, or
|
|
1287
|
+
// an ephemeral host port chosen by Docker when none was requested.
|
|
1288
|
+
"-p",
|
|
1289
|
+
`127.0.0.1:${requestedHostPort}:${containerPort}`,
|
|
1290
|
+
"--env-file",
|
|
1291
|
+
envFilePath,
|
|
1292
|
+
image,
|
|
1293
|
+
...command ?? []
|
|
1294
|
+
];
|
|
1295
|
+
emit(out, `\u25B2 container vercel dev: starting container ${image}`);
|
|
1296
|
+
debug(`docker ${args.join(" ")}`);
|
|
1297
|
+
const child = (0, import_node_child_process3.spawn)("docker", args, {
|
|
1298
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
1299
|
+
});
|
|
1300
|
+
child.stdout?.on("data", (data) => onStdout?.(data));
|
|
1301
|
+
child.stderr?.on("data", (data) => onStderr?.(data));
|
|
1302
|
+
const cleanupEnvFile = () => {
|
|
1303
|
+
(0, import_node_fs4.rmSync)(import_node_path4.default.dirname(envFilePath), { recursive: true, force: true });
|
|
1304
|
+
};
|
|
1305
|
+
const shutdown = async () => {
|
|
1306
|
+
try {
|
|
1307
|
+
await runForwarded("docker", ["stop", containerName], out, {
|
|
1308
|
+
quiet: true
|
|
1309
|
+
});
|
|
1310
|
+
} catch (err) {
|
|
1311
|
+
debug(
|
|
1312
|
+
`docker stop ${containerName} failed: ${err.message}`
|
|
1313
|
+
);
|
|
1314
|
+
} finally {
|
|
1315
|
+
cleanupEnvFile();
|
|
1316
|
+
}
|
|
1317
|
+
};
|
|
1318
|
+
let hostPort;
|
|
1319
|
+
const deadline = Date.now() + 3e4;
|
|
1320
|
+
let lastErr;
|
|
1321
|
+
try {
|
|
1322
|
+
while (Date.now() < deadline) {
|
|
1323
|
+
if (child.exitCode !== null) {
|
|
1324
|
+
throw new Error(
|
|
1325
|
+
`Container "${options.service?.name}" exited (code ${child.exitCode}) before becoming ready.`
|
|
1326
|
+
);
|
|
1327
|
+
}
|
|
1328
|
+
try {
|
|
1329
|
+
hostPort = await readMappedHostPort(
|
|
1330
|
+
containerName,
|
|
1331
|
+
containerPort,
|
|
1332
|
+
out
|
|
1333
|
+
);
|
|
1334
|
+
break;
|
|
1335
|
+
} catch (err) {
|
|
1336
|
+
lastErr = err;
|
|
1337
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
if (hostPort === void 0) {
|
|
1341
|
+
throw new Error(
|
|
1342
|
+
`Timed out waiting for container "${options.service?.name}" to publish port ${containerPort}.` + (lastErr ? ` Last error: ${lastErr.message}` : "")
|
|
1343
|
+
);
|
|
1344
|
+
}
|
|
1345
|
+
} catch (err) {
|
|
1346
|
+
await shutdown();
|
|
1347
|
+
throw err;
|
|
1348
|
+
}
|
|
1349
|
+
span?.setAttributes({
|
|
1350
|
+
"container.dev.host_port": String(hostPort),
|
|
1351
|
+
"container.dev.container_port": String(containerPort),
|
|
1352
|
+
"container.name": containerName
|
|
1353
|
+
});
|
|
1354
|
+
emit(out, `\u25B2 container container ready on localhost:${hostPort}`);
|
|
1355
|
+
return {
|
|
1356
|
+
port: hostPort,
|
|
1357
|
+
pid: child.pid ?? 0,
|
|
1358
|
+
shutdown
|
|
1359
|
+
};
|
|
1360
|
+
}
|
|
1361
|
+
);
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
// src/prepare-cache.ts
|
|
1365
|
+
var import_build_utils2 = require("@vercel/build-utils");
|
|
1366
|
+
var import_node_fs5 = require("fs");
|
|
1367
|
+
var import_node_path5 = require("path");
|
|
1368
|
+
var CACHE_ROOT = "/vercel";
|
|
1369
|
+
var GRAPH_ROOT_REL = import_node_path5.posix.relative(CACHE_ROOT, BUILDAH_GRAPH_ROOT);
|
|
1370
|
+
async function prepareCache(_options) {
|
|
1371
|
+
if (process.env.VERCEL_VCR_DISABLE_LAYER_CACHE) {
|
|
1372
|
+
debug("layer cache disabled (VERCEL_VCR_DISABLE_LAYER_CACHE)");
|
|
1373
|
+
return {};
|
|
1374
|
+
}
|
|
1375
|
+
if (!isBuildContainer()) {
|
|
1376
|
+
debug("skipping container layer cache (not in build container)");
|
|
1377
|
+
return {};
|
|
1378
|
+
}
|
|
1379
|
+
if (!(0, import_node_fs5.existsSync)(BUILDAH_GRAPH_ROOT)) {
|
|
1380
|
+
debug(`no buildah store to cache at ${BUILDAH_GRAPH_ROOT}`);
|
|
1381
|
+
return {};
|
|
1382
|
+
}
|
|
1383
|
+
const start = Date.now();
|
|
1384
|
+
const files = await (0, import_build_utils2.glob)(`${GRAPH_ROOT_REL}/**`, CACHE_ROOT);
|
|
1385
|
+
const count = Object.keys(files).length;
|
|
1386
|
+
info(
|
|
1387
|
+
`cached container layer store: ${count} files from ${BUILDAH_GRAPH_ROOT} in ${Date.now() - start}ms`
|
|
1388
|
+
);
|
|
1389
|
+
return files;
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
// src/index.ts
|
|
1393
|
+
var version = 2;
|
|
1394
|
+
function normalizeCommand2(command) {
|
|
1395
|
+
if (typeof command === "string") {
|
|
1396
|
+
return [command];
|
|
1397
|
+
}
|
|
1398
|
+
if (Array.isArray(command) && command.every((item) => typeof item === "string")) {
|
|
1399
|
+
return command;
|
|
1400
|
+
}
|
|
1401
|
+
return void 0;
|
|
1402
|
+
}
|
|
1403
|
+
function isDockerfileRef2(ref) {
|
|
1404
|
+
const base = import_node_path6.default.basename(ref).toLowerCase();
|
|
1405
|
+
return base === "dockerfile" || base === "containerfile" || base.endsWith(".dockerfile") || // Vercel-specific container opt-in markers, used to deploy a project as a
|
|
1406
|
+
// container even when another framework (e.g. Next.js) is also present.
|
|
1407
|
+
base === "dockerfile.vercel" || base === "containerfile.vercel";
|
|
1408
|
+
}
|
|
1409
|
+
var DOCKERFILE_CANDIDATES = ["Dockerfile.vercel", "Containerfile.vercel"];
|
|
1410
|
+
function findDockerfile(workPath) {
|
|
1411
|
+
return DOCKERFILE_CANDIDATES.find(
|
|
1412
|
+
(name) => (0, import_node_fs6.existsSync)(import_node_path6.default.join(workPath, name))
|
|
1413
|
+
);
|
|
1414
|
+
}
|
|
1415
|
+
function sanitizeRepository(name) {
|
|
1416
|
+
const sanitized = name.toLowerCase().replace(/[^a-z0-9-_./]/g, "-").replace(/-+/g, "-").replace(/(^[-/.]+)|([-/.]+$)/g, "");
|
|
1417
|
+
return sanitized || "service";
|
|
1418
|
+
}
|
|
1419
|
+
function resolveImageTag() {
|
|
1420
|
+
const sha = readString(process.env.VERCEL_GIT_COMMIT_SHA);
|
|
1421
|
+
if (sha) {
|
|
1422
|
+
return sha.slice(0, 12);
|
|
1423
|
+
}
|
|
1424
|
+
const deploymentId = readString(process.env.VERCEL_DEPLOYMENT_ID);
|
|
1425
|
+
if (deploymentId) {
|
|
1426
|
+
return deploymentId.replace(/[^a-z0-9-_.]/gi, "-");
|
|
1427
|
+
}
|
|
1428
|
+
return `build-${Date.now().toString(36)}`;
|
|
1429
|
+
}
|
|
1430
|
+
async function buildAndPushImage(params) {
|
|
1431
|
+
const { contextDir, dockerfilePath, repository, tag, buildArgs, parentSpan } = params;
|
|
1432
|
+
const engine = selectContainerEngine();
|
|
1433
|
+
return withSpan(
|
|
1434
|
+
parentSpan,
|
|
1435
|
+
"container.build_and_push",
|
|
1436
|
+
{
|
|
1437
|
+
"container.engine": engine.name,
|
|
1438
|
+
"container.registry": VCR_REGISTRY,
|
|
1439
|
+
"container.repository": repository
|
|
1440
|
+
},
|
|
1441
|
+
async (buildSpan) => {
|
|
1442
|
+
const token = await withSpan(
|
|
1443
|
+
buildSpan,
|
|
1444
|
+
"container.mint_oidc",
|
|
1445
|
+
{},
|
|
1446
|
+
(s) => resolveOidcTokenForBuild(s)
|
|
1447
|
+
);
|
|
1448
|
+
const claims = decodeOidcClaims(token);
|
|
1449
|
+
debug(`registry token: ${tokenFingerprint(token)}`);
|
|
1450
|
+
debugTokenClaims("OIDC token claims", token);
|
|
1451
|
+
const username = claims.owner_id;
|
|
1452
|
+
if (!username) {
|
|
1453
|
+
throw new Error(
|
|
1454
|
+
"VERCEL_OIDC_TOKEN is missing the `owner_id` (team id) claim required to authenticate to the container registry."
|
|
1455
|
+
);
|
|
1456
|
+
}
|
|
1457
|
+
const fullRepository = [claims.owner, claims.project, repository].join(
|
|
1458
|
+
"/"
|
|
1459
|
+
);
|
|
1460
|
+
const imageRef = `${VCR_REGISTRY}/${fullRepository}:${tag}`;
|
|
1461
|
+
buildSpan?.setAttributes({
|
|
1462
|
+
"container.repository": fullRepository,
|
|
1463
|
+
"image.tag": tag,
|
|
1464
|
+
"image.ref": imageRef,
|
|
1465
|
+
"registry.username": username
|
|
1466
|
+
});
|
|
1467
|
+
return engine.withRuntime(buildSpan, async () => {
|
|
1468
|
+
await withSpan(
|
|
1469
|
+
buildSpan,
|
|
1470
|
+
"container.ensure_toolchain_ready",
|
|
1471
|
+
{ "container.engine": engine.name },
|
|
1472
|
+
(s) => engine.ensureReady(s)
|
|
1473
|
+
);
|
|
1474
|
+
await withSpan(
|
|
1475
|
+
buildSpan,
|
|
1476
|
+
"container.toolchain_diagnostics",
|
|
1477
|
+
{ "container.engine": engine.name },
|
|
1478
|
+
(s) => engine.logDiagnostics(s)
|
|
1479
|
+
);
|
|
1480
|
+
await withSpan(
|
|
1481
|
+
buildSpan,
|
|
1482
|
+
"container.verify_storage",
|
|
1483
|
+
{ "container.engine": engine.name },
|
|
1484
|
+
(s) => engine.verifyStorage?.(s) ?? Promise.resolve()
|
|
1485
|
+
);
|
|
1486
|
+
const buildParams = {
|
|
1487
|
+
contextDir,
|
|
1488
|
+
dockerfilePath,
|
|
1489
|
+
imageRef,
|
|
1490
|
+
registry: VCR_REGISTRY,
|
|
1491
|
+
username,
|
|
1492
|
+
token,
|
|
1493
|
+
repository,
|
|
1494
|
+
buildArgs,
|
|
1495
|
+
span: buildSpan
|
|
1496
|
+
};
|
|
1497
|
+
const forceLogin = readString(process.env.VERCEL_VCR_FORCE_LOGIN) === "1";
|
|
1498
|
+
const authFile = forceLogin ? void 0 : existingRegistryAuthFile();
|
|
1499
|
+
if (authFile) {
|
|
1500
|
+
debug(`registry auth file present: ${authFile}`);
|
|
1501
|
+
step(`Using registry credentials from ${authFile}`);
|
|
1502
|
+
buildSpan?.setAttributes({
|
|
1503
|
+
"container.registry": VCR_REGISTRY,
|
|
1504
|
+
"registry.username": username,
|
|
1505
|
+
"registry.auth_file": authFile,
|
|
1506
|
+
"registry.login_skipped": toTag(true)
|
|
1507
|
+
});
|
|
1508
|
+
done("authenticated via provisioned credentials");
|
|
1509
|
+
} else {
|
|
1510
|
+
step(`Authenticating to ${VCR_REGISTRY} as ${username}`);
|
|
1511
|
+
await withSpan(
|
|
1512
|
+
buildSpan,
|
|
1513
|
+
"container.registry_login",
|
|
1514
|
+
{
|
|
1515
|
+
"container.registry": VCR_REGISTRY,
|
|
1516
|
+
"registry.username": username
|
|
1517
|
+
},
|
|
1518
|
+
() => engine.login(buildParams)
|
|
1519
|
+
);
|
|
1520
|
+
done("authenticated");
|
|
1521
|
+
}
|
|
1522
|
+
await withSpan(
|
|
1523
|
+
buildSpan,
|
|
1524
|
+
"container.ensure_repository",
|
|
1525
|
+
{ "container.repository": repository },
|
|
1526
|
+
(s) => ensureRepository(repository, token, claims, s)
|
|
1527
|
+
);
|
|
1528
|
+
info(`Building image ${imageRef} (${engine.name})`);
|
|
1529
|
+
debug(`dockerfile: ${dockerfilePath}`);
|
|
1530
|
+
debug(`context: ${contextDir}`);
|
|
1531
|
+
debug(`platform: ${TARGET_PLATFORM}`);
|
|
1532
|
+
debug(
|
|
1533
|
+
`build args: ${buildArgs ? Object.keys(buildArgs).length : 0} (from project build env)`
|
|
1534
|
+
);
|
|
1535
|
+
const buildStart = Date.now();
|
|
1536
|
+
step(`${engine.name} build (${TARGET_PLATFORM})`);
|
|
1537
|
+
await withSpan(
|
|
1538
|
+
buildSpan,
|
|
1539
|
+
"container.image_build",
|
|
1540
|
+
{ "image.ref": imageRef, "image.platform": TARGET_PLATFORM },
|
|
1541
|
+
() => engine.build(buildParams)
|
|
1542
|
+
);
|
|
1543
|
+
done(`built in ${elapsed(buildStart)}`);
|
|
1544
|
+
const pushStart = Date.now();
|
|
1545
|
+
step(`Pushing ${imageRef}`);
|
|
1546
|
+
const digest = await withSpan(
|
|
1547
|
+
buildSpan,
|
|
1548
|
+
"container.push",
|
|
1549
|
+
{ "image.ref": imageRef },
|
|
1550
|
+
() => engine.push(buildParams)
|
|
1551
|
+
);
|
|
1552
|
+
done(
|
|
1553
|
+
digest ? `pushed ${shortDigest(digest)} in ${elapsed(pushStart)}` : `pushed in ${elapsed(pushStart)}`
|
|
1554
|
+
);
|
|
1555
|
+
await withSpan(
|
|
1556
|
+
buildSpan,
|
|
1557
|
+
"container.report_storage",
|
|
1558
|
+
{ "container.engine": engine.name },
|
|
1559
|
+
(s) => engine.reportStorage?.(s) ?? Promise.resolve()
|
|
1560
|
+
);
|
|
1561
|
+
const resolvedRef = digest ? `${VCR_REGISTRY}/${fullRepository}@${digest}` : imageRef;
|
|
1562
|
+
buildSpan?.setAttributes({
|
|
1563
|
+
"image.digest": digest,
|
|
1564
|
+
"image.resolved_ref": resolvedRef
|
|
1565
|
+
});
|
|
1566
|
+
info(`Image reference ${resolvedRef}`);
|
|
1567
|
+
debug(
|
|
1568
|
+
`container build_and_push total: ${elapsed(buildStart)} (build + push + storage report)`
|
|
1569
|
+
);
|
|
1570
|
+
return resolvedRef;
|
|
1571
|
+
});
|
|
1572
|
+
}
|
|
1573
|
+
);
|
|
1574
|
+
}
|
|
1575
|
+
async function resolveImageHandler(options, span) {
|
|
1576
|
+
const { config, workPath, entrypoint, meta } = options;
|
|
1577
|
+
const entrypointRef = readString(entrypoint);
|
|
1578
|
+
const dockerfileConfigured = entrypointRef && isDockerfileRef2(entrypointRef) ? entrypointRef : findDockerfile(workPath);
|
|
1579
|
+
const dockerfileRel = dockerfileConfigured ?? "Dockerfile";
|
|
1580
|
+
const dockerfilePath = import_node_path6.default.join(workPath, dockerfileRel);
|
|
1581
|
+
const hasDockerfile = dockerfileConfigured !== void 0 || (0, import_node_fs6.existsSync)(dockerfilePath);
|
|
1582
|
+
const prebuiltImage = readString(config.handler) ?? (hasDockerfile ? void 0 : entrypointRef);
|
|
1583
|
+
span?.setAttributes({
|
|
1584
|
+
"container.has_dockerfile": toTag(hasDockerfile),
|
|
1585
|
+
"container.is_dev": toTag(Boolean(meta?.isDev))
|
|
1586
|
+
});
|
|
1587
|
+
if (!hasDockerfile) {
|
|
1588
|
+
if (!prebuiltImage) {
|
|
1589
|
+
throw new Error(
|
|
1590
|
+
"Container service must specify an entrypoint: a prebuilt OCI image reference, or a Dockerfile path to build."
|
|
1591
|
+
);
|
|
1592
|
+
}
|
|
1593
|
+
span?.setAttributes({ "container.mode": "prebuilt" });
|
|
1594
|
+
info(`Using prebuilt image ${prebuiltImage}`);
|
|
1595
|
+
return prebuiltImage;
|
|
1596
|
+
}
|
|
1597
|
+
if (meta?.isDev) {
|
|
1598
|
+
if (prebuiltImage) {
|
|
1599
|
+
span?.setAttributes({ "container.mode": "prebuilt_dev" });
|
|
1600
|
+
info(`vercel dev: using prebuilt image ${prebuiltImage}`);
|
|
1601
|
+
return prebuiltImage;
|
|
1602
|
+
}
|
|
1603
|
+
throw new Error(
|
|
1604
|
+
'`vercel dev` cannot build container images from a Dockerfile. Specify a prebuilt "image" for local development.'
|
|
1605
|
+
);
|
|
1606
|
+
}
|
|
1607
|
+
if (!(0, import_node_fs6.existsSync)(dockerfilePath)) {
|
|
1608
|
+
throw new Error(
|
|
1609
|
+
`Dockerfile not found at "${dockerfilePath}" for container service.`
|
|
1610
|
+
);
|
|
1611
|
+
}
|
|
1612
|
+
const serviceName = options.service?.name;
|
|
1613
|
+
const repository = sanitizeRepository(
|
|
1614
|
+
serviceName ?? import_node_path6.default.basename(dockerfileRel).split(".")[0]
|
|
1615
|
+
);
|
|
1616
|
+
const tag = resolveImageTag();
|
|
1617
|
+
const contextDir = import_node_path6.default.dirname(dockerfilePath);
|
|
1618
|
+
const buildArgs = buildArgsFromEnv(meta?.buildEnv);
|
|
1619
|
+
span?.setAttributes({
|
|
1620
|
+
"container.mode": "build_and_push",
|
|
1621
|
+
"container.repository": repository,
|
|
1622
|
+
"image.tag": tag
|
|
1623
|
+
});
|
|
1624
|
+
return buildAndPushImage({
|
|
1625
|
+
contextDir,
|
|
1626
|
+
dockerfilePath,
|
|
1627
|
+
repository,
|
|
1628
|
+
tag,
|
|
1629
|
+
buildArgs,
|
|
1630
|
+
parentSpan: span
|
|
1631
|
+
});
|
|
1632
|
+
}
|
|
1633
|
+
function buildArgsFromEnv(env) {
|
|
1634
|
+
if (!env) {
|
|
1635
|
+
return void 0;
|
|
1636
|
+
}
|
|
1637
|
+
const out = {};
|
|
1638
|
+
for (const [key, value] of Object.entries(env)) {
|
|
1639
|
+
if (typeof value === "string") {
|
|
1640
|
+
out[key] = value;
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
1644
|
+
}
|
|
1645
|
+
async function build(options) {
|
|
1646
|
+
const image = await withSpan(
|
|
1647
|
+
options.span,
|
|
1648
|
+
"container.resolve_image",
|
|
1649
|
+
{ "service.name": options.service?.name },
|
|
1650
|
+
(span) => resolveImageHandler(options, span)
|
|
1651
|
+
);
|
|
1652
|
+
const command = normalizeCommand2(options.config.command);
|
|
1653
|
+
const routes = [
|
|
1654
|
+
{ handle: "filesystem" },
|
|
1655
|
+
{ src: "/(.*)", dest: "/index" }
|
|
1656
|
+
];
|
|
1657
|
+
return {
|
|
1658
|
+
routes,
|
|
1659
|
+
output: {
|
|
1660
|
+
index: {
|
|
1661
|
+
type: "Lambda",
|
|
1662
|
+
files: {},
|
|
1663
|
+
// For `runtime: 'container'` the OCI image reference is carried in
|
|
1664
|
+
// `handler`; the platform surfaces it as the container image downstream
|
|
1665
|
+
// (vercel/api#76729).
|
|
1666
|
+
handler: image,
|
|
1667
|
+
runtime: "container",
|
|
1668
|
+
environment: {},
|
|
1669
|
+
...command ? { command } : {}
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
};
|
|
1673
|
+
}
|
|
1674
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1675
|
+
0 && (module.exports = {
|
|
1676
|
+
build,
|
|
1677
|
+
prepareCache,
|
|
1678
|
+
startDevServer,
|
|
1679
|
+
version
|
|
1680
|
+
});
|