@vite-hub/queue 0.0.3 → 0.0.4

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.
@@ -0,0 +1,4414 @@
1
+ import { n as isPlainObject, r as getHostingProvider, t as normalizeQueueOptions } from "./config-CNgAeIND.js";
2
+ import { t as getCloudflareQueueBindingName } from "./cloudflare-GosJefIK.js";
3
+ import { t as getCloudflareQueueName } from "./cloudflare-resource-name-R8zYQiZb.js";
4
+ import { t as getVercelQueueTopicName } from "./vercel-C_4vqxcl.js";
5
+ import { createRequire } from "node:module";
6
+ import { hash, randomUUID } from "node:crypto";
7
+ import { existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, statSync } from "node:fs";
8
+ import { cp, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
9
+ import { tmpdir } from "node:os";
10
+ import { basename, dirname, extname, isAbsolute, relative, resolve, sep } from "node:path";
11
+ import { basename as basename$1, dirname as dirname$1, relative as relative$1, resolve as resolve$1 } from "pathe";
12
+ import { fileURLToPath, pathToFileURL } from "node:url";
13
+ import { build } from "esbuild";
14
+ import { isDeepStrictEqual } from "node:util";
15
+ const VITEHUB_MODES = {
16
+ e2e: "e2e",
17
+ blob: "blob",
18
+ chat: "chat",
19
+ db: "db",
20
+ env: "env",
21
+ kv: "kv",
22
+ queue: "queue",
23
+ schedule: "schedule",
24
+ sandbox: "sandbox",
25
+ workspace: "workspace",
26
+ workflow: "workflow"
27
+ };
28
+ function isViteCli(argv) {
29
+ return argv.some((arg) => /(?:^|[/\\])vite(?:\.[cm]?js)?$/.test(arg) || arg === "vite");
30
+ }
31
+ function getViteCliMode(argv = process.argv) {
32
+ if (!isViteCli(argv)) return;
33
+ const modes = new Set(Object.values(VITEHUB_MODES));
34
+ for (let index = 0; index < argv.length; index += 1) {
35
+ const arg = argv[index];
36
+ const mode = arg === "--mode" || arg === "-m" ? argv[index + 1] : arg.startsWith("--mode=") ? arg.slice(7) : void 0;
37
+ if (mode && modes.has(mode)) return mode;
38
+ }
39
+ }
40
+ function getViteMode(env = process.env) {
41
+ return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
42
+ }
43
+ //#endregion
44
+ //#region ../internal/src/build/client-output.ts
45
+ function hasStaticIndex(clientDir) {
46
+ return existsSync(resolve$1(clientDir, "index.html"));
47
+ }
48
+ async function copyClientOutput(clientDir, targetDir) {
49
+ const resolvedClientDir = resolve$1(clientDir);
50
+ const resolvedTargetDir = resolve$1(targetDir);
51
+ if (resolvedClientDir === resolvedTargetDir) return;
52
+ await rm(resolvedTargetDir, {
53
+ force: true,
54
+ recursive: true
55
+ });
56
+ await mkdir(dirname$1(resolvedTargetDir), { recursive: true });
57
+ const targetRelativePath = relative$1(resolvedClientDir, resolvedTargetDir);
58
+ if (targetRelativePath && !targetRelativePath.startsWith("../")) {
59
+ const [targetRootEntry] = targetRelativePath.split("/", 1);
60
+ await mkdir(resolvedTargetDir, { recursive: true });
61
+ await Promise.all((await readdir(resolvedClientDir)).filter((entry) => entry !== targetRootEntry).map((entry) => cp(resolve$1(resolvedClientDir, entry), resolve$1(resolvedTargetDir, entry), { recursive: true })));
62
+ return;
63
+ }
64
+ await cp(resolvedClientDir, resolvedTargetDir, { recursive: true });
65
+ }
66
+ //#endregion
67
+ //#region ../internal/src/build/provider-output-config.ts
68
+ function isProviderJsonArray(value, ancestors) {
69
+ if (Object.getPrototypeOf(value) !== Array.prototype || ancestors.has(value)) return false;
70
+ if (Reflect.ownKeys(value).length !== value.length + 1) return false;
71
+ ancestors.add(value);
72
+ try {
73
+ for (let index = 0; index < value.length; index++) {
74
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
75
+ if (!descriptor?.enumerable || !("value" in descriptor) || !isProviderJsonValue(descriptor.value, ancestors)) return false;
76
+ }
77
+ return true;
78
+ } finally {
79
+ ancestors.delete(value);
80
+ }
81
+ }
82
+ function isProviderJsonRecordValue(value, ancestors) {
83
+ const prototype = Object.getPrototypeOf(value);
84
+ if (prototype !== Object.prototype && prototype !== null || ancestors.has(value)) return false;
85
+ ancestors.add(value);
86
+ try {
87
+ return Reflect.ownKeys(value).every((key) => {
88
+ if (typeof key !== "string") return false;
89
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
90
+ return descriptor?.enumerable === true && "value" in descriptor && isProviderJsonValue(descriptor.value, ancestors);
91
+ });
92
+ } finally {
93
+ ancestors.delete(value);
94
+ }
95
+ }
96
+ function isProviderJsonValue(value, ancestors) {
97
+ if (value === null || typeof value === "boolean" || typeof value === "string") return true;
98
+ if (typeof value === "number") return Number.isFinite(value);
99
+ if (Array.isArray(value)) return isProviderJsonArray(value, ancestors);
100
+ return typeof value === "object" && isProviderJsonRecordValue(value, ancestors);
101
+ }
102
+ function isProviderJsonRecord(value) {
103
+ try {
104
+ return typeof value === "object" && value !== null && !Array.isArray(value) && isProviderJsonRecordValue(value, /* @__PURE__ */ new Set());
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+ function assertProviderJsonRecord(value) {
110
+ if (!isProviderJsonRecord(value)) throw new TypeError("[vitehub] Provider output config must be a JSON object.");
111
+ }
112
+ function isFileNotFoundError(error) {
113
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
114
+ }
115
+ async function readProviderJsonRecord(file) {
116
+ try {
117
+ const parsed = JSON.parse(await readFile(file, "utf8"));
118
+ assertProviderJsonRecord(parsed);
119
+ return parsed;
120
+ } catch (error) {
121
+ if (isFileNotFoundError(error)) return;
122
+ throw error;
123
+ }
124
+ }
125
+ function deleteOwnedFields(value, ownership, cleanup = false) {
126
+ const next = { ...value };
127
+ for (const key of ownership.keys ?? []) delete next[key];
128
+ for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) if (!cleanup || !arrayOwnership.preserveOnCleanup) delete next[field];
129
+ return next;
130
+ }
131
+ function getKeyedArrayEntryValue(value, key) {
132
+ if (key === void 0) return value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string" ? value : void 0;
133
+ if (!isProviderJsonRecord(value)) return;
134
+ const entryValue = value[key];
135
+ return entryValue === null || typeof entryValue === "boolean" || typeof entryValue === "number" || typeof entryValue === "string" ? entryValue : void 0;
136
+ }
137
+ function preserveUnownedKeyedArrayEntries(value, ownership, replacements = []) {
138
+ const current = Array.isArray(value) ? value : [];
139
+ const replacementKeys = replacements.flatMap((entry) => {
140
+ const key = getKeyedArrayEntryValue(entry, ownership.key);
141
+ return key === void 0 ? [] : [key];
142
+ });
143
+ const ownedKeys = new Set([...ownership.values ?? [], ...replacementKeys]);
144
+ return current.filter((entry) => {
145
+ const key = getKeyedArrayEntryValue(entry, ownership.key);
146
+ return key === void 0 || !ownedKeys.has(key);
147
+ });
148
+ }
149
+ function mergeOwnedArrays(existing, value, arrays) {
150
+ const next = { ...value };
151
+ for (const [field, ownership] of Object.entries(arrays ?? {})) {
152
+ const incoming = Array.isArray(value[field]) ? value[field] : [];
153
+ const merged = [...preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming), ...incoming];
154
+ if (merged.length) next[field] = merged;
155
+ else delete next[field];
156
+ }
157
+ return next;
158
+ }
159
+ async function persistProviderJsonRecord(file, value, removeIfEmpty) {
160
+ if (removeIfEmpty && !Object.keys(value).length) {
161
+ await rm(file, { force: true });
162
+ return;
163
+ }
164
+ await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
165
+ }
166
+ async function writeProviderOutputConfig(file, value, ownership = {}, options = {}) {
167
+ const existing = await readProviderJsonRecord(file) ?? {};
168
+ const defaults = options.defaults ?? {};
169
+ assertProviderJsonRecord(defaults);
170
+ await persistProviderJsonRecord(file, mergeProviderOutputConfig({
171
+ ...defaults,
172
+ ...existing
173
+ }, value, ownership), options.removeIfEmpty === true);
174
+ }
175
+ function mergeProviderOutputConfig(existing, value, ownership = {}) {
176
+ assertProviderJsonRecord(existing);
177
+ assertProviderJsonRecord(value);
178
+ return {
179
+ ...deleteOwnedFields(existing, ownership),
180
+ ...mergeOwnedArrays(existing, value, ownership.arrays)
181
+ };
182
+ }
183
+ function stringifyProviderOutputConfig(value) {
184
+ assertProviderJsonRecord(value);
185
+ return JSON.stringify(value, null, 2);
186
+ }
187
+ async function cleanProviderOutputConfig(file, ownership) {
188
+ if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
189
+ const existing = await readProviderJsonRecord(file);
190
+ if (!existing) return;
191
+ const next = deleteOwnedFields(existing, ownership, true);
192
+ let changed = (ownership.keys ?? []).some((key) => key in existing);
193
+ for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
194
+ if (arrayOwnership.preserveOnCleanup) continue;
195
+ if (!(field in existing)) continue;
196
+ const current = existing[field];
197
+ const retained = arrayOwnership.retainOnCleanup ?? [];
198
+ const preserved = [...preserveUnownedKeyedArrayEntries(current, arrayOwnership, retained), ...retained];
199
+ changed ||= retained.length > 0 || !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
200
+ if (preserved.length) next[field] = preserved;
201
+ }
202
+ if (!changed) return;
203
+ await persistProviderJsonRecord(file, next, true);
204
+ }
205
+ //#endregion
206
+ //#region ../internal/src/build/user-entry.ts
207
+ function toSafeAppName(rootDir) {
208
+ return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
209
+ }
210
+ const DEFAULT_ENTRY_NAMES = [
211
+ "server.ts",
212
+ "server.mts",
213
+ "server.js",
214
+ "server.mjs",
215
+ "worker.ts",
216
+ "worker.mts",
217
+ "worker.js",
218
+ "worker.mjs"
219
+ ];
220
+ function resolveUserAppEntry(rootDir, options = {}) {
221
+ const names = options.names ?? DEFAULT_ENTRY_NAMES;
222
+ const srcSubdir = options.srcSubdir ?? "src";
223
+ return names.map((name) => resolve(rootDir, srcSubdir, name)).find(existsSync);
224
+ }
225
+ //#endregion
226
+ //#region ../internal/src/build/cloudflare.ts
227
+ const defaultCloudflareCompatibilityDate = "2026-04-20";
228
+ function createDefaultCloudflareOutputRoot(rootDir) {
229
+ return resolve(rootDir, "dist", toSafeAppName(rootDir));
230
+ }
231
+ async function writeCloudflareWranglerConfig(options) {
232
+ const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
233
+ const configFile = resolve(outputRoot, "wrangler.json");
234
+ if (!options.wranglerConfig) {
235
+ await cleanProviderOutputConfig(configFile, options.wranglerConfigOwnership ?? {});
236
+ return;
237
+ }
238
+ await mkdir(outputRoot, { recursive: true });
239
+ await writeProviderOutputConfig(configFile, options.wranglerConfig, options.wranglerConfigOwnership, {
240
+ defaults: options.wranglerConfigDefaults,
241
+ removeIfEmpty: true
242
+ });
243
+ }
244
+ //#endregion
245
+ //#region ../internal/src/build/esbuild.ts
246
+ const viteRawNamespace = "vitehub-vite-raw";
247
+ const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
248
+ const markdownTemplateFileSuffix = ".template.md";
249
+ const markdownTemplateModuleQuery = "markdown-template";
250
+ const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
251
+ const skipResolvedAlias = "vitehubSkipResolvedAlias";
252
+ const encodedAliasPrefixMarker = "\0vitehub-prefix:";
253
+ const encodedAliasExactMarker = "\0vitehub-exact:";
254
+ const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
255
+ function normalizePathSeparators(path) {
256
+ return path.replaceAll("\\", "/");
257
+ }
258
+ function escapeRegExp(value) {
259
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
260
+ }
261
+ function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
262
+ if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
263
+ if (!Array.isArray(exportsValue) && !isPlainObject(exportsValue)) return [];
264
+ const candidates = [];
265
+ const exportEntries = isPlainObject(exportsValue) && Object.keys(exportsValue).some((exportKey) => exportKey.startsWith(".")) ? Object.entries(exportsValue) : [[".", exportsValue]];
266
+ for (const [exportKey, target] of exportEntries) {
267
+ const targets = [target];
268
+ while (targets.length) {
269
+ const value = targets.shift();
270
+ if (typeof value === "string") {
271
+ const normalizedTarget = normalizePathSeparators(value).replace(/^\.\//, "");
272
+ const targetParts = normalizedTarget.split("*");
273
+ if (targetParts.length === 1) {
274
+ if (normalizedTarget === packageRelativePath) candidates.push(`${packageName}${exportKey.slice(1)}`);
275
+ continue;
276
+ }
277
+ const targetPattern = `${escapeRegExp(targetParts[0])}(.*?)${targetParts.slice(1).map((part, index) => `${index ? "\\1" : ""}${escapeRegExp(part)}`).join("")}`;
278
+ const wildcard = new RegExp(`^${targetPattern}$`).exec(packageRelativePath)?.[1];
279
+ if (wildcard === void 0) continue;
280
+ candidates.push(`${packageName}${exportKey.slice(1).replace("*", wildcard)}`);
281
+ } else if (Array.isArray(value)) targets.push(...value);
282
+ else if (isPlainObject(value)) targets.push(...Object.values(value));
283
+ }
284
+ }
285
+ return candidates;
286
+ }
287
+ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
288
+ const entries = Object.entries(aliases || {});
289
+ if (!entries.length) return;
290
+ const resolvedEntries = Promise.all(entries.map(async ([encodedSpecifier, replacement]) => {
291
+ const prefixMarkerIndex = encodedSpecifier.lastIndexOf(encodedAliasPrefixMarker);
292
+ const exactMarkerIndex = encodedSpecifier.lastIndexOf(encodedAliasExactMarker);
293
+ const explicitlyEncodedPrefix = prefixMarkerIndex !== -1;
294
+ const markerIndex = Math.max(prefixMarkerIndex, exactMarkerIndex);
295
+ const specifier = markerIndex === -1 ? encodedSpecifier : encodedSpecifier.slice(0, markerIndex);
296
+ const prefix = explicitlyEncodedPrefix || specifier.endsWith("/") && !Object.hasOwn(aliases, `${specifier}/`);
297
+ const resolvedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
298
+ const canonicalSpecifier = isAbsolute(resolvedSpecifier) ? normalizePathSeparators(await realpath(resolvedSpecifier).catch(() => resolvedSpecifier)) : resolvedSpecifier;
299
+ const resolvedReplacement = isAbsolute(replacement) ? normalizePathSeparators(resolve(replacement)) : replacement;
300
+ return {
301
+ canonicalSpecifier: `${canonicalSpecifier}${prefix && !canonicalSpecifier.endsWith("/") ? "/" : ""}`,
302
+ prefix,
303
+ replacement: `${resolvedReplacement}${prefix && !/[\\/]$/.test(resolvedReplacement) ? "/" : ""}`,
304
+ specifier: `${resolvedSpecifier}${prefix && !resolvedSpecifier.endsWith("/") ? "/" : ""}`
305
+ };
306
+ }));
307
+ return {
308
+ name: "vitehub-resolved-alias",
309
+ setup(build) {
310
+ const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
311
+ build.onResolve({ filter: /.*/ }, async (args) => {
312
+ if (args.pluginData?.[skipResolvedAlias]) return;
313
+ const aliases = await resolvedEntries;
314
+ let match = aliases.find(({ prefix, specifier }) => /^\.\.?[\\/]/.test(specifier) && (prefix ? args.path.startsWith(specifier) : args.path === specifier));
315
+ let matchedAlias = match?.specifier;
316
+ let matchedSpecifier = match ? args.path : void 0;
317
+ let specifier = args.resolveDir && /^\.\.?[\\/]/.test(args.path) ? resolve(args.resolveDir, args.path) : args.path;
318
+ let normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
319
+ let canonicalSpecifier = normalizedSpecifier;
320
+ const canonicalizeSpecifier = async () => {
321
+ canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
322
+ return canonicalSpecifier;
323
+ };
324
+ match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
325
+ if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
326
+ await canonicalizeSpecifier();
327
+ match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
328
+ }
329
+ if (!match && isAbsolute(args.path)) for (const alias of aliases) {
330
+ if (isAbsolute(alias.specifier)) continue;
331
+ const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
332
+ const aliasSegments = packageAlias.split("/");
333
+ if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
334
+ let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
335
+ if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
336
+ const scopeMarker = `/node_modules/${packageAlias}/`;
337
+ const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
338
+ const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
339
+ if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
340
+ }
341
+ const packageMarker = `/node_modules/${packageName}/`;
342
+ const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
343
+ const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
344
+ const cacheKey = [
345
+ alias.specifier,
346
+ alias.prefix,
347
+ resolutionScope,
348
+ args.importer,
349
+ args.resolveDir,
350
+ args.kind,
351
+ args.namespace,
352
+ JSON.stringify(args.with)
353
+ ].join("\0");
354
+ let resolution = args.pluginData ? void 0 : resolvedBareAliasPaths.get(cacheKey);
355
+ if (!resolution) {
356
+ resolution = (async () => {
357
+ let resolvedAliasPath;
358
+ if (alias.prefix && /^\.\.?[\\/]/.test(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
359
+ else if (resolutionScope) {
360
+ const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
361
+ const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
362
+ if (!isPlainObject(parsedPackageJson)) return;
363
+ const packageJson = parsedPackageJson;
364
+ if (packageJson.exports === void 0 && !alias.prefix) {
365
+ const resolvedCandidate = await build.resolve(alias.specifier, {
366
+ importer: args.importer,
367
+ kind: args.kind,
368
+ namespace: args.namespace,
369
+ pluginData: {
370
+ ...args.pluginData,
371
+ [skipResolvedAlias]: true
372
+ },
373
+ resolveDir: args.resolveDir,
374
+ with: args.with
375
+ });
376
+ if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve(resolvedCandidate.path)) === normalizedSpecifier) return {
377
+ canonical: alias.specifier,
378
+ normalized: alias.specifier,
379
+ publicSpecifier: alias.specifier
380
+ };
381
+ return;
382
+ }
383
+ const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
384
+ for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
385
+ const resolvedCandidate = await build.resolve(publicSpecifier, {
386
+ importer: args.importer,
387
+ kind: args.kind,
388
+ namespace: args.namespace,
389
+ pluginData: {
390
+ ...args.pluginData,
391
+ [skipResolvedAlias]: true
392
+ },
393
+ resolveDir: args.resolveDir,
394
+ with: args.with
395
+ });
396
+ if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
397
+ if (normalizePathSeparators(resolve(resolvedCandidate.path)) !== normalizedSpecifier) continue;
398
+ matchingPublicSpecifiers.add(publicSpecifier);
399
+ }
400
+ if (matchingPublicSpecifiers.size === 1) {
401
+ const publicSpecifier = [...matchingPublicSpecifiers][0];
402
+ if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
403
+ canonical: publicSpecifier,
404
+ normalized: publicSpecifier,
405
+ publicSpecifier
406
+ };
407
+ }
408
+ return;
409
+ } else {
410
+ const resolvedAlias = await build.resolve(alias.specifier, {
411
+ importer: args.importer,
412
+ kind: args.kind,
413
+ namespace: args.namespace,
414
+ pluginData: {
415
+ ...args.pluginData,
416
+ [skipResolvedAlias]: true
417
+ },
418
+ resolveDir: args.resolveDir,
419
+ with: args.with
420
+ });
421
+ if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
422
+ resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.path));
423
+ }
424
+ const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
425
+ return {
426
+ canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
427
+ normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
428
+ };
429
+ })();
430
+ if (!args.pluginData) resolvedBareAliasPaths.set(cacheKey, resolution);
431
+ }
432
+ const paths = await resolution;
433
+ if (!paths) continue;
434
+ if (paths.publicSpecifier) {
435
+ match = alias;
436
+ matchedAlias = alias.specifier;
437
+ matchedSpecifier = paths.publicSpecifier;
438
+ break;
439
+ }
440
+ const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
441
+ let canonicalMatch = false;
442
+ if (!normalizedMatch && paths.canonical !== paths.normalized) {
443
+ await canonicalizeSpecifier();
444
+ canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
445
+ }
446
+ if (normalizedMatch || canonicalMatch) {
447
+ match = alias;
448
+ matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
449
+ matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
450
+ break;
451
+ }
452
+ }
453
+ matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
454
+ matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
455
+ if (!match) return;
456
+ const target = match?.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match?.replacement ?? "");
457
+ if (!target) return;
458
+ const resolvedTarget = /^\.\.?[\\/]/.test(target) ? resolve(aliasResolveDir, target) : target;
459
+ return build.resolve(resolvedTarget, {
460
+ importer: args.importer,
461
+ kind: args.kind,
462
+ namespace: args.namespace,
463
+ pluginData: {
464
+ ...args.pluginData,
465
+ [skipResolvedAlias]: true
466
+ },
467
+ resolveDir: args.resolveDir,
468
+ with: args.with
469
+ });
470
+ });
471
+ }
472
+ };
473
+ }
474
+ function createViteAliasPlugin(aliases) {
475
+ if (!Array.isArray(aliases)) return;
476
+ const resolvingAlias = "vitehubResolvingAlias";
477
+ return {
478
+ name: "vitehub-vite-alias",
479
+ setup(build) {
480
+ build.onResolve({ filter: /.*/ }, async (args) => {
481
+ if (args.pluginData?.[resolvingAlias]) return;
482
+ const alias = aliases.find(({ find }) => {
483
+ if (typeof find === "string") return args.path === find || args.path.startsWith(`${find}/`);
484
+ find.lastIndex = 0;
485
+ return find.test(args.path);
486
+ });
487
+ if (!alias) return;
488
+ if (alias.customResolver) return { errors: [{ text: `[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(args.path)} because it uses customResolver.` }] };
489
+ if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
490
+ const replacement = typeof alias.find === "string" ? `${alias.replacement}${args.path.slice(alias.find.length)}` : args.path.replace(alias.find, alias.replacement);
491
+ const result = await build.resolve(replacement, {
492
+ importer: args.importer,
493
+ kind: args.kind,
494
+ namespace: args.namespace,
495
+ pluginData: Object.assign({}, args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {}, { [resolvingAlias]: true }),
496
+ resolveDir: args.resolveDir,
497
+ with: args.with
498
+ });
499
+ const pluginData = Object.assign({}, result.pluginData);
500
+ Reflect.deleteProperty(pluginData, resolvingAlias);
501
+ return {
502
+ ...result,
503
+ pluginData
504
+ };
505
+ });
506
+ }
507
+ };
508
+ }
509
+ function stripMarkdownCode(template) {
510
+ let fence;
511
+ let inList = false;
512
+ let previousLineBlank = true;
513
+ return template.split("\n").map((line) => {
514
+ const content = line.replace(/^(?: {0,3}> ?)+/, "");
515
+ if (!fence) {
516
+ const listIndented = inList && /^ {4}(?:`{3,}|~{3,})/.test(content);
517
+ const opening = (listIndented ? content.slice(4) : content).match(/^ {0,3}(`{3,}|~{3,})/);
518
+ if (!opening) {
519
+ if (/^ {0,3}(?:[-+*]|\d+[.)])\s+/.test(content)) inList = true;
520
+ else if (content.trim() && !/^ {2,}/.test(content)) inList = false;
521
+ const indentedCode = !inList && previousLineBlank && /^(?: {4}|\t)/.test(content) || inList && previousLineBlank && /^(?: {8}| {4}\t|\t{2})/.test(content);
522
+ previousLineBlank = content.trim() === "";
523
+ return indentedCode ? "" : line;
524
+ }
525
+ fence = {
526
+ marker: opening[1][0],
527
+ length: opening[1].length,
528
+ listIndented
529
+ };
530
+ previousLineBlank = false;
531
+ return "";
532
+ }
533
+ const closing = (fence.listIndented ? content.replace(/^ {4}/, "") : content).match(/^ {0,3}(`+|~+)\s*$/)?.[1];
534
+ if (closing?.[0] === fence.marker && closing.length >= fence.length) fence = void 0;
535
+ previousLineBlank = false;
536
+ return "";
537
+ }).join("\n");
538
+ }
539
+ function extractMarkdownTemplateImportSpecifiers(template) {
540
+ const visible = stripMarkdownCode(template).replace(/(`+)[\s\S]*?\1/g, "").replace(/(!?\[[^\]]*\])\([^)]*\)/g, "$1").replace(/^ {0,3}\[[^\]]+\]:\s*\S+/gm, "").replace(/<[^>]*>/g, "");
541
+ const specifiers = /* @__PURE__ */ new Set();
542
+ for (const match of visible.matchAll(/@(\.\.?\/[^\s<>{}[\]]+)/g)) {
543
+ const token = match[1];
544
+ const trailing = token.match(/[.,;:!?)]*$/)?.[0] || "";
545
+ specifiers.add(token.slice(0, token.length - trailing.length));
546
+ }
547
+ return [...specifiers];
548
+ }
549
+ function parseMarkdownTemplateRequest(id) {
550
+ const queryIndex = id.indexOf("?");
551
+ const path = id.split(/[?#]/, 1)[0];
552
+ if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
553
+ const query = id.slice(queryIndex + 1).split("#", 1)[0];
554
+ if (!new URLSearchParams(query).has(markdownTemplateModuleQuery)) return;
555
+ return { path };
556
+ }
557
+ function renderMarkdownTemplateModule(template, sourceId, imports = {}) {
558
+ return [
559
+ `import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
560
+ `const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
561
+ `const vitehubMarkdownTemplateSourceId = ${JSON.stringify(sourceId)}`,
562
+ `const vitehubMarkdownTemplateImports = ${JSON.stringify(imports)}`,
563
+ "export default function render(data = {}) {",
564
+ " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data, sourceId: vitehubMarkdownTemplateSourceId, resolveImport: (specifier, importer) => vitehubMarkdownTemplateImports[`${importer}\\0${specifier}`] })",
565
+ "}",
566
+ ""
567
+ ].join("\n");
568
+ }
569
+ function hasViteRawQuery(path) {
570
+ const queryIndex = path.indexOf("?");
571
+ return queryIndex !== -1 && /(?:^|&)raw(?:&|$)/.test(path.slice(queryIndex + 1));
572
+ }
573
+ async function resolveViteRawSpecifier(path, rootDir) {
574
+ if (path.startsWith("/@fs/")) return path.slice(5);
575
+ if (!rootDir || !path.startsWith("/")) return path;
576
+ const rootRelativePath = path.slice(1);
577
+ const publicPath = resolve(rootDir, "public", rootRelativePath);
578
+ try {
579
+ await stat(publicPath);
580
+ return publicPath;
581
+ } catch (error) {
582
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
583
+ return resolve(rootDir, rootRelativePath);
584
+ }
585
+ }
586
+ function createViteRawPlugin(rootDir, frameworkRuntime) {
587
+ return {
588
+ name: "vitehub-vite-raw",
589
+ setup(build) {
590
+ build.onResolve({
591
+ filter: /^@vite-hub\/markdown-template$/,
592
+ namespace: viteMarkdownTemplateNamespace
593
+ }, async (args) => {
594
+ if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
595
+ return build.resolve("vite-hub/_internal/markdown-template", {
596
+ importer: args.importer,
597
+ kind: args.kind,
598
+ resolveDir: args.resolveDir
599
+ });
600
+ });
601
+ build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
602
+ if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
603
+ const markdownTemplate = parseMarkdownTemplateRequest(args.path);
604
+ const raw = hasViteRawQuery(args.path);
605
+ if (!markdownTemplate && !raw) return;
606
+ const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
607
+ let pluginData = args.pluginData;
608
+ if (markdownTemplate) pluginData = {
609
+ ...args.pluginData,
610
+ [skipMarkdownTemplateResolve]: true
611
+ };
612
+ const resolved = await build.resolve(specifier, {
613
+ importer: args.importer,
614
+ kind: args.kind,
615
+ namespace: args.namespace,
616
+ pluginData,
617
+ resolveDir: args.resolveDir,
618
+ with: args.with
619
+ });
620
+ if (resolved.errors.length) return {
621
+ errors: resolved.errors,
622
+ warnings: resolved.warnings
623
+ };
624
+ if (resolved.external) return {
625
+ external: true,
626
+ namespace: resolved.namespace,
627
+ path: resolved.path,
628
+ pluginData: resolved.pluginData,
629
+ sideEffects: resolved.sideEffects,
630
+ suffix: resolved.suffix,
631
+ warnings: resolved.warnings
632
+ };
633
+ if (resolved.namespace !== "file") return {
634
+ errors: [{ text: markdownTemplate ? `[vitehub] Markdown template fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this template import in a caller plugin.` : `[vitehub] Vite raw fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this raw import in a caller plugin.` }],
635
+ warnings: resolved.warnings
636
+ };
637
+ return {
638
+ namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
639
+ path: resolved.path,
640
+ pluginData: resolved.pluginData,
641
+ sideEffects: resolved.sideEffects,
642
+ suffix: resolved.suffix,
643
+ warnings: resolved.warnings
644
+ };
645
+ });
646
+ build.onLoad({
647
+ filter: /.*/,
648
+ namespace: viteRawNamespace
649
+ }, async (args) => ({
650
+ contents: await readFile(args.path),
651
+ loader: "text"
652
+ }));
653
+ build.onLoad({
654
+ filter: /.*/,
655
+ namespace: viteMarkdownTemplateNamespace
656
+ }, async (args) => ({
657
+ contents: await (async () => {
658
+ const template = await readFile(args.path, "utf8");
659
+ const imports = {};
660
+ const visited = new Set([args.path]);
661
+ const visit = async (source, importer) => {
662
+ for (const specifier of extractMarkdownTemplateImportSpecifiers(source)) {
663
+ const key = `${importer}\0${specifier}`;
664
+ if (imports[key]) continue;
665
+ const resolved = await build.resolve(specifier, {
666
+ importer,
667
+ kind: "import-statement",
668
+ pluginData: {
669
+ ...args.pluginData,
670
+ [skipMarkdownTemplateResolve]: true
671
+ },
672
+ resolveDir: dirname(importer)
673
+ });
674
+ if (resolved.errors.length) return Promise.reject(new Error(resolved.errors.map((error) => error.text).join("\n")));
675
+ if (resolved.external || resolved.namespace !== "file") throw new Error(`[vitehub] Could not resolve Markdown template import ${JSON.stringify(specifier)} from ${JSON.stringify(importer)} to a file.`);
676
+ const imported = {
677
+ id: resolved.path,
678
+ template: await readFile(resolved.path, "utf8")
679
+ };
680
+ imports[key] = imported;
681
+ if (!visited.has(imported.id)) {
682
+ visited.add(imported.id);
683
+ await visit(imported.template, imported.id);
684
+ }
685
+ }
686
+ };
687
+ await visit(template, args.path);
688
+ return renderMarkdownTemplateModule(template, args.path, imports);
689
+ })(),
690
+ loader: "js",
691
+ resolveDir: dirname(args.path)
692
+ }));
693
+ }
694
+ };
695
+ }
696
+ function createFileUrlPlugin() {
697
+ return {
698
+ name: "vitehub-file-url",
699
+ setup(build) {
700
+ build.onResolve({ filter: /^file:/ }, (args) => ({ path: fileURLToPath(args.path) }));
701
+ }
702
+ };
703
+ }
704
+ async function bundleEsmEntry(entryFile, outfile, options = {}) {
705
+ options.signal?.throwIfAborted();
706
+ const format = options.format || "esm";
707
+ const platform = options.platform || "neutral";
708
+ const viteAliasPlugin = createViteAliasPlugin(options.alias);
709
+ const frameworkRuntime = (Array.isArray(options.alias) ? options.alias.flatMap((alias) => typeof alias.find === "string" ? [alias.find] : []) : Object.keys(options.alias || {})).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
710
+ const plugins = [];
711
+ const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd());
712
+ if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
713
+ plugins.push(...options.plugins ?? [], createFileUrlPlugin());
714
+ if (viteAliasPlugin) plugins.push(viteAliasPlugin);
715
+ plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime));
716
+ const result = await build({
717
+ absWorkingDir: options.workingDir,
718
+ banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
719
+ "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
720
+ " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
721
+ " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
722
+ " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
723
+ "}"
724
+ ] : []].filter(Boolean).join("\n") } : void 0,
725
+ bundle: true,
726
+ conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
727
+ entryPoints: [entryFile],
728
+ external: options.external,
729
+ format,
730
+ logLevel: "silent",
731
+ mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
732
+ resolveExtensions: options.extensions,
733
+ minifyIdentifiers: options.minifyIdentifiers,
734
+ minifyWhitespace: options.minifyWhitespace,
735
+ outfile,
736
+ packages: options.packages,
737
+ platform,
738
+ preserveSymlinks: options.preserveSymlinks,
739
+ plugins,
740
+ sourcemap: false,
741
+ target: "es2022",
742
+ write: options.signal ? false : true
743
+ });
744
+ options.signal?.throwIfAborted();
745
+ if (options.signal) {
746
+ await Promise.all((result.outputFiles ?? []).map(async (output) => {
747
+ await mkdir(dirname(output.path), { recursive: true });
748
+ options.signal.throwIfAborted();
749
+ await writeFile(output.path, output.contents, { signal: options.signal });
750
+ }));
751
+ options.signal.throwIfAborted();
752
+ }
753
+ }
754
+ //#endregion
755
+ //#region ../internal/src/build/paths.ts
756
+ function generatedDirSegments(productName) {
757
+ return [".vitehub", productName];
758
+ }
759
+ function ensureGeneratedDir(rootDir, productName) {
760
+ return resolve$1(rootDir, ...generatedDirSegments(productName));
761
+ }
762
+ function toGeneratedPath(rootDir, productName, filename) {
763
+ return relative$1(rootDir, resolve$1(rootDir, ...generatedDirSegments(productName), filename));
764
+ }
765
+ function computePackageDir(importMetaUrl) {
766
+ const currentFileDir = dirname$1(fileURLToPath(importMetaUrl));
767
+ return resolve$1(currentFileDir, basename$1(currentFileDir) === "internal" ? "../.." : "..");
768
+ }
769
+ function resolveRuntimeModule$1(packageDir, modulePath) {
770
+ const distFile = resolve$1(packageDir, "dist", `${modulePath}.js`);
771
+ return existsSync(distFile) ? distFile : resolve$1(packageDir, "src", `${modulePath}.ts`);
772
+ }
773
+ function createImportPath(fromFile, targetFile) {
774
+ const importPath = relative$1(realpathIfExists(dirname$1(fromFile)), realpathIfExists(targetFile));
775
+ return importPath.startsWith(".") ? importPath : `./${importPath}`;
776
+ }
777
+ function realpathIfExists(path) {
778
+ try {
779
+ return realpathSync.native(path);
780
+ } catch {
781
+ return resolve$1(path);
782
+ }
783
+ }
784
+ //#endregion
785
+ //#region ../internal/src/source-scanner.ts
786
+ function isQuote(char) {
787
+ return char === "\"" || char === "'" || char === "`";
788
+ }
789
+ function skipQuoted(source, index, controlFlowRegexes = /* @__PURE__ */ new Map()) {
790
+ const quote = source[index];
791
+ if (quote === "`") return skipTemplateLiteral(source, index, controlFlowRegexes);
792
+ index += 1;
793
+ while (index < source.length) {
794
+ if (source[index] === "\\") {
795
+ index += 2;
796
+ continue;
797
+ }
798
+ if (source[index] === quote) return index + 1;
799
+ index += 1;
800
+ }
801
+ return index;
802
+ }
803
+ function skipTemplateLiteral(source, index, controlFlowRegexes) {
804
+ index += 1;
805
+ let expressionDepth = 0;
806
+ let previousSignificant = "";
807
+ while (index < source.length) {
808
+ const char = source[index];
809
+ const next = source[index + 1];
810
+ if (char === "\\") {
811
+ index += 2;
812
+ continue;
813
+ }
814
+ if (expressionDepth === 0) {
815
+ if (char === "`") return index + 1;
816
+ if (char === "$" && next === "{") {
817
+ expressionDepth = 1;
818
+ previousSignificant = "{";
819
+ index += 2;
820
+ continue;
821
+ }
822
+ index += 1;
823
+ continue;
824
+ }
825
+ if (char === "\"" || char === "'") {
826
+ index = skipQuoted(source, index, controlFlowRegexes);
827
+ previousSignificant = "literal";
828
+ continue;
829
+ }
830
+ if (char === "`") {
831
+ index = skipTemplateLiteral(source, index, controlFlowRegexes);
832
+ previousSignificant = "literal";
833
+ continue;
834
+ }
835
+ if (char === "/" && next === "/") {
836
+ index = skipLineComment(source, index);
837
+ continue;
838
+ }
839
+ if (char === "/" && next === "*") {
840
+ index = skipBlockComment(source, index);
841
+ continue;
842
+ }
843
+ if (char === "/" && (isRegexLiteralStart(previousSignificant) || isControlFlowRegexStart(source, index, controlFlowRegexes))) {
844
+ index = skipRegexLiteral(source, index);
845
+ previousSignificant = "/";
846
+ continue;
847
+ }
848
+ if (char === "{") expressionDepth += 1;
849
+ if (char === "}") expressionDepth -= 1;
850
+ previousSignificant = trackSignificant(previousSignificant, char);
851
+ index += 1;
852
+ }
853
+ return index;
854
+ }
855
+ function skipLineComment(source, index) {
856
+ const end = source.indexOf("\n", index + 2);
857
+ return end === -1 ? source.length : end + 1;
858
+ }
859
+ function skipBlockComment(source, index) {
860
+ const end = source.indexOf("*/", index + 2);
861
+ return end === -1 ? source.length : end + 2;
862
+ }
863
+ function isRegexLiteralStart(previousSignificant) {
864
+ const token = previousSignificant.trimEnd();
865
+ if (/^\.[\w$]+$/.test(token)) return false;
866
+ return !token || /[({[=,:!&|?;>+\-*%^~]/.test(token) || /\b(?:await|case|delete|do|else|in|instanceof|return|throw|typeof|void|yield)$/.test(token);
867
+ }
868
+ function findLineCommentStart(source, start, end, controlFlowRegexes) {
869
+ for (let index = start; index <= end;) {
870
+ const char = source[index];
871
+ const next = source[index + 1];
872
+ if (isQuote(char)) {
873
+ index = skipQuoted(source, index, controlFlowRegexes);
874
+ continue;
875
+ }
876
+ if (char === "/" && next === "*") {
877
+ index = skipBlockComment(source, index);
878
+ continue;
879
+ }
880
+ if (char === "/" && next === "/") return index;
881
+ index += 1;
882
+ }
883
+ return -1;
884
+ }
885
+ function previousCodeIndex(source, index, controlFlowRegexes) {
886
+ let current = index;
887
+ while (current >= 0) {
888
+ while (/\s/.test(source[current] ?? "")) current--;
889
+ if (source[current] === "/" && source[current - 1] === "*") {
890
+ const start = source.lastIndexOf("/*", current - 2);
891
+ if (start === -1) return current;
892
+ current = start - 1;
893
+ continue;
894
+ }
895
+ const lineStart = source.lastIndexOf("\n", current) + 1;
896
+ const lineComment = findLineCommentStart(source, lineStart, current, controlFlowRegexes);
897
+ if (lineComment !== -1 && lineComment <= current) {
898
+ current = lineStart - 1;
899
+ continue;
900
+ }
901
+ return current;
902
+ }
903
+ return current;
904
+ }
905
+ function isControlFlowRegexStart(source, index, controlFlowRegexes = /* @__PURE__ */ new Map()) {
906
+ const cached = controlFlowRegexes.get(index);
907
+ if (cached !== void 0) return cached;
908
+ if (controlFlowRegexes.has(index)) return true;
909
+ controlFlowRegexes.set(index, void 0);
910
+ try {
911
+ const closeParen = previousCodeIndex(source, index - 1, controlFlowRegexes);
912
+ if (source[closeParen] !== ")") {
913
+ controlFlowRegexes.set(index, false);
914
+ return false;
915
+ }
916
+ for (let current = closeParen; current >= 0; current--) {
917
+ if (source[current] !== "(") continue;
918
+ if (findMatching(source, current, "(", ")", controlFlowRegexes) !== closeParen) continue;
919
+ const head = source.slice(0, current).replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, " ");
920
+ const result = /(?:^|[^\w$])(?:catch|for|if|while|with)\s*$/.test(head);
921
+ controlFlowRegexes.set(index, result);
922
+ return result;
923
+ }
924
+ controlFlowRegexes.set(index, false);
925
+ return false;
926
+ } catch (error) {
927
+ controlFlowRegexes.delete(index);
928
+ throw error;
929
+ }
930
+ }
931
+ function skipRegexLiteral(source, index) {
932
+ index += 1;
933
+ while (index < source.length) {
934
+ const char = source[index];
935
+ if (char === "\\") {
936
+ index += 2;
937
+ continue;
938
+ }
939
+ if (char === "[") {
940
+ index += 1;
941
+ while (index < source.length) {
942
+ if (source[index] === "\\") {
943
+ index += 2;
944
+ continue;
945
+ }
946
+ if (source[index] === "]") break;
947
+ index += 1;
948
+ }
949
+ }
950
+ if (char === "/") {
951
+ index += 1;
952
+ while (/[a-z]/i.test(source[index] ?? "")) index += 1;
953
+ return index;
954
+ }
955
+ index += 1;
956
+ }
957
+ return index;
958
+ }
959
+ function trackSignificant(previousSignificant, char) {
960
+ if (/[a-z$]/i.test(char ?? "")) return /[\w$]$/.test(previousSignificant) || previousSignificant === "." ? previousSignificant + char : char ?? "";
961
+ if (/\s/.test(char ?? "")) return /[\w$]$/.test(previousSignificant) ? `${previousSignificant} ` : previousSignificant;
962
+ if (!/\s/.test(char ?? "")) return char ?? "";
963
+ return previousSignificant;
964
+ }
965
+ function nextNonWhitespace(source, index) {
966
+ return source[skipWhitespaceAndComments(source, index)];
967
+ }
968
+ function skipWhitespaceAndComments(source, index) {
969
+ while (index < source.length) {
970
+ if (/\s/.test(source[index] ?? "")) {
971
+ index += 1;
972
+ continue;
973
+ }
974
+ if (source[index] === "/" && source[index + 1] === "/") {
975
+ index = skipLineComment(source, index);
976
+ continue;
977
+ }
978
+ if (source[index] === "/" && source[index + 1] === "*") {
979
+ index = skipBlockComment(source, index);
980
+ continue;
981
+ }
982
+ return index;
983
+ }
984
+ return index;
985
+ }
986
+ function maskSourceLiterals(source) {
987
+ const output = source.split("");
988
+ let previousSignificant = "";
989
+ const mask = (start, end) => {
990
+ for (let index = start; index < end; index++) if (output[index] !== "\n" && output[index] !== "\r") output[index] = " ";
991
+ };
992
+ for (let index = 0; index < source.length;) {
993
+ const char = source[index];
994
+ const next = source[index + 1];
995
+ let end;
996
+ if (isQuote(char)) {
997
+ end = skipQuoted(source, index);
998
+ previousSignificant = "literal";
999
+ } else if (char === "/" && next === "/") end = skipLineComment(source, index);
1000
+ else if (char === "/" && next === "*") end = skipBlockComment(source, index);
1001
+ else if (char === "/" && (isRegexLiteralStart(previousSignificant) || isControlFlowRegexStart(source, index))) {
1002
+ end = skipRegexLiteral(source, index);
1003
+ previousSignificant = "/";
1004
+ }
1005
+ if (end !== void 0) {
1006
+ mask(index, end);
1007
+ index = end;
1008
+ continue;
1009
+ }
1010
+ previousSignificant = trackSignificant(previousSignificant, char);
1011
+ index += 1;
1012
+ }
1013
+ return output.join("");
1014
+ }
1015
+ function findMatching(source, index, open, close, controlFlowRegexes = /* @__PURE__ */ new Map()) {
1016
+ let depth = 0;
1017
+ let previousSignificant = "";
1018
+ for (let current = index; current < source.length; current++) {
1019
+ const char = source[current];
1020
+ const next = source[current + 1];
1021
+ if (isQuote(char)) {
1022
+ current = skipQuoted(source, current, controlFlowRegexes) - 1;
1023
+ previousSignificant = "literal";
1024
+ continue;
1025
+ }
1026
+ if (char === "/" && next === "/") {
1027
+ current = skipLineComment(source, current) - 1;
1028
+ continue;
1029
+ }
1030
+ if (char === "/" && next === "*") {
1031
+ current = skipBlockComment(source, current) - 1;
1032
+ continue;
1033
+ }
1034
+ if (char === "/" && (isRegexLiteralStart(previousSignificant) || isControlFlowRegexStart(source, current, controlFlowRegexes))) {
1035
+ current = skipRegexLiteral(source, current) - 1;
1036
+ previousSignificant = "/";
1037
+ continue;
1038
+ }
1039
+ if (char === open) {
1040
+ depth += 1;
1041
+ previousSignificant = char;
1042
+ continue;
1043
+ }
1044
+ if (char === close && !(open === "<" && close === ">" && source[current - 1] === "=")) {
1045
+ depth -= 1;
1046
+ if (depth === 0) return current;
1047
+ previousSignificant = char;
1048
+ continue;
1049
+ }
1050
+ previousSignificant = trackSignificant(previousSignificant, char);
1051
+ }
1052
+ }
1053
+ function splitTopLevel(source, separator = ",") {
1054
+ const parts = [];
1055
+ let depth = 0;
1056
+ let previousSignificant = "";
1057
+ let start = 0;
1058
+ for (let index = 0; index < source.length; index++) {
1059
+ const char = source[index];
1060
+ const next = source[index + 1];
1061
+ if (isQuote(char)) {
1062
+ index = skipQuoted(source, index) - 1;
1063
+ previousSignificant = "literal";
1064
+ continue;
1065
+ }
1066
+ if (char === "/" && next === "/") {
1067
+ index = skipLineComment(source, index) - 1;
1068
+ continue;
1069
+ }
1070
+ if (char === "/" && next === "*") {
1071
+ index = skipBlockComment(source, index) - 1;
1072
+ continue;
1073
+ }
1074
+ if (char === "/" && (isRegexLiteralStart(previousSignificant) || isControlFlowRegexStart(source, index))) {
1075
+ index = skipRegexLiteral(source, index) - 1;
1076
+ previousSignificant = "/";
1077
+ continue;
1078
+ }
1079
+ if (char === "<") {
1080
+ const genericEnd = findMatching(source, index, "<", ">");
1081
+ if (genericEnd !== void 0 && nextNonWhitespace(source, genericEnd + 1) === "(") {
1082
+ index = genericEnd;
1083
+ previousSignificant = ">";
1084
+ continue;
1085
+ }
1086
+ }
1087
+ if (char === "(" || char === "{" || char === "[") {
1088
+ depth += 1;
1089
+ previousSignificant = char;
1090
+ continue;
1091
+ }
1092
+ if (char === ")" || char === "}" || char === "]") {
1093
+ depth -= 1;
1094
+ previousSignificant = char;
1095
+ continue;
1096
+ }
1097
+ if (char === separator && depth === 0) {
1098
+ parts.push(source.slice(start, index).trim());
1099
+ start = index + 1;
1100
+ continue;
1101
+ }
1102
+ previousSignificant = trackSignificant(previousSignificant, char);
1103
+ }
1104
+ parts.push(source.slice(start).trim());
1105
+ return parts;
1106
+ }
1107
+ //#endregion
1108
+ //#region ../internal/src/build/provider-output-sources.ts
1109
+ async function rebaseCapturedAbsoluteSourceLinks(stagedSourcesDir, sourceRoot, publishedSourcesDir) {
1110
+ const visit = async (directory) => {
1111
+ const entries = await readdir(directory, { withFileTypes: true });
1112
+ await Promise.all(entries.map(async (entry) => {
1113
+ const path = resolve(directory, entry.name);
1114
+ if (entry.isDirectory()) {
1115
+ await visit(path);
1116
+ return;
1117
+ }
1118
+ if (!entry.isSymbolicLink()) return;
1119
+ const link = await readlink(path);
1120
+ if (!isAbsolute(link) || !pathContains$1(sourceRoot, link)) return;
1121
+ const target = resolve(stagedSourcesDir, relative(sourceRoot, link));
1122
+ const publishedTarget = resolve(publishedSourcesDir, relative(sourceRoot, link));
1123
+ const targetType = await stat(target).catch((error) => {
1124
+ if (error.code === "ENOENT") return void 0;
1125
+ throw error;
1126
+ });
1127
+ if (!targetType) return;
1128
+ const type = targetType.isDirectory() ? process.platform === "win32" ? "junction" : "dir" : "file";
1129
+ const rebasedLink = type === "junction" ? publishedTarget : relative(dirname(path), target) || ".";
1130
+ await rm(path, {
1131
+ force: true,
1132
+ recursive: true
1133
+ });
1134
+ await symlink(rebasedLink, path, type);
1135
+ }));
1136
+ };
1137
+ await visit(stagedSourcesDir);
1138
+ }
1139
+ /** Rewrites both sides of absolute aliases and retains the original key for imports that still use it. */
1140
+ function retainProviderOutputAliases(aliases, retainedSources) {
1141
+ const retainedAliases = Object.create(null);
1142
+ const retain = (specifier, target) => {
1143
+ if (!Object.hasOwn(retainedAliases, specifier)) retainedAliases[specifier] = target;
1144
+ };
1145
+ for (const [specifier, target] of Object.entries(aliases)) {
1146
+ const retainedSpecifier = retainedSources.resolve(specifier);
1147
+ const retainedTarget = retainedSources.resolve(target);
1148
+ retain(specifier, retainedTarget);
1149
+ if (retainedSpecifier !== specifier) retain(retainedSpecifier, retainedTarget);
1150
+ }
1151
+ return retainedAliases;
1152
+ }
1153
+ const ignoredSourceDirectories = new Set([
1154
+ ".git",
1155
+ ".netlify",
1156
+ ".nuxt",
1157
+ ".output",
1158
+ ".vercel",
1159
+ ".vitehub",
1160
+ ".vitest-tmp",
1161
+ "coverage",
1162
+ "dist",
1163
+ "node_modules"
1164
+ ]);
1165
+ const ignoredGeneratedDirectories = new Set([".vitehub", ".vitest-tmp"]);
1166
+ function isTransientSourceDirectory(path) {
1167
+ return basename(path).startsWith(".drizzle-generate-");
1168
+ }
1169
+ function pathContains$1(parent, child) {
1170
+ const nested = relative(parent, child);
1171
+ return !nested || !nested.startsWith(`..${sep}`) && nested !== ".." && !isAbsolute(nested);
1172
+ }
1173
+ function packageRoot(file) {
1174
+ let current = statSync(file).isDirectory() ? file : dirname(file);
1175
+ while (true) {
1176
+ if (existsSync(resolve(current, "package.json"))) return current;
1177
+ const parent = dirname(current);
1178
+ if (parent === current) return statSync(file).isDirectory() ? file : dirname(file);
1179
+ current = parent;
1180
+ }
1181
+ }
1182
+ function boundSourceRootOutsideTemporaryStaging(root, source) {
1183
+ if (!pathContains$1(root, resolve(tmpdir()))) return root;
1184
+ return statSync(source).isDirectory() ? source : dirname(source);
1185
+ }
1186
+ function dependencyRoots(root) {
1187
+ const resolvedRoot = realpathSync(root);
1188
+ const roots = [];
1189
+ let current = resolvedRoot;
1190
+ while (current !== dirname(current)) {
1191
+ const nested = resolve(current, "node_modules");
1192
+ if (existsSync(nested)) roots.push(nested);
1193
+ if (basename(current) === "node_modules") {
1194
+ roots.push(current);
1195
+ break;
1196
+ }
1197
+ current = dirname(current);
1198
+ }
1199
+ return [...new Set(roots)];
1200
+ }
1201
+ async function linkDependencies(source, target, resolveLinkTarget = (source) => source) {
1202
+ await mkdir(target, { recursive: true });
1203
+ for (const entry of await readdir(source, { withFileTypes: true })) {
1204
+ if (entry.name === ".bin" || entry.name === ".pnpm") continue;
1205
+ const sourceEntry = resolve(source, entry.name);
1206
+ const targetEntry = resolve(target, entry.name);
1207
+ if (!existsSync(sourceEntry)) continue;
1208
+ const resolvedSourceEntry = realpathSync(sourceEntry);
1209
+ if (!statSync(resolvedSourceEntry).isDirectory()) continue;
1210
+ if (entry.name.startsWith("@") && entry.isDirectory() && !entry.isSymbolicLink()) {
1211
+ await linkDependencies(sourceEntry, targetEntry, resolveLinkTarget);
1212
+ continue;
1213
+ }
1214
+ if (existsSync(targetEntry)) continue;
1215
+ await symlink(resolveLinkTarget(resolvedSourceEntry), targetEntry, process.platform === "win32" ? "junction" : "dir");
1216
+ }
1217
+ }
1218
+ /** Removes retained provider output after readers release it, tolerating transient filesystem contention. */
1219
+ async function removeProviderOutputArtifactDir(path) {
1220
+ await rm(path, {
1221
+ force: true,
1222
+ maxRetries: 5,
1223
+ recursive: true,
1224
+ retryDelay: 50
1225
+ });
1226
+ }
1227
+ function sourceClosureRoot(root) {
1228
+ let current = root;
1229
+ while (true) {
1230
+ if (existsSync(resolve(current, ".git")) || existsSync(resolve(current, "pnpm-workspace.yaml"))) return current;
1231
+ const parent = dirname(current);
1232
+ if (parent === current) return root;
1233
+ current = parent;
1234
+ }
1235
+ }
1236
+ function commonSourceRoot(root, paths) {
1237
+ let common = root;
1238
+ for (const path of paths) while (!pathContains$1(common, path)) {
1239
+ const parent = dirname(common);
1240
+ if (parent === common) return common;
1241
+ common = parent;
1242
+ }
1243
+ return common;
1244
+ }
1245
+ const traceableSourceExtensions = new Set([
1246
+ ".cjs",
1247
+ ".cts",
1248
+ ".js",
1249
+ ".jsx",
1250
+ ".mjs",
1251
+ ".mts",
1252
+ ".ts",
1253
+ ".tsx"
1254
+ ]);
1255
+ function resolveComputedModuleSource(file, specifier, resolveFrom = file) {
1256
+ try {
1257
+ const imported = createRequire(resolveFrom).resolve(specifier);
1258
+ return existsSync(imported) ? imported : void 0;
1259
+ } catch {
1260
+ return;
1261
+ }
1262
+ }
1263
+ function traceComputedModuleSources(file, source, onRuntimePackageRequest) {
1264
+ const masked = maskSourceLiterals(source);
1265
+ const bindings = /* @__PURE__ */ new Map();
1266
+ for (const match of source.matchAll(/\b(?:const|let|var)\s+([A-Z_$][\w$]*)\s*=\s*([`"'])(.*?)\2/gis)) {
1267
+ const quoteOffset = match[0].indexOf(match[2]);
1268
+ if (!/\b(?:const|let|var)\s+[A-Z_$][\w$]*\s*=\s*$/i.test(masked.slice(match.index, match.index + quoteOffset))) continue;
1269
+ if (match[2] === "`" && match[3].includes("${")) continue;
1270
+ bindings.set(match[1], match[3]);
1271
+ }
1272
+ const createRequireNames = new Set(["createRequire"]);
1273
+ for (const match of source.matchAll(/\bimport\s+(?:[A-Z_$][\w$]*\s*,\s*)?\{([^}]*)\}\s*from\s*([`"'])(?:node:)?module\2/gis)) for (const specifier of match[1].split(",")) {
1274
+ const binding = /^\s*createRequire(?:\s+as\s+([A-Z_$][\w$]*))?\s*$/i.exec(specifier)?.[1];
1275
+ if (binding) createRequireNames.add(binding);
1276
+ }
1277
+ for (const match of source.matchAll(/\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\s*\(\s*([`"'])(?:node:)?module\2\s*\)/gis)) for (const property of match[1].split(",")) {
1278
+ const binding = /^\s*createRequire(?:\s*:\s*([A-Z_$][\w$]*))?\s*$/i.exec(property)?.[1];
1279
+ if (binding) createRequireNames.add(binding);
1280
+ }
1281
+ const createRequireNamespaceNames = /* @__PURE__ */ new Set();
1282
+ for (const match of source.matchAll(/\bimport\s+([A-Z_$][\w$]*)\s*(?:,\s*(?:\{[^}]*\}|\*\s+as\s+[A-Z_$][\w$]*))?\s+from\s*([`"'])(?:node:)?module\2/gis)) createRequireNamespaceNames.add(match[1]);
1283
+ for (const match of source.matchAll(/\bimport\s*\*\s*as\s*([A-Z_$][\w$]*)\s*from\s*([`"'])(?:node:)?module\2/gis)) createRequireNamespaceNames.add(match[1]);
1284
+ for (const match of source.matchAll(/\b(?:const|let|var)\s+([A-Z_$][\w$]*)\s*=\s*require\s*\(\s*([`"'])(?:node:)?module\2\s*\)/gis)) createRequireNamespaceNames.add(match[1]);
1285
+ const isCreateRequireExpression = (expression) => {
1286
+ const normalized = expression.replace(/\s/g, "");
1287
+ if (createRequireNames.has(normalized)) return true;
1288
+ const namespace = /^([A-Z_$][\w$]*)\.createRequire$/i.exec(normalized)?.[1];
1289
+ return Boolean(namespace && createRequireNamespaceNames.has(namespace));
1290
+ };
1291
+ const staticModuleSpecifier = (expression) => {
1292
+ const normalized = expression.trim();
1293
+ const binding = /^([A-Z_$][\w$]*)$/i.exec(normalized)?.[1];
1294
+ if (binding) return bindings.get(binding);
1295
+ const literal = /^([`"'])([\s\S]*)\1$/.exec(normalized);
1296
+ if (!literal || literal[1] === "`" && literal[2].includes("${")) return void 0;
1297
+ return literal[2];
1298
+ };
1299
+ const createRequireBase = (expression) => {
1300
+ const normalized = expression.trim();
1301
+ if (normalized === "import.meta.url" || normalized === "__filename") return file;
1302
+ const direct = staticModuleSpecifier(normalized);
1303
+ if (direct) return direct;
1304
+ const newUrl = /^new\s+URL\s*\(/i.exec(normalized);
1305
+ if (!newUrl) return file;
1306
+ const openParen = normalized.indexOf("(", newUrl.index);
1307
+ const closeParen = findMatching(normalized, openParen, "(", ")");
1308
+ if (closeParen === void 0 || normalized.slice(closeParen + 1).trim()) return file;
1309
+ const [relativeUrl, baseUrl] = splitTopLevel(normalized.slice(openParen + 1, closeParen));
1310
+ const relativePath = relativeUrl ? staticModuleSpecifier(relativeUrl) : void 0;
1311
+ if (!relativePath || baseUrl?.replace(/\s/g, "") !== "import.meta.url") return file;
1312
+ return fileURLToPath(new URL(relativePath, pathToFileURL(file)));
1313
+ };
1314
+ const boundRequireBases = /* @__PURE__ */ new Map();
1315
+ for (const match of masked.matchAll(/\b(?:const|let|var)\s+([A-Z_$][\w$]*)\s*=\s*([A-Z_$][\w$]*(?:\s*\.\s*createRequire)?)\s*\(/gi)) {
1316
+ if (!isCreateRequireExpression(match[2])) continue;
1317
+ const openParen = match.index + match[0].lastIndexOf("(");
1318
+ const closeParen = findMatching(masked, openParen, "(", ")");
1319
+ const base = closeParen === void 0 ? file : createRequireBase(source.slice(openParen + 1, closeParen));
1320
+ boundRequireBases.set(match[1], base);
1321
+ }
1322
+ const boundResolveBases = /* @__PURE__ */ new Map();
1323
+ const recordBoundResolve = (properties, base) => {
1324
+ const resolveBinding = properties.split(",").map((property) => /^\s*resolve(?:\s*:\s*([A-Z_$][\w$]*))?\s*$/i.exec(property)).find(Boolean);
1325
+ if (resolveBinding) boundResolveBases.set(resolveBinding[1] ?? "resolve", base);
1326
+ };
1327
+ for (const match of masked.matchAll(/\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*([A-Z_$][\w$]*(?:\s*\.\s*createRequire)?)\s*\(/gi)) {
1328
+ if (!isCreateRequireExpression(match[2])) continue;
1329
+ const openParen = match.index + match[0].lastIndexOf("(");
1330
+ const closeParen = findMatching(masked, openParen, "(", ")");
1331
+ const base = closeParen === void 0 ? file : createRequireBase(source.slice(openParen + 1, closeParen));
1332
+ recordBoundResolve(match[1], base);
1333
+ }
1334
+ for (const match of masked.matchAll(/\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*([A-Z_$][\w$]*)\b/gi)) {
1335
+ const base = boundRequireBases.get(match[2]);
1336
+ if (base) recordBoundResolve(match[1], base);
1337
+ }
1338
+ const paths = [];
1339
+ const recordRequest = (specifier, kind, resolveFrom = file) => {
1340
+ if (!specifier.startsWith(".") && !isAbsolute(specifier)) {
1341
+ onRuntimePackageRequest?.({
1342
+ kind,
1343
+ resolveFrom,
1344
+ specifier
1345
+ });
1346
+ return;
1347
+ }
1348
+ const imported = resolveComputedModuleSource(file, specifier, resolveFrom);
1349
+ if (imported) paths.push(imported);
1350
+ };
1351
+ for (const request of [
1352
+ {
1353
+ kind: "dynamic-import",
1354
+ pattern: /\bimport\s*\(\s*([A-Z_$][\w$]*)\s*\)/gi
1355
+ },
1356
+ {
1357
+ kind: "require-call",
1358
+ pattern: /\brequire\s*\(\s*([A-Z_$][\w$]*)\s*\)/gi
1359
+ },
1360
+ {
1361
+ kind: "dynamic-import",
1362
+ pattern: /\bimport\s*\.\s*meta\s*\.\s*resolve\s*\(\s*([A-Z_$][\w$]*)\s*\)/gi
1363
+ },
1364
+ {
1365
+ kind: "require-resolve",
1366
+ pattern: /\brequire\s*\.\s*resolve\s*\(\s*([A-Z_$][\w$]*)\s*\)/gi
1367
+ },
1368
+ {
1369
+ kind: "require-call",
1370
+ pattern: /\bmodule\s*\.\s*require\s*\(\s*([A-Z_$][\w$]*)\s*\)/gi
1371
+ }
1372
+ ]) for (const match of masked.matchAll(request.pattern)) {
1373
+ const specifier = bindings.get(match[1]);
1374
+ if (specifier) recordRequest(specifier, request.kind);
1375
+ }
1376
+ for (const match of masked.matchAll(/\b([A-Z_$][\w$]*(?:\s*\.\s*createRequire)?)\s*\(/gi)) {
1377
+ if (!isCreateRequireExpression(match[1])) continue;
1378
+ const openParen = match.index + match[0].lastIndexOf("(");
1379
+ const closeParen = findMatching(masked, openParen, "(", ")");
1380
+ if (closeParen === void 0) continue;
1381
+ const invocation = /^\s*(?:\.\s*resolve\s*)?\(/i.exec(masked.slice(closeParen + 1));
1382
+ if (!invocation) continue;
1383
+ const invocationOpenParen = closeParen + 1 + invocation[0].lastIndexOf("(");
1384
+ const invocationCloseParen = findMatching(masked, invocationOpenParen, "(", ")");
1385
+ if (invocationCloseParen === void 0) continue;
1386
+ const [target] = splitTopLevel(source.slice(invocationOpenParen + 1, invocationCloseParen));
1387
+ const specifier = target ? staticModuleSpecifier(target) : void 0;
1388
+ if (specifier) recordRequest(specifier, /\.\s*resolve/i.test(invocation[0]) ? "require-resolve" : "require-call", createRequireBase(source.slice(openParen + 1, closeParen)));
1389
+ }
1390
+ for (const match of masked.matchAll(/\b([A-Z_$][\w$]*)\s*\(\s*([A-Z_$][\w$]*)\s*\)/gi)) {
1391
+ const specifier = bindings.get(match[2]);
1392
+ if (!specifier) continue;
1393
+ const requireFrom = boundRequireBases.get(match[1]);
1394
+ if (requireFrom) recordRequest(specifier, "require-call", requireFrom);
1395
+ const resolveFrom = boundResolveBases.get(match[1]);
1396
+ if (resolveFrom) recordRequest(specifier, "require-resolve", resolveFrom);
1397
+ }
1398
+ for (const match of masked.matchAll(/\b([A-Z_$][\w$]*)\s*\.\s*resolve\s*\(\s*([A-Z_$][\w$]*)\s*\)/gi)) {
1399
+ const resolveFrom = boundRequireBases.get(match[1]);
1400
+ if (!resolveFrom) continue;
1401
+ const specifier = bindings.get(match[2]);
1402
+ if (specifier) recordRequest(specifier, "require-resolve", resolveFrom);
1403
+ }
1404
+ for (const request of [
1405
+ {
1406
+ kind: "dynamic-import",
1407
+ pattern: /\bimport\s*\.\s*meta\s*\.\s*resolve\s*\(\s*([`"'])(.*?)\1/gi,
1408
+ prefix: /\bimport\s*\.\s*meta\s*\.\s*resolve\s*\(\s*$/i
1409
+ },
1410
+ {
1411
+ kind: "require-resolve",
1412
+ pattern: /\brequire\s*\.\s*resolve\s*\(\s*([`"'])(.*?)\1/gi,
1413
+ prefix: /\brequire\s*\.\s*resolve\s*\(\s*$/i
1414
+ },
1415
+ {
1416
+ kind: "require-call",
1417
+ pattern: /\bmodule\s*\.\s*require\s*\(\s*([`"'])(.*?)\1/gi,
1418
+ prefix: /\bmodule\s*\.\s*require\s*\(\s*$/i
1419
+ }
1420
+ ]) for (const match of source.matchAll(request.pattern)) {
1421
+ const quoteOffset = match[0].indexOf(match[1]);
1422
+ if (!request.prefix.test(masked.slice(match.index, match.index + quoteOffset))) continue;
1423
+ const specifier = match[2];
1424
+ if (match[1] === "`" && specifier.includes("${")) continue;
1425
+ recordRequest(specifier, request.kind);
1426
+ }
1427
+ for (const match of source.matchAll(/\b([A-Z_$][\w$]*)\s*\(\s*([`"'])(.*?)\2/gis)) {
1428
+ const requireFrom = boundRequireBases.get(match[1]);
1429
+ const resolveFrom = boundResolveBases.get(match[1]);
1430
+ if (!requireFrom && !resolveFrom) continue;
1431
+ const quoteOffset = match[0].indexOf(match[2]);
1432
+ if (!/\b[A-Z_$][\w$]*\s*\(\s*$/i.test(masked.slice(match.index, match.index + quoteOffset))) continue;
1433
+ const specifier = match[3];
1434
+ if (match[2] === "`" && specifier.includes("${")) continue;
1435
+ if (requireFrom) recordRequest(specifier, "require-call", requireFrom);
1436
+ if (resolveFrom) recordRequest(specifier, "require-resolve", resolveFrom);
1437
+ }
1438
+ for (const match of source.matchAll(/\b([A-Z_$][\w$]*)\s*\.\s*resolve\s*\(\s*([`"'])(.*?)\2/gis)) {
1439
+ const resolveFrom = boundRequireBases.get(match[1]);
1440
+ if (!resolveFrom) continue;
1441
+ const quoteOffset = match[0].indexOf(match[2]);
1442
+ if (!/\b[A-Z_$][\w$]*\s*\.\s*resolve\s*\(\s*$/i.test(masked.slice(match.index, match.index + quoteOffset))) continue;
1443
+ const specifier = match[3];
1444
+ if (match[2] === "`" && specifier.includes("${")) continue;
1445
+ recordRequest(specifier, "require-resolve", resolveFrom);
1446
+ }
1447
+ return paths;
1448
+ }
1449
+ async function traceImportedSources(paths, root, configuredRoots) {
1450
+ const entries = paths.filter((path) => traceableSourceExtensions.has(extname(path)));
1451
+ if (!entries.length) return /* @__PURE__ */ new Set();
1452
+ const physicalRoot = realpathSync(root);
1453
+ const traceBuildVariants = [
1454
+ { platform: "node" },
1455
+ { platform: "neutral" },
1456
+ {
1457
+ conditions: [
1458
+ "workerd",
1459
+ "worker",
1460
+ "browser",
1461
+ "default"
1462
+ ],
1463
+ platform: "neutral"
1464
+ },
1465
+ {
1466
+ conditions: [
1467
+ "vitehub-hosted",
1468
+ "workerd",
1469
+ "worker",
1470
+ "browser",
1471
+ "default"
1472
+ ],
1473
+ platform: "neutral"
1474
+ },
1475
+ {
1476
+ conditions: [
1477
+ "vitehub-hosted",
1478
+ "node",
1479
+ "default"
1480
+ ],
1481
+ platform: "node"
1482
+ }
1483
+ ];
1484
+ try {
1485
+ const importedSources = new Set(entries);
1486
+ const scannedModuleRequestSources = /* @__PURE__ */ new Set();
1487
+ const tracedEntries = /* @__PURE__ */ new Set();
1488
+ let pendingEntries = entries;
1489
+ while (pendingEntries.length) {
1490
+ const tracedBatch = pendingEntries;
1491
+ pendingEntries = [];
1492
+ for (const entry of tracedBatch) tracedEntries.add(entry);
1493
+ const queriedResourceSources = /* @__PURE__ */ new Set();
1494
+ const importedSourceHints = /* @__PURE__ */ new Set();
1495
+ const results = [];
1496
+ for (const variant of traceBuildVariants) {
1497
+ const [result] = await Promise.allSettled([build({
1498
+ absWorkingDir: root,
1499
+ bundle: true,
1500
+ entryPoints: tracedBatch,
1501
+ format: "esm",
1502
+ logLevel: "silent",
1503
+ metafile: true,
1504
+ outdir: resolve(root, ".vitehub-provider-trace"),
1505
+ packages: "bundle",
1506
+ ...variant,
1507
+ plugins: [{
1508
+ name: "vitehub-provider-vite-resource-query",
1509
+ setup(traceBuild) {
1510
+ const resolvingPackageImportHint = "vitehubResolvingPackageImportHint";
1511
+ traceBuild.onResolve({ filter: /^\.\.?\// }, (request) => {
1512
+ const source = request.resolveDir && resolve(request.resolveDir, request.path.split(/[?#]/, 1)[0]);
1513
+ if (source && existsSync(source)) importedSourceHints.add(source);
1514
+ });
1515
+ traceBuild.onResolve({ filter: /^#/ }, async (request) => {
1516
+ if (request.pluginData?.[resolvingPackageImportHint]) return void 0;
1517
+ if (!request.importer) return void 0;
1518
+ const suffixOffset = request.path.slice(1).search(/[?#]/);
1519
+ const packageImport = suffixOffset === -1 ? request.path : request.path.slice(0, suffixOffset + 1);
1520
+ const resolution = await traceBuild.resolve(packageImport, {
1521
+ importer: request.importer,
1522
+ kind: request.kind,
1523
+ namespace: request.namespace,
1524
+ pluginData: {
1525
+ ...request.pluginData,
1526
+ [resolvingPackageImportHint]: true
1527
+ },
1528
+ resolveDir: request.resolveDir,
1529
+ with: request.with
1530
+ });
1531
+ if (!resolution.errors.length && !resolution.external && resolution.namespace === "file" && existsSync(resolution.path)) importedSourceHints.add(resolution.path);
1532
+ });
1533
+ const resolvingBarePackageHint = "vitehubResolvingBarePackageHint";
1534
+ traceBuild.onResolve({ filter: /^[^./#]/ }, async (request) => {
1535
+ if (request.pluginData?.[resolvingBarePackageHint]) return void 0;
1536
+ if (!request.importer) return void 0;
1537
+ const suffixOffset = request.path.search(/[?#]/);
1538
+ const packageImport = suffixOffset === -1 ? request.path : request.path.slice(0, suffixOffset);
1539
+ const resolution = await traceBuild.resolve(packageImport, {
1540
+ importer: request.importer,
1541
+ kind: request.kind,
1542
+ namespace: request.namespace,
1543
+ pluginData: {
1544
+ ...request.pluginData,
1545
+ [resolvingBarePackageHint]: true
1546
+ },
1547
+ resolveDir: request.resolveDir,
1548
+ with: request.with
1549
+ });
1550
+ const source = pathContains$1(root, resolution.path) ? resolution.path : pathContains$1(physicalRoot, resolution.path) ? resolve(root, relative(physicalRoot, resolution.path)) : void 0;
1551
+ if (!resolution.errors.length && !resolution.external && resolution.namespace === "file" && source && existsSync(source) && !relative(root, source).split(sep).includes("node_modules")) importedSourceHints.add(source);
1552
+ return {
1553
+ external: true,
1554
+ path: request.path
1555
+ };
1556
+ });
1557
+ traceBuild.onResolve({ filter: /[?#]/ }, (request) => {
1558
+ if (request.pluginData?.[resolvingPackageImportHint]) return void 0;
1559
+ const resourcePath = request.path.split(/[?#]/, 1)[0];
1560
+ let resourceSource;
1561
+ if (request.resolveDir && (resourcePath.startsWith("./") || resourcePath.startsWith("../"))) resourceSource = resolve(request.resolveDir, resourcePath);
1562
+ else if (request.resolveDir && resourcePath.startsWith("/")) {
1563
+ const projectRoot = configuredRoots.filter((configuredRoot) => pathContains$1(configuredRoot, request.resolveDir)).sort((left, right) => right.length - left.length)[0] ?? root;
1564
+ const rootRelativePath = resourcePath.slice(1);
1565
+ const publicSource = resolve(projectRoot, "public", rootRelativePath);
1566
+ resourceSource = existsSync(publicSource) ? publicSource : resolve(projectRoot, rootRelativePath);
1567
+ }
1568
+ if (resourceSource && existsSync(resourceSource)) queriedResourceSources.add(resourceSource);
1569
+ return {
1570
+ external: true,
1571
+ path: request.path
1572
+ };
1573
+ });
1574
+ traceBuild.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (request) => {
1575
+ const sourcePath = pathContains$1(root, request.path) ? request.path : pathContains$1(physicalRoot, request.path) ? resolve(root, relative(physicalRoot, request.path)) : void 0;
1576
+ if (!sourcePath || relative(root, sourcePath).split(sep).includes("node_modules")) return void 0;
1577
+ const source = await readFile(request.path, "utf8").catch(() => void 0);
1578
+ if (!source) return void 0;
1579
+ const runtimeRequests = /* @__PURE__ */ new Map();
1580
+ traceComputedModuleSources(request.path, source, (runtimeRequest) => {
1581
+ runtimeRequests.set(`${runtimeRequest.kind}\0${runtimeRequest.resolveFrom}\0${runtimeRequest.specifier}`, runtimeRequest);
1582
+ });
1583
+ await Promise.all([...runtimeRequests.values()].map(async (runtimeRequest) => {
1584
+ const resolveFrom = runtimeRequest.resolveFrom ?? request.path;
1585
+ const resolution = await traceBuild.resolve(runtimeRequest.specifier, {
1586
+ importer: resolveFrom,
1587
+ kind: runtimeRequest.kind,
1588
+ namespace: request.namespace,
1589
+ resolveDir: dirname(resolveFrom)
1590
+ });
1591
+ const resolvedSource = pathContains$1(root, resolution.path) ? resolution.path : pathContains$1(physicalRoot, resolution.path) ? resolve(root, relative(physicalRoot, resolution.path)) : void 0;
1592
+ if (!resolution.errors.length && !resolution.external && resolution.namespace === "file" && resolvedSource && existsSync(resolvedSource) && !relative(root, resolvedSource).split(sep).includes("node_modules")) importedSourceHints.add(resolvedSource);
1593
+ }));
1594
+ });
1595
+ }
1596
+ }],
1597
+ write: false
1598
+ })]);
1599
+ if (result?.status === "fulfilled") results.push(result.value);
1600
+ }
1601
+ for (const result of results) for (const path of Object.keys(result.metafile.inputs)) importedSources.add(resolve(root, path));
1602
+ for (const path of importedSourceHints) {
1603
+ importedSources.add(path);
1604
+ if (traceableSourceExtensions.has(extname(path)) && !tracedEntries.has(path)) pendingEntries.push(path);
1605
+ }
1606
+ for (const resourceSource of queriedResourceSources) {
1607
+ importedSources.add(resourceSource);
1608
+ if (traceableSourceExtensions.has(extname(resourceSource)) && !tracedEntries.has(resourceSource)) pendingEntries.push(resourceSource);
1609
+ }
1610
+ const moduleRequestSources = [...importedSources].filter((path) => traceableSourceExtensions.has(extname(path)) && !scannedModuleRequestSources.has(path));
1611
+ const moduleRequestSourceContents = await Promise.all(moduleRequestSources.map(async (path) => [path, await readFile(path, "utf8")]));
1612
+ for (const [file, source] of moduleRequestSourceContents) {
1613
+ scannedModuleRequestSources.add(file);
1614
+ for (const imported of traceComputedModuleSources(file, source)) {
1615
+ importedSources.add(imported);
1616
+ if (traceableSourceExtensions.has(extname(imported)) && !tracedEntries.has(imported) && !pendingEntries.includes(imported)) pendingEntries.push(imported);
1617
+ }
1618
+ }
1619
+ }
1620
+ return importedSources;
1621
+ } catch {
1622
+ return new Set(entries);
1623
+ }
1624
+ }
1625
+ function symlinkSourcesForRequestedPath(root, path) {
1626
+ const sources = [];
1627
+ let current = path;
1628
+ while (pathContains$1(root, current)) {
1629
+ if (lstatSync(current).isSymbolicLink()) sources.push(current);
1630
+ if (current === root) break;
1631
+ current = dirname(current);
1632
+ }
1633
+ return sources.reverse();
1634
+ }
1635
+ function packageMetadataSourcesForPath(root, path) {
1636
+ const sources = [];
1637
+ let current = statSync(path).isDirectory() ? path : dirname(path);
1638
+ while (pathContains$1(root, current)) {
1639
+ const packageJson = resolve(current, "package.json");
1640
+ if (existsSync(packageJson)) sources.push(packageJson);
1641
+ if (current === root) break;
1642
+ current = dirname(current);
1643
+ }
1644
+ return sources;
1645
+ }
1646
+ function parseJsonWithComments(source) {
1647
+ let output = "";
1648
+ let blockComment = false;
1649
+ let lineComment = false;
1650
+ let quoted = false;
1651
+ for (let index = 0; index < source.length; index += 1) {
1652
+ const char = source[index];
1653
+ const next = source[index + 1];
1654
+ if (lineComment) {
1655
+ if (char === "\n" || char === "\r") {
1656
+ lineComment = false;
1657
+ output += char;
1658
+ } else output += " ";
1659
+ continue;
1660
+ }
1661
+ if (blockComment) {
1662
+ if (char === "*" && next === "/") {
1663
+ blockComment = false;
1664
+ output += " ";
1665
+ index += 1;
1666
+ } else output += char === "\n" || char === "\r" ? char : " ";
1667
+ continue;
1668
+ }
1669
+ if (!quoted && char === "/" && next === "/") {
1670
+ lineComment = true;
1671
+ output += " ";
1672
+ index += 1;
1673
+ continue;
1674
+ }
1675
+ if (!quoted && char === "/" && next === "*") {
1676
+ blockComment = true;
1677
+ output += " ";
1678
+ index += 1;
1679
+ continue;
1680
+ }
1681
+ output += char;
1682
+ if (char === "\"") {
1683
+ let backslashes = 0;
1684
+ for (let previous = index - 1; source[previous] === "\\"; previous -= 1) backslashes += 1;
1685
+ if (backslashes % 2 === 0) quoted = !quoted;
1686
+ }
1687
+ }
1688
+ let withoutTrailingCommas = "";
1689
+ quoted = false;
1690
+ for (let index = 0; index < output.length; index += 1) {
1691
+ const char = output[index];
1692
+ if (char === "\"") {
1693
+ let backslashes = 0;
1694
+ for (let previous = index - 1; output[previous] === "\\"; previous -= 1) backslashes += 1;
1695
+ if (backslashes % 2 === 0) quoted = !quoted;
1696
+ }
1697
+ if (!quoted && char === ",") {
1698
+ let next = index + 1;
1699
+ while (/\s/.test(output[next] ?? "")) next += 1;
1700
+ if (output[next] === "}" || output[next] === "]") continue;
1701
+ }
1702
+ withoutTrailingCommas += char;
1703
+ }
1704
+ return JSON.parse(withoutTrailingCommas);
1705
+ }
1706
+ function resolveTsconfigReference(config, reference) {
1707
+ const candidates = reference.startsWith(".") || isAbsolute(reference) ? [
1708
+ resolve(dirname(config), reference),
1709
+ resolve(dirname(config), `${reference}.json`),
1710
+ resolve(dirname(config), reference, "tsconfig.json")
1711
+ ] : [reference, `${reference}/tsconfig.json`];
1712
+ for (const candidate of candidates) try {
1713
+ const resolved = isAbsolute(candidate) ? candidate : createRequire(config).resolve(candidate);
1714
+ if (existsSync(resolved)) return resolved;
1715
+ } catch {}
1716
+ }
1717
+ async function tsconfigSourcesForPaths(root, paths) {
1718
+ const pending = [];
1719
+ for (const path of paths) {
1720
+ let current = statSync(path).isDirectory() ? path : dirname(path);
1721
+ while (pathContains$1(root, current)) {
1722
+ const config = resolve(current, "tsconfig.json");
1723
+ if (existsSync(config)) {
1724
+ pending.push(config);
1725
+ break;
1726
+ }
1727
+ if (current === root) break;
1728
+ current = dirname(current);
1729
+ }
1730
+ }
1731
+ const sources = /* @__PURE__ */ new Set();
1732
+ while (pending.length) {
1733
+ const config = pending.pop();
1734
+ if (sources.has(config)) continue;
1735
+ sources.add(config);
1736
+ try {
1737
+ const parsed = parseJsonWithComments(await readFile(config, "utf8"));
1738
+ const references = Array.isArray(parsed.extends) ? parsed.extends : parsed.extends ? [parsed.extends] : [];
1739
+ for (const reference of references) {
1740
+ const resolved = resolveTsconfigReference(config, reference);
1741
+ if (resolved && !sources.has(resolved)) pending.push(resolved);
1742
+ }
1743
+ } catch {}
1744
+ }
1745
+ return [...sources];
1746
+ }
1747
+ /** Retains one build generation's source trees while preserving every module's import base. */
1748
+ async function retainProviderOutputSources(options) {
1749
+ const artifactDir = resolve(options.artifactDir);
1750
+ const paths = [...new Set((options.paths ?? []).filter(isAbsolute).map((path) => resolve(path)).filter(existsSync))];
1751
+ const configuredRoots = [...new Set(options.roots.map((root) => resolve(root)).filter(existsSync))];
1752
+ const sourceRootByPath = /* @__PURE__ */ new Map();
1753
+ const packageRoots = /* @__PURE__ */ new Set();
1754
+ for (const path of paths) {
1755
+ const configuredRoot = configuredRoots.filter((root) => pathContains$1(root, path)).sort((left, right) => right.length - left.length)[0];
1756
+ const pathSegments = configuredRoot ? relative(configuredRoot, path).split(sep) : [];
1757
+ const nestedInRetainedOutput = pathSegments.includes(".vitehub") || pathSegments.includes("node_modules");
1758
+ const discoveredPackageRoot = packageRoot(path);
1759
+ const hasNestedPackage = Boolean(configuredRoot && nestedInRetainedOutput && discoveredPackageRoot !== configuredRoot);
1760
+ const sourceRoot = boundSourceRootOutsideTemporaryStaging(configuredRoot && !hasNestedPackage ? sourceClosureRoot(configuredRoot) : discoveredPackageRoot, path);
1761
+ sourceRootByPath.set(path, sourceRoot);
1762
+ if (!configuredRoot || hasNestedPackage) packageRoots.add(sourceRoot);
1763
+ }
1764
+ for (const root of configuredRoots) sourceRootByPath.set(root, boundSourceRootOutsideTemporaryStaging(sourceClosureRoot(root), root));
1765
+ const roots = [...new Set(sourceRootByPath.values())];
1766
+ const retainedRoots = /* @__PURE__ */ new Map();
1767
+ const retainedPaths = /* @__PURE__ */ new Map();
1768
+ const pendingRoots = roots.entries();
1769
+ let firstFailure;
1770
+ const retainNextRoot = async () => {
1771
+ if (firstFailure) return;
1772
+ const next = pendingRoots.next();
1773
+ if (next.done) return;
1774
+ const [index, root] = next.value;
1775
+ const requested = paths.filter((path) => path !== root && pathContains$1(root, path));
1776
+ const nestedConfiguredRoots = configuredRoots.filter((path) => pathContains$1(root, path));
1777
+ const importedSources = await traceImportedSources(requested, root, nestedConfiguredRoots);
1778
+ const materializedSourcePaths = [...requested, ...importedSources];
1779
+ const tsconfigSources = await tsconfigSourcesForPaths(root, materializedSourcePaths);
1780
+ materializedSourcePaths.push(...tsconfigSources);
1781
+ const governingPackageMetadata = materializedSourcePaths.flatMap((path) => packageMetadataSourcesForPath(packageRoot(path), path));
1782
+ const captureRoot = commonSourceRoot(root, [
1783
+ ...importedSources,
1784
+ ...tsconfigSources,
1785
+ ...governingPackageMetadata
1786
+ ]);
1787
+ const retainedContainer = resolve(artifactDir, String(index));
1788
+ const retainedRoot = resolve(retainedContainer, relative(captureRoot, root));
1789
+ retainedRoots.set(root, retainedRoot);
1790
+ const materializedSources = [...new Set([
1791
+ ...materializedSourcePaths,
1792
+ ...governingPackageMetadata,
1793
+ ...materializedSourcePaths.flatMap((path) => packageMetadataSourcesForPath(captureRoot, path))
1794
+ ])];
1795
+ for (const source of materializedSources.filter((source) => !pathContains$1(root, source))) retainedPaths.set(source, resolve(retainedContainer, relative(captureRoot, source)));
1796
+ const requestedSymlinks = [...new Set([root, ...materializedSources].flatMap((path) => symlinkSourcesForRequestedPath(root, path)))].sort((left, right) => relative(root, left).split(sep).length - relative(root, right).split(sep).length);
1797
+ const configuredOutputClosures = nestedConfiguredRoots.flatMap((configuredRoot) => {
1798
+ const segments = relative(root, configuredRoot).split(sep);
1799
+ const ignoredIndex = segments.findIndex((segment) => ignoredGeneratedDirectories.has(segment));
1800
+ if (ignoredIndex === -1 || ignoredIndex === segments.length - 1) return [];
1801
+ return [resolve(root, ...segments.slice(0, ignoredIndex + 2))];
1802
+ });
1803
+ const requestedOutputRoots = requested.flatMap((path) => {
1804
+ const scopedRoot = nestedConfiguredRoots.filter((root) => pathContains$1(root, path)).sort((left, right) => right.length - left.length)[0] ?? root;
1805
+ const segments = relative(scopedRoot, path).split(sep);
1806
+ const ignoredIndex = segments.findIndex((segment) => ignoredSourceDirectories.has(segment));
1807
+ if (ignoredIndex === -1) return [];
1808
+ const generationIndex = ignoredGeneratedDirectories.has(segments[ignoredIndex]) && segments[ignoredIndex + 1]?.endsWith("-generations") ? ignoredIndex + 1 : -1;
1809
+ const retainedSourcesIndex = generationIndex === ignoredIndex + 1 ? segments.findIndex((segment, index) => index > generationIndex && (segment === "sources" || segment.endsWith("-sources"))) : -1;
1810
+ const generatedOutputIndex = ignoredGeneratedDirectories.has(segments[ignoredIndex]) ? Math.min(ignoredIndex + 1, segments.length - 1) : ignoredIndex;
1811
+ const outputRootIndex = retainedSourcesIndex !== -1 ? retainedSourcesIndex : generationIndex !== -1 ? Math.min(generationIndex + 1, segments.length - 1) : generatedOutputIndex;
1812
+ return [resolve(scopedRoot, ...segments.slice(0, outputRootIndex + 1))];
1813
+ });
1814
+ const nestedDependencyRoots = /* @__PURE__ */ new Map();
1815
+ const temporaryRoot = await mkdtemp(resolve(tmpdir(), "vitehub-provider-sources-"));
1816
+ const stagedContainer = resolve(temporaryRoot, "source");
1817
+ const stagedRoot = resolve(stagedContainer, relative(captureRoot, root));
1818
+ try {
1819
+ const shouldCopySource = (resolvedSource) => {
1820
+ if (pathContains$1(artifactDir, resolvedSource)) return false;
1821
+ if (isTransientSourceDirectory(resolvedSource) && !requested.some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource))) return false;
1822
+ if (resolvedSource !== root && existsSync(resolve(resolvedSource, ".git")) && !requested.some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) && ![...importedSources].some((path) => pathContains$1(resolvedSource, path)) && !nestedConfiguredRoots.some((configuredRoot) => pathContains$1(resolvedSource, configuredRoot)) && !configuredOutputClosures.some((outputRoot) => pathContains$1(outputRoot, resolvedSource))) return false;
1823
+ const nested = relative(root, resolvedSource);
1824
+ if (!nested) return true;
1825
+ const segments = nested.split(sep);
1826
+ const dependencyIndex = segments.indexOf("node_modules");
1827
+ if (dependencyIndex !== -1) {
1828
+ if (dependencyIndex === segments.length - 1 && dirname(resolvedSource) !== root) nestedDependencyRoots.set(resolve(retainedRoot, nested), resolvedSource);
1829
+ return false;
1830
+ }
1831
+ const first = segments[0];
1832
+ const containingConfiguredRoot = nestedConfiguredRoots.filter((configuredRoot) => pathContains$1(configuredRoot, resolvedSource)).sort((left, right) => right.length - left.length)[0];
1833
+ const scopedSegments = relative(containingConfiguredRoot ?? root, resolvedSource).split(sep);
1834
+ const scopedFirst = containingConfiguredRoot ? scopedSegments[0] : first;
1835
+ if (scopedFirst === ".nuxt") return requested.some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) || scopedSegments.length === 1 || scopedSegments.length === 2 && /^tsconfig(?:\.[^.]+)?\.json$/i.test(scopedSegments[1]);
1836
+ if (scopedSegments.some((segment) => ignoredGeneratedDirectories.has(segment)) || scopedFirst && ignoredSourceDirectories.has(scopedFirst) && !(packageRoots.has(root) && !containingConfiguredRoot && scopedFirst === "dist")) return requested.some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) || [...importedSources].some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) || requestedOutputRoots.some((outputRoot) => pathContains$1(outputRoot, resolvedSource)) || configuredOutputClosures.some((outputRoot) => pathContains$1(outputRoot, resolvedSource) && !relative(outputRoot, resolvedSource).split(sep).some((segment) => ignoredSourceDirectories.has(segment))) && !nestedConfiguredRoots.some((configuredRoot) => pathContains$1(configuredRoot, resolvedSource)) || nestedConfiguredRoots.some((configuredRoot) => pathContains$1(resolvedSource, configuredRoot));
1837
+ return true;
1838
+ };
1839
+ await cp(root, stagedRoot, {
1840
+ recursive: true,
1841
+ filter: (source) => shouldCopySource(resolve(source))
1842
+ });
1843
+ const escapedMaterializedSources = materializedSources.filter((source) => !pathContains$1(root, source)).filter((source, _, sources) => !sources.some((parent) => parent !== source && statSync(parent).isDirectory() && pathContains$1(parent, source)));
1844
+ for (const source of escapedMaterializedSources) {
1845
+ const retainedSource = resolve(stagedContainer, relative(captureRoot, source));
1846
+ await mkdir(dirname(retainedSource), { recursive: true });
1847
+ await cp(realpathSync(source), retainedSource, { recursive: statSync(source).isDirectory() });
1848
+ }
1849
+ for (const source of requestedSymlinks) {
1850
+ const retainedSource = resolve(stagedRoot, relative(root, source));
1851
+ const sourceTarget = realpathSync(source);
1852
+ await rm(retainedSource, {
1853
+ force: true,
1854
+ recursive: true
1855
+ });
1856
+ await cp(sourceTarget, retainedSource, {
1857
+ recursive: statSync(source).isDirectory(),
1858
+ filter(candidate) {
1859
+ const physicalCandidate = resolve(candidate);
1860
+ const logicalCandidate = resolve(source, relative(sourceTarget, physicalCandidate));
1861
+ return materializedSources.some((path) => pathContains$1(logicalCandidate, path) || pathContains$1(path, logicalCandidate) || pathContains$1(physicalCandidate, path) || pathContains$1(path, physicalCandidate)) && shouldCopySource(logicalCandidate);
1862
+ }
1863
+ });
1864
+ }
1865
+ await rebaseCapturedAbsoluteSourceLinks(stagedContainer, captureRoot, retainedContainer);
1866
+ await mkdir(dirname(retainedContainer), { recursive: true });
1867
+ try {
1868
+ await rename(stagedContainer, retainedContainer);
1869
+ } catch (error) {
1870
+ if (error.code !== "EXDEV") throw error;
1871
+ await cp(stagedContainer, retainedContainer, { recursive: true });
1872
+ }
1873
+ const resolveRetainedDependencyTarget = (source) => {
1874
+ if (!pathContains$1(root, source) || relative(root, source).split(sep).includes("node_modules")) return source;
1875
+ const retainedSource = resolve(retainedRoot, relative(root, source));
1876
+ return existsSync(retainedSource) ? retainedSource : source;
1877
+ };
1878
+ for (const dependencies of dependencyRoots(root)) await linkDependencies(dependencies, resolve(retainedRoot, "node_modules"), resolveRetainedDependencyTarget);
1879
+ for (const source of escapedMaterializedSources) {
1880
+ const sourceDirectory = statSync(source).isDirectory() ? source : dirname(source);
1881
+ for (const dependencies of dependencyRoots(sourceDirectory)) await linkDependencies(dependencies, pathContains$1(captureRoot, dependencies) ? resolve(retainedContainer, relative(captureRoot, dependencies)) : resolve(retainedContainer, "node_modules"), resolveRetainedDependencyTarget);
1882
+ }
1883
+ for (const [target, dependencies] of nestedDependencyRoots) await linkDependencies(dependencies, target, resolveRetainedDependencyTarget);
1884
+ } finally {
1885
+ await rm(temporaryRoot, {
1886
+ force: true,
1887
+ recursive: true
1888
+ });
1889
+ }
1890
+ await retainNextRoot();
1891
+ };
1892
+ await Promise.all(Array.from({ length: Math.min(2, roots.length) }, async () => {
1893
+ try {
1894
+ await retainNextRoot();
1895
+ } catch (error) {
1896
+ firstFailure ??= { error };
1897
+ }
1898
+ }));
1899
+ if (firstFailure) throw firstFailure.error;
1900
+ return { resolve(path) {
1901
+ if (!isAbsolute(path)) return path;
1902
+ const resolvedPath = resolve(path);
1903
+ const retainedPath = retainedPaths.get(resolvedPath);
1904
+ if (retainedPath) return retainedPath;
1905
+ const root = sourceRootByPath.get(resolvedPath) ?? roots.filter((candidate) => pathContains$1(candidate, resolvedPath)).sort((left, right) => right.length - left.length)[0];
1906
+ return root ? resolve(retainedRoots.get(root), relative(root, resolvedPath)) : path;
1907
+ } };
1908
+ }
1909
+ //#endregion
1910
+ //#region ../internal/src/build/vercel-config.ts
1911
+ function createVercelConfigJson() {
1912
+ return {
1913
+ routes: [{ handle: "filesystem" }, {
1914
+ src: "/(.*)",
1915
+ dest: "/__server"
1916
+ }],
1917
+ version: 3
1918
+ };
1919
+ }
1920
+ function createNodeFunctionConfig(extra = {}) {
1921
+ return {
1922
+ handler: "index.mjs",
1923
+ launcherType: "Nodejs",
1924
+ runtime: "nodejs22.x",
1925
+ shouldAddHelpers: false,
1926
+ supportsResponseStreaming: true,
1927
+ ...extra
1928
+ };
1929
+ }
1930
+ //#endregion
1931
+ //#region ../internal/src/build/cloudflare-provider-output.ts
1932
+ const providerOutputCatalogRegistry$1 = globalThis;
1933
+ const providerOutputCatalogByNitroValue = providerOutputCatalogRegistry$1.__vitehubProviderOutputCatalogsByNitroValue ??= /* @__PURE__ */ new WeakMap();
1934
+ function cloneRecord(value) {
1935
+ return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
1936
+ }
1937
+ function cloneProviderRecord(value) {
1938
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1939
+ return Object.fromEntries(Object.entries(value).flatMap(([key, entry]) => typeof entry === "undefined" ? [] : [[key, cloneProviderValue(entry)]]));
1940
+ }
1941
+ function cloneProviderValue(value) {
1942
+ if (Array.isArray(value)) return value.map((entry) => typeof entry === "undefined" ? null : cloneProviderValue(entry));
1943
+ if (value && typeof value === "object") return cloneProviderRecord(value);
1944
+ return value;
1945
+ }
1946
+ function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner) {
1947
+ const current = Array.isArray(existing) ? existing.map(cloneProviderRecord) : [];
1948
+ return (incoming ?? []).filter((entry) => {
1949
+ const identity = entry[identityKey];
1950
+ const match = current.find((candidate) => candidate[identityKey] === identity);
1951
+ if (!match) {
1952
+ current.push(entry);
1953
+ return true;
1954
+ }
1955
+ if (conflictKeys.some((key) => !isDeepStrictEqual(match[key], entry[key]))) throw new Error(`[vitehub] Cloudflare ${identityKey} ${JSON.stringify(identity)} from ${owner} is already assigned to an incompatible resource.`);
1956
+ return false;
1957
+ });
1958
+ }
1959
+ function removeEntries(existing, entries) {
1960
+ if (!Array.isArray(existing) || !entries?.length) return Array.isArray(existing) ? existing : [];
1961
+ return existing.filter((entry) => !entries.some((previous) => isDeepStrictEqual(entry, previous)));
1962
+ }
1963
+ function removeContribution(wrangler, contribution) {
1964
+ const queues = cloneProviderRecord(wrangler.queues);
1965
+ const secrets = cloneProviderRecord(wrangler.secrets);
1966
+ const environments = cloneProviderRecord(wrangler.env);
1967
+ const hasQueues = Boolean(contribution.queues?.consumers?.length || contribution.queues?.producers?.length);
1968
+ const hasSecrets = Boolean(contribution.requiredSecrets?.length || Object.keys(contribution.requiredSecretsByEnvironment ?? {}).length);
1969
+ if (contribution.queues?.consumers?.length) {
1970
+ const consumers = removeEntries(queues.consumers, contribution.queues.consumers);
1971
+ if (consumers.length) queues.consumers = consumers;
1972
+ else delete queues.consumers;
1973
+ }
1974
+ if (contribution.queues?.producers?.length) {
1975
+ const producers = removeEntries(queues.producers, contribution.queues.producers);
1976
+ if (producers.length) queues.producers = producers;
1977
+ else delete queues.producers;
1978
+ }
1979
+ if (contribution.requiredSecrets?.length) {
1980
+ const required = removeEntries(secrets.required, contribution.requiredSecrets);
1981
+ if (required.length) secrets.required = required;
1982
+ else delete secrets.required;
1983
+ }
1984
+ for (const [name, requiredSecrets] of Object.entries(contribution.requiredSecretsByEnvironment ?? {})) {
1985
+ if (!(name in environments)) continue;
1986
+ const environment = cloneProviderRecord(environments[name]);
1987
+ const environmentSecrets = cloneProviderRecord(environment.secrets);
1988
+ const required = removeEntries(environmentSecrets.required, requiredSecrets);
1989
+ if (required.length) environmentSecrets.required = required;
1990
+ else delete environmentSecrets.required;
1991
+ if (Object.keys(environmentSecrets).length) environment.secrets = environmentSecrets;
1992
+ else delete environment.secrets;
1993
+ environments[name] = environment;
1994
+ }
1995
+ const withoutOwned = { ...wrangler };
1996
+ if (hasQueues) delete withoutOwned.queues;
1997
+ if (hasSecrets) delete withoutOwned.secrets;
1998
+ if (hasSecrets) delete withoutOwned.env;
1999
+ return {
2000
+ ...withoutOwned,
2001
+ ...hasQueues && Object.keys(queues).length ? { queues } : {},
2002
+ ...hasSecrets && Object.keys(secrets).length ? { secrets } : {},
2003
+ ...hasSecrets && Object.keys(environments).length ? { env: environments } : {},
2004
+ ...contribution.r2Buckets?.length ? { r2_buckets: removeEntries(wrangler.r2_buckets, contribution.r2Buckets) } : {},
2005
+ ...contribution.rateLimits?.length ? { ratelimits: removeEntries(wrangler.ratelimits, contribution.rateLimits) } : {}
2006
+ };
2007
+ }
2008
+ function mergeContribution(wrangler, owner, contribution) {
2009
+ const queues = cloneProviderRecord(wrangler.queues);
2010
+ const secrets = cloneProviderRecord(wrangler.secrets);
2011
+ const environments = cloneProviderRecord(wrangler.env);
2012
+ const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner);
2013
+ const producers = compatibleEntries(queues.producers, contribution.queues?.producers, "binding", ["queue"], owner);
2014
+ const r2Buckets = compatibleEntries(wrangler.r2_buckets, contribution.r2Buckets, "binding", ["bucket_name"], owner);
2015
+ const rateLimits = compatibleEntries(wrangler.ratelimits, contribution.rateLimits, "name", ["namespace_id", "simple"], owner);
2016
+ const currentRequiredSecrets = Array.isArray(secrets.required) ? secrets.required : [];
2017
+ const requiredSecrets = (contribution.requiredSecrets ?? []).filter((name) => !currentRequiredSecrets.includes(name));
2018
+ if (requiredSecrets.length) secrets.required = [...currentRequiredSecrets, ...requiredSecrets];
2019
+ const requiredSecretsByEnvironment = {};
2020
+ for (const [name, value] of Object.entries(environments)) {
2021
+ const environment = cloneProviderRecord(value);
2022
+ const environmentSecrets = cloneProviderRecord(environment.secrets);
2023
+ const current = Array.isArray(environmentSecrets.required) ? environmentSecrets.required : [];
2024
+ const required = (contribution.requiredSecrets ?? []).filter((secret) => !current.includes(secret));
2025
+ if (required.length) {
2026
+ environmentSecrets.required = [...current, ...required];
2027
+ environment.secrets = environmentSecrets;
2028
+ environments[name] = environment;
2029
+ requiredSecretsByEnvironment[name] = required;
2030
+ }
2031
+ }
2032
+ const nextQueues = mergeProviderOutputConfig(queues, {
2033
+ ...consumers.length ? { consumers } : {},
2034
+ ...producers.length ? { producers } : {}
2035
+ }, { arrays: {
2036
+ consumers: { key: "queue" },
2037
+ producers: { key: "binding" }
2038
+ } });
2039
+ return [mergeProviderOutputConfig(wrangler, {
2040
+ ...Object.keys(nextQueues).length ? { queues: nextQueues } : {},
2041
+ ...r2Buckets.length ? { r2_buckets: r2Buckets } : {},
2042
+ ...rateLimits.length ? { ratelimits: rateLimits } : {},
2043
+ ...Object.keys(secrets).length ? { secrets } : {},
2044
+ ...Object.keys(environments).length ? { env: environments } : {}
2045
+ }, { arrays: {
2046
+ r2_buckets: { key: "binding" },
2047
+ ratelimits: { key: "name" }
2048
+ } }), {
2049
+ queues: {
2050
+ consumers,
2051
+ producers
2052
+ },
2053
+ r2Buckets,
2054
+ rateLimits,
2055
+ requiredSecrets,
2056
+ requiredSecretsByEnvironment
2057
+ }];
2058
+ }
2059
+ function inheritedProviderOutputCatalog(value) {
2060
+ if (!value || typeof value !== "object") return;
2061
+ const cloudflare = value.cloudflare;
2062
+ const wrangler = cloudflare && typeof cloudflare === "object" ? cloudflare.wrangler : void 0;
2063
+ return providerOutputCatalogByNitroValue.get(value) ?? (cloudflare && typeof cloudflare === "object" ? providerOutputCatalogByNitroValue.get(cloudflare) : void 0) ?? (wrangler && typeof wrangler === "object" ? providerOutputCatalogByNitroValue.get(wrangler) : void 0);
2064
+ }
2065
+ function associateProviderOutputCatalog(output, catalog) {
2066
+ providerOutputCatalogByNitroValue.set(output, catalog);
2067
+ const cloudflare = output.cloudflare;
2068
+ if (!cloudflare || typeof cloudflare !== "object") return;
2069
+ providerOutputCatalogByNitroValue.set(cloudflare, catalog);
2070
+ const wrangler = cloudflare.wrangler;
2071
+ if (wrangler && typeof wrangler === "object") providerOutputCatalogByNitroValue.set(wrangler, catalog);
2072
+ }
2073
+ function composeNitroCloudflareProviderOutput(catalog, value, inheritedValue = value) {
2074
+ const nitro = cloneRecord(value);
2075
+ const cloudflare = cloneRecord(nitro.cloudflare);
2076
+ const inherited = inheritedProviderOutputCatalog(inheritedValue) ?? inheritedProviderOutputCatalog(value);
2077
+ if (inherited && inherited !== catalog) catalog.inheritCloudflareContributions(inherited);
2078
+ let wrangler = cloneProviderRecord(cloudflare.wrangler);
2079
+ for (const contribution of catalog.appliedCloudflareContributions()) wrangler = removeContribution(wrangler, contribution);
2080
+ catalog.clearAppliedCloudflareContributions();
2081
+ for (const [owner, contribution] of catalog.cloudflareContributions()) {
2082
+ const [merged, applied] = mergeContribution(wrangler, owner, contribution);
2083
+ wrangler = merged;
2084
+ catalog.replaceAppliedCloudflareContribution(owner, applied);
2085
+ }
2086
+ const output = !Object.keys(cloudflare).length && !Object.keys(wrangler).length ? nitro : {
2087
+ ...nitro,
2088
+ cloudflare: {
2089
+ ...cloudflare,
2090
+ wrangler
2091
+ }
2092
+ };
2093
+ associateProviderOutputCatalog(output, catalog);
2094
+ return output;
2095
+ }
2096
+ //#endregion
2097
+ //#region ../internal/src/build/provider-output-catalog.ts
2098
+ var ProviderOutputCatalog = class {
2099
+ #appliedCloudflareContributions = /* @__PURE__ */ new Map();
2100
+ #cloudflareContributions = /* @__PURE__ */ new Map();
2101
+ #runtimeContributions = /* @__PURE__ */ new Map();
2102
+ #runtimeContributionsByGeneration = /* @__PURE__ */ new WeakMap();
2103
+ #deploymentContributionSequence = 0;
2104
+ #deploymentContributions = /* @__PURE__ */ new Map();
2105
+ #deploymentGenerationRefs = /* @__PURE__ */ new WeakMap();
2106
+ #deploymentGenerations = /* @__PURE__ */ new Set();
2107
+ #pendingDeploymentDiscards = [];
2108
+ #takenDeploymentContributions = /* @__PURE__ */ new Map();
2109
+ appliedCloudflareContributions() {
2110
+ return this.#appliedCloudflareContributions.values();
2111
+ }
2112
+ appliedCloudflareContributionEntries() {
2113
+ return this.#appliedCloudflareContributions.entries();
2114
+ }
2115
+ clearAppliedCloudflareContributions() {
2116
+ this.#appliedCloudflareContributions.clear();
2117
+ }
2118
+ cloudflareContributions() {
2119
+ return this.#cloudflareContributions.entries();
2120
+ }
2121
+ inheritCloudflareContributions(catalog) {
2122
+ for (const [owner, contribution] of catalog.appliedCloudflareContributionEntries()) this.#appliedCloudflareContributions.set(owner, contribution);
2123
+ for (const [owner, contribution] of [...catalog.cloudflareContributions(), ...this.#cloudflareContributions]) this.#cloudflareContributions.set(owner, contribution);
2124
+ }
2125
+ replaceAppliedCloudflareContribution(owner, contribution) {
2126
+ this.#appliedCloudflareContributions.set(owner, contribution);
2127
+ }
2128
+ replaceCloudflareContribution(owner, contribution) {
2129
+ this.#cloudflareContributions.set(owner, contribution);
2130
+ }
2131
+ replaceRuntimeContribution(contribution, generation) {
2132
+ if (!generation) {
2133
+ this.#runtimeContributions.set(contribution.owner, contribution);
2134
+ return;
2135
+ }
2136
+ let contributions = this.#runtimeContributionsByGeneration.get(generation);
2137
+ if (!contributions) {
2138
+ contributions = /* @__PURE__ */ new Map();
2139
+ this.#runtimeContributionsByGeneration.set(generation, contributions);
2140
+ }
2141
+ contributions.set(contribution.owner, contribution);
2142
+ }
2143
+ runtimeContribution(product, generation) {
2144
+ return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.get(product);
2145
+ }
2146
+ runtimeContributions(generation) {
2147
+ return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.entries() ?? (/* @__PURE__ */ new Map()).entries();
2148
+ }
2149
+ resetRuntimeContributions() {
2150
+ this.#runtimeContributions.clear();
2151
+ }
2152
+ createDeploymentGeneration() {
2153
+ const generation = { valid: true };
2154
+ this.#trackDeploymentGeneration(generation);
2155
+ return generation;
2156
+ }
2157
+ replaceDeploymentContribution(contribution, generation) {
2158
+ const entry = {
2159
+ contribution,
2160
+ generation,
2161
+ sequence: this.#deploymentContributionSequence++
2162
+ };
2163
+ if (generation && !generation.valid) {
2164
+ this.#queueDeploymentDiscard(entry);
2165
+ return;
2166
+ }
2167
+ this.#restoreDeploymentContribution(entry);
2168
+ }
2169
+ resetDeploymentContributions(generation) {
2170
+ if (!generation) {
2171
+ for (const reference of this.#deploymentGenerations) {
2172
+ const current = reference.deref();
2173
+ if (current) current.valid = false;
2174
+ }
2175
+ this.#deploymentGenerations.clear();
2176
+ for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry);
2177
+ for (const taken of this.#takenDeploymentContributions.values()) {
2178
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
2179
+ for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback);
2180
+ }
2181
+ this.#deploymentContributions.clear();
2182
+ this.#takenDeploymentContributions.clear();
2183
+ return;
2184
+ }
2185
+ generation.valid = false;
2186
+ this.#deleteDeploymentGeneration(generation);
2187
+ for (const [owner, entries] of this.#deploymentContributions) {
2188
+ for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry);
2189
+ const remaining = entries.filter((entry) => entry.generation !== generation);
2190
+ if (remaining.length) this.#deploymentContributions.set(owner, remaining);
2191
+ else this.#deploymentContributions.delete(owner);
2192
+ }
2193
+ for (const [contribution, taken] of this.#takenDeploymentContributions) {
2194
+ const invalidatedFallbacks = taken.fallbacks.filter((entry) => entry.generation === generation);
2195
+ taken.fallbacks = taken.fallbacks.filter((entry) => entry.generation !== generation);
2196
+ for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback);
2197
+ if (taken.entry.generation !== generation) continue;
2198
+ this.#takenDeploymentContributions.delete(contribution);
2199
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
2200
+ for (const fallback of taken.fallbacks) if (taken.committed) this.#queueDeploymentDiscard(fallback);
2201
+ else this.#restoreDeploymentContribution(fallback);
2202
+ }
2203
+ }
2204
+ hasDeploymentContributions() {
2205
+ return this.#deploymentContributions.size > 0;
2206
+ }
2207
+ takeDeploymentContributions() {
2208
+ const contributions = [];
2209
+ for (const [owner, entries] of this.#deploymentContributions) {
2210
+ const entry = entries.at(-1);
2211
+ contributions.push(entry.contribution);
2212
+ this.#takenDeploymentContributions.set(entry.contribution, {
2213
+ committed: false,
2214
+ entry,
2215
+ entryDiscarded: false,
2216
+ fallbacks: entries.slice(0, -1)
2217
+ });
2218
+ this.#deploymentContributions.delete(owner);
2219
+ }
2220
+ return contributions;
2221
+ }
2222
+ deploymentContributionGeneration(contribution) {
2223
+ return this.#takenDeploymentContributions.get(contribution)?.entry.generation;
2224
+ }
2225
+ commitDeploymentContributions(contributions) {
2226
+ for (const contribution of contributions) {
2227
+ const taken = this.#takenDeploymentContributions.get(contribution);
2228
+ if (taken) taken.committed = true;
2229
+ }
2230
+ }
2231
+ async prepareDeploymentContributions(contributions) {
2232
+ const discarded = this.#pendingDeploymentDiscards.splice(0);
2233
+ for (const contribution of contributions) {
2234
+ const taken = this.#takenDeploymentContributions.get(contribution);
2235
+ if (!taken || taken.entryDiscarded || !taken.entry.contribution.discard) continue;
2236
+ taken.entryDiscarded = true;
2237
+ discarded.push(Promise.resolve().then(taken.entry.contribution.discard));
2238
+ }
2239
+ const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
2240
+ if (failure) throw failure.reason;
2241
+ }
2242
+ async completeDeploymentContributions(contributions) {
2243
+ const discarded = this.#pendingDeploymentDiscards.splice(0);
2244
+ const completedGenerations = /* @__PURE__ */ new Set();
2245
+ for (const contribution of contributions) {
2246
+ const taken = this.#takenDeploymentContributions.get(contribution);
2247
+ if (!taken) continue;
2248
+ this.#takenDeploymentContributions.delete(contribution);
2249
+ const entries = taken.entryDiscarded ? taken.fallbacks : [...taken.fallbacks, taken.entry];
2250
+ for (const entry of entries) {
2251
+ if (entry.generation) completedGenerations.add(entry.generation);
2252
+ if (entry.contribution.discard) discarded.push(entry.contribution.discard());
2253
+ }
2254
+ }
2255
+ for (const generation of completedGenerations) this.#retireDeploymentGeneration(generation);
2256
+ const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
2257
+ if (failure) throw failure.reason;
2258
+ }
2259
+ rollbackDeploymentContributions(contributions) {
2260
+ for (const contribution of contributions) {
2261
+ const taken = this.#takenDeploymentContributions.get(contribution);
2262
+ if (!taken) continue;
2263
+ this.#takenDeploymentContributions.delete(contribution);
2264
+ for (const entry of [...taken.fallbacks, taken.entry]) this.#restoreDeploymentContribution(entry);
2265
+ }
2266
+ }
2267
+ #restoreDeploymentContribution(entry) {
2268
+ if (entry.generation && !entry.generation.valid) return;
2269
+ if (entry.generation) this.#trackDeploymentGeneration(entry.generation);
2270
+ const entries = this.#deploymentContributions.get(entry.contribution.owner) ?? [];
2271
+ const replaced = entries.findIndex((candidate) => candidate.generation === entry.generation);
2272
+ if (replaced >= 0) {
2273
+ if (entries[replaced].sequence > entry.sequence) return;
2274
+ entries.splice(replaced, 1);
2275
+ }
2276
+ entries.push(entry);
2277
+ entries.sort((left, right) => left.sequence - right.sequence);
2278
+ this.#deploymentContributions.set(entry.contribution.owner, entries);
2279
+ }
2280
+ #retireDeploymentGeneration(generation) {
2281
+ const pending = [...this.#deploymentContributions.values()].some((entries) => entries.some((entry) => entry.generation === generation));
2282
+ const taken = [...this.#takenDeploymentContributions.values()].some((entry) => entry.entry.generation === generation || entry.fallbacks.some((fallback) => fallback.generation === generation));
2283
+ if (!pending && !taken) this.#deleteDeploymentGeneration(generation);
2284
+ }
2285
+ #trackDeploymentGeneration(generation) {
2286
+ if (this.#deploymentGenerationRefs.has(generation)) return;
2287
+ const reference = new WeakRef(generation);
2288
+ this.#deploymentGenerationRefs.set(generation, reference);
2289
+ this.#deploymentGenerations.add(reference);
2290
+ }
2291
+ #deleteDeploymentGeneration(generation) {
2292
+ const reference = this.#deploymentGenerationRefs.get(generation);
2293
+ if (reference) this.#deploymentGenerations.delete(reference);
2294
+ this.#deploymentGenerationRefs.delete(generation);
2295
+ }
2296
+ #queueDeploymentDiscard(entry) {
2297
+ if (!entry.contribution.discard) return;
2298
+ const discard = Promise.resolve().then(entry.contribution.discard);
2299
+ discard.catch(() => {});
2300
+ this.#pendingDeploymentDiscards.push(discard);
2301
+ }
2302
+ };
2303
+ const providerOutputCatalogRegistry = globalThis;
2304
+ const providerOutputCatalogs = providerOutputCatalogRegistry.__vitehubProviderOutputCatalogs ??= /* @__PURE__ */ new WeakMap();
2305
+ const providerOutputCatalog = Symbol.for("vitehub.provider-output-catalog");
2306
+ function createProviderOutputCatalog() {
2307
+ return new ProviderOutputCatalog();
2308
+ }
2309
+ function useProviderOutputCatalog(config) {
2310
+ const owner = config;
2311
+ let catalog = owner[providerOutputCatalog] ?? providerOutputCatalogs.get(config);
2312
+ if (!catalog) catalog = createProviderOutputCatalog();
2313
+ owner[providerOutputCatalog] = catalog;
2314
+ providerOutputCatalogs.set(config, catalog);
2315
+ return catalog;
2316
+ }
2317
+ function contributeCloudflareProviderOutput(catalog, contribution) {
2318
+ const { owner, ...value } = contribution;
2319
+ catalog.replaceCloudflareContribution(owner, value);
2320
+ }
2321
+ function getProviderRuntimeModule(catalog, product, provider, generation) {
2322
+ const contribution = catalog?.runtimeContribution(product, generation);
2323
+ if (!contribution) return;
2324
+ return contribution.runtimeModules[provider];
2325
+ }
2326
+ function getVercelRuntimePackages(catalog, product, generation) {
2327
+ const contribution = catalog?.runtimeContribution(product, generation);
2328
+ return contribution?.owner === "blob" ? contribution.vercelRuntimePackages ?? [] : [];
2329
+ }
2330
+ //#endregion
2331
+ //#region ../internal/src/build/vite.ts
2332
+ function createNoExternalMerger(packageName) {
2333
+ return (current) => {
2334
+ if (current === true) return true;
2335
+ if (!current) return [packageName];
2336
+ const values = Array.isArray(current) ? current : [current];
2337
+ return values.includes(packageName) ? values : [...values, packageName];
2338
+ };
2339
+ }
2340
+ function isServerEnvironment(name, config) {
2341
+ return name === "ssr" || config.consumer === "server";
2342
+ }
2343
+ const VITEHUB_NITRO_CONFIG_CONTEXT = "__vitehubNitroConfigContext";
2344
+ function includesNitroVitePlugin(value) {
2345
+ if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
2346
+ if (!value || typeof value !== "object") return false;
2347
+ return "name" in value && value.name === "nitro:main";
2348
+ }
2349
+ function hasNitroConfigContext(config) {
2350
+ return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
2351
+ }
2352
+ function resolveNitroVercelFunctionName(config, product, env = process.env) {
2353
+ const preset = config.nitro?.preset || env.NITRO_PRESET || env.SERVER_PRESET;
2354
+ const nitro = Boolean(preset) || hasNitroConfigContext(config);
2355
+ const clientOutDir = config.environments?.client?.build?.outDir;
2356
+ const vercel = preset ? preset.startsWith("vercel") : env.VITEHUB_HOSTING === "vercel" || Boolean(env.VERCEL) || Boolean(clientOutDir && /(^|[/\\])\.vercel[/\\]output([/\\]|$)/.test(clientOutDir));
2357
+ return nitro && vercel ? `__${product}.func` : void 0;
2358
+ }
2359
+ function shouldSkipViteProviderBuild(command, mode) {
2360
+ return command === "serve" || mode === "e2e";
2361
+ }
2362
+ //#endregion
2363
+ //#region ../internal/src/build/deployment-output.ts
2364
+ const providerDeploymentOutputRegistry = globalThis;
2365
+ const providerDeploymentOutputWrites = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputWrites ??= /* @__PURE__ */ new Map();
2366
+ const providerDeploymentOutputFinalizations = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputFinalizations ??= /* @__PURE__ */ new WeakMap();
2367
+ const providerDeploymentOutputCompletedResets = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputCompletedResets ??= /* @__PURE__ */ new WeakMap();
2368
+ const providerDeploymentOutputRootStates = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputRootStates ??= /* @__PURE__ */ new Map();
2369
+ const providerDeploymentOutputOwnerOrder = [
2370
+ "agent",
2371
+ "database",
2372
+ "blob",
2373
+ "queue",
2374
+ "rate-limit",
2375
+ "schedule",
2376
+ "workflow",
2377
+ "vite-hub",
2378
+ "browser",
2379
+ "kv",
2380
+ "workspace"
2381
+ ];
2382
+ function throwIfProviderOutputAborted(signal) {
2383
+ if (!signal.aborted) return;
2384
+ throw signal.reason ?? new DOMException("Provider Output finalization aborted.", "AbortError");
2385
+ }
2386
+ async function settleWrites(writes) {
2387
+ const failure = (await Promise.allSettled(writes)).find((result) => result.status === "rejected");
2388
+ if (failure) throw failure.reason;
2389
+ }
2390
+ function resolveClientOutput(rootDir, clientOutDir) {
2391
+ const clientDir = resolve(rootDir, clientOutDir);
2392
+ return {
2393
+ clientDir,
2394
+ staticIndex: hasStaticIndex(clientDir)
2395
+ };
2396
+ }
2397
+ function createDefaultCloudflareStaticOutputDir(rootDir) {
2398
+ return resolve(rootDir, "dist", "client");
2399
+ }
2400
+ function resolveProviderOutputOwnershipFile(outputRoot, fileName) {
2401
+ if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") throw new TypeError(`Invalid Provider Output ownership file name: ${JSON.stringify(fileName)}`);
2402
+ return resolve(outputRoot, fileName);
2403
+ }
2404
+ async function readProviderOutputOwnershipFile(outputRoot, fileName) {
2405
+ try {
2406
+ const parsed = JSON.parse(await readFile(resolveProviderOutputOwnershipFile(outputRoot, fileName), "utf8"));
2407
+ if (!Array.isArray(parsed) || !parsed.every((value) => typeof value === "string")) throw new TypeError(`Invalid Provider Output ownership file schema: ${JSON.stringify(fileName)}`);
2408
+ return parsed;
2409
+ } catch (error) {
2410
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
2411
+ throw error;
2412
+ }
2413
+ }
2414
+ async function readCloudflareProviderDeploymentOutputState(rootDir, options) {
2415
+ const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
2416
+ let wranglerConfig = {};
2417
+ try {
2418
+ wranglerConfig = JSON.parse(await readFile(resolve(outputRoot, "wrangler.json"), "utf8"));
2419
+ } catch (error) {
2420
+ if (error.code !== "ENOENT") throw error;
2421
+ }
2422
+ return {
2423
+ wranglerConfig,
2424
+ wranglerConfigOwnership: await resolvePersistedProviderOutputOwnership(outputRoot, options.wranglerConfigOwnership, options.wranglerConfigOwnershipFiles)
2425
+ };
2426
+ }
2427
+ async function resolvePersistedProviderOutputOwnership(outputRoot, ownership, files) {
2428
+ if (!files || !Object.keys(files).length) return ownership;
2429
+ const arrays = { ...ownership?.arrays };
2430
+ await Promise.all(Object.entries(files).map(async ([field, fileName]) => {
2431
+ const current = arrays[field];
2432
+ if (!current) throw new TypeError(`Provider Output ownership file for ${JSON.stringify(field)} requires array ownership.`);
2433
+ arrays[field] = {
2434
+ ...current,
2435
+ values: [...await readProviderOutputOwnershipFile(outputRoot, fileName), ...current.values ?? []]
2436
+ };
2437
+ }));
2438
+ return {
2439
+ ...ownership,
2440
+ arrays
2441
+ };
2442
+ }
2443
+ async function writeProviderOutputOwnershipFiles(outputRoot, ownership, files) {
2444
+ await Promise.all(Object.entries(files ?? {}).map(async ([field, fileName]) => {
2445
+ const file = resolveProviderOutputOwnershipFile(outputRoot, fileName);
2446
+ const values = [...new Set(ownership?.arrays?.[field]?.values ?? [])];
2447
+ if (!values.length) {
2448
+ await rm(file, { force: true });
2449
+ return;
2450
+ }
2451
+ await mkdir(outputRoot, { recursive: true });
2452
+ await writeFile(file, `${JSON.stringify(values, null, 2)}\n`, "utf8");
2453
+ }));
2454
+ }
2455
+ function createDefaultVercelOutputRoot(rootDir) {
2456
+ return resolve(rootDir, ".vercel", "output");
2457
+ }
2458
+ function createDefaultNetlifyOutputRoot(rootDir) {
2459
+ return resolve(rootDir, ".netlify", "v1");
2460
+ }
2461
+ function assertNetlifyFunctionName(functionName) {
2462
+ if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Invalid Netlify function name: ${functionName}`);
2463
+ }
2464
+ function resolveNetlifyFunctionFile(functionsRoot, functionName) {
2465
+ assertNetlifyFunctionName(functionName);
2466
+ return resolve(functionsRoot, `${functionName}.mjs`);
2467
+ }
2468
+ async function appendNetlifyFunctionConfig(outfile, config) {
2469
+ if (!config) return;
2470
+ await writeFile(outfile, `${(await readFile(outfile, "utf8")).trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
2471
+ }
2472
+ async function writeCloudflareDeploymentOutput(options, signal) {
2473
+ signal?.throwIfAborted();
2474
+ const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
2475
+ const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
2476
+ const staticOutputDir = options.staticOutputDir ?? createDefaultCloudflareStaticOutputDir(options.rootDir);
2477
+ const copiesStaticOutput = Boolean(options.bundleEntry && staticIndex && resolve(clientDir) !== resolve(staticOutputDir));
2478
+ const files = Object.entries(options.files ?? {});
2479
+ const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
2480
+ if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw new Error(`Cloudflare output file conflicts with bundle outfile: ${workerOutfile}`);
2481
+ const backupRoot = copiesStaticOutput ? await mkdtemp(resolve(options.rootDir, ".vitehub-cloudflare-output-")) : void 0;
2482
+ const previousOutputRoot = backupRoot ? resolve(backupRoot, "output") : `${outputRoot}.previous`;
2483
+ const previousStaticOutputDir = backupRoot ? resolve(backupRoot, "static") : `${staticOutputDir}.previous`;
2484
+ if (!backupRoot) await rm(previousOutputRoot, {
2485
+ force: true,
2486
+ recursive: true
2487
+ });
2488
+ if (copiesStaticOutput && !backupRoot) await rm(previousStaticOutputDir, {
2489
+ force: true,
2490
+ recursive: true
2491
+ });
2492
+ let hadPreviousOutput = false;
2493
+ let hadPreviousStaticOutput = false;
2494
+ let publicationSucceeded = false;
2495
+ let publicationStarted = false;
2496
+ let outputRestorationSucceeded = false;
2497
+ let staticRestorationSucceeded = false;
2498
+ try {
2499
+ try {
2500
+ await cp(outputRoot, previousOutputRoot, { recursive: true });
2501
+ hadPreviousOutput = true;
2502
+ } catch (error) {
2503
+ if (error.code !== "ENOENT") throw error;
2504
+ }
2505
+ if (copiesStaticOutput) try {
2506
+ await cp(staticOutputDir, previousStaticOutputDir, { recursive: true });
2507
+ hadPreviousStaticOutput = true;
2508
+ } catch (error) {
2509
+ if (error.code !== "ENOENT") throw error;
2510
+ }
2511
+ publicationStarted = true;
2512
+ await mkdir(outputRoot, { recursive: true });
2513
+ const wranglerConfigOwnership = await resolvePersistedProviderOutputOwnership(outputRoot, options.wranglerConfigOwnership ?? { keys: options.wranglerConfigKeys }, options.wranglerConfigOwnershipFiles);
2514
+ const writes = [
2515
+ writeCloudflareWranglerConfig({
2516
+ outputRoot,
2517
+ rootDir: options.rootDir,
2518
+ wranglerConfig: options.wranglerConfig,
2519
+ wranglerConfigDefaults: options.wranglerConfigDefaults,
2520
+ wranglerConfigOwnership
2521
+ }),
2522
+ options.bundleEntry && staticIndex ? copyClientOutput(clientDir, staticOutputDir) : Promise.resolve(),
2523
+ ...files.map(([fileName, contents]) => writeFile(resolve(outputRoot, fileName), contents, "utf8"))
2524
+ ];
2525
+ if (options.bundleEntry && workerOutfile) {
2526
+ const stagedWorkerOutfile = `${workerOutfile}.pending`;
2527
+ writes.push((async () => {
2528
+ try {
2529
+ await rm(stagedWorkerOutfile, {
2530
+ force: true,
2531
+ recursive: true
2532
+ });
2533
+ await bundleEsmEntry(options.bundleEntry, stagedWorkerOutfile, {
2534
+ ...options.bundleOptions,
2535
+ rootDir: options.sourceRootDir ?? options.rootDir,
2536
+ signal
2537
+ });
2538
+ signal?.throwIfAborted();
2539
+ await rename(stagedWorkerOutfile, workerOutfile);
2540
+ } catch (error) {
2541
+ await rm(stagedWorkerOutfile, {
2542
+ force: true,
2543
+ recursive: true
2544
+ });
2545
+ throw error;
2546
+ }
2547
+ })());
2548
+ }
2549
+ await settleWrites(writes);
2550
+ await writeProviderOutputOwnershipFiles(outputRoot, options.wranglerConfigOwnership, options.wranglerConfigOwnershipFiles);
2551
+ signal?.throwIfAborted();
2552
+ publicationSucceeded = true;
2553
+ } catch (error) {
2554
+ if (publicationStarted) {
2555
+ await rm(outputRoot, {
2556
+ force: true,
2557
+ recursive: true
2558
+ });
2559
+ if (hadPreviousOutput) {
2560
+ await cp(previousOutputRoot, outputRoot, { recursive: true });
2561
+ outputRestorationSucceeded = true;
2562
+ }
2563
+ if (copiesStaticOutput) {
2564
+ await rm(staticOutputDir, {
2565
+ force: true,
2566
+ recursive: true
2567
+ });
2568
+ if (hadPreviousStaticOutput) {
2569
+ await cp(previousStaticOutputDir, staticOutputDir, { recursive: true });
2570
+ staticRestorationSucceeded = true;
2571
+ }
2572
+ }
2573
+ }
2574
+ throw error;
2575
+ } finally {
2576
+ if (!publicationStarted || publicationSucceeded || outputRestorationSucceeded || !hadPreviousOutput) await rm(previousOutputRoot, {
2577
+ force: true,
2578
+ recursive: true
2579
+ }).catch(() => void 0);
2580
+ if (copiesStaticOutput && (!publicationStarted || publicationSucceeded || staticRestorationSucceeded || !hadPreviousStaticOutput)) await rm(previousStaticOutputDir, {
2581
+ force: true,
2582
+ recursive: true
2583
+ }).catch(() => void 0);
2584
+ if (backupRoot) await rmdir(backupRoot).catch(() => void 0);
2585
+ }
2586
+ }
2587
+ async function copyVercelClientOutput(rootDir, clientDir, staticOutputDir) {
2588
+ const cloudflareOutputRoot = createDefaultCloudflareOutputRoot(rootDir);
2589
+ const outputRelativePath = relative(clientDir, cloudflareOutputRoot);
2590
+ const excludesCloudflareOutput = outputRelativePath && outputRelativePath !== ".." && !outputRelativePath.startsWith(`..${sep}`) && !isAbsolute(outputRelativePath);
2591
+ await copyClientOutput(clientDir, staticOutputDir);
2592
+ if (resolve(clientDir) === resolve(staticOutputDir) || !excludesCloudflareOutput) return;
2593
+ try {
2594
+ await readFile(resolve(cloudflareOutputRoot, "wrangler.json"));
2595
+ } catch (error) {
2596
+ if (error.code === "ENOENT") return;
2597
+ throw error;
2598
+ }
2599
+ await rm(resolve(staticOutputDir, outputRelativePath), {
2600
+ force: true,
2601
+ recursive: true
2602
+ });
2603
+ }
2604
+ async function writeVercelDeploymentOutput(options, signal) {
2605
+ signal?.throwIfAborted();
2606
+ const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
2607
+ const outputRoot = options.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir);
2608
+ const stagedOutputRoot = `${outputRoot}.pending`;
2609
+ const previousOutputRoot = `${outputRoot}.previous`;
2610
+ const functionOutput = options.function ?? { kind: "root" };
2611
+ const serverFunctionName = functionOutput.kind === "root" ? "__server.func" : functionOutput.name;
2612
+ const config = options.config ?? (functionOutput.kind === "root" ? createVercelConfigJson() : {});
2613
+ const serverDir = resolve(stagedOutputRoot, "functions", serverFunctionName);
2614
+ const serverEntry = resolve(serverDir, "index.mjs");
2615
+ const staticOutputDir = options.staticOutputDir ?? resolve(outputRoot, "static");
2616
+ const staticRelativePath = relative(outputRoot, staticOutputDir);
2617
+ const staticInsideOutputRoot = !staticRelativePath.startsWith(`..${sep}`) && !isAbsolute(staticRelativePath);
2618
+ const externalStaticNeedsCommit = staticIndex && !staticInsideOutputRoot && resolve(clientDir) !== resolve(staticOutputDir);
2619
+ const stagedStaticOutputDir = staticInsideOutputRoot ? resolve(stagedOutputRoot, staticRelativePath) : externalStaticNeedsCommit ? `${staticOutputDir}.pending` : staticOutputDir;
2620
+ const previousStaticOutputDir = `${staticOutputDir}.previous`;
2621
+ let replacedOutput = false;
2622
+ let installedOutput = false;
2623
+ let replacedExternalStatic = false;
2624
+ let installedExternalStatic = false;
2625
+ try {
2626
+ await rm(stagedOutputRoot, {
2627
+ force: true,
2628
+ recursive: true
2629
+ });
2630
+ try {
2631
+ await cp(outputRoot, stagedOutputRoot, { recursive: true });
2632
+ } catch (error) {
2633
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
2634
+ }
2635
+ await mkdir(serverDir, { recursive: true });
2636
+ await rm(serverDir, {
2637
+ force: true,
2638
+ recursive: true
2639
+ });
2640
+ await mkdir(serverDir, { recursive: true });
2641
+ try {
2642
+ await cp(resolve(outputRoot, "functions", serverFunctionName, "node_modules"), resolve(serverDir, "node_modules"), { recursive: true });
2643
+ } catch (error) {
2644
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
2645
+ }
2646
+ await bundleEsmEntry(options.bundleEntry, serverEntry, {
2647
+ ...options.bundleOptions,
2648
+ rootDir: options.sourceRootDir ?? options.rootDir,
2649
+ signal
2650
+ });
2651
+ await writeFile(resolve(serverDir, ".vc-config.json"), `${stringifyProviderOutputConfig(options.functionConfig ?? createNodeFunctionConfig())}\n`, "utf8");
2652
+ const failedWrite = (await Promise.allSettled([writeProviderOutputConfig(resolve(stagedOutputRoot, "config.json"), config, { keys: options.configKeys }), staticIndex ? copyVercelClientOutput(options.rootDir, clientDir, stagedStaticOutputDir) : Promise.resolve()])).find((result) => result.status === "rejected");
2653
+ if (failedWrite?.status === "rejected") throw failedWrite.reason;
2654
+ signal?.throwIfAborted();
2655
+ rmSync(previousOutputRoot, {
2656
+ force: true,
2657
+ recursive: true
2658
+ });
2659
+ if (existsSync(outputRoot)) {
2660
+ renameSync(outputRoot, previousOutputRoot);
2661
+ replacedOutput = true;
2662
+ }
2663
+ try {
2664
+ renameSync(stagedOutputRoot, outputRoot);
2665
+ installedOutput = true;
2666
+ } catch (error) {
2667
+ if (replacedOutput && existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
2668
+ replacedOutput = false;
2669
+ throw error;
2670
+ }
2671
+ signal?.throwIfAborted();
2672
+ if (externalStaticNeedsCommit) {
2673
+ rmSync(previousStaticOutputDir, {
2674
+ force: true,
2675
+ recursive: true
2676
+ });
2677
+ if (existsSync(staticOutputDir)) {
2678
+ renameSync(staticOutputDir, previousStaticOutputDir);
2679
+ replacedExternalStatic = true;
2680
+ }
2681
+ try {
2682
+ renameSync(stagedStaticOutputDir, staticOutputDir);
2683
+ installedExternalStatic = true;
2684
+ } catch (error) {
2685
+ if (replacedExternalStatic && existsSync(previousStaticOutputDir)) renameSync(previousStaticOutputDir, staticOutputDir);
2686
+ replacedExternalStatic = false;
2687
+ throw error;
2688
+ }
2689
+ signal?.throwIfAborted();
2690
+ }
2691
+ try {
2692
+ rmSync(previousOutputRoot, {
2693
+ force: true,
2694
+ recursive: true
2695
+ });
2696
+ } catch {}
2697
+ if (replacedExternalStatic) try {
2698
+ rmSync(previousStaticOutputDir, {
2699
+ force: true,
2700
+ recursive: true
2701
+ });
2702
+ } catch {}
2703
+ } catch (error) {
2704
+ await rm(stagedOutputRoot, {
2705
+ force: true,
2706
+ recursive: true
2707
+ });
2708
+ if (externalStaticNeedsCommit) await rm(stagedStaticOutputDir, {
2709
+ force: true,
2710
+ recursive: true
2711
+ });
2712
+ if (installedExternalStatic) rmSync(staticOutputDir, {
2713
+ force: true,
2714
+ recursive: true
2715
+ });
2716
+ if (replacedExternalStatic) {
2717
+ if (existsSync(previousStaticOutputDir)) renameSync(previousStaticOutputDir, staticOutputDir);
2718
+ }
2719
+ if (installedOutput) rmSync(outputRoot, {
2720
+ force: true,
2721
+ recursive: true
2722
+ });
2723
+ if (replacedOutput) {
2724
+ if (existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
2725
+ }
2726
+ throw error;
2727
+ }
2728
+ }
2729
+ async function writeNetlifyDeploymentOutput(options, signal) {
2730
+ signal?.throwIfAborted();
2731
+ const outputRoot = options.outputRoot ?? createDefaultNetlifyOutputRoot(options.rootDir);
2732
+ const stagedOutputRoot = `${outputRoot}.pending`;
2733
+ const previousOutputRoot = `${outputRoot}.previous`;
2734
+ const functionsRoot = resolve(stagedOutputRoot, "functions");
2735
+ let replacedOutput = false;
2736
+ let installedOutput = false;
2737
+ await rm(stagedOutputRoot, {
2738
+ force: true,
2739
+ recursive: true
2740
+ });
2741
+ await rm(previousOutputRoot, {
2742
+ force: true,
2743
+ recursive: true
2744
+ });
2745
+ try {
2746
+ await cp(outputRoot, stagedOutputRoot, { recursive: true });
2747
+ } catch (error) {
2748
+ if (error.code !== "ENOENT") throw error;
2749
+ }
2750
+ const functionWrites = (options.functions ?? []).map(async (func) => {
2751
+ const outfile = resolveNetlifyFunctionFile(functionsRoot, func.functionName);
2752
+ await mkdir(dirname(outfile), { recursive: true });
2753
+ await bundleEsmEntry(func.bundleEntry, outfile, {
2754
+ ...func.bundleOptions,
2755
+ minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers,
2756
+ rootDir: options.sourceRootDir ?? options.rootDir,
2757
+ signal
2758
+ });
2759
+ await appendNetlifyFunctionConfig(outfile, func.config);
2760
+ });
2761
+ try {
2762
+ await mkdir(stagedOutputRoot, { recursive: true });
2763
+ await settleWrites([writeProviderOutputConfig(resolve(stagedOutputRoot, "config.json"), options.config ?? {}, { keys: options.configKeys }), ...functionWrites]);
2764
+ signal?.throwIfAborted();
2765
+ if (existsSync(outputRoot)) {
2766
+ renameSync(outputRoot, previousOutputRoot);
2767
+ replacedOutput = true;
2768
+ }
2769
+ renameSync(stagedOutputRoot, outputRoot);
2770
+ installedOutput = true;
2771
+ signal?.throwIfAborted();
2772
+ } catch (error) {
2773
+ await rm(stagedOutputRoot, {
2774
+ force: true,
2775
+ recursive: true
2776
+ });
2777
+ if (installedOutput) rmSync(outputRoot, {
2778
+ force: true,
2779
+ recursive: true
2780
+ });
2781
+ if (replacedOutput && existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
2782
+ throw error;
2783
+ }
2784
+ try {
2785
+ rmSync(previousOutputRoot, {
2786
+ force: true,
2787
+ recursive: true
2788
+ });
2789
+ } catch {}
2790
+ }
2791
+ async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput, signal) {
2792
+ const cleanup = typeof cleanupInput === "function" ? await cleanupInput() : cleanupInput;
2793
+ signal?.throwIfAborted();
2794
+ const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
2795
+ if (!shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup)) return;
2796
+ const wranglerConfigOwnership = await resolvePersistedProviderOutputOwnership(outputRoot, cleanup.wranglerConfigOwnership, cleanup.wranglerConfigOwnershipFiles);
2797
+ const writes = (cleanup.fileNames ?? []).map((fileName) => rm(resolve(outputRoot, fileName), {
2798
+ force: true,
2799
+ recursive: true
2800
+ }));
2801
+ writes.push(writeCloudflareWranglerConfig({
2802
+ outputRoot,
2803
+ rootDir,
2804
+ wranglerConfigOwnership
2805
+ }));
2806
+ await Promise.all(writes);
2807
+ await writeProviderOutputOwnershipFiles(outputRoot, cleanup.wranglerConfigOwnership, cleanup.wranglerConfigOwnershipFiles);
2808
+ try {
2809
+ await rmdir(outputRoot);
2810
+ } catch (error) {
2811
+ const code = error.code;
2812
+ if (code !== "ENOENT" && code !== "ENOTEMPTY") throw error;
2813
+ }
2814
+ }
2815
+ function shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup) {
2816
+ return !cleanup.requirePersistedOwnership || Object.values(cleanup.wranglerConfigOwnershipFiles ?? {}).some((fileName) => existsSync(resolveProviderOutputOwnershipFile(outputRoot, fileName)));
2817
+ }
2818
+ async function cleanupVercelDeploymentOutput(rootDir, cleanup, signal) {
2819
+ signal?.throwIfAborted();
2820
+ const outputRoot = cleanup.outputRoot ?? createDefaultVercelOutputRoot(rootDir);
2821
+ const writes = [];
2822
+ if (cleanup.serverFunctionName) writes.push(rm(resolve(outputRoot, "functions", cleanup.serverFunctionName), {
2823
+ force: true,
2824
+ recursive: true
2825
+ }));
2826
+ writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
2827
+ await Promise.all(writes);
2828
+ }
2829
+ async function cleanupVercelDeploymentOutputs(rootDir, cleanup, signal) {
2830
+ await Promise.all((Array.isArray(cleanup) ? cleanup : [cleanup]).map((item) => cleanupVercelDeploymentOutput(rootDir, item, signal)));
2831
+ }
2832
+ async function cleanupNetlifyDeploymentOutput(rootDir, cleanup, signal) {
2833
+ signal?.throwIfAborted();
2834
+ const outputRoot = cleanup.outputRoot ?? createDefaultNetlifyOutputRoot(rootDir);
2835
+ const functionsRoot = resolve(outputRoot, "functions");
2836
+ const writes = (cleanup.functionNames ?? []).map((functionName) => rm(resolveNetlifyFunctionFile(functionsRoot, functionName), {
2837
+ force: true,
2838
+ recursive: true
2839
+ }));
2840
+ writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
2841
+ await Promise.all(writes);
2842
+ }
2843
+ async function writeProviderDeploymentOutputsNow(options, signal, transaction) {
2844
+ signal?.throwIfAborted();
2845
+ const clientDir = resolve(options.rootDir, options.clientOutDir);
2846
+ await transaction?.snapshot(providerDeploymentOutputPaths(options), [clientDir]);
2847
+ const writes = [];
2848
+ if (options.cloudflare) writes.push(writeCloudflareDeploymentOutput({
2849
+ ...options.cloudflare,
2850
+ clientOutDir: options.clientOutDir,
2851
+ rootDir: options.rootDir,
2852
+ sourceRootDir: options.sourceRootDir
2853
+ }, signal));
2854
+ if (options.netlify) writes.push(writeNetlifyDeploymentOutput({
2855
+ ...options.netlify,
2856
+ clientOutDir: options.clientOutDir,
2857
+ rootDir: options.rootDir,
2858
+ sourceRootDir: options.sourceRootDir
2859
+ }, signal));
2860
+ if (options.vercel) writes.push(writeVercelDeploymentOutput({
2861
+ ...options.vercel,
2862
+ clientOutDir: options.clientOutDir,
2863
+ rootDir: options.rootDir,
2864
+ sourceRootDir: options.sourceRootDir
2865
+ }, signal));
2866
+ await settleWrites(writes);
2867
+ if (options.cloudflare && transaction) transaction.cloudflareWritten = true;
2868
+ signal?.throwIfAborted();
2869
+ await options.afterWrite?.(signal);
2870
+ signal?.throwIfAborted();
2871
+ const cleanups = [];
2872
+ const cleanupPaths = [];
2873
+ if (!options.cloudflare && options.cleanup?.cloudflare) {
2874
+ let cleanup = typeof options.cleanup.cloudflare === "function" ? await options.cleanup.cloudflare() : options.cleanup.cloudflare;
2875
+ const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
2876
+ if (resolve(outputRoot) === clientDir) cleanup = {
2877
+ ...cleanup,
2878
+ fileNames: []
2879
+ };
2880
+ else if (transaction?.cloudflareWritten) cleanup = {
2881
+ ...cleanup,
2882
+ fileNames: []
2883
+ };
2884
+ if (shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup)) {
2885
+ cleanupPaths.push(outputRoot);
2886
+ cleanups.push(async () => await cleanupCloudflareDeploymentOutput(options.rootDir, cleanup, signal));
2887
+ }
2888
+ }
2889
+ if (!options.netlify && options.cleanup?.netlify) {
2890
+ const cleanup = options.cleanup.netlify;
2891
+ cleanupPaths.push(cleanup.outputRoot ?? createDefaultNetlifyOutputRoot(options.rootDir));
2892
+ cleanups.push(async () => await cleanupNetlifyDeploymentOutput(options.rootDir, cleanup, signal));
2893
+ }
2894
+ if (!options.vercel && options.cleanup?.vercel) {
2895
+ const cleanup = typeof options.cleanup.vercel === "function" ? await options.cleanup.vercel() : options.cleanup.vercel;
2896
+ signal?.throwIfAborted();
2897
+ if (cleanup) {
2898
+ const items = Array.isArray(cleanup) ? cleanup : [cleanup];
2899
+ cleanupPaths.push(...items.map((item) => item.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir)));
2900
+ cleanups.push(async () => await cleanupVercelDeploymentOutputs(options.rootDir, cleanup, signal));
2901
+ }
2902
+ }
2903
+ await transaction?.snapshot(cleanupPaths, [clientDir]);
2904
+ await settleWrites(cleanups.map((cleanup) => cleanup()));
2905
+ signal?.throwIfAborted();
2906
+ }
2907
+ function providerDeploymentOutputPaths(options) {
2908
+ const clientDir = resolve(options.rootDir, options.clientOutDir);
2909
+ return [
2910
+ options.cloudflare && (options.cloudflare.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir)),
2911
+ options.cloudflare?.staticOutputDir,
2912
+ options.netlify?.outputRoot,
2913
+ options.vercel?.outputRoot,
2914
+ options.vercel?.staticOutputDir
2915
+ ].filter((path) => Boolean(path) && resolve(path) !== clientDir);
2916
+ }
2917
+ async function withProviderDeploymentOutputRootLock(rootDir, operation) {
2918
+ const key = resolve(rootDir);
2919
+ const state = providerDeploymentOutputRootStates.get(key) ?? { pending: 0 };
2920
+ providerDeploymentOutputRootStates.set(key, state);
2921
+ state.pending++;
2922
+ const current = (providerDeploymentOutputWrites.get(key) ?? Promise.resolve()).catch(() => void 0).then(async () => await operation(state));
2923
+ providerDeploymentOutputWrites.set(key, current);
2924
+ try {
2925
+ return await current;
2926
+ } finally {
2927
+ if (providerDeploymentOutputWrites.get(key) === current) providerDeploymentOutputWrites.delete(key);
2928
+ state.pending--;
2929
+ if (state.pending === 0 && providerDeploymentOutputRootStates.get(key) === state) providerDeploymentOutputRootStates.delete(key);
2930
+ }
2931
+ }
2932
+ function pathContains(parent, child) {
2933
+ const nested = relative(parent, child);
2934
+ return !nested || !nested.startsWith(`..${sep}`) && nested !== ".." && !isAbsolute(nested);
2935
+ }
2936
+ async function restoreProviderDeploymentOutputSnapshot(snapshot) {
2937
+ if (snapshot.present) await mkdir(dirname(snapshot.path), { recursive: true });
2938
+ const restoreRoot = await mkdtemp(resolve(snapshot.present ? dirname(snapshot.path) : tmpdir(), "vitehub-provider-output-restore-"));
2939
+ const staged = resolve(restoreRoot, "snapshot");
2940
+ const preservedRoot = resolve(restoreRoot, "preserved");
2941
+ try {
2942
+ await mkdir(preservedRoot, { recursive: true });
2943
+ const preserved = snapshot.preservedPaths.map((path, index) => ({
2944
+ backup: resolve(preservedRoot, String(index)),
2945
+ path,
2946
+ present: existsSync(path)
2947
+ }));
2948
+ await Promise.all(preserved.map(async (entry) => {
2949
+ if (entry.present) await cp(entry.path, entry.backup, { recursive: true });
2950
+ }));
2951
+ if (snapshot.present) await cp(snapshot.backup, staged, { recursive: true });
2952
+ await rm(snapshot.path, {
2953
+ force: true,
2954
+ recursive: true
2955
+ });
2956
+ if (snapshot.present) await rename(staged, snapshot.path);
2957
+ for (const entry of preserved) {
2958
+ await rm(entry.path, {
2959
+ force: true,
2960
+ recursive: true
2961
+ });
2962
+ if (entry.present) {
2963
+ await mkdir(dirname(entry.path), { recursive: true });
2964
+ await cp(entry.backup, entry.path, { recursive: true });
2965
+ }
2966
+ }
2967
+ } finally {
2968
+ await rm(restoreRoot, {
2969
+ force: true,
2970
+ recursive: true
2971
+ });
2972
+ }
2973
+ }
2974
+ async function withProviderDeploymentOutputRootTransaction(rootDir, operation, options = {}) {
2975
+ const roots = [
2976
+ createDefaultCloudflareOutputRoot(rootDir),
2977
+ createDefaultNetlifyOutputRoot(rootDir),
2978
+ createDefaultVercelOutputRoot(rootDir),
2979
+ resolve(rootDir, ".vitehub/agent"),
2980
+ resolve(rootDir, ".vitehub/blob/cloudflare-output.json"),
2981
+ resolve(rootDir, ".vitehub/queue/cloudflare-output.json"),
2982
+ resolve(rootDir, ".vitehub/queue/registry.mjs"),
2983
+ resolve(rootDir, ".vitehub/queue/vercel-output.json"),
2984
+ resolve(rootDir, ".vitehub/rate-limit/cloudflare-output.json"),
2985
+ resolve(rootDir, ".vitehub/rate-limit/manifest.json"),
2986
+ resolve(rootDir, ".vitehub/schedule"),
2987
+ resolve(rootDir, ".vitehub/workflow")
2988
+ ];
2989
+ const transactionRoot = await mkdtemp(resolve(tmpdir(), "vitehub-provider-output-"));
2990
+ const snapshots = /* @__PURE__ */ new Map();
2991
+ let snapshotIndex = 0;
2992
+ const transaction = {
2993
+ cloudflareWritten: false,
2994
+ async snapshot(paths, preservedPaths = []) {
2995
+ const resolvedPreservedPaths = [...new Set(preservedPaths.map((path) => resolve(path)))];
2996
+ for (const snapshot of snapshots.values()) {
2997
+ const additions = resolvedPreservedPaths.filter((path) => path !== snapshot.path && pathContains(snapshot.path, path) && !snapshot.preservedPaths.includes(path));
2998
+ snapshot.preservedPaths.push(...additions);
2999
+ if (snapshot.present) await Promise.all(additions.map((path) => rm(resolve(snapshot.backup, relative(snapshot.path, path)), {
3000
+ force: true,
3001
+ recursive: true
3002
+ })));
3003
+ }
3004
+ const pending = [...new Set(paths.map((path) => resolve(path)))].sort((left, right) => left.length - right.length).filter((path, index, all) => !all.slice(0, index).some((parent) => pathContains(parent, path))).filter((path) => ![...snapshots.keys()].some((parent) => pathContains(parent, path))).map((path) => ({
3005
+ backup: resolve(transactionRoot, String(snapshotIndex++)),
3006
+ path,
3007
+ present: existsSync(path),
3008
+ preservedPaths: resolvedPreservedPaths.filter((preserved) => preserved !== path && pathContains(path, preserved))
3009
+ }));
3010
+ const failure = (await Promise.allSettled(pending.map(async (snapshot) => {
3011
+ if (snapshot.present) {
3012
+ await cp(snapshot.path, snapshot.backup, { recursive: true });
3013
+ await Promise.all(snapshot.preservedPaths.map((path) => rm(resolve(snapshot.backup, relative(snapshot.path, path)), {
3014
+ force: true,
3015
+ recursive: true
3016
+ })));
3017
+ }
3018
+ }))).find((result) => result.status === "rejected");
3019
+ if (failure) {
3020
+ await Promise.all(pending.map((snapshot) => rm(snapshot.backup, {
3021
+ force: true,
3022
+ recursive: true
3023
+ })));
3024
+ throw failure.reason;
3025
+ }
3026
+ for (const snapshot of pending) {
3027
+ const children = [...snapshots.values()].filter((child) => pathContains(snapshot.path, child.path));
3028
+ if (snapshot.present) for (const child of children) {
3029
+ const nestedBackup = resolve(snapshot.backup, relative(snapshot.path, child.path));
3030
+ await rm(nestedBackup, {
3031
+ force: true,
3032
+ recursive: true
3033
+ });
3034
+ if (child.present) {
3035
+ await mkdir(dirname(nestedBackup), { recursive: true });
3036
+ await cp(child.backup, nestedBackup, { recursive: true });
3037
+ }
3038
+ }
3039
+ for (const child of children) {
3040
+ snapshots.delete(child.path);
3041
+ await rm(child.backup, {
3042
+ force: true,
3043
+ recursive: true
3044
+ });
3045
+ }
3046
+ snapshot.preservedPaths.push(...children.flatMap((child) => child.preservedPaths).filter((path) => !snapshot.preservedPaths.includes(path)));
3047
+ if (snapshot.present) await Promise.all(snapshot.preservedPaths.map((path) => rm(resolve(snapshot.backup, relative(snapshot.path, path)), {
3048
+ force: true,
3049
+ recursive: true
3050
+ })));
3051
+ snapshots.set(snapshot.path, snapshot);
3052
+ }
3053
+ }
3054
+ };
3055
+ try {
3056
+ if (options.snapshotInitialRoots !== false) await transaction.snapshot(roots);
3057
+ const result = await operation(transaction);
3058
+ await removeProviderOutputArtifactDir(transactionRoot).catch(() => void 0);
3059
+ return result;
3060
+ } catch (error) {
3061
+ const restorations = await Promise.allSettled([...snapshots.values()].map(restoreProviderDeploymentOutputSnapshot));
3062
+ if (restorations.every((result) => result.status === "fulfilled")) await rm(transactionRoot, {
3063
+ force: true,
3064
+ recursive: true
3065
+ });
3066
+ const restorationFailure = restorations.find((result) => result.status === "rejected");
3067
+ if (restorationFailure) throw new AggregateError([error, restorationFailure.reason], "Provider Output rollback failed");
3068
+ throw error;
3069
+ }
3070
+ }
3071
+ function contributeProviderDeploymentOutput(catalog, contribution, generation) {
3072
+ closeProviderDeploymentOutputGenerationCapture(generation);
3073
+ catalog?.replaceDeploymentContribution(contribution, generation);
3074
+ }
3075
+ const providerDeploymentOutputEnvironmentGenerations = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputEnvironmentGenerations ??= /* @__PURE__ */ new WeakMap();
3076
+ const providerDeploymentOutputGenerationEnvironments = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputGenerationEnvironments ??= /* @__PURE__ */ new WeakMap();
3077
+ const providerDeploymentOutputFallbackEnvironment = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputFallbackEnvironment ??= {};
3078
+ function closeProviderDeploymentOutputGenerationCapture(generation) {
3079
+ if (!generation) return;
3080
+ const captured = providerDeploymentOutputGenerationEnvironments.get(generation);
3081
+ if (!captured) return;
3082
+ const generations = providerDeploymentOutputEnvironmentGenerations.get(captured.catalog);
3083
+ if (generations?.get(captured.environment) === generation) generations.delete(captured.environment);
3084
+ providerDeploymentOutputGenerationEnvironments.delete(generation);
3085
+ }
3086
+ function createProviderDeploymentOutputGenerationState() {
3087
+ const generations = /* @__PURE__ */ new WeakMap();
3088
+ const readiness = /* @__PURE__ */ new WeakMap();
3089
+ const localEnvironment = (context) => context?.environment ?? context ?? providerDeploymentOutputFallbackEnvironment;
3090
+ const sharedEnvironment = (context) => context?.environment ?? providerDeploymentOutputFallbackEnvironment;
3091
+ return {
3092
+ capture(context, catalog) {
3093
+ const localEnvironmentKey = localEnvironment(context);
3094
+ readiness.delete(localEnvironmentKey);
3095
+ if (!catalog) {
3096
+ generations.set(localEnvironmentKey, void 0);
3097
+ return;
3098
+ }
3099
+ const environmentKey = sharedEnvironment(context);
3100
+ let catalogGenerations = providerDeploymentOutputEnvironmentGenerations.get(catalog);
3101
+ if (!catalogGenerations) {
3102
+ catalogGenerations = /* @__PURE__ */ new WeakMap();
3103
+ providerDeploymentOutputEnvironmentGenerations.set(catalog, catalogGenerations);
3104
+ }
3105
+ const sharedGeneration = catalogGenerations.get(environmentKey);
3106
+ const generation = !sharedGeneration || generations.get(localEnvironmentKey) === sharedGeneration ? catalog.createDeploymentGeneration() : sharedGeneration;
3107
+ catalogGenerations.set(environmentKey, generation);
3108
+ providerDeploymentOutputGenerationEnvironments.set(generation, {
3109
+ catalog,
3110
+ environment: environmentKey
3111
+ });
3112
+ generations.set(localEnvironmentKey, generation);
3113
+ },
3114
+ defer(context, catalog, contribution) {
3115
+ const localEnvironmentKey = localEnvironment(context);
3116
+ const state = { ready: false };
3117
+ readiness.set(localEnvironmentKey, state);
3118
+ contributeProviderDeploymentOutput(catalog, {
3119
+ ...contribution,
3120
+ ready: () => state.ready
3121
+ }, generations.get(localEnvironmentKey));
3122
+ },
3123
+ get(context) {
3124
+ return generations.get(localEnvironment(context));
3125
+ },
3126
+ ready(context) {
3127
+ const state = readiness.get(localEnvironment(context));
3128
+ if (state) state.ready = true;
3129
+ },
3130
+ async reset(context, catalog, failure) {
3131
+ const localEnvironmentKey = localEnvironment(context);
3132
+ const generation = generations.get(localEnvironmentKey);
3133
+ readiness.delete(localEnvironmentKey);
3134
+ closeProviderDeploymentOutputGenerationCapture(generation);
3135
+ await resetProviderDeploymentOutputs(catalog, failure, generation);
3136
+ }
3137
+ };
3138
+ }
3139
+ async function resetProviderDeploymentOutputs(catalog, failure, generation) {
3140
+ if (!catalog) return;
3141
+ const completedReset = providerDeploymentOutputCompletedResets.get(catalog);
3142
+ if (completedReset && failure !== void 0 && completedReset.failures.has(failure)) {
3143
+ if (generation) catalog.resetDeploymentContributions(generation);
3144
+ await completedReset.promise;
3145
+ return;
3146
+ }
3147
+ if (completedReset) providerDeploymentOutputCompletedResets.delete(catalog);
3148
+ if (generation) catalog.resetDeploymentContributions(generation);
3149
+ const active = providerDeploymentOutputFinalizations.get(catalog);
3150
+ if (active?.reset) {
3151
+ if (failure !== void 0 && !active.reset.failures.has(failure)) {
3152
+ active.reset.failures.add(failure);
3153
+ if (!generation) catalog.resetDeploymentContributions();
3154
+ }
3155
+ providerDeploymentOutputCompletedResets.set(catalog, active.reset);
3156
+ await active.reset.promise;
3157
+ return;
3158
+ }
3159
+ if (!generation) catalog.resetDeploymentContributions();
3160
+ if (active && (!generation || active.state.generations.has(generation))) {
3161
+ active.state.rollback = true;
3162
+ active.controller.abort(/* @__PURE__ */ new Error("Provider Output finalization reset"));
3163
+ active.reset = {
3164
+ failures: new Set([failure]),
3165
+ promise: active.promise.catch(() => void 0)
3166
+ };
3167
+ providerDeploymentOutputCompletedResets.set(catalog, active.reset);
3168
+ await active.reset.promise;
3169
+ } else if (failure !== void 0) providerDeploymentOutputCompletedResets.set(catalog, {
3170
+ failures: new Set([failure]),
3171
+ promise: Promise.resolve()
3172
+ });
3173
+ }
3174
+ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
3175
+ if (!catalog) return;
3176
+ const existing = providerDeploymentOutputFinalizations.get(catalog);
3177
+ if (existing) {
3178
+ try {
3179
+ await existing.promise;
3180
+ } catch (error) {
3181
+ if (!catalog.hasDeploymentContributions()) throw error;
3182
+ existing.handoff ??= (async () => {
3183
+ await existing.promise.catch(() => void 0);
3184
+ if (providerDeploymentOutputFinalizations.get(catalog) === existing) providerDeploymentOutputFinalizations.delete(catalog);
3185
+ await finalizeProviderDeploymentOutputs(catalog, options);
3186
+ })();
3187
+ await existing.handoff;
3188
+ return;
3189
+ }
3190
+ if (providerDeploymentOutputFinalizations.get(catalog) === existing) providerDeploymentOutputFinalizations.delete(catalog);
3191
+ if (catalog.hasDeploymentContributions()) await finalizeProviderDeploymentOutputs(catalog, options);
3192
+ return;
3193
+ }
3194
+ const controller = new AbortController();
3195
+ const state = {
3196
+ generations: /* @__PURE__ */ new Set(),
3197
+ rollback: false
3198
+ };
3199
+ const finalization = (async () => {
3200
+ const order = new Map(providerDeploymentOutputOwnerOrder.map((owner, index) => [owner, index]));
3201
+ const abort = () => controller.abort(options.signal?.reason);
3202
+ if (options.signal?.aborted) abort();
3203
+ else options.signal?.addEventListener("abort", abort, { once: true });
3204
+ try {
3205
+ while (true) {
3206
+ const contributions = catalog.takeDeploymentContributions();
3207
+ if (!contributions.length) return;
3208
+ try {
3209
+ if (contributions.some((contribution) => contribution.ready?.() === false)) {
3210
+ if (controller.signal.aborted) {
3211
+ await catalog.completeDeploymentContributions(contributions);
3212
+ throwIfProviderOutputAborted(controller.signal);
3213
+ }
3214
+ catalog.rollbackDeploymentContributions(contributions);
3215
+ return;
3216
+ }
3217
+ } catch (error) {
3218
+ catalog.rollbackDeploymentContributions(contributions);
3219
+ throw error;
3220
+ }
3221
+ for (const contribution of contributions) {
3222
+ const generation = catalog.deploymentContributionGeneration(contribution);
3223
+ if (generation) state.generations.add(generation);
3224
+ }
3225
+ contributions.sort((left, right) => order.get(left.owner) - order.get(right.owner));
3226
+ const grouped = /* @__PURE__ */ new Map();
3227
+ for (const contribution of contributions) {
3228
+ const rootDir = resolve(contribution.rootDir);
3229
+ const rootContributions = grouped.get(rootDir) ?? [];
3230
+ rootContributions.push(contribution);
3231
+ grouped.set(rootDir, rootContributions);
3232
+ }
3233
+ try {
3234
+ let decideRoots;
3235
+ const rootDecision = new Promise((resolve) => {
3236
+ decideRoots = resolve;
3237
+ });
3238
+ const roots = [...grouped.entries()].map(([rootDir, rootContributions]) => {
3239
+ let ready;
3240
+ let rejectReady;
3241
+ const readiness = new Promise((resolve, reject) => {
3242
+ ready = resolve;
3243
+ rejectReady = reject;
3244
+ });
3245
+ const write = withProviderDeploymentOutputRootLock(rootDir, async () => {
3246
+ await withProviderDeploymentOutputRootTransaction(rootDir, async (transaction) => {
3247
+ try {
3248
+ for (const contribution of rootContributions) {
3249
+ throwIfProviderOutputAborted(controller.signal);
3250
+ await contribution.write({
3251
+ readCloudflareState: async (options) => await readCloudflareProviderDeploymentOutputState(rootDir, options),
3252
+ signal: controller.signal,
3253
+ write: async (writeOptions) => {
3254
+ throwIfProviderOutputAborted(controller.signal);
3255
+ await writeProviderDeploymentOutputsNow(writeOptions, controller.signal, transaction);
3256
+ }
3257
+ });
3258
+ throwIfProviderOutputAborted(controller.signal);
3259
+ }
3260
+ ready();
3261
+ const rollback = await rootDecision;
3262
+ if (rollback !== void 0) throw rollback;
3263
+ throwIfProviderOutputAborted(controller.signal);
3264
+ } catch (error) {
3265
+ controller.abort(error);
3266
+ rejectReady(error);
3267
+ throw error;
3268
+ }
3269
+ }, { snapshotInitialRoots: rootContributions.some((contribution) => contribution.owner !== "kv") });
3270
+ });
3271
+ write.catch(rejectReady);
3272
+ return {
3273
+ readiness,
3274
+ write
3275
+ };
3276
+ });
3277
+ const failedRoot = (await Promise.allSettled(roots.map((root) => root.readiness))).find((result) => result.status === "rejected");
3278
+ if (failedRoot) {
3279
+ decideRoots(failedRoot.reason);
3280
+ await settleWrites(roots.map((root) => root.write));
3281
+ }
3282
+ try {
3283
+ await catalog.prepareDeploymentContributions(contributions);
3284
+ throwIfProviderOutputAborted(controller.signal);
3285
+ } catch (error) {
3286
+ decideRoots(error);
3287
+ await settleWrites(roots.map((root) => root.write));
3288
+ throw error;
3289
+ }
3290
+ catalog.commitDeploymentContributions(contributions);
3291
+ state.generations.clear();
3292
+ decideRoots(void 0);
3293
+ await settleWrites(roots.map((root) => root.write));
3294
+ await catalog.completeDeploymentContributions(contributions);
3295
+ } catch (error) {
3296
+ if (state.rollback) catalog.rollbackDeploymentContributions(contributions);
3297
+ else await catalog.completeDeploymentContributions(contributions);
3298
+ throw error;
3299
+ } finally {
3300
+ state.generations.clear();
3301
+ }
3302
+ }
3303
+ } finally {
3304
+ options.signal?.removeEventListener("abort", abort);
3305
+ }
3306
+ })();
3307
+ const active = {
3308
+ controller,
3309
+ promise: finalization,
3310
+ state
3311
+ };
3312
+ providerDeploymentOutputFinalizations.set(catalog, active);
3313
+ try {
3314
+ await finalization;
3315
+ } finally {
3316
+ if (providerDeploymentOutputFinalizations.get(catalog) === active) providerDeploymentOutputFinalizations.delete(catalog);
3317
+ }
3318
+ }
3319
+ async function withProviderDeploymentOutputLock(rootDir, operation) {
3320
+ return await withProviderDeploymentOutputRootLock(rootDir, async () => await withProviderDeploymentOutputRootTransaction(rootDir, async (transaction) => await operation(async (options) => await writeProviderDeploymentOutputsNow(options, void 0, transaction))));
3321
+ }
3322
+ async function writeProviderDeploymentOutputs(options) {
3323
+ await withProviderDeploymentOutputLock(options.rootDir, async (write) => await write(options));
3324
+ }
3325
+ //#endregion
3326
+ //#region ../internal/src/definition-catalog.ts
3327
+ const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
3328
+ const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
3329
+ const ignoredDirs = new Set([
3330
+ "node_modules",
3331
+ "dist",
3332
+ ".output",
3333
+ ".nuxt",
3334
+ ".vercel",
3335
+ ".git",
3336
+ ".vitehub"
3337
+ ]);
3338
+ function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
3339
+ return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
3340
+ }
3341
+ function createDirectoryDefinitionSource(source, scanDirs, subdir, options = {}) {
3342
+ return {
3343
+ ...options,
3344
+ kind: "directory",
3345
+ scanDirs,
3346
+ source,
3347
+ subdir
3348
+ };
3349
+ }
3350
+ function createSuffixDefinitionSource(source, roots, pattern, normalizeName, options = {}) {
3351
+ return {
3352
+ ...options,
3353
+ kind: "suffix",
3354
+ normalizeName,
3355
+ pattern,
3356
+ roots,
3357
+ source
3358
+ };
3359
+ }
3360
+ function readDirEntries(root) {
3361
+ try {
3362
+ return readdirSync(root, { withFileTypes: true });
3363
+ } catch (error) {
3364
+ if (error.code === "ENOENT") return [];
3365
+ throw error;
3366
+ }
3367
+ }
3368
+ function isGitRepositoryDirectory(directory) {
3369
+ return existsSync(resolve$1(directory, ".git"));
3370
+ }
3371
+ function listMatchingFiles(root, predicate, options = {}) {
3372
+ const files = [];
3373
+ for (const entry of readDirEntries(root)) {
3374
+ const absolute = resolve$1(root, entry.name);
3375
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
3376
+ if (isGitRepositoryDirectory(absolute)) continue;
3377
+ if (entry.name.startsWith(".")) continue;
3378
+ if (ignoredDirs.has(entry.name)) continue;
3379
+ files.push(...listMatchingFiles(absolute, predicate, options));
3380
+ continue;
3381
+ }
3382
+ if (entry.name.startsWith(".") && !options.includeHidden) continue;
3383
+ if (entry.isFile() && predicate(entry.name)) files.push(absolute);
3384
+ }
3385
+ return files.sort();
3386
+ }
3387
+ function listSourceFiles(root, options = {}) {
3388
+ return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
3389
+ }
3390
+ function normalizePathDefinitionName(rootDir, file) {
3391
+ return relative$1(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
3392
+ }
3393
+ function normalizeSuffixDefinitionName(rootDir, file, pattern, options = {}) {
3394
+ const normalized = relative$1(rootDir, file).replace(pattern, "");
3395
+ if (options.stripPrefix && normalized.startsWith(options.stripPrefix)) return normalized.slice(options.stripPrefix.length);
3396
+ return normalized;
3397
+ }
3398
+ function sortDefinitions(definitions) {
3399
+ return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
3400
+ }
3401
+ function registerDefinition(definitions, definition, sourceLabel) {
3402
+ const existing = definitions.get(definition.name);
3403
+ if (existing) throw new Error(`Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}`);
3404
+ definitions.set(definition.name, definition);
3405
+ }
3406
+ function mergeDefinitions(feature, ...sources) {
3407
+ const definitions = /* @__PURE__ */ new Map();
3408
+ for (const source of sources) {
3409
+ if (!source) continue;
3410
+ for (const definition of source) {
3411
+ const existing = definitions.get(definition.name);
3412
+ if (existing && existing.handler !== definition.handler) throw new Error(`Duplicate ${feature} name "${definition.name}" from multiple discovery sources:\n - ${existing.handler} (${existing.source ?? "unknown"})\n - ${definition.handler} (${definition.source ?? "unknown"})`);
3413
+ if (!existing) definitions.set(definition.name, definition);
3414
+ }
3415
+ }
3416
+ return sortDefinitions(definitions);
3417
+ }
3418
+ function createDefinition(source, file, name) {
3419
+ if (source.createDefinition) return source.createDefinition({
3420
+ file,
3421
+ name
3422
+ });
3423
+ return {
3424
+ handler: file,
3425
+ name,
3426
+ source: source.source
3427
+ };
3428
+ }
3429
+ function scanSuffixDefinitions(feature, source) {
3430
+ const definitions = /* @__PURE__ */ new Map();
3431
+ for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => source.pattern.test(name), { includeHidden: source.includeHidden })) {
3432
+ const name = source.normalizeName(root, file);
3433
+ if (!name) continue;
3434
+ registerDefinition(definitions, createDefinition(source, file, name), feature);
3435
+ }
3436
+ return sortDefinitions(definitions);
3437
+ }
3438
+ function scanDirectoryDefinitions(feature, source) {
3439
+ const definitions = /* @__PURE__ */ new Map();
3440
+ for (const scanDir of source.scanDirs) {
3441
+ const directory = resolve$1(scanDir, source.subdir);
3442
+ for (const file of listSourceFiles(directory, { includeHidden: source.includeHidden })) {
3443
+ const name = source.normalizeName ? source.normalizeName(directory, file) : normalizePathDefinitionName(directory, file);
3444
+ if (!name) continue;
3445
+ registerDefinition(definitions, createDefinition(source, file, name), feature);
3446
+ }
3447
+ }
3448
+ return sortDefinitions(definitions);
3449
+ }
3450
+ function discoverDefinitions(feature, sources) {
3451
+ return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
3452
+ }
3453
+ function createImportExpression(registryFile, file) {
3454
+ const importPath = relative$1(resolve$1(registryFile, ".."), file);
3455
+ return `import(${JSON.stringify(importPath.startsWith(".") ? importPath : `./${importPath}`)})`;
3456
+ }
3457
+ function createRuntimeRegistryContents(registryFile, definitions) {
3458
+ return [
3459
+ "",
3460
+ "const registry = {",
3461
+ ...definitions.map((definition) => ` ${JSON.stringify(definition.name)}: async () => ${createImportExpression(registryFile, definition.handler)},`),
3462
+ "}",
3463
+ "",
3464
+ "export default registry",
3465
+ ""
3466
+ ].join("\n");
3467
+ }
3468
+ //#endregion
3469
+ //#region src/discovery.ts
3470
+ const queueSuffixPattern = /\.queue\.(?:c|m)?[jt]s$/i;
3471
+ function normalizeSuffixQueueName(rootDir, file) {
3472
+ return normalizeSuffixDefinitionName(rootDir, file, queueSuffixPattern, { stripPrefix: "src/" });
3473
+ }
3474
+ function discoverQueueDefinitions(options) {
3475
+ if (options.mode === "server-queues") return discoverDefinitions("queue", [createDirectoryDefinitionSource("server-queues", options.scanDirs, "queues")]);
3476
+ const roots = resolveDefinitionScanRoots(options.rootDir, options.scanDirs);
3477
+ const serverScanDirs = options.serverDirs || [...new Set(options.serverRootDirs || roots)].map((root) => resolve$1(root, "server"));
3478
+ return mergeDefinitions("queue", discoverDefinitions("queue", [createSuffixDefinitionSource("vite-suffix", roots, queueSuffixPattern, normalizeSuffixQueueName)]), discoverDefinitions("queue", [createDirectoryDefinitionSource("server-queues", serverScanDirs, "queues")]));
3479
+ }
3480
+ //#endregion
3481
+ //#region src/internal/vite-build.ts
3482
+ const queuePackageName = "@vite-hub/queue";
3483
+ const cloudflareQueueWorkerMarker = "vitehub-queue-worker";
3484
+ const cloudflareQueueOutputState = ".vitehub/queue/cloudflare-output.json";
3485
+ const vercelQueueOutputState = ".vitehub/queue/vercel-output.json";
3486
+ const vercelQueueFunctionMarker = ".vitehub-queue-output.json";
3487
+ const productName = "queue";
3488
+ const generatedRegistryFileName = "registry.mjs";
3489
+ const generatedQueueNitroPlugin = ".vitehub/nitro/queue/plugin.ts";
3490
+ const generatedQueueNitroMiddleware = ".vitehub/nitro/queue/middleware.ts";
3491
+ const packageDir = computePackageDir(import.meta.url);
3492
+ const packageRequire = createRequire(resolve(packageDir, "package.json"));
3493
+ const resolvePackageDependency = (specifier) => packageRequire.resolve(specifier);
3494
+ const resolveRuntimeModule = (modulePath) => resolveRuntimeModule$1(packageDir, modulePath);
3495
+ const providerEntrySpecs = [{
3496
+ name: "cloudflare",
3497
+ entryFile: "cloudflare-worker.mjs",
3498
+ runtimeModule: "internal/runtime/cloudflare-vite",
3499
+ factory: "createQueueCloudflareWorker",
3500
+ hosting: "cloudflare"
3501
+ }, {
3502
+ name: "vercel",
3503
+ entryFile: "vercel-server.mjs",
3504
+ runtimeModule: "internal/runtime/vercel-vite",
3505
+ factory: "createQueueVercelServer",
3506
+ hosting: "vercel"
3507
+ }];
3508
+ function isVercelQueueEnabled(queueConfig) {
3509
+ return queueConfig !== false && queueConfig.provider === "vercel";
3510
+ }
3511
+ function resolveOutputQueueConfig(queue, hosting) {
3512
+ if (typeof queue === "undefined") return false;
3513
+ return normalizeQueueOptions(queue, { hosting }) || false;
3514
+ }
3515
+ function shouldWriteProviderEntry(spec, queue) {
3516
+ const queueConfig = resolveOutputQueueConfig(queue, spec.hosting);
3517
+ return queueConfig === false ? spec.name === "vercel" : queueConfig.provider === spec.name;
3518
+ }
3519
+ function shouldCreateVercelOutput(queue) {
3520
+ const queueConfig = resolveOutputQueueConfig(queue, "vercel");
3521
+ return queueConfig === false || queueConfig.provider === "vercel";
3522
+ }
3523
+ function renderProviderEntry(spec, entryFile, registryFile, userAppEntry, queueConfig, preloadVercelQueue = false, queueDefinitions) {
3524
+ const vercelRuntime = spec.name === "vercel" && queueConfig !== false && queueConfig.provider === "vercel";
3525
+ const imports = [`import { ${spec.factory} } from ${JSON.stringify(createImportPath(entryFile, resolveRuntimeModule(spec.runtimeModule)))}`, `import queueRegistry from ${JSON.stringify(`./${generatedRegistryFileName}`)}`];
3526
+ if (vercelRuntime) imports.push(`import { createVercelQueueRuntimeClient } from ${JSON.stringify(createImportPath(entryFile, resolveRuntimeModule("internal/runtime/vercel-client")))}`);
3527
+ if (preloadVercelQueue) imports.unshift(`import * as __vitehubVercelQueue from ${JSON.stringify(createImportPath(entryFile, resolvePackageDependency("@vercel/queue")))}`);
3528
+ if (userAppEntry) imports.push(`import queueApp from ${JSON.stringify(createImportPath(entryFile, userAppEntry))}`);
3529
+ return [
3530
+ ...imports,
3531
+ preloadVercelQueue ? "globalThis.__vitehubVercelQueue = __vitehubVercelQueue" : "",
3532
+ "",
3533
+ `const queueConfig = ${JSON.stringify(queueConfig, null, 2)}`,
3534
+ queueDefinitions ? `const queueDefinitions = ${JSON.stringify(queueDefinitions, null, 2)}` : "",
3535
+ "",
3536
+ `export default ${spec.factory}({`,
3537
+ userAppEntry ? " app: queueApp," : "",
3538
+ vercelRuntime ? " createClient: createVercelQueueRuntimeClient," : "",
3539
+ queueDefinitions ? " definitions: queueDefinitions," : "",
3540
+ " queue: queueConfig,",
3541
+ " registry: queueRegistry,",
3542
+ "})",
3543
+ ""
3544
+ ].filter(Boolean).join("\n");
3545
+ }
3546
+ async function writeProviderEntries(rootDir, queue, definitions = discoverQueueDefinitions({ rootDir }), sourceRootDir = rootDir, artifactDir) {
3547
+ const generatedDir = artifactDir ?? ensureGeneratedDir(rootDir, productName);
3548
+ await mkdir(generatedDir, { recursive: true });
3549
+ const registryFile = resolve(generatedDir, generatedRegistryFileName);
3550
+ const userAppEntry = resolveUserAppEntry(sourceRootDir);
3551
+ await writeQueueRegistry(rootDir, definitions, generatedDir);
3552
+ const entryFiles = {
3553
+ cloudflare: "",
3554
+ vercel: ""
3555
+ };
3556
+ for (const spec of providerEntrySpecs) {
3557
+ if (!shouldWriteProviderEntry(spec, queue)) continue;
3558
+ const entryFile = resolve(generatedDir, spec.entryFile);
3559
+ const queueConfig = resolveOutputQueueConfig(queue, spec.hosting);
3560
+ await writeFile(entryFile, renderProviderEntry(spec, entryFile, registryFile, userAppEntry, queueConfig, spec.name === "vercel" && isVercelQueueEnabled(queueConfig), spec.name === "cloudflare" ? createCloudflareQueueDefinitionNames(definitions, queueConfig !== false && queueConfig.provider === "cloudflare" ? queueConfig.namePrefix : void 0) : void 0), "utf8");
3561
+ entryFiles[spec.name] = entryFile;
3562
+ }
3563
+ return {
3564
+ cloudflareWorkerFile: entryFiles.cloudflare,
3565
+ definitions,
3566
+ generatedDir,
3567
+ registryFile,
3568
+ vercelServerFile: entryFiles.vercel
3569
+ };
3570
+ }
3571
+ async function writeQueueRegistry(rootDir, definitions, generatedDir = ensureGeneratedDir(rootDir, productName)) {
3572
+ await mkdir(generatedDir, { recursive: true });
3573
+ const registryFile = resolve(generatedDir, generatedRegistryFileName);
3574
+ await writeFile(registryFile, createRuntimeRegistryContents(registryFile, definitions), "utf8");
3575
+ }
3576
+ function createCloudflareQueueDefinitionNames(definitions, namePrefix = "") {
3577
+ const names = /* @__PURE__ */ new Map();
3578
+ for (const definition of definitions) {
3579
+ const physicalName = getCloudflareQueueName(definition.name, namePrefix);
3580
+ const existing = names.get(physicalName);
3581
+ if (existing) throw new Error(`Queue names ${JSON.stringify(existing.name)} and ${JSON.stringify(definition.name)} collide after Cloudflare resource name derivation:\n - ${existing.handler}\n - ${definition.handler}\nResolved Queue name: ${physicalName}`);
3582
+ names.set(physicalName, definition);
3583
+ }
3584
+ return Object.fromEntries([...names].map(([physicalName, definition]) => [physicalName, definition.name]));
3585
+ }
3586
+ function createCloudflareQueueBindings(definitions, namePrefix = "") {
3587
+ if (!definitions.length) return;
3588
+ const names = createCloudflareQueueDefinitionNames(definitions, namePrefix);
3589
+ return {
3590
+ consumers: Object.keys(names).map((queue) => ({ queue })),
3591
+ producers: definitions.map((definition) => ({
3592
+ binding: getCloudflareQueueBindingName(definition.name),
3593
+ queue: getCloudflareQueueName(definition.name, namePrefix)
3594
+ }))
3595
+ };
3596
+ }
3597
+ function renderNitroPlugin(pluginFile, registryFile, queueConfig, cloudflareQueues, queueDefinitions, development) {
3598
+ const cloudflareRuntime = queueConfig !== false && queueConfig.provider === "cloudflare";
3599
+ const vercelRuntime = queueConfig !== false && queueConfig.provider === "vercel";
3600
+ const cloudflare = cloudflareQueues && cloudflareRuntime;
3601
+ const cloudflareGlobals = cloudflareRuntime && !development;
3602
+ const runtimeClientFactory = cloudflareRuntime ? "createCloudflareQueueRuntimeClient" : vercelRuntime ? "createVercelQueueRuntimeClient" : void 0;
3603
+ return [
3604
+ "import { definePlugin } from 'nitro'",
3605
+ ...vercelRuntime ? [`import * as __vitehubVercelQueue from ${JSON.stringify(createImportPath(pluginFile, resolvePackageDependency("@vercel/queue")))}`] : [],
3606
+ ...cloudflareGlobals ? ["import * as vitehubCloudflareWorkers from 'cloudflare:workers'"] : [],
3607
+ ...cloudflare ? [`import { createQueueCloudflareWorker } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/cloudflare-vite")))}`] : [],
3608
+ ...cloudflareRuntime ? [`import { createCloudflareQueueRuntimeClient } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/cloudflare-client")))}`] : [],
3609
+ ...vercelRuntime ? [`import { createVercelQueueRuntimeClient } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/vercel-client")))}`] : [],
3610
+ `import { setQueueRuntimeConfig, setQueueRuntimeEventDefaults, setQueueRuntimeRegistry } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/state")))}`,
3611
+ `import queueRegistry from ${JSON.stringify(createImportPath(pluginFile, registryFile))}`,
3612
+ "",
3613
+ ...cloudflareGlobals ? ["const { env: vitehubEnv, waitUntil: vitehubWaitUntil } = vitehubCloudflareWorkers as unknown as { env: Record<string, unknown>, waitUntil(promise: Promise<unknown>): void }", ""] : [],
3614
+ ...vercelRuntime ? ["globalThis.__vitehubVercelQueue = __vitehubVercelQueue", ""] : [],
3615
+ `const queueConfig = ${JSON.stringify(queueConfig, null, 2)}`,
3616
+ ...cloudflare ? [`const queueDefinitions = ${JSON.stringify(queueDefinitions, null, 2)}`, "const queueWorker = createQueueCloudflareWorker({ definitions: queueDefinitions, queue: queueConfig, registry: queueRegistry })"] : [],
3617
+ "",
3618
+ `export default definePlugin((${cloudflare ? "nitro" : ""}) => {`,
3619
+ ` setQueueRuntimeConfig(queueConfig${runtimeClientFactory ? `, ${runtimeClientFactory}` : ""})`,
3620
+ " setQueueRuntimeRegistry(queueRegistry)",
3621
+ ...cloudflareGlobals ? [" setQueueRuntimeEventDefaults({ env: vitehubEnv, waitUntil: vitehubWaitUntil })"] : [],
3622
+ ...cloudflare ? [" nitro.hooks.hook('cloudflare:queue', ({ batch, context, env }) => queueWorker.queue(batch, env, context))"] : [],
3623
+ "})",
3624
+ ""
3625
+ ].join("\n");
3626
+ }
3627
+ function renderNitroMiddleware(middlewareFile, queueConfig, hasDefinitions, development) {
3628
+ const cloudflare = queueConfig !== false && queueConfig.provider === "cloudflare";
3629
+ const cloudflareGlobals = cloudflare && !development;
3630
+ const vercel = hasDefinitions && queueConfig !== false && queueConfig.provider === "vercel";
3631
+ return [
3632
+ "import { defineMiddleware } from 'nitro'",
3633
+ ...vercel ? [`import { waitUntil as vitehubWaitUntil } from ${JSON.stringify(createImportPath(middlewareFile, resolvePackageDependency("@vercel/functions")))}`] : [],
3634
+ ...cloudflareGlobals ? ["import * as vitehubCloudflareWorkers from 'cloudflare:workers'"] : [],
3635
+ `import { enterQueueRuntimeEvent } from ${JSON.stringify(createImportPath(middlewareFile, resolveRuntimeModule("internal/runtime/state")))}`,
3636
+ "",
3637
+ ...cloudflareGlobals ? ["const { env: vitehubEnv, waitUntil: vitehubWaitUntil } = vitehubCloudflareWorkers as unknown as { env: Record<string, unknown>, waitUntil(promise: Promise<unknown>): void }", ""] : [],
3638
+ "export default defineMiddleware((event) => {",
3639
+ ...cloudflare ? [" const runtimeEvent = event as any"] : [],
3640
+ ...vercel ? [" Object.assign(event, { waitUntil: vitehubWaitUntil })"] : [],
3641
+ ...cloudflare ? [` Object.assign(event, { env: runtimeEvent.env ?? runtimeEvent.context?.cloudflare?.env ?? runtimeEvent.context?._platform?.cloudflare?.env ?? runtimeEvent.req?.runtime?.cloudflare?.env ?? runtimeEvent.node?.req?.runtime?.cloudflare?.env${cloudflareGlobals ? " ?? vitehubEnv, waitUntil: vitehubWaitUntil" : ""} })`] : [],
3642
+ " enterQueueRuntimeEvent(event)",
3643
+ "})",
3644
+ ""
3645
+ ].join("\n");
3646
+ }
3647
+ async function writeQueueNitroIntegration(rootDir, queue, hosting, cloudflareQueues = true, definitions = discoverQueueDefinitions({ rootDir }), development = false) {
3648
+ const generatedDir = ensureGeneratedDir(rootDir, productName);
3649
+ const registryFile = resolve(generatedDir, generatedRegistryFileName);
3650
+ const pluginFile = resolve(rootDir, generatedQueueNitroPlugin);
3651
+ const middlewareFile = resolve(rootDir, generatedQueueNitroMiddleware);
3652
+ const queueConfig = resolveOutputQueueConfig(typeof queue === "undefined" ? {} : queue, hosting);
3653
+ const queueDefinitions = cloudflareQueues && queueConfig !== false && queueConfig.provider === "cloudflare" ? createCloudflareQueueDefinitionNames(definitions, queueConfig.namePrefix) : {};
3654
+ await Promise.all([mkdir(dirname(pluginFile), { recursive: true }), mkdir(generatedDir, { recursive: true })]);
3655
+ await Promise.all([
3656
+ writeFile(registryFile, createRuntimeRegistryContents(registryFile, definitions), "utf8"),
3657
+ writeFile(pluginFile, renderNitroPlugin(pluginFile, registryFile, queueConfig, cloudflareQueues, queueDefinitions, development), "utf8"),
3658
+ writeFile(middlewareFile, renderNitroMiddleware(middlewareFile, queueConfig, definitions.length > 0, development), "utf8")
3659
+ ]);
3660
+ }
3661
+ async function createCloudflareQueueConfig(options = {}) {
3662
+ const rootDir = resolve(process.cwd(), options.rootDir || ".");
3663
+ const queues = createCloudflareQueueBindings((await writeProviderEntries(rootDir, { provider: "cloudflare" })).definitions);
3664
+ return {
3665
+ assets: { run_worker_first: ["/api/*"] },
3666
+ compatibility_date: options.compatibilityDate || "2026-04-20",
3667
+ compatibility_flags: ["nodejs_compat"],
3668
+ main: toGeneratedPath(rootDir, productName, providerEntrySpecs[0].entryFile),
3669
+ observability: { enabled: true },
3670
+ ...queues ? { queues } : {}
3671
+ };
3672
+ }
3673
+ function createProviderRuntimeAliases(providerOutput, provider, providerImportAliases = {}, generation) {
3674
+ const blobRuntime = getProviderRuntimeModule(providerOutput, "blob", provider, generation);
3675
+ return {
3676
+ ...providerImportAliases,
3677
+ ...blobRuntime ? { "@vite-hub/blob": blobRuntime } : {}
3678
+ };
3679
+ }
3680
+ function captureQueueProviderRuntimeInputs(providerOutput, providerImportAliases = {}, generation) {
3681
+ return {
3682
+ aliases: {
3683
+ cloudflare: createProviderRuntimeAliases(providerOutput, "cloudflare", providerImportAliases, generation),
3684
+ vercel: createProviderRuntimeAliases(providerOutput, "vercel", providerImportAliases, generation)
3685
+ },
3686
+ vercelPackages: getVercelRuntimePackages(providerOutput, "blob", generation).map((runtimePackage) => ({ ...runtimePackage }))
3687
+ };
3688
+ }
3689
+ async function copyVercelRuntimePackages(options) {
3690
+ const { copyVercelFunctionRuntimePackageDirectories } = await import("./vercel-runtime-package-copy-CEToJtCu.js");
3691
+ await copyVercelFunctionRuntimePackageDirectories(options);
3692
+ }
3693
+ function createCloudflareOutput(artifacts, providerRuntimeAliases, namePrefix = "") {
3694
+ const queues = createCloudflareQueueBindings(artifacts.definitions, namePrefix);
3695
+ const wranglerConfig = {
3696
+ compatibility_date: defaultCloudflareCompatibilityDate,
3697
+ compatibility_flags: ["nodejs_compat"],
3698
+ main: "index.js",
3699
+ observability: { enabled: true },
3700
+ ...queues ? { queues } : {}
3701
+ };
3702
+ return {
3703
+ bundleEntry: artifacts.cloudflareWorkerFile,
3704
+ bundleOptions: {
3705
+ alias: providerRuntimeAliases,
3706
+ banner: `// ${cloudflareQueueWorkerMarker}`,
3707
+ conditions: [
3708
+ "workerd",
3709
+ "worker",
3710
+ "browser",
3711
+ "default"
3712
+ ],
3713
+ external: [
3714
+ "@vercel/queue",
3715
+ "cloudflare:workers",
3716
+ "node:async_hooks",
3717
+ "node:fs",
3718
+ "node:fs/promises",
3719
+ "node:path",
3720
+ "node:url"
3721
+ ],
3722
+ format: "esm",
3723
+ platform: "neutral"
3724
+ },
3725
+ wranglerConfigKeys: ["queues"],
3726
+ wranglerConfig
3727
+ };
3728
+ }
3729
+ function isLegacyCloudflareQueueWorker(contents, wrangler) {
3730
+ if (!contents.includes("createQueueCloudflareWorker({") || !contents.includes("getCloudflareQueueDefinitionName(batch.queue)") || !contents.includes("label: \"queue\"") || contents.includes("cloudflare:queue")) return false;
3731
+ if (!wrangler || typeof wrangler !== "object" || Array.isArray(wrangler)) return false;
3732
+ const config = wrangler;
3733
+ const observability = config.observability;
3734
+ return config.main === "index.js" && Array.isArray(config.compatibility_flags) && config.compatibility_flags.includes("nodejs_compat") && Boolean(observability) && typeof observability === "object" && !Array.isArray(observability) && observability.enabled === true;
3735
+ }
3736
+ async function createNitroCloudflareCleanup(rootDir, hasCurrentContribution) {
3737
+ const outputRoot = createDefaultCloudflareOutputRoot(rootDir);
3738
+ let ownsWorker = false;
3739
+ let ownsQueues = false;
3740
+ try {
3741
+ const contents = await readFile(resolve(outputRoot, "index.js"), "utf8");
3742
+ if (contents.includes(cloudflareQueueWorkerMarker)) ownsWorker = true;
3743
+ else ownsWorker = isLegacyCloudflareQueueWorker(contents, JSON.parse(await readFile(resolve(outputRoot, "wrangler.json"), "utf8")));
3744
+ } catch (error) {
3745
+ if (error.code !== "ENOENT") throw error;
3746
+ }
3747
+ try {
3748
+ const [state, wrangler] = await Promise.all([readFile(resolve(rootDir, cloudflareQueueOutputState), "utf8").then((value) => JSON.parse(value)), readFile(resolve(outputRoot, "wrangler.json"), "utf8").then((value) => JSON.parse(value))]);
3749
+ ownsQueues = JSON.stringify(state.queues) === JSON.stringify(wrangler.queues);
3750
+ await rm(resolve(rootDir, cloudflareQueueOutputState), { force: true });
3751
+ } catch (error) {
3752
+ if (error.code !== "ENOENT") throw error;
3753
+ }
3754
+ return {
3755
+ fileNames: ownsWorker ? ["index.js"] : [],
3756
+ outputRoot,
3757
+ wranglerConfigOwnership: { keys: [...ownsWorker ? [
3758
+ "compatibility_date",
3759
+ "compatibility_flags",
3760
+ "main",
3761
+ "observability"
3762
+ ] : [], ...ownsWorker || ownsQueues && !hasCurrentContribution ? ["queues"] : []] }
3763
+ };
3764
+ }
3765
+ function sanitizeVercelConsumerName(functionPath) {
3766
+ let result = "";
3767
+ for (const char of functionPath) if (char === "_") result += "__";
3768
+ else if (char === "/") result += "_S";
3769
+ else if (char === ".") result += "_D";
3770
+ else if (/[A-Za-z0-9-]/.test(char)) result += char;
3771
+ else result += `_${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`;
3772
+ return result;
3773
+ }
3774
+ function createVercelQueueWrapperContents(file, registryFile, name, queueConfig) {
3775
+ return [
3776
+ `import * as __vitehubVercelQueue from ${JSON.stringify(createImportPath(file, resolvePackageDependency("@vercel/queue")))}`,
3777
+ `import { H3 } from ${JSON.stringify(createImportPath(file, resolvePackageDependency("h3")))}`,
3778
+ `import { toNodeHandler } from ${JSON.stringify(createImportPath(file, resolvePackageDependency("h3/node")))}`,
3779
+ `import { createVercelQueueRuntimeClient } from ${JSON.stringify(createImportPath(file, resolveRuntimeModule("internal/runtime/vercel-client")))}`,
3780
+ `import { handleHostedVercelQueueCallback, hostedVercelWaitUntil } from ${JSON.stringify(createImportPath(file, resolveRuntimeModule("runtime/hosted")))}`,
3781
+ `import { loadQueueDefinition, runWithQueueRuntimeEvent, setQueueRuntimeConfig, setQueueRuntimeRegistry } from ${JSON.stringify(createImportPath(file, resolveRuntimeModule("internal/runtime/state")))}`,
3782
+ `import queueRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
3783
+ "",
3784
+ "globalThis.__vitehubVercelQueue = __vitehubVercelQueue",
3785
+ "",
3786
+ `setQueueRuntimeConfig(${JSON.stringify(queueConfig, null, 2)}, createVercelQueueRuntimeClient)`,
3787
+ "setQueueRuntimeRegistry(queueRegistry)",
3788
+ "",
3789
+ "const app = new H3()",
3790
+ "app.use(async (event) => {",
3791
+ ` const definition = await loadQueueDefinition(${JSON.stringify(name)})`,
3792
+ " if (!definition) {",
3793
+ " throw new Error('Missing queue definition.')",
3794
+ " }",
3795
+ ` return await handleHostedVercelQueueCallback(event, ${JSON.stringify(name)}, definition)`,
3796
+ "})",
3797
+ "",
3798
+ "const handler = toNodeHandler(app)",
3799
+ "export default function queueHandler(req, res) {",
3800
+ " return runWithQueueRuntimeEvent({ req, res, waitUntil: hostedVercelWaitUntil }, () => handler(req, res))",
3801
+ "}",
3802
+ ""
3803
+ ].join("\n");
3804
+ }
3805
+ function createVercelOutput(artifacts, providerRuntimeAliases, serverFunctionName) {
3806
+ return {
3807
+ bundleEntry: artifacts.vercelServerFile,
3808
+ bundleOptions: {
3809
+ alias: providerRuntimeAliases,
3810
+ format: "esm",
3811
+ platform: "node"
3812
+ },
3813
+ ...serverFunctionName ? { function: {
3814
+ kind: "isolated",
3815
+ name: serverFunctionName
3816
+ } } : {}
3817
+ };
3818
+ }
3819
+ async function readVercelQueueOutputState(rootDir) {
3820
+ try {
3821
+ const state = JSON.parse(await readFile(resolve(rootDir, vercelQueueOutputState), "utf8"));
3822
+ return typeof state.serverFunctionName === "string" && /^[^/\\]+\.func$/.test(state.serverFunctionName) && typeof state.digest === "string" && /^[0-9a-f]{64}$/.test(state.digest) ? {
3823
+ digest: state.digest,
3824
+ serverFunctionName: state.serverFunctionName
3825
+ } : void 0;
3826
+ } catch (error) {
3827
+ if (error.code === "ENOENT") return void 0;
3828
+ throw error;
3829
+ }
3830
+ }
3831
+ async function isVercelQueueFunctionOwned(rootDir, serverFunctionName, state) {
3832
+ try {
3833
+ const functionRoot = resolve(createDefaultVercelOutputRoot(rootDir), "functions", serverFunctionName);
3834
+ const digest = hash("sha256", await readFile(resolve(functionRoot, "index.mjs")), "hex");
3835
+ if (state?.serverFunctionName === serverFunctionName && state.digest === digest) return true;
3836
+ return JSON.parse(await readFile(resolve(functionRoot, vercelQueueFunctionMarker), "utf8")).digest === digest;
3837
+ } catch (error) {
3838
+ if (error.code === "ENOENT") return false;
3839
+ throw error;
3840
+ }
3841
+ }
3842
+ async function writeVercelQueueFunctions(rootDir, queue, artifacts, providerRuntimeAliases, vercelRuntimePackages, sourceRootDir, signal) {
3843
+ signal?.throwIfAborted();
3844
+ const outputRoot = createDefaultVercelOutputRoot(rootDir);
3845
+ const queueRoot = resolve(outputRoot, "functions", "api", "vitehub", "queues", "vercel");
3846
+ const stagedOutputRoot = resolve(outputRoot, ".vitehub-queue.pending");
3847
+ const stagedQueueRoot = resolve(stagedOutputRoot, "functions", "api", "vitehub", "queues", "vercel");
3848
+ const backupQueueRoot = `${queueRoot}.previous`;
3849
+ const queueConfig = resolveOutputQueueConfig(queue, "vercel");
3850
+ const callbackAliases = Object.hasOwn(providerRuntimeAliases, "@vite-hub/queue") ? providerRuntimeAliases : {
3851
+ ...providerRuntimeAliases,
3852
+ [queuePackageName]: packageRequire.resolve(queuePackageName)
3853
+ };
3854
+ await rm(stagedOutputRoot, {
3855
+ force: true,
3856
+ recursive: true
3857
+ });
3858
+ signal?.throwIfAborted();
3859
+ const functionDirs = /* @__PURE__ */ new Map();
3860
+ for (const definition of isVercelQueueEnabled(queueConfig) ? artifacts.definitions : []) {
3861
+ const segments = definition.name.replace(/[^a-z0-9/_-]+/gi, "_").split("/");
3862
+ const functionDirKey = [...segments, `${segments.at(-1)}.func`].join("/");
3863
+ const existing = functionDirs.get(functionDirKey);
3864
+ if (existing) throw new Error(`Queue names "${existing.name}" and "${definition.name}" collide after Vercel output sanitization:\n - ${existing.handler}\n - ${definition.handler}\nResolved output path: ${functionDirKey}`);
3865
+ functionDirs.set(functionDirKey, definition);
3866
+ const functionDir = resolve(stagedQueueRoot, ...segments, `${segments.at(-1)}.func`);
3867
+ const functionFile = resolve(functionDir, "index.mjs");
3868
+ const wrapperFile = resolve(functionDir, "index.source.mjs");
3869
+ const functionPath = relative(resolve(stagedOutputRoot, "functions"), functionDir).replace(/\\/g, "/");
3870
+ const consumer = sanitizeVercelConsumerName(functionPath);
3871
+ await mkdir(functionDir, { recursive: true });
3872
+ signal?.throwIfAborted();
3873
+ await writeFile(wrapperFile, createVercelQueueWrapperContents(wrapperFile, artifacts.registryFile, definition.name, queueConfig), "utf8");
3874
+ await bundleEsmEntry(wrapperFile, functionFile, {
3875
+ alias: callbackAliases,
3876
+ format: "esm",
3877
+ platform: "node",
3878
+ rootDir: sourceRootDir ?? rootDir,
3879
+ signal
3880
+ });
3881
+ signal?.throwIfAborted();
3882
+ await copyVercelRuntimePackages({
3883
+ outputRoot: stagedOutputRoot,
3884
+ packages: vercelRuntimePackages,
3885
+ rootDir,
3886
+ serverFunctionName: functionPath
3887
+ });
3888
+ signal?.throwIfAborted();
3889
+ await rm(wrapperFile, { force: true });
3890
+ signal?.throwIfAborted();
3891
+ await writeFile(resolve(functionDir, ".vc-config.json"), `${JSON.stringify(createNodeFunctionConfig({ experimentalTriggers: [{
3892
+ consumer,
3893
+ topic: getVercelQueueTopicName(definition.name),
3894
+ type: "queue/v2beta"
3895
+ }] }), null, 2)}\n`, "utf8");
3896
+ }
3897
+ signal?.throwIfAborted();
3898
+ if (isVercelQueueEnabled(queueConfig)) await mkdir(stagedQueueRoot, { recursive: true });
3899
+ signal?.throwIfAborted();
3900
+ rmSync(backupQueueRoot, {
3901
+ force: true,
3902
+ recursive: true
3903
+ });
3904
+ try {
3905
+ renameSync(queueRoot, backupQueueRoot);
3906
+ } catch (error) {
3907
+ if (error.code !== "ENOENT") throw error;
3908
+ }
3909
+ try {
3910
+ if (isVercelQueueEnabled(queueConfig)) {
3911
+ mkdirSync(dirname(queueRoot), { recursive: true });
3912
+ renameSync(stagedQueueRoot, queueRoot);
3913
+ }
3914
+ await rm(stagedOutputRoot, {
3915
+ force: true,
3916
+ recursive: true
3917
+ });
3918
+ signal?.throwIfAborted();
3919
+ } catch (error) {
3920
+ rmSync(queueRoot, {
3921
+ force: true,
3922
+ recursive: true
3923
+ });
3924
+ if (existsSync(backupQueueRoot)) renameSync(backupQueueRoot, queueRoot);
3925
+ throw error;
3926
+ }
3927
+ try {
3928
+ rmSync(backupQueueRoot, {
3929
+ force: true,
3930
+ recursive: true
3931
+ });
3932
+ } catch {}
3933
+ }
3934
+ async function generateProviderOutputs(options, write = writeProviderDeploymentOutputs) {
3935
+ const capturedProviderRuntimeInputs = options.providerRuntimeInputs ?? captureQueueProviderRuntimeInputs(options.providerOutput, options.providerImportAliases);
3936
+ const vercelPackages = [...capturedProviderRuntimeInputs.vercelPackages];
3937
+ if (capturedProviderRuntimeInputs.aliases.vercel["@vite-hub/blob"] && !vercelPackages.some((runtimePackage) => runtimePackage.name === "@vite-hub/blob")) vercelPackages.push({
3938
+ name: "@vite-hub/blob",
3939
+ resolveFrom: resolve(options.rootDir, "package.json")
3940
+ });
3941
+ const providerRuntimeInputs = {
3942
+ aliases: capturedProviderRuntimeInputs.aliases,
3943
+ vercelPackages
3944
+ };
3945
+ const artifacts = await writeProviderEntries(options.rootDir, options.queue, options.definitions, options.sourceRootDir, options.artifactDir);
3946
+ options.signal?.throwIfAborted();
3947
+ const cloudflareQueueConfig = resolveOutputQueueConfig(options.queue, "cloudflare");
3948
+ const usesCloudflare = cloudflareQueueConfig !== false && cloudflareQueueConfig.provider === "cloudflare";
3949
+ const cloudflareNamePrefix = cloudflareQueueConfig !== false && cloudflareQueueConfig.provider === "cloudflare" ? cloudflareQueueConfig.namePrefix : void 0;
3950
+ const createCloudflare = !options.cloudflareOwnedByNitro && usesCloudflare;
3951
+ const createVercel = shouldCreateVercelOutput(options.queue);
3952
+ const vercelFunctionName = options.serverFunctionName ?? "__server.func";
3953
+ if (!createCloudflare) await write({
3954
+ clientOutDir: options.clientOutDir,
3955
+ cleanup: { cloudflare: options.cloudflareOwnedByNitro ? () => createNitroCloudflareCleanup(options.rootDir, usesCloudflare && artifacts.definitions.length > 0) : { wranglerConfigOwnership: { keys: ["queues"] } } },
3956
+ rootDir: options.rootDir
3957
+ });
3958
+ await write({
3959
+ afterWrite: async () => {
3960
+ const previousVercelOutput = await readVercelQueueOutputState(options.rootDir);
3961
+ options.signal?.throwIfAborted();
3962
+ const vercelFunctionCandidates = new Set(["__server.func", "__queue.func"]);
3963
+ if (previousVercelOutput) vercelFunctionCandidates.add(previousVercelOutput.serverFunctionName);
3964
+ const ownedVercelFunctions = [];
3965
+ for (const serverFunctionName of vercelFunctionCandidates) if (await isVercelQueueFunctionOwned(options.rootDir, serverFunctionName, previousVercelOutput)) ownedVercelFunctions.push(serverFunctionName);
3966
+ options.signal?.throwIfAborted();
3967
+ await Promise.all(ownedVercelFunctions.filter((serverFunctionName) => !createVercel || serverFunctionName !== vercelFunctionName).map((serverFunctionName) => rm(resolve(createDefaultVercelOutputRoot(options.rootDir), "functions", serverFunctionName), {
3968
+ force: true,
3969
+ recursive: true
3970
+ })));
3971
+ if (createVercel) {
3972
+ options.signal?.throwIfAborted();
3973
+ const functionRoot = resolve(createDefaultVercelOutputRoot(options.rootDir), "functions", vercelFunctionName);
3974
+ const contents = await readFile(resolve(functionRoot, "index.mjs"));
3975
+ options.signal?.throwIfAborted();
3976
+ const digest = hash("sha256", contents, "hex");
3977
+ await writeFile(resolve(functionRoot, vercelQueueFunctionMarker), `${JSON.stringify({ digest }, null, 2)}\n`, "utf8");
3978
+ options.signal?.throwIfAborted();
3979
+ await mkdir(dirname(resolve(options.rootDir, vercelQueueOutputState)), { recursive: true });
3980
+ options.signal?.throwIfAborted();
3981
+ await writeFile(resolve(options.rootDir, vercelQueueOutputState), `${JSON.stringify({
3982
+ digest,
3983
+ serverFunctionName: vercelFunctionName
3984
+ }, null, 2)}\n`, "utf8");
3985
+ } else {
3986
+ options.signal?.throwIfAborted();
3987
+ await rm(resolve(options.rootDir, vercelQueueOutputState), { force: true });
3988
+ }
3989
+ },
3990
+ clientOutDir: options.clientOutDir,
3991
+ cloudflare: createCloudflare ? createCloudflareOutput(artifacts, providerRuntimeInputs.aliases.cloudflare, cloudflareNamePrefix) : void 0,
3992
+ rootDir: options.rootDir,
3993
+ sourceRootDir: options.sourceRootDir,
3994
+ vercel: createVercel ? createVercelOutput(artifacts, providerRuntimeInputs.aliases.vercel, options.serverFunctionName) : void 0
3995
+ });
3996
+ if (createCloudflare) {
3997
+ options.signal?.throwIfAborted();
3998
+ const queues = createCloudflareQueueBindings(artifacts.definitions, cloudflareNamePrefix);
3999
+ await mkdir(dirname(resolve(options.rootDir, cloudflareQueueOutputState)), { recursive: true });
4000
+ await writeFile(resolve(options.rootDir, cloudflareQueueOutputState), `${JSON.stringify({ queues }, null, 2)}\n`, "utf8");
4001
+ } else {
4002
+ options.signal?.throwIfAborted();
4003
+ await rm(resolve(options.rootDir, cloudflareQueueOutputState), { force: true });
4004
+ }
4005
+ await writeVercelQueueFunctions(options.rootDir, options.queue, artifacts, providerRuntimeInputs.aliases.vercel, providerRuntimeInputs.vercelPackages, options.sourceRootDir, options.signal);
4006
+ if (createVercel) {
4007
+ options.signal?.throwIfAborted();
4008
+ await copyVercelRuntimePackages({
4009
+ packages: providerRuntimeInputs.vercelPackages,
4010
+ rootDir: options.rootDir,
4011
+ serverFunctionName: vercelFunctionName,
4012
+ signal: options.signal
4013
+ });
4014
+ }
4015
+ return artifacts;
4016
+ }
4017
+ //#endregion
4018
+ //#region ../internal/src/provision.ts
4019
+ function resolveCloudflareProvisionConfig(env) {
4020
+ const accountId = trimmedEnv(env.CLOUDFLARE_ACCOUNT_ID);
4021
+ const token = trimmedEnv(env.CLOUDFLARE_API_TOKEN);
4022
+ if (!accountId || !token) return;
4023
+ return {
4024
+ accountId,
4025
+ token
4026
+ };
4027
+ }
4028
+ var ProvisionRequestError = class extends Error {
4029
+ codes;
4030
+ status;
4031
+ constructor(method, path, status, codes = []) {
4032
+ const suffix = codes.length ? ` Provider code${codes.length === 1 ? "" : "s"}: ${codes.join(", ")}.` : "";
4033
+ super(`Provision request failed: ${method} ${path} (${status}).${suffix}`);
4034
+ this.name = "ProvisionRequestError";
4035
+ this.codes = codes;
4036
+ this.status = status;
4037
+ }
4038
+ };
4039
+ function createJsonClient(baseURL, headers, fetchImpl, baseQuery) {
4040
+ return async function request(path, options = {}) {
4041
+ const url = new URL(`${baseURL}${path}`);
4042
+ for (const [key, value] of Object.entries({
4043
+ ...baseQuery,
4044
+ ...options.query
4045
+ })) url.searchParams.set(key, value);
4046
+ const init = {
4047
+ method: options.method ?? "GET",
4048
+ headers: { ...headers }
4049
+ };
4050
+ if (options.body !== void 0) {
4051
+ init.headers = {
4052
+ ...init.headers,
4053
+ "content-type": "application/json"
4054
+ };
4055
+ init.body = JSON.stringify(options.body);
4056
+ }
4057
+ const response = await fetchImpl(url, init);
4058
+ if (!response.ok) {
4059
+ const body = await response.json().catch(() => void 0);
4060
+ const codes = [body?.error?.code, ...body?.errors?.map((error) => error.code) ?? []].filter((code) => typeof code === "number" || typeof code === "string" && /^[\w.-]{1,128}$/.test(code));
4061
+ throw new ProvisionRequestError(options.method ?? "GET", path, response.status, codes);
4062
+ }
4063
+ const value = await response.json();
4064
+ return "parse" in options ? options.parse(value) : value;
4065
+ };
4066
+ }
4067
+ function createCloudflareProvisionClient(config, fetchImpl = globalThis.fetch) {
4068
+ const client = createJsonClient(`https://api.cloudflare.com/client/v4/accounts/${config.accountId}`, { authorization: `Bearer ${config.token}` }, fetchImpl);
4069
+ return async (path, options = {}) => {
4070
+ const parse = "parse" in options ? options.parse : (value) => value;
4071
+ return await client(path, {
4072
+ ...options,
4073
+ parse(value) {
4074
+ if (!value || Object(value) !== value) throw new Error("Cloudflare provisioning returned an invalid response.");
4075
+ const envelope = value;
4076
+ return {
4077
+ ...envelope,
4078
+ result: envelope.result === void 0 ? void 0 : parse(envelope.result)
4079
+ };
4080
+ }
4081
+ });
4082
+ };
4083
+ }
4084
+ function trimmedEnv(value) {
4085
+ const trimmed = value?.trim();
4086
+ return trimmed ? trimmed : void 0;
4087
+ }
4088
+ //#endregion
4089
+ //#region src/provision.ts
4090
+ function parseQueues(value) {
4091
+ if (!Array.isArray(value)) throw new Error("Cloudflare provisioning returned an invalid queue list.");
4092
+ return value;
4093
+ }
4094
+ function createQueueProvisionStep(resolveRootDir, resolveNamePrefix = () => void 0) {
4095
+ return {
4096
+ id: "queue:cloudflare-queues",
4097
+ provider: "cloudflare",
4098
+ async plan(context) {
4099
+ const config = resolveCloudflareProvisionConfig(context.env);
4100
+ if (!config) {
4101
+ context.logger.warn("queue: skipping Cloudflare queues, missing CLOUDFLARE_ACCOUNT_ID/CLOUDFLARE_API_TOKEN.");
4102
+ return [];
4103
+ }
4104
+ const request = createCloudflareProvisionClient(config, context.fetch);
4105
+ const namePrefix = resolveNamePrefix();
4106
+ const names = discoverQueueDefinitions({ rootDir: resolveRootDir() }).map((definition) => getCloudflareQueueName(definition.name, namePrefix));
4107
+ if (!names.length) return [];
4108
+ const listed = await request("/queues", { parse: parseQueues });
4109
+ const existing = new Set((listed.result ?? []).map((queue) => queue.queue_name).filter((name) => Boolean(name)));
4110
+ return names.map((name) => ({
4111
+ kind: "cloudflare-queue",
4112
+ name,
4113
+ exists: existing.has(name),
4114
+ apply: async () => {
4115
+ if (!existing.has(name)) await request("/queues", {
4116
+ method: "POST",
4117
+ body: { queue_name: name }
4118
+ });
4119
+ return {};
4120
+ }
4121
+ }));
4122
+ }
4123
+ };
4124
+ }
4125
+ //#endregion
4126
+ //#region src/vite.ts
4127
+ const mergeNoExternal = createNoExternalMerger(queuePackageName);
4128
+ async function createQueueNitroConfig(plugin, options) {
4129
+ const createNitroConfig = plugin.vitehub?.queue?.createNitroConfig;
4130
+ if (!createNitroConfig) throw new Error("The existing @vite-hub/queue/vite plugin does not expose Queue Nitro configuration.");
4131
+ return createNitroConfig(options);
4132
+ }
4133
+ function resolveStableQueueDefinitions(resolveDefinitions, snapshot, context) {
4134
+ const definitions = resolveDefinitions();
4135
+ if (JSON.stringify(definitions) !== JSON.stringify(snapshot)) throw new Error(`[vitehub] ${context} Queue Definitions changed after config resolution. Generate Queue Definition source files before Vite config resolves.`);
4136
+ return definitions;
4137
+ }
4138
+ function cloneNitroConfig(value) {
4139
+ return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
4140
+ }
4141
+ function mergeNitroExternal(value, addition) {
4142
+ if (typeof value === "undefined") return [addition];
4143
+ if (Array.isArray(value)) return value.includes(addition) ? [...value] : [...value, addition];
4144
+ if (typeof value === "string" || value instanceof RegExp) return [value, addition];
4145
+ if (typeof value === "function") return (source, importer, isResolved) => source === addition || Boolean(value(source, importer, isResolved));
4146
+ return value;
4147
+ }
4148
+ function resolveQueueHosting(queue, nitro) {
4149
+ return getHostingProvider(typeof nitro.preset === "string" ? nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOSTING) || queue !== false && queue?.provider || "vercel";
4150
+ }
4151
+ function resolveNitroHosting(nitro) {
4152
+ return getHostingProvider(typeof nitro.preset === "string" ? nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOSTING);
4153
+ }
4154
+ function supportsCloudflareQueues(nitro) {
4155
+ return !(typeof nitro.preset === "string" ? nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOSTING || "").replaceAll("-", "_").includes("cloudflare_pages");
4156
+ }
4157
+ function isGeneratedNitroRegistration(value, generatedPath) {
4158
+ return typeof value === "string" && (value === generatedPath || value.replaceAll("\\", "/").endsWith(`/${generatedPath}`));
4159
+ }
4160
+ function mergeNitroConfig(config, value, queue, root, definitions = discoverQueueDefinitions({ rootDir: root })) {
4161
+ const providerOutput = useProviderOutputCatalog(config);
4162
+ const nitro = cloneNitroConfig(value);
4163
+ const nitroHosting = resolveNitroHosting(nitro);
4164
+ const providerMismatch = queue !== false && queue?.provider && nitroHosting && queue.provider !== nitroHosting;
4165
+ const runtimeEnabled = queue !== false && !providerMismatch;
4166
+ const nitroOwnsPaths = hasNitroConfigContext(config);
4167
+ const plugin = nitroOwnsPaths ? resolve$1(root, generatedQueueNitroPlugin) : generatedQueueNitroPlugin;
4168
+ const middleware = nitroOwnsPaths ? resolve$1(root, generatedQueueNitroMiddleware) : generatedQueueNitroMiddleware;
4169
+ const plugins = Array.isArray(nitro.plugins) ? nitro.plugins.filter((entry) => !isGeneratedNitroRegistration(entry, generatedQueueNitroPlugin)) : [];
4170
+ const handlers = Array.isArray(nitro.handlers) ? nitro.handlers.filter((handler) => !isGeneratedNitroRegistration(handler?.handler, generatedQueueNitroMiddleware)) : [];
4171
+ if (!runtimeEnabled) {
4172
+ contributeCloudflareProviderOutput(providerOutput, { owner: "queue" });
4173
+ return composeNitroCloudflareProviderOutput(providerOutput, {
4174
+ ...nitro,
4175
+ handlers,
4176
+ plugins
4177
+ }, value);
4178
+ }
4179
+ if (!plugins.includes(plugin)) plugins.unshift(plugin);
4180
+ handlers.unshift({
4181
+ handler: middleware,
4182
+ middleware: true,
4183
+ route: "/**"
4184
+ });
4185
+ const queueHosting = resolveQueueHosting(queue, nitro);
4186
+ if (queueHosting !== "cloudflare") {
4187
+ contributeCloudflareProviderOutput(providerOutput, { owner: "queue" });
4188
+ return composeNitroCloudflareProviderOutput(providerOutput, {
4189
+ ...nitro,
4190
+ handlers,
4191
+ plugins
4192
+ }, value);
4193
+ }
4194
+ const cloudflare = cloneNitroConfig(nitro.cloudflare);
4195
+ const wrangler = cloneNitroConfig(cloudflare.wrangler);
4196
+ const compatibilityFlags = Array.isArray(wrangler.compatibility_flags) ? [...wrangler.compatibility_flags] : [];
4197
+ if (!compatibilityFlags.includes("nodejs_compat")) compatibilityFlags.push("nodejs_compat");
4198
+ const cloudflareQueues = supportsCloudflareQueues(nitro);
4199
+ const rollupConfig = cloneNitroConfig(nitro.rollupConfig);
4200
+ const resolvedQueue = normalizeQueueOptions(queue, { hosting: queueHosting });
4201
+ const generated = createCloudflareQueueBindings(definitions, resolvedQueue?.provider === "cloudflare" ? resolvedQueue.namePrefix : void 0);
4202
+ const baseNitro = {
4203
+ ...nitro,
4204
+ ...cloudflareQueues ? { rollupConfig: {
4205
+ ...rollupConfig,
4206
+ external: mergeNitroExternal(rollupConfig.external, "cloudflare:workers")
4207
+ } } : {},
4208
+ cloudflare: {
4209
+ ...cloudflare,
4210
+ wrangler: {
4211
+ ...wrangler,
4212
+ compatibility_flags: compatibilityFlags
4213
+ }
4214
+ },
4215
+ handlers,
4216
+ plugins
4217
+ };
4218
+ if (!generated) {
4219
+ contributeCloudflareProviderOutput(providerOutput, { owner: "queue" });
4220
+ return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
4221
+ }
4222
+ const binding = resolvedQueue?.provider === "cloudflare" && typeof resolvedQueue.binding === "string" ? resolvedQueue.binding : void 0;
4223
+ if (binding && generated.producers.length > 1) throw new Error("A custom Cloudflare queue binding can only be used with one Queue Definition.");
4224
+ const generatedProducers = binding ? generated.producers.map((producer) => ({
4225
+ ...producer,
4226
+ binding
4227
+ })) : generated.producers;
4228
+ contributeCloudflareProviderOutput(providerOutput, {
4229
+ owner: "queue",
4230
+ queues: {
4231
+ ...cloudflareQueues ? { consumers: generated.consumers } : {},
4232
+ producers: generatedProducers
4233
+ }
4234
+ });
4235
+ return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
4236
+ }
4237
+ function hubQueue(options) {
4238
+ const internalOptions = options;
4239
+ let resolved;
4240
+ let queue = options;
4241
+ let hosting = "vercel";
4242
+ let cloudflareQueues = true;
4243
+ let configuredDefinitions = [];
4244
+ let localDevelopment = false;
4245
+ let nitroOwnsCloudflareWorker = false;
4246
+ let nitroQueue = queue;
4247
+ let nuxtConfiguredDefinitions;
4248
+ let nuxtProjectRoot;
4249
+ let resolveNuxtDefinitions;
4250
+ let nuxtServerQueueDirs = [];
4251
+ let nuxtOwnsCloudflareWorker = false;
4252
+ let providerOutput;
4253
+ const providerOutputGenerations = createProviderDeploymentOutputGenerationState();
4254
+ let validatesNitroDefinitions = false;
4255
+ return {
4256
+ name: "@vite-hub/queue/vite",
4257
+ vitehub: {
4258
+ cli: async () => {
4259
+ return {
4260
+ namespaces: [],
4261
+ provision: [createQueueProvisionStep(() => resolved?.root ?? process.cwd(), () => {
4262
+ const resolvedQueue = normalizeQueueOptions(queue, { hosting: "cloudflare" });
4263
+ return resolvedQueue?.provider === "cloudflare" ? resolvedQueue.namePrefix : void 0;
4264
+ })]
4265
+ };
4266
+ },
4267
+ queue: { async createNitroConfig({ development = false, nitro, projectRoot, root, serverDirs }) {
4268
+ const config = {
4269
+ [VITEHUB_NITRO_CONFIG_CONTEXT]: true,
4270
+ nitro
4271
+ };
4272
+ nuxtProjectRoot = projectRoot;
4273
+ nuxtServerQueueDirs = [...new Set(serverDirs || [resolve$1(projectRoot, "server"), resolve$1(root, "server")])].map((dir) => `${resolve$1(dir, "queues").replace(/\\/g, "/")}/`);
4274
+ resolveNuxtDefinitions = () => discoverQueueDefinitions({
4275
+ rootDir: root,
4276
+ serverDirs,
4277
+ serverRootDirs: [projectRoot, root]
4278
+ });
4279
+ const definitions = resolveNuxtDefinitions();
4280
+ nuxtConfiguredDefinitions = definitions;
4281
+ const configuredNitro = mergeNitroConfig(config, nitro, queue, projectRoot, definitions);
4282
+ hosting = resolveQueueHosting(queue, configuredNitro);
4283
+ const nitroHosting = resolveNitroHosting(configuredNitro);
4284
+ nitroQueue = queue !== false && queue?.provider && nitroHosting && queue.provider !== nitroHosting ? false : queue;
4285
+ cloudflareQueues = supportsCloudflareQueues(configuredNitro);
4286
+ nuxtOwnsCloudflareWorker = nitroQueue !== false && nitroHosting === "cloudflare" && cloudflareQueues;
4287
+ localDevelopment = development;
4288
+ await writeQueueNitroIntegration(projectRoot, nitroQueue, hosting, cloudflareQueues, definitions, localDevelopment);
4289
+ return configuredNitro;
4290
+ } }
4291
+ },
4292
+ config(config) {
4293
+ queue = config.queue ?? queue;
4294
+ const nitro = config.nitro;
4295
+ config.nitro = mergeNitroConfig(config, nitro, queue, config.root || process.cwd());
4296
+ },
4297
+ async configResolved(config) {
4298
+ resolved = config;
4299
+ queue = config.queue ?? queue;
4300
+ const configuredNitro = config.nitro;
4301
+ const configuredNitroConfig = cloneNitroConfig(configuredNitro);
4302
+ nitroOwnsCloudflareWorker = hasNitroConfigContext(config) && resolveNitroHosting(configuredNitroConfig) === "cloudflare" && supportsCloudflareQueues(configuredNitroConfig);
4303
+ configuredDefinitions = discoverQueueDefinitions({ rootDir: config.root });
4304
+ const nitro = mergeNitroConfig(config, configuredNitro, queue, config.root, configuredDefinitions);
4305
+ config.nitro = nitro;
4306
+ providerOutput = useProviderOutputCatalog(config);
4307
+ hosting = resolveQueueHosting(queue, nitro);
4308
+ cloudflareQueues = supportsCloudflareQueues(nitro);
4309
+ const nitroHosting = resolveNitroHosting(nitro);
4310
+ nitroQueue = queue !== false && queue?.provider && nitroHosting && queue.provider !== nitroHosting ? false : queue;
4311
+ validatesNitroDefinitions = hasNitroConfigContext(config) && nitroQueue !== false;
4312
+ localDevelopment = config.command === "serve";
4313
+ await writeQueueNitroIntegration(config.root, nitroQueue, hosting, cloudflareQueues, configuredDefinitions, localDevelopment);
4314
+ },
4315
+ configEnvironment(name, config) {
4316
+ if (!isServerEnvironment(name, config)) return;
4317
+ return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
4318
+ },
4319
+ async handleHotUpdate(context) {
4320
+ const file = context.file.replace(/\\/g, "/");
4321
+ const isDirectoryDefinition = /\.(?:c|m)?[jt]s$/i.test(file) && (/\/server\/queues\//.test(file) || nuxtServerQueueDirs.some((dir) => file.startsWith(dir)));
4322
+ if (!/\.queue\.(?:c|m)?[jt]s$/i.test(file) && !isDirectoryDefinition) return;
4323
+ resolved = context.server.config;
4324
+ await writeQueueNitroIntegration(nuxtProjectRoot || resolved.root, nitroQueue, hosting, cloudflareQueues, resolveNuxtDefinitions?.(), localDevelopment);
4325
+ },
4326
+ buildStart() {
4327
+ providerOutputGenerations.capture(this, providerOutput);
4328
+ },
4329
+ async buildEnd(error) {
4330
+ if (error) {
4331
+ await providerOutputGenerations.reset(this, providerOutput, error);
4332
+ return;
4333
+ }
4334
+ if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
4335
+ let artifactDir;
4336
+ try {
4337
+ let definitions;
4338
+ if (resolveNuxtDefinitions && nuxtConfiguredDefinitions) definitions = resolveStableQueueDefinitions(resolveNuxtDefinitions, nuxtConfiguredDefinitions, "Nuxt");
4339
+ else if (validatesNitroDefinitions) definitions = resolveStableQueueDefinitions(() => discoverQueueDefinitions({ rootDir: resolved.root }), configuredDefinitions, "Nitro Cloudflare");
4340
+ else definitions = discoverQueueDefinitions({ rootDir: resolved.root });
4341
+ const config = resolved;
4342
+ const rootDir = nuxtProjectRoot || config.root;
4343
+ artifactDir = resolve$1(rootDir, ".vitehub/queue-generations", randomUUID());
4344
+ const contributionArtifactDir = artifactDir;
4345
+ const providerImportAliases = internalOptions?.providerImportAliases ?? {};
4346
+ const retainedSources = await retainProviderOutputSources({
4347
+ artifactDir: resolve$1(contributionArtifactDir, "sources"),
4348
+ paths: [
4349
+ ...definitions.map((definition) => definition.handler),
4350
+ ...Object.keys(providerImportAliases),
4351
+ ...Object.values(providerImportAliases)
4352
+ ],
4353
+ roots: [rootDir]
4354
+ });
4355
+ const retainedDefinitions = definitions.map((definition) => ({
4356
+ ...definition,
4357
+ handler: retainedSources.resolve(definition.handler)
4358
+ }));
4359
+ const retainedProviderImportAliases = retainProviderOutputAliases(providerImportAliases, retainedSources);
4360
+ const nitro = config.nitro;
4361
+ const generation = providerOutputGenerations.get(this);
4362
+ contributeProviderDeploymentOutput(providerOutput, {
4363
+ discard: async () => await removeProviderOutputArtifactDir(contributionArtifactDir),
4364
+ owner: "queue",
4365
+ rootDir,
4366
+ write: async ({ signal, write }) => {
4367
+ const providerRuntimeInputs = captureQueueProviderRuntimeInputs(providerOutput, retainedProviderImportAliases, generation);
4368
+ const retainedRuntimeSources = await retainProviderOutputSources({
4369
+ artifactDir: resolve$1(contributionArtifactDir, "runtime-sources"),
4370
+ paths: Object.values(providerRuntimeInputs.aliases).flatMap((aliases) => [...Object.keys(aliases), ...Object.values(aliases)]),
4371
+ roots: [rootDir]
4372
+ });
4373
+ const typedRetainedRuntimeAliases = Object.fromEntries(Object.entries(providerRuntimeInputs.aliases).map(([provider, aliases]) => [provider, retainProviderOutputAliases(aliases, retainedRuntimeSources)]));
4374
+ await generateProviderOutputs({
4375
+ artifactDir: resolve$1(contributionArtifactDir, "output"),
4376
+ clientOutDir: config.build.outDir,
4377
+ cloudflareOwnedByNitro: nitroOwnsCloudflareWorker || nuxtOwnsCloudflareWorker,
4378
+ definitions: retainedDefinitions,
4379
+ providerImportAliases: retainedProviderImportAliases,
4380
+ providerRuntimeInputs: {
4381
+ aliases: typedRetainedRuntimeAliases,
4382
+ vercelPackages: providerRuntimeInputs.vercelPackages.filter((runtimePackage) => runtimePackage.name === "@vite-hub/blob")
4383
+ },
4384
+ queue: queue ?? (resolveNitroHosting(cloneNitroConfig(nitro)) ? { provider: hosting === "cloudflare" ? "cloudflare" : "vercel" } : void 0),
4385
+ rootDir,
4386
+ sourceRootDir: retainedSources.resolve(rootDir),
4387
+ serverFunctionName: resolveNitroVercelFunctionName(config, "queue"),
4388
+ signal
4389
+ }, write);
4390
+ signal.throwIfAborted();
4391
+ await writeQueueRegistry(rootDir, definitions);
4392
+ }
4393
+ }, generation);
4394
+ } catch (error) {
4395
+ if (artifactDir) await removeProviderOutputArtifactDir(artifactDir);
4396
+ await providerOutputGenerations.reset(this, providerOutput, error);
4397
+ throw error;
4398
+ }
4399
+ },
4400
+ async renderError(error) {
4401
+ await providerOutputGenerations.reset(this, providerOutput, error);
4402
+ },
4403
+ closeBundle: {
4404
+ order: "post",
4405
+ sequential: true,
4406
+ async handler() {
4407
+ if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
4408
+ await finalizeProviderDeploymentOutputs(providerOutput);
4409
+ }
4410
+ }
4411
+ };
4412
+ }
4413
+ //#endregion
4414
+ export { createDefaultVercelOutputRoot as a, discoverQueueDefinitions as i, hubQueue as n, createCloudflareQueueConfig as r, createQueueNitroConfig as t };