@gadicc/loom 1.29.0 → 1.31.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 (40) hide show
  1. package/README.md +7 -0
  2. package/esm/mod.d.ts +1 -0
  3. package/esm/mod.d.ts.map +1 -1
  4. package/esm/mod.js +1 -0
  5. package/esm/src/cli/mod.d.ts.map +1 -1
  6. package/esm/src/cli/mod.js +134 -10
  7. package/esm/src/cli/vercelProjectRelease.d.ts +38 -0
  8. package/esm/src/cli/vercelProjectRelease.d.ts.map +1 -0
  9. package/esm/src/cli/vercelProjectRelease.js +600 -0
  10. package/esm/src/clientData/identity.d.ts +89 -0
  11. package/esm/src/clientData/identity.d.ts.map +1 -0
  12. package/esm/src/clientData/identity.js +127 -0
  13. package/esm/src/clientData/mod.d.ts +3 -0
  14. package/esm/src/clientData/mod.d.ts.map +1 -0
  15. package/esm/src/clientData/mod.js +1 -0
  16. package/esm/src/next/auth/client.d.ts +7 -0
  17. package/esm/src/next/auth/client.d.ts.map +1 -1
  18. package/esm/src/next/auth/client.js +7 -0
  19. package/package.json +14 -2
  20. package/script/mod.d.ts +1 -0
  21. package/script/mod.d.ts.map +1 -1
  22. package/script/mod.js +1 -0
  23. package/script/src/cli/mod.d.ts.map +1 -1
  24. package/script/src/cli/mod.js +134 -10
  25. package/script/src/cli/vercelProjectRelease.d.ts +38 -0
  26. package/script/src/cli/vercelProjectRelease.d.ts.map +1 -0
  27. package/script/src/cli/vercelProjectRelease.js +606 -0
  28. package/script/src/clientData/identity.d.ts +89 -0
  29. package/script/src/clientData/identity.d.ts.map +1 -0
  30. package/script/src/clientData/identity.js +134 -0
  31. package/script/src/clientData/mod.d.ts +3 -0
  32. package/script/src/clientData/mod.d.ts.map +1 -0
  33. package/script/src/clientData/mod.js +18 -0
  34. package/script/src/next/auth/client.d.ts +7 -0
  35. package/script/src/next/auth/client.d.ts.map +1 -1
  36. package/script/src/next/auth/client.js +7 -0
  37. package/skills/loom/SKILL.md +6 -4
  38. package/skills/loom-auth/SKILL.md +9 -7
  39. package/skills/loom-db/SKILL.md +7 -2
  40. package/skills/modernize-app/SKILL.md +6 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vercelProjectRelease.d.ts","sourceRoot":"","sources":["../../../src/src/cli/vercelProjectRelease.ts"],"names":[],"mappings":"AA2BA,KAAK,SAAS,GAAG;IACf,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAC7B,CAAC;AAQF,KAAK,WAAW,GAAG,OAAO,KAAK,CAAC;AAEhC,KAAK,qBAAqB,GAAG;IAC3B,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;IACxC,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,WAAW,CAAC;IACxB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,KAAK,cAAc,GAAG;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC;IACxC,SAAS,CAAC,EAAE,WAAW,CAAC;IACxB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,KAAK,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,+EAA+E;AAC/E,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,MAAM,UAatD;AA2JD,4EAA4E;AAC5E,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,UAsChC;AAgND,gFAAgF;AAChF,wBAAsB,2BAA2B,CAC/C,OAAO,EAAE,qBAAqB,EAC9B,EAAE,GAAE,SAAgD;;;;GAkGrD;AAyGD,iFAAiF;AACjF,wBAAsB,2BAA2B,CAC/C,OAAO,EAAE,cAAc,EACvB,EAAE,GAAE,SAAgD;;;GAsGrD"}
@@ -0,0 +1,606 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseVercelReleaseTimeout = parseVercelReleaseTimeout;
4
+ exports.serializeVercelPulledEnvironment = serializeVercelPulledEnvironment;
5
+ exports.prepareVercelProjectRelease = prepareVercelProjectRelease;
6
+ exports.promoteVercelProjectRelease = promoteVercelProjectRelease;
7
+ const node_crypto_1 = require("node:crypto");
8
+ const node_fs_1 = require("node:fs");
9
+ const node_path_1 = require("node:path");
10
+ const node_util_1 = require("node:util");
11
+ const API_ORIGIN = "https://api.vercel.com";
12
+ const FETCH_TIMEOUT_MS = 30_000;
13
+ const MAX_PROJECT_BYTES = 2 * 1024 * 1024;
14
+ const MAX_ENV_BYTES = 8 * 1024 * 1024;
15
+ const MAX_METADATA_BYTES = 8 * 1024 * 1024;
16
+ const ENV_PREFIX = "# Created by Vercel CLI\n";
17
+ const IGNORED_ENV_KEYS = new Set([
18
+ "VERCEL_ANALYTICS_ID",
19
+ "VERCEL_SPEED_INSIGHTS_ID",
20
+ "VERCEL_WEB_ANALYTICS_ID",
21
+ ]);
22
+ /** Parse the bounded duration accepted by project-scoped promotion polling. */
23
+ function parseVercelReleaseTimeout(value) {
24
+ const match = value.match(/^(\d+)(ms|s|m)$/);
25
+ if (!match)
26
+ throw new Error("Vercel promotion timeout is invalid.");
27
+ const unit = match[2];
28
+ const multiplier = unit === "m" ? 60_000 : unit === "s" ? 1_000 : 1;
29
+ const milliseconds = Number(match[1]) * multiplier;
30
+ if (!Number.isSafeInteger(milliseconds) || milliseconds < 1_000 ||
31
+ milliseconds > 900_000) {
32
+ throw new Error("Vercel promotion timeout must be between 1s and 15m.");
33
+ }
34
+ return milliseconds;
35
+ }
36
+ function object(value) {
37
+ return typeof value === "object" && value !== null && !Array.isArray(value);
38
+ }
39
+ function requireReleaseIdentity(env) {
40
+ const token = env.VERCEL_TOKEN?.trim();
41
+ const orgId = env.VERCEL_ORG_ID?.trim();
42
+ const projectId = env.VERCEL_PROJECT_ID?.trim();
43
+ if (!token || !orgId || !projectId) {
44
+ throw new Error("VERCEL_TOKEN, VERCEL_ORG_ID, and VERCEL_PROJECT_ID are required.");
45
+ }
46
+ if (!/^team_[A-Za-z0-9]+$/.test(orgId)) {
47
+ throw new Error("VERCEL_ORG_ID is invalid.");
48
+ }
49
+ if (!/^prj_[A-Za-z0-9]+$/.test(projectId)) {
50
+ throw new Error("VERCEL_PROJECT_ID is invalid.");
51
+ }
52
+ return { orgId, projectId, token };
53
+ }
54
+ function query(path, values) {
55
+ const url = new URL(path, API_ORIGIN);
56
+ for (const [key, value] of Object.entries(values)) {
57
+ url.searchParams.set(key, value);
58
+ }
59
+ return url;
60
+ }
61
+ async function cancelQuietly(reader) {
62
+ try {
63
+ await Promise.race([
64
+ reader.cancel(),
65
+ new Promise((resolve) => setTimeout(resolve, 100)),
66
+ ]);
67
+ }
68
+ catch {
69
+ // Cancellation is best effort after a bounded read has already failed.
70
+ }
71
+ }
72
+ async function readBoundedJson(response, maxBytes) {
73
+ const declared = response.headers.get("content-length");
74
+ if (declared !== null) {
75
+ const bytes = Number(declared);
76
+ if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > maxBytes) {
77
+ if (response.body)
78
+ void cancelQuietly(response.body.getReader());
79
+ throw new Error("Vercel returned an oversized response.");
80
+ }
81
+ }
82
+ if (!response.body)
83
+ throw new Error("Vercel returned an empty response.");
84
+ const reader = response.body.getReader();
85
+ const chunks = [];
86
+ let total = 0;
87
+ try {
88
+ while (true) {
89
+ const { done, value } = await reader.read();
90
+ if (done)
91
+ break;
92
+ total += value.byteLength;
93
+ if (total > maxBytes) {
94
+ void cancelQuietly(reader);
95
+ throw new Error("Vercel returned an oversized response.");
96
+ }
97
+ chunks.push(value);
98
+ }
99
+ }
100
+ catch (error) {
101
+ void cancelQuietly(reader);
102
+ if (error instanceof Error && error.message.includes("oversized")) {
103
+ throw error;
104
+ }
105
+ throw new Error("Vercel response could not be read.");
106
+ }
107
+ const bytes = new Uint8Array(total);
108
+ let offset = 0;
109
+ for (const chunk of chunks) {
110
+ bytes.set(chunk, offset);
111
+ offset += chunk.byteLength;
112
+ }
113
+ let text;
114
+ try {
115
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
116
+ }
117
+ catch {
118
+ throw new Error("Vercel returned invalid UTF-8.");
119
+ }
120
+ try {
121
+ return JSON.parse(text);
122
+ }
123
+ catch {
124
+ throw new Error("Vercel returned invalid JSON.");
125
+ }
126
+ }
127
+ async function fetchJson(identity, url, options) {
128
+ const controller = new AbortController();
129
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs);
130
+ let response;
131
+ try {
132
+ response = await options.fetchImpl(url, {
133
+ body: options.body,
134
+ headers: {
135
+ authorization: `Bearer ${identity.token}`,
136
+ ...(options.body === undefined
137
+ ? {}
138
+ : { "content-type": "application/json" }),
139
+ },
140
+ method: options.method ?? "GET",
141
+ redirect: "error",
142
+ signal: controller.signal,
143
+ });
144
+ if (!response.ok) {
145
+ if (response.body)
146
+ void cancelQuietly(response.body.getReader());
147
+ throw new Error(`Vercel request failed with HTTP ${response.status}.`);
148
+ }
149
+ return await readBoundedJson(response, options.maxBytes);
150
+ }
151
+ catch (error) {
152
+ if (error instanceof Error && error.message.startsWith("Vercel ")) {
153
+ throw error;
154
+ }
155
+ throw new Error("Vercel request did not complete.");
156
+ }
157
+ finally {
158
+ clearTimeout(timer);
159
+ }
160
+ }
161
+ function requireStringMap(value, label) {
162
+ if (!object(value))
163
+ throw new Error(`${label} is invalid.`);
164
+ const result = Object.create(null);
165
+ for (const [key, item] of Object.entries(value)) {
166
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || typeof item !== "string") {
167
+ throw new Error(`${label} is invalid.`);
168
+ }
169
+ result[key] = item;
170
+ }
171
+ return result;
172
+ }
173
+ function escapeLikeVercelCli(value) {
174
+ return value.replaceAll("\n", "\\n").replaceAll("\r", "\\r");
175
+ }
176
+ /** Serialize a pulled Vercel env map without changing its parsed values. */
177
+ function serializeVercelPulledEnvironment(records) {
178
+ const included = Object.keys(records).sort().filter((key) => !IGNORED_ENV_KEYS.has(key));
179
+ if (included.some((key) => records[key].includes("$") || records[key].includes('"') ||
180
+ records[key].includes("\0") || records[key].includes("\r") ||
181
+ records[key].includes("\\n") || records[key].includes("\\r"))) {
182
+ throw new Error("Vercel environment contains a value that the release dotenv format would change.");
183
+ }
184
+ const source = ENV_PREFIX +
185
+ included.map((key) => `${key}="${escapeLikeVercelCli(records[key])}"`).join("\n") + "\n";
186
+ let roundTrip;
187
+ try {
188
+ roundTrip = (0, node_util_1.parseEnv)(source);
189
+ }
190
+ catch {
191
+ throw new Error("Vercel environment could not be represented safely.");
192
+ }
193
+ for (const key of included) {
194
+ if (roundTrip[key] !== records[key]) {
195
+ throw new Error(`Vercel environment value for ${key} cannot be represented safely.`);
196
+ }
197
+ }
198
+ if (Object.keys(roundTrip).length !== included.length) {
199
+ throw new Error("Vercel environment could not be represented safely.");
200
+ }
201
+ return source;
202
+ }
203
+ function optionalStringOrNull(value, label) {
204
+ if (value === undefined || value === null || typeof value === "string") {
205
+ return value;
206
+ }
207
+ throw new Error(`Vercel project ${label} is invalid.`);
208
+ }
209
+ function projectFileFromResponse(value, identity) {
210
+ if (!object(value))
211
+ throw new Error("Vercel project response is invalid.");
212
+ if (value.id !== identity.projectId || value.accountId !== identity.orgId) {
213
+ throw new Error("Vercel project identity does not match release config.");
214
+ }
215
+ if (typeof value.name !== "string" || !value.name) {
216
+ throw new Error("Vercel project name is invalid.");
217
+ }
218
+ let analyticsId;
219
+ if (object(value.analytics) && typeof value.analytics.id === "string") {
220
+ const disabledAt = value.analytics.disabledAt;
221
+ const enabledAt = value.analytics.enabledAt;
222
+ if (disabledAt === undefined || disabledAt === null ||
223
+ (typeof enabledAt === "number" && typeof disabledAt === "number" &&
224
+ enabledAt > disabledAt))
225
+ analyticsId = value.analytics.id;
226
+ }
227
+ const settings = {};
228
+ if (value.createdAt !== undefined) {
229
+ if (typeof value.createdAt !== "number" || !Number.isFinite(value.createdAt)) {
230
+ throw new Error("Vercel project createdAt is invalid.");
231
+ }
232
+ settings.createdAt = value.createdAt;
233
+ }
234
+ for (const key of [
235
+ "framework",
236
+ "devCommand",
237
+ "installCommand",
238
+ "buildCommand",
239
+ "outputDirectory",
240
+ "rootDirectory",
241
+ "nodeVersion",
242
+ ]) {
243
+ const item = optionalStringOrNull(value[key], key);
244
+ if (item !== undefined)
245
+ settings[key] = item;
246
+ }
247
+ if (value.directoryListing !== undefined) {
248
+ if (typeof value.directoryListing !== "boolean") {
249
+ throw new Error("Vercel project directoryListing is invalid.");
250
+ }
251
+ settings.directoryListing = value.directoryListing;
252
+ }
253
+ if (analyticsId !== undefined)
254
+ settings.analyticsId = analyticsId;
255
+ return {
256
+ orgId: identity.orgId,
257
+ projectId: identity.projectId,
258
+ projectName: value.name,
259
+ settings,
260
+ };
261
+ }
262
+ function normalizeMetadata(value) {
263
+ if (!object(value) || !Array.isArray(value.envs)) {
264
+ throw new Error("Vercel environment metadata is invalid.");
265
+ }
266
+ if (value.pagination !== undefined && !object(value.pagination)) {
267
+ throw new Error("Vercel environment metadata pagination is invalid.");
268
+ }
269
+ if (object(value.pagination) &&
270
+ (value.pagination.next !== undefined && value.pagination.next !== null)) {
271
+ throw new Error("Vercel environment metadata pagination is incomplete.");
272
+ }
273
+ const envs = value.envs.map((item) => {
274
+ if (!object(item) || typeof item.key !== "string" ||
275
+ !/^[A-Za-z_][A-Za-z0-9_]*$/.test(item.key) ||
276
+ typeof item.type !== "string")
277
+ throw new Error("Vercel environment metadata is invalid.");
278
+ const targets = Array.isArray(item.target)
279
+ ? [...item.target]
280
+ : [item.target];
281
+ if (targets.length === 0 ||
282
+ targets.some((target) => typeof target !== "string"))
283
+ throw new Error("Vercel environment metadata is invalid.");
284
+ if (typeof item.id !== "string" || !item.id) {
285
+ throw new Error("Vercel environment metadata is invalid.");
286
+ }
287
+ if (!targets.includes("production")) {
288
+ throw new Error("Vercel environment metadata target is invalid.");
289
+ }
290
+ targets.sort();
291
+ const normalized = {
292
+ id: item.id,
293
+ key: item.key,
294
+ target: targets,
295
+ type: item.type,
296
+ };
297
+ if (item.createdAt !== undefined) {
298
+ if (typeof item.createdAt !== "number" || !Number.isFinite(item.createdAt)) {
299
+ throw new Error("Vercel environment metadata is invalid.");
300
+ }
301
+ normalized.createdAt = item.createdAt;
302
+ }
303
+ if (item.updatedAt !== undefined) {
304
+ if (typeof item.updatedAt !== "number" || !Number.isFinite(item.updatedAt)) {
305
+ throw new Error("Vercel environment metadata is invalid.");
306
+ }
307
+ normalized.updatedAt = item.updatedAt;
308
+ }
309
+ if (item.gitBranch !== undefined) {
310
+ if (typeof item.gitBranch !== "string" && item.gitBranch !== null) {
311
+ throw new Error("Vercel environment metadata is invalid.");
312
+ }
313
+ normalized.gitBranch = item.gitBranch;
314
+ }
315
+ if (item.customEnvironmentIds !== undefined) {
316
+ if (!Array.isArray(item.customEnvironmentIds) ||
317
+ item.customEnvironmentIds.some((id) => typeof id !== "string")) {
318
+ throw new Error("Vercel environment metadata is invalid.");
319
+ }
320
+ normalized.customEnvironmentIds = [...item.customEnvironmentIds].sort();
321
+ }
322
+ return normalized;
323
+ }).sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right)));
324
+ return { envs };
325
+ }
326
+ function withSensitiveSentinels(records, metadata) {
327
+ const result = Object.assign(Object.create(null), records);
328
+ const sensitiveKeys = new Set(metadata.envs.flatMap((entry) => entry.type === "sensitive" && typeof entry.key === "string"
329
+ ? [entry.key]
330
+ : []));
331
+ for (const key of sensitiveKeys) {
332
+ if (key in result && !result[key])
333
+ result[key] = "[SENSITIVE]";
334
+ }
335
+ return result;
336
+ }
337
+ function assertReplaceable(path) {
338
+ try {
339
+ const stat = (0, node_fs_1.lstatSync)(path);
340
+ if (!stat.isFile() || stat.isSymbolicLink()) {
341
+ throw new Error(`Refusing to replace non-file output: ${path}`);
342
+ }
343
+ }
344
+ catch (error) {
345
+ if (error.code !== "ENOENT")
346
+ throw error;
347
+ }
348
+ }
349
+ function stageFile(path, contents) {
350
+ (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(path), { recursive: true, mode: 0o700 });
351
+ assertReplaceable(path);
352
+ const temporary = `${path}.loom-${(0, node_crypto_1.randomBytes)(12).toString("hex")}.tmp`;
353
+ const fd = (0, node_fs_1.openSync)(temporary, "wx", 0o600);
354
+ try {
355
+ (0, node_fs_1.writeFileSync)(fd, contents, "utf8");
356
+ (0, node_fs_1.fsyncSync)(fd);
357
+ }
358
+ catch (error) {
359
+ (0, node_fs_1.closeSync)(fd);
360
+ (0, node_fs_1.unlinkSync)(temporary);
361
+ throw error;
362
+ }
363
+ (0, node_fs_1.closeSync)(fd);
364
+ return temporary;
365
+ }
366
+ function publishStaged(path, temporary) {
367
+ (0, node_fs_1.renameSync)(temporary, path);
368
+ (0, node_fs_1.chmodSync)(path, 0o600);
369
+ const parent = (0, node_fs_1.openSync)((0, node_path_1.dirname)(path), "r");
370
+ try {
371
+ (0, node_fs_1.fsyncSync)(parent);
372
+ }
373
+ finally {
374
+ (0, node_fs_1.closeSync)(parent);
375
+ }
376
+ }
377
+ /** Materialize private Production release inputs through project-bound APIs. */
378
+ async function prepareVercelProjectRelease(options, io = { out: (line) => console.log(line) }) {
379
+ const identity = requireReleaseIdentity(options.env);
380
+ const fetchImpl = options.fetchImpl ?? fetch;
381
+ const timeoutMs = options.timeoutMs ?? FETCH_TIMEOUT_MS;
382
+ const common = { teamId: identity.orgId };
383
+ const [projectResponse, metadataBeforeResponse] = await Promise.all([
384
+ fetchJson(identity, query(`/v9/projects/${encodeURIComponent(identity.projectId)}`, common), { fetchImpl, maxBytes: MAX_PROJECT_BYTES, timeoutMs }),
385
+ fetchJson(identity, query(`/v10/projects/${encodeURIComponent(identity.projectId)}/env`, {
386
+ target: "production",
387
+ source: "vercel-cli:pull",
388
+ decrypt: "false",
389
+ ...common,
390
+ }), { fetchImpl, maxBytes: MAX_METADATA_BYTES, timeoutMs }),
391
+ ]);
392
+ const pullResponse = await fetchJson(identity, query(`/v3/env/pull/${encodeURIComponent(identity.projectId)}/production`, { source: "vercel-cli:pull", ...common }), { fetchImpl, maxBytes: MAX_ENV_BYTES, timeoutMs });
393
+ const metadataAfterResponse = await fetchJson(identity, query(`/v10/projects/${encodeURIComponent(identity.projectId)}/env`, {
394
+ target: "production",
395
+ source: "vercel-cli:pull",
396
+ decrypt: "false",
397
+ ...common,
398
+ }), { fetchImpl, maxBytes: MAX_METADATA_BYTES, timeoutMs });
399
+ const projectFile = projectFileFromResponse(projectResponse, identity);
400
+ if (!object(pullResponse)) {
401
+ throw new Error("Vercel pulled environment is invalid.");
402
+ }
403
+ const pulledRecords = requireStringMap(pullResponse.env, "Vercel pulled environment");
404
+ if (pullResponse.buildEnv !== undefined) {
405
+ requireStringMap(pullResponse.buildEnv, "Vercel pulled build environment");
406
+ }
407
+ const metadata = normalizeMetadata(metadataBeforeResponse);
408
+ const metadataAfter = normalizeMetadata(metadataAfterResponse);
409
+ if (JSON.stringify(metadata) !== JSON.stringify(metadataAfter)) {
410
+ throw new Error("Vercel environment metadata changed during the pull.");
411
+ }
412
+ const records = withSensitiveSentinels(pulledRecords, metadata);
413
+ const envSource = serializeVercelPulledEnvironment(records);
414
+ const outputs = [
415
+ [(0, node_path_1.resolve)(options.metadataFile), JSON.stringify(metadata, null, 2) + "\n"],
416
+ [(0, node_path_1.resolve)(options.envFile), envSource],
417
+ [(0, node_path_1.resolve)(options.projectFile), JSON.stringify(projectFile, null, 2) + "\n"],
418
+ ];
419
+ if (new Set(outputs.map(([path]) => path)).size !== outputs.length) {
420
+ throw new Error("Vercel release output paths must be distinct.");
421
+ }
422
+ const staged = [];
423
+ try {
424
+ for (const [path, contents] of outputs) {
425
+ staged.push({ path, temporary: stageFile(path, contents) });
426
+ }
427
+ for (const output of staged)
428
+ publishStaged(output.path, output.temporary);
429
+ }
430
+ catch (error) {
431
+ for (const output of staged) {
432
+ try {
433
+ (0, node_fs_1.unlinkSync)(output.temporary);
434
+ }
435
+ catch {
436
+ // Ignore cleanup after a failed or already-published staged file.
437
+ }
438
+ }
439
+ throw error;
440
+ }
441
+ io.out(`Prepared Vercel Production project settings, ${Object.keys(records).length} pulled variables, and ${metadata.envs.length} metadata records.`);
442
+ return {
443
+ metadataCount: metadata.envs.length,
444
+ projectId: identity.projectId,
445
+ pulledCount: Object.keys(records).length,
446
+ };
447
+ }
448
+ function deploymentFromResponse(value, identity, deploymentId) {
449
+ if (!object(value))
450
+ throw new Error("Vercel deployment response is invalid.");
451
+ if (value.id !== deploymentId || value.projectId !== identity.projectId ||
452
+ value.ownerId !== identity.orgId || value.target !== "production" ||
453
+ value.readyState !== "READY") {
454
+ throw new Error("Vercel deployment is not a READY Production deployment for the configured project.");
455
+ }
456
+ return { id: value.id };
457
+ }
458
+ function promotionState(value, deploymentId) {
459
+ if (!object(value))
460
+ throw new Error("Vercel project response is invalid.");
461
+ if (value.rollingRelease) {
462
+ throw new Error("Rolling Release promotion is not supported by this command.");
463
+ }
464
+ const request = value.lastAliasRequest;
465
+ if (!object(request) || request.toDeploymentId !== deploymentId) {
466
+ return { state: "absent" };
467
+ }
468
+ if (request.type !== "promote") {
469
+ return { state: "absent" };
470
+ }
471
+ if (typeof request.requestedAt !== "number" ||
472
+ !Number.isFinite(request.requestedAt))
473
+ return { state: "absent" };
474
+ const jobStatus = request.jobStatus;
475
+ if (jobStatus === "succeeded") {
476
+ return { requestedAt: request.requestedAt, state: "succeeded" };
477
+ }
478
+ if (jobStatus === "failed" || jobStatus === "skipped") {
479
+ return { requestedAt: request.requestedAt, state: "failed" };
480
+ }
481
+ if (jobStatus === "pending" || jobStatus === "in-progress") {
482
+ return { requestedAt: request.requestedAt, state: "pending" };
483
+ }
484
+ return { state: "absent" };
485
+ }
486
+ function currentProductionDeploymentId(value) {
487
+ if (!object(value) || !object(value.targets))
488
+ return null;
489
+ const production = value.targets.production;
490
+ return object(production) && typeof production.id === "string"
491
+ ? production.id
492
+ : null;
493
+ }
494
+ async function requestPromotion(identity, deploymentId, fetchImpl, timeoutMs) {
495
+ const controller = new AbortController();
496
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
497
+ try {
498
+ const response = await fetchImpl(query(`/v10/projects/${encodeURIComponent(identity.projectId)}/promote/${encodeURIComponent(deploymentId)}`, { teamId: identity.orgId }), {
499
+ body: "{}",
500
+ headers: {
501
+ authorization: `Bearer ${identity.token}`,
502
+ "content-type": "application/json",
503
+ },
504
+ method: "POST",
505
+ redirect: "error",
506
+ signal: controller.signal,
507
+ });
508
+ if (response.body)
509
+ void cancelQuietly(response.body.getReader());
510
+ if (response.status >= 400 && response.status < 500) {
511
+ throw new PromotionRejectedError(response.status);
512
+ }
513
+ if (response.status !== 201 && response.status !== 202) {
514
+ throw new Error("Vercel promotion request had an uncertain result.");
515
+ }
516
+ return response.status;
517
+ }
518
+ finally {
519
+ clearTimeout(timer);
520
+ }
521
+ }
522
+ class PromotionRejectedError extends Error {
523
+ constructor(status) {
524
+ super(`Vercel promotion was rejected with HTTP ${status}.`);
525
+ }
526
+ }
527
+ /** Promote one exact deployment and require matching terminal provider state. */
528
+ async function promoteVercelProjectRelease(options, io = { out: (line) => console.log(line) }) {
529
+ const identity = requireReleaseIdentity(options.env);
530
+ if (!/^dpl_[A-Za-z0-9]+$/.test(options.deploymentId)) {
531
+ throw new Error("Deployment ID is invalid.");
532
+ }
533
+ const fetchImpl = options.fetchImpl ?? fetch;
534
+ const timeoutMs = options.timeoutMs ?? 180_000;
535
+ const pollIntervalMs = options.pollIntervalMs ?? 500;
536
+ const now = options.now ?? Date.now;
537
+ const sleep = options.sleep ??
538
+ ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
539
+ const requestTimeoutMs = Math.min(FETCH_TIMEOUT_MS, timeoutMs);
540
+ const teamId = identity.orgId;
541
+ const projectUrl = query(`/v9/projects/${encodeURIComponent(identity.projectId)}`, { teamId });
542
+ const deployment = deploymentFromResponse(await fetchJson(identity, query(`/v13/deployments/${encodeURIComponent(options.deploymentId)}`, {
543
+ teamId,
544
+ }), { fetchImpl, maxBytes: MAX_PROJECT_BYTES, timeoutMs: requestTimeoutMs }), identity, options.deploymentId);
545
+ const initialProject = await fetchJson(identity, projectUrl, {
546
+ fetchImpl,
547
+ maxBytes: MAX_PROJECT_BYTES,
548
+ timeoutMs: requestTimeoutMs,
549
+ });
550
+ projectFileFromResponse(initialProject, identity);
551
+ const initialState = promotionState(initialProject, deployment.id);
552
+ if (initialState.state === "succeeded") {
553
+ if (currentProductionDeploymentId(initialProject) !== deployment.id) {
554
+ throw new Error("The prior promotion succeeded, but Production no longer points to this deployment.");
555
+ }
556
+ io.out("Verified that the Production deployment is already promoted.");
557
+ return { replayed: true, status: "succeeded" };
558
+ }
559
+ if (initialState.state === "failed") {
560
+ throw new Error("A previous promotion of this deployment failed.");
561
+ }
562
+ const resumePending = initialState.state === "pending";
563
+ const providerBaseline = initialState.state === "absent"
564
+ ? undefined
565
+ : initialState.requestedAt;
566
+ let requestUncertain = false;
567
+ if (!resumePending) {
568
+ try {
569
+ await requestPromotion(identity, deployment.id, fetchImpl, requestTimeoutMs);
570
+ }
571
+ catch (error) {
572
+ if (error instanceof PromotionRejectedError)
573
+ throw error;
574
+ requestUncertain = true;
575
+ }
576
+ }
577
+ const deadline = now() + timeoutMs;
578
+ let delay = pollIntervalMs;
579
+ while (now() < deadline) {
580
+ const project = await fetchJson(identity, projectUrl, {
581
+ fetchImpl,
582
+ maxBytes: MAX_PROJECT_BYTES,
583
+ timeoutMs: Math.min(requestTimeoutMs, Math.max(1, deadline - now())),
584
+ });
585
+ projectFileFromResponse(project, identity);
586
+ const state = promotionState(project, deployment.id);
587
+ const isCurrentRequest = state.state !== "absent" &&
588
+ (resumePending
589
+ ? state.requestedAt === providerBaseline
590
+ : providerBaseline === undefined ||
591
+ state.requestedAt > providerBaseline);
592
+ if (isCurrentRequest && state.state === "succeeded" &&
593
+ currentProductionDeploymentId(project) === deployment.id) {
594
+ io.out("Verified terminal success for the Vercel Production promotion.");
595
+ return { replayed: resumePending, status: "succeeded" };
596
+ }
597
+ if (isCurrentRequest && state.state === "failed") {
598
+ throw new Error("Vercel Production promotion failed.");
599
+ }
600
+ await sleep(Math.min(delay, Math.max(1, deadline - now())));
601
+ delay = Math.min(2_000, Math.ceil(delay * 1.5));
602
+ }
603
+ throw new Error(requestUncertain
604
+ ? "Vercel promotion request was uncertain and no terminal result was observed."
605
+ : "Vercel promotion did not reach a terminal result before the timeout.");
606
+ }