@vite-hub/kv 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.
package/dist/vite.js CHANGED
@@ -1,6 +1,14 @@
1
- import { n as readEnv, r as trimmed, t as normalizeKVOptions } from "./config-C1ofyzSt.js";
2
- import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
3
- import { basename, join, resolve } from "node:path";
1
+ import { i as trimmed, n as isPlainObject, r as readEnv, t as normalizeKVOptions } from "./config-aM9Ae7tH.js";
2
+ import { createRequire } from "node:module";
3
+ import { existsSync, renameSync, rmSync } from "node:fs";
4
+ import { cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ //#region \0rolldown/runtime.js
9
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
10
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
11
+ //#endregion
4
12
  //#region src/vite-config.ts
5
13
  const KV_VITE_PLUGIN_NAME = "@vite-hub/kv/vite";
6
14
  const KV_VIRTUAL_CONFIG_ID = "#vitehub/kv/config";
@@ -20,151 +28,4379 @@ function resolveKVViteConfig(kv, input = {}) {
20
28
  };
21
29
  }
22
30
  //#endregion
31
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
32
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
33
+ function normalizeWindowsPath(input = "") {
34
+ if (!input) return input;
35
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
36
+ }
37
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
38
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
39
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
40
+ function cwd() {
41
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
42
+ return "/";
43
+ }
44
+ const resolve$1 = function(...arguments_) {
45
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
46
+ let resolvedPath = "";
47
+ let resolvedAbsolute = false;
48
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
49
+ const path = index >= 0 ? arguments_[index] : cwd();
50
+ if (!path || path.length === 0) continue;
51
+ resolvedPath = `${path}/${resolvedPath}`;
52
+ resolvedAbsolute = isAbsolute$1(path);
53
+ }
54
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
55
+ if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
56
+ return resolvedPath.length > 0 ? resolvedPath : ".";
57
+ };
58
+ function normalizeString(path, allowAboveRoot) {
59
+ let res = "";
60
+ let lastSegmentLength = 0;
61
+ let lastSlash = -1;
62
+ let dots = 0;
63
+ let char = null;
64
+ for (let index = 0; index <= path.length; ++index) {
65
+ if (index < path.length) char = path[index];
66
+ else if (char === "/") break;
67
+ else char = "/";
68
+ if (char === "/") {
69
+ if (lastSlash === index - 1 || dots === 1);
70
+ else if (dots === 2) {
71
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
72
+ if (res.length > 2) {
73
+ const lastSlashIndex = res.lastIndexOf("/");
74
+ if (lastSlashIndex === -1) {
75
+ res = "";
76
+ lastSegmentLength = 0;
77
+ } else {
78
+ res = res.slice(0, lastSlashIndex);
79
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
80
+ }
81
+ lastSlash = index;
82
+ dots = 0;
83
+ continue;
84
+ } else if (res.length > 0) {
85
+ res = "";
86
+ lastSegmentLength = 0;
87
+ lastSlash = index;
88
+ dots = 0;
89
+ continue;
90
+ }
91
+ }
92
+ if (allowAboveRoot) {
93
+ res += res.length > 0 ? "/.." : "..";
94
+ lastSegmentLength = 2;
95
+ }
96
+ } else {
97
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
98
+ else res = path.slice(lastSlash + 1, index);
99
+ lastSegmentLength = index - lastSlash - 1;
100
+ }
101
+ lastSlash = index;
102
+ dots = 0;
103
+ } else if (char === "." && dots !== -1) ++dots;
104
+ else dots = -1;
105
+ }
106
+ return res;
107
+ }
108
+ const isAbsolute$1 = function(p) {
109
+ return _IS_ABSOLUTE_RE.test(p);
110
+ };
111
+ const relative$1 = function(from, to) {
112
+ const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
113
+ const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
114
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
115
+ const _fromCopy = [..._from];
116
+ for (const segment of _fromCopy) {
117
+ if (_to[0] !== segment) break;
118
+ _from.shift();
119
+ _to.shift();
120
+ }
121
+ return [..._from.map(() => ".."), ..._to].join("/");
122
+ };
123
+ const dirname$1 = function(p) {
124
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
125
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
126
+ return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
127
+ };
128
+ //#endregion
129
+ //#region ../internal/src/build/client-output.ts
130
+ function hasStaticIndex(clientDir) {
131
+ return existsSync(resolve$1(clientDir, "index.html"));
132
+ }
133
+ async function copyClientOutput(clientDir, targetDir) {
134
+ const resolvedClientDir = resolve$1(clientDir);
135
+ const resolvedTargetDir = resolve$1(targetDir);
136
+ if (resolvedClientDir === resolvedTargetDir) return;
137
+ await rm(resolvedTargetDir, {
138
+ force: true,
139
+ recursive: true
140
+ });
141
+ await mkdir(dirname$1(resolvedTargetDir), { recursive: true });
142
+ const targetRelativePath = relative$1(resolvedClientDir, resolvedTargetDir);
143
+ if (targetRelativePath && !targetRelativePath.startsWith("../")) {
144
+ const [targetRootEntry] = targetRelativePath.split("/", 1);
145
+ await mkdir(resolvedTargetDir, { recursive: true });
146
+ await Promise.all((await readdir(resolvedClientDir)).filter((entry) => entry !== targetRootEntry).map((entry) => cp(resolve$1(resolvedClientDir, entry), resolve$1(resolvedTargetDir, entry), { recursive: true })));
147
+ return;
148
+ }
149
+ await cp(resolvedClientDir, resolvedTargetDir, { recursive: true });
150
+ }
151
+ //#endregion
23
152
  //#region ../internal/src/build/provider-output-config.ts
24
153
  function isProviderJsonArray(value, ancestors) {
25
154
  if (Object.getPrototypeOf(value) !== Array.prototype || ancestors.has(value)) return false;
26
155
  if (Reflect.ownKeys(value).length !== value.length + 1) return false;
27
156
  ancestors.add(value);
28
157
  try {
29
- for (let index = 0; index < value.length; index++) {
30
- const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
31
- if (!descriptor?.enumerable || !("value" in descriptor) || !isProviderJsonValue(descriptor.value, ancestors)) return false;
158
+ for (let index = 0; index < value.length; index++) {
159
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
160
+ if (!descriptor?.enumerable || !("value" in descriptor) || !isProviderJsonValue(descriptor.value, ancestors)) return false;
161
+ }
162
+ return true;
163
+ } finally {
164
+ ancestors.delete(value);
165
+ }
166
+ }
167
+ function isProviderJsonRecordValue(value, ancestors) {
168
+ const prototype = Object.getPrototypeOf(value);
169
+ if (prototype !== Object.prototype && prototype !== null || ancestors.has(value)) return false;
170
+ ancestors.add(value);
171
+ try {
172
+ return Reflect.ownKeys(value).every((key) => {
173
+ if (typeof key !== "string") return false;
174
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
175
+ return descriptor?.enumerable === true && "value" in descriptor && isProviderJsonValue(descriptor.value, ancestors);
176
+ });
177
+ } finally {
178
+ ancestors.delete(value);
179
+ }
180
+ }
181
+ function isProviderJsonValue(value, ancestors) {
182
+ if (value === null || typeof value === "boolean" || typeof value === "string") return true;
183
+ if (typeof value === "number") return Number.isFinite(value);
184
+ if (Array.isArray(value)) return isProviderJsonArray(value, ancestors);
185
+ return typeof value === "object" && isProviderJsonRecordValue(value, ancestors);
186
+ }
187
+ function isProviderJsonRecord(value) {
188
+ try {
189
+ return typeof value === "object" && value !== null && !Array.isArray(value) && isProviderJsonRecordValue(value, /* @__PURE__ */ new Set());
190
+ } catch {
191
+ return false;
192
+ }
193
+ }
194
+ function assertProviderJsonRecord(value) {
195
+ if (!isProviderJsonRecord(value)) throw new TypeError("[vitehub] Provider output config must be a JSON object.");
196
+ }
197
+ function isFileNotFoundError(error) {
198
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
199
+ }
200
+ async function readProviderJsonRecord(file) {
201
+ try {
202
+ const parsed = JSON.parse(await readFile(file, "utf8"));
203
+ assertProviderJsonRecord(parsed);
204
+ return parsed;
205
+ } catch (error) {
206
+ if (isFileNotFoundError(error)) return;
207
+ throw error;
208
+ }
209
+ }
210
+ function deleteOwnedFields(value, ownership, cleanup = false) {
211
+ const next = { ...value };
212
+ for (const key of ownership.keys ?? []) delete next[key];
213
+ for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) if (!cleanup || !arrayOwnership.preserveOnCleanup) delete next[field];
214
+ return next;
215
+ }
216
+ function getKeyedArrayEntryValue(value, key) {
217
+ if (key === void 0) return value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string" ? value : void 0;
218
+ if (!isProviderJsonRecord(value)) return;
219
+ const entryValue = value[key];
220
+ return entryValue === null || typeof entryValue === "boolean" || typeof entryValue === "number" || typeof entryValue === "string" ? entryValue : void 0;
221
+ }
222
+ function preserveUnownedKeyedArrayEntries(value, ownership, replacements = []) {
223
+ const current = Array.isArray(value) ? value : [];
224
+ const replacementKeys = replacements.flatMap((entry) => {
225
+ const key = getKeyedArrayEntryValue(entry, ownership.key);
226
+ return key === void 0 ? [] : [key];
227
+ });
228
+ const ownedKeys = new Set([...ownership.values ?? [], ...replacementKeys]);
229
+ return current.filter((entry) => {
230
+ const key = getKeyedArrayEntryValue(entry, ownership.key);
231
+ return key === void 0 || !ownedKeys.has(key);
232
+ });
233
+ }
234
+ function mergeOwnedArrays(existing, value, arrays) {
235
+ const next = { ...value };
236
+ for (const [field, ownership] of Object.entries(arrays ?? {})) {
237
+ const incoming = Array.isArray(value[field]) ? value[field] : [];
238
+ const merged = [...preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming), ...incoming];
239
+ if (merged.length) next[field] = merged;
240
+ else delete next[field];
241
+ }
242
+ return next;
243
+ }
244
+ async function persistProviderJsonRecord(file, value, removeIfEmpty) {
245
+ if (removeIfEmpty && !Object.keys(value).length) {
246
+ await rm(file, { force: true });
247
+ return;
248
+ }
249
+ await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
250
+ }
251
+ async function writeProviderOutputConfig(file, value, ownership = {}, options = {}) {
252
+ const existing = await readProviderJsonRecord(file) ?? {};
253
+ const defaults = options.defaults ?? {};
254
+ assertProviderJsonRecord(defaults);
255
+ await persistProviderJsonRecord(file, mergeProviderOutputConfig({
256
+ ...defaults,
257
+ ...existing
258
+ }, value, ownership), options.removeIfEmpty === true);
259
+ }
260
+ function mergeProviderOutputConfig(existing, value, ownership = {}) {
261
+ assertProviderJsonRecord(existing);
262
+ assertProviderJsonRecord(value);
263
+ return {
264
+ ...deleteOwnedFields(existing, ownership),
265
+ ...mergeOwnedArrays(existing, value, ownership.arrays)
266
+ };
267
+ }
268
+ function stringifyProviderOutputConfig(value) {
269
+ assertProviderJsonRecord(value);
270
+ return JSON.stringify(value, null, 2);
271
+ }
272
+ async function cleanProviderOutputConfig(file, ownership) {
273
+ if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
274
+ const existing = await readProviderJsonRecord(file);
275
+ if (!existing) return;
276
+ const next = deleteOwnedFields(existing, ownership, true);
277
+ let changed = (ownership.keys ?? []).some((key) => key in existing);
278
+ for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
279
+ if (arrayOwnership.preserveOnCleanup) continue;
280
+ if (!(field in existing)) continue;
281
+ const current = existing[field];
282
+ const retained = arrayOwnership.retainOnCleanup ?? [];
283
+ const preserved = [...preserveUnownedKeyedArrayEntries(current, arrayOwnership, retained), ...retained];
284
+ changed ||= retained.length > 0 || !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
285
+ if (preserved.length) next[field] = preserved;
286
+ }
287
+ if (!changed) return;
288
+ await persistProviderJsonRecord(file, next, true);
289
+ }
290
+ //#endregion
291
+ //#region ../internal/src/build/user-entry.ts
292
+ function toSafeAppName(rootDir) {
293
+ return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
294
+ }
295
+ //#endregion
296
+ //#region ../internal/src/build/cloudflare.ts
297
+ function createDefaultCloudflareOutputRoot(rootDir) {
298
+ return resolve(rootDir, "dist", toSafeAppName(rootDir));
299
+ }
300
+ async function writeCloudflareWranglerConfig(options) {
301
+ const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
302
+ const configFile = resolve(outputRoot, "wrangler.json");
303
+ if (!options.wranglerConfig) {
304
+ await cleanProviderOutputConfig(configFile, options.wranglerConfigOwnership ?? {});
305
+ return;
306
+ }
307
+ await mkdir(outputRoot, { recursive: true });
308
+ await writeProviderOutputConfig(configFile, options.wranglerConfig, options.wranglerConfigOwnership, {
309
+ defaults: options.wranglerConfigDefaults,
310
+ removeIfEmpty: true
311
+ });
312
+ }
313
+ //#endregion
314
+ //#region ../internal/src/build/esbuild.ts
315
+ var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
316
+ var __defProp = Object.defineProperty;
317
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
318
+ var __getOwnPropNames = Object.getOwnPropertyNames;
319
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
320
+ var __export = (target, all) => {
321
+ for (var name in all) __defProp(target, name, {
322
+ get: all[name],
323
+ enumerable: true
324
+ });
325
+ };
326
+ var __copyProps = (to, from, except, desc) => {
327
+ if (from && typeof from === "object" || typeof from === "function") {
328
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
329
+ get: () => from[key],
330
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
331
+ });
332
+ }
333
+ return to;
334
+ };
335
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
336
+ var node_exports = {};
337
+ __export(node_exports, {
338
+ analyzeMetafile: () => analyzeMetafile,
339
+ analyzeMetafileSync: () => analyzeMetafileSync,
340
+ build: () => build,
341
+ buildSync: () => buildSync,
342
+ context: () => context,
343
+ default: () => node_default,
344
+ formatMessages: () => formatMessages,
345
+ formatMessagesSync: () => formatMessagesSync,
346
+ initialize: () => initialize,
347
+ stop: () => stop,
348
+ transform: () => transform,
349
+ transformSync: () => transformSync,
350
+ version: () => version
351
+ });
352
+ module.exports = __toCommonJS(node_exports);
353
+ function encodePacket(packet) {
354
+ let visit = (value) => {
355
+ if (value === null) bb.write8(0);
356
+ else if (typeof value === "boolean") {
357
+ bb.write8(1);
358
+ bb.write8(+value);
359
+ } else if (typeof value === "number") {
360
+ bb.write8(2);
361
+ bb.write32(value | 0);
362
+ } else if (typeof value === "string") {
363
+ bb.write8(3);
364
+ bb.write(encodeUTF8(value));
365
+ } else if (value instanceof Uint8Array) {
366
+ bb.write8(4);
367
+ bb.write(value);
368
+ } else if (value instanceof Array) {
369
+ bb.write8(5);
370
+ bb.write32(value.length);
371
+ for (let item of value) visit(item);
372
+ } else {
373
+ let keys = Object.keys(value);
374
+ bb.write8(6);
375
+ bb.write32(keys.length);
376
+ for (let key of keys) {
377
+ bb.write(encodeUTF8(key));
378
+ visit(value[key]);
379
+ }
380
+ }
381
+ };
382
+ let bb = new ByteBuffer();
383
+ bb.write32(0);
384
+ bb.write32(packet.id << 1 | +!packet.isRequest);
385
+ visit(packet.value);
386
+ writeUInt32LE(bb.buf, bb.len - 4, 0);
387
+ return bb.buf.subarray(0, bb.len);
388
+ }
389
+ function decodePacket(bytes) {
390
+ let visit = () => {
391
+ switch (bb.read8()) {
392
+ case 0: return null;
393
+ case 1: return !!bb.read8();
394
+ case 2: return bb.read32();
395
+ case 3: return decodeUTF8(bb.read());
396
+ case 4: return bb.read();
397
+ case 5: {
398
+ let count = bb.read32();
399
+ let value2 = [];
400
+ for (let i = 0; i < count; i++) value2.push(visit());
401
+ return value2;
402
+ }
403
+ case 6: {
404
+ let count = bb.read32();
405
+ let value2 = {};
406
+ for (let i = 0; i < count; i++) value2[decodeUTF8(bb.read())] = visit();
407
+ return value2;
408
+ }
409
+ default: throw new Error("Invalid packet");
410
+ }
411
+ };
412
+ let bb = new ByteBuffer(bytes);
413
+ let id = bb.read32();
414
+ let isRequest = (id & 1) === 0;
415
+ id >>>= 1;
416
+ let value = visit();
417
+ if (bb.ptr !== bytes.length) throw new Error("Invalid packet");
418
+ return {
419
+ id,
420
+ isRequest,
421
+ value
422
+ };
423
+ }
424
+ var ByteBuffer = class {
425
+ constructor(buf = new Uint8Array(1024)) {
426
+ this.buf = buf;
427
+ this.len = 0;
428
+ this.ptr = 0;
429
+ }
430
+ _write(delta) {
431
+ if (this.len + delta > this.buf.length) {
432
+ let clone = new Uint8Array((this.len + delta) * 2);
433
+ clone.set(this.buf);
434
+ this.buf = clone;
435
+ }
436
+ this.len += delta;
437
+ return this.len - delta;
438
+ }
439
+ write8(value) {
440
+ let offset = this._write(1);
441
+ this.buf[offset] = value;
442
+ }
443
+ write32(value) {
444
+ let offset = this._write(4);
445
+ writeUInt32LE(this.buf, value, offset);
446
+ }
447
+ write(bytes) {
448
+ let offset = this._write(4 + bytes.length);
449
+ writeUInt32LE(this.buf, bytes.length, offset);
450
+ this.buf.set(bytes, offset + 4);
451
+ }
452
+ _read(delta) {
453
+ if (this.ptr + delta > this.buf.length) throw new Error("Invalid packet");
454
+ this.ptr += delta;
455
+ return this.ptr - delta;
456
+ }
457
+ read8() {
458
+ return this.buf[this._read(1)];
459
+ }
460
+ read32() {
461
+ return readUInt32LE(this.buf, this._read(4));
462
+ }
463
+ read() {
464
+ let length = this.read32();
465
+ let bytes = new Uint8Array(length);
466
+ let ptr = this._read(bytes.length);
467
+ bytes.set(this.buf.subarray(ptr, ptr + length));
468
+ return bytes;
469
+ }
470
+ };
471
+ var encodeUTF8;
472
+ var decodeUTF8;
473
+ var encodeInvariant;
474
+ if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
475
+ let encoder = new TextEncoder();
476
+ let decoder = new TextDecoder();
477
+ encodeUTF8 = (text) => encoder.encode(text);
478
+ decodeUTF8 = (bytes) => decoder.decode(bytes);
479
+ encodeInvariant = "new TextEncoder().encode(\"\")";
480
+ } else if (typeof Buffer !== "undefined") {
481
+ encodeUTF8 = (text) => Buffer.from(text);
482
+ decodeUTF8 = (bytes) => {
483
+ let { buffer, byteOffset, byteLength } = bytes;
484
+ return Buffer.from(buffer, byteOffset, byteLength).toString();
485
+ };
486
+ encodeInvariant = "Buffer.from(\"\")";
487
+ } else throw new Error("No UTF-8 codec found");
488
+ if (!(encodeUTF8("") instanceof Uint8Array)) throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
489
+
490
+ This indicates that your JavaScript environment is broken. You cannot use
491
+ esbuild in this environment because esbuild relies on this invariant. This
492
+ is not a problem with esbuild. You need to fix your environment instead.
493
+ `);
494
+ function readUInt32LE(buffer, offset) {
495
+ return (buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24) >>> 0;
496
+ }
497
+ function writeUInt32LE(buffer, value, offset) {
498
+ buffer[offset++] = value;
499
+ buffer[offset++] = value >> 8;
500
+ buffer[offset++] = value >> 16;
501
+ buffer[offset++] = value >> 24;
502
+ }
503
+ var fromCharCode = String.fromCharCode;
504
+ function throwSyntaxError(bytes, index, message) {
505
+ const c = bytes[index];
506
+ let line = 1;
507
+ let column = 0;
508
+ for (let i = 0; i < index; i++) if (bytes[i] === 10) {
509
+ line++;
510
+ column = 0;
511
+ } else column++;
512
+ throw new SyntaxError(message ? message : index === bytes.length ? "Unexpected end of input while parsing JSON" : c >= 32 && c <= 126 ? `Unexpected character ${fromCharCode(c)} in JSON at position ${index} (line ${line}, column ${column})` : `Unexpected byte 0x${c.toString(16)} in JSON at position ${index} (line ${line}, column ${column})`);
513
+ }
514
+ function JSON_parse(bytes) {
515
+ if (!(bytes instanceof Uint8Array)) throw new Error(`JSON input must be a Uint8Array`);
516
+ const propertyStack = [];
517
+ const objectStack = [];
518
+ const stateStack = [];
519
+ const length = bytes.length;
520
+ let property = null;
521
+ let state = 0;
522
+ let object;
523
+ let i = 0;
524
+ while (i < length) {
525
+ let c = bytes[i++];
526
+ if (c <= 32) continue;
527
+ let value;
528
+ if (state === 2 && property === null && c !== 34 && c !== 125) throwSyntaxError(bytes, --i);
529
+ switch (c) {
530
+ case 116:
531
+ if (bytes[i++] !== 114 || bytes[i++] !== 117 || bytes[i++] !== 101) throwSyntaxError(bytes, --i);
532
+ value = true;
533
+ break;
534
+ case 102:
535
+ if (bytes[i++] !== 97 || bytes[i++] !== 108 || bytes[i++] !== 115 || bytes[i++] !== 101) throwSyntaxError(bytes, --i);
536
+ value = false;
537
+ break;
538
+ case 110:
539
+ if (bytes[i++] !== 117 || bytes[i++] !== 108 || bytes[i++] !== 108) throwSyntaxError(bytes, --i);
540
+ value = null;
541
+ break;
542
+ case 45:
543
+ case 46:
544
+ case 48:
545
+ case 49:
546
+ case 50:
547
+ case 51:
548
+ case 52:
549
+ case 53:
550
+ case 54:
551
+ case 55:
552
+ case 56:
553
+ case 57: {
554
+ let index = i;
555
+ value = fromCharCode(c);
556
+ c = bytes[i];
557
+ while (true) {
558
+ switch (c) {
559
+ case 43:
560
+ case 45:
561
+ case 46:
562
+ case 48:
563
+ case 49:
564
+ case 50:
565
+ case 51:
566
+ case 52:
567
+ case 53:
568
+ case 54:
569
+ case 55:
570
+ case 56:
571
+ case 57:
572
+ case 101:
573
+ case 69:
574
+ value += fromCharCode(c);
575
+ c = bytes[++i];
576
+ continue;
577
+ }
578
+ break;
579
+ }
580
+ value = +value;
581
+ if (isNaN(value)) throwSyntaxError(bytes, --index, "Invalid number");
582
+ break;
583
+ }
584
+ case 34:
585
+ value = "";
586
+ while (true) {
587
+ if (i >= length) throwSyntaxError(bytes, length);
588
+ c = bytes[i++];
589
+ if (c === 34) break;
590
+ else if (c === 92) switch (bytes[i++]) {
591
+ case 34:
592
+ value += "\"";
593
+ break;
594
+ case 47:
595
+ value += "/";
596
+ break;
597
+ case 92:
598
+ value += "\\";
599
+ break;
600
+ case 98:
601
+ value += "\b";
602
+ break;
603
+ case 102:
604
+ value += "\f";
605
+ break;
606
+ case 110:
607
+ value += "\n";
608
+ break;
609
+ case 114:
610
+ value += "\r";
611
+ break;
612
+ case 116:
613
+ value += " ";
614
+ break;
615
+ case 117: {
616
+ let code = 0;
617
+ for (let j = 0; j < 4; j++) {
618
+ c = bytes[i++];
619
+ code <<= 4;
620
+ if (c >= 48 && c <= 57) code |= c - 48;
621
+ else if (c >= 97 && c <= 102) code |= c + -87;
622
+ else if (c >= 65 && c <= 70) code |= c + -55;
623
+ else throwSyntaxError(bytes, --i);
624
+ }
625
+ value += fromCharCode(code);
626
+ break;
627
+ }
628
+ default:
629
+ throwSyntaxError(bytes, --i);
630
+ break;
631
+ }
632
+ else if (c <= 127) value += fromCharCode(c);
633
+ else if ((c & 224) === 192) value += fromCharCode((c & 31) << 6 | bytes[i++] & 63);
634
+ else if ((c & 240) === 224) value += fromCharCode((c & 15) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63);
635
+ else if ((c & 248) == 240) {
636
+ let codePoint = (c & 7) << 18 | (bytes[i++] & 63) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63;
637
+ if (codePoint > 65535) {
638
+ codePoint -= 65536;
639
+ value += fromCharCode(codePoint >> 10 & 1023 | 55296);
640
+ codePoint = 56320 | codePoint & 1023;
641
+ }
642
+ value += fromCharCode(codePoint);
643
+ }
644
+ }
645
+ value[0];
646
+ break;
647
+ case 91:
648
+ value = [];
649
+ propertyStack.push(property);
650
+ objectStack.push(object);
651
+ stateStack.push(state);
652
+ property = null;
653
+ object = value;
654
+ state = 1;
655
+ continue;
656
+ case 123:
657
+ value = {};
658
+ propertyStack.push(property);
659
+ objectStack.push(object);
660
+ stateStack.push(state);
661
+ property = null;
662
+ object = value;
663
+ state = 2;
664
+ continue;
665
+ case 93:
666
+ if (state !== 1) throwSyntaxError(bytes, --i);
667
+ value = object;
668
+ property = propertyStack.pop();
669
+ object = objectStack.pop();
670
+ state = stateStack.pop();
671
+ break;
672
+ case 125:
673
+ if (state !== 2) throwSyntaxError(bytes, --i);
674
+ value = object;
675
+ property = propertyStack.pop();
676
+ object = objectStack.pop();
677
+ state = stateStack.pop();
678
+ break;
679
+ default: throwSyntaxError(bytes, --i);
680
+ }
681
+ c = bytes[i];
682
+ while (c <= 32) c = bytes[++i];
683
+ switch (state) {
684
+ case 0:
685
+ if (i === length) return value;
686
+ break;
687
+ case 1:
688
+ object.push(value);
689
+ if (c === 44) {
690
+ i++;
691
+ continue;
692
+ }
693
+ if (c === 93) continue;
694
+ break;
695
+ case 2:
696
+ if (property === null) {
697
+ property = value;
698
+ if (c === 58) {
699
+ i++;
700
+ continue;
701
+ }
702
+ } else {
703
+ object[property] = value;
704
+ property = null;
705
+ if (c === 44) {
706
+ i++;
707
+ continue;
708
+ }
709
+ if (c === 125) continue;
710
+ }
711
+ break;
712
+ }
713
+ break;
714
+ }
715
+ throwSyntaxError(bytes, i);
716
+ }
717
+ var quote = JSON.stringify;
718
+ var buildLogLevelDefault = "warning";
719
+ var transformLogLevelDefault = "silent";
720
+ function validateAndJoinStringArray(values, what) {
721
+ const toJoin = [];
722
+ for (const value of values) {
723
+ validateStringValue(value, what);
724
+ if (value.indexOf(",") >= 0) throw new Error(`Invalid ${what}: ${value}`);
725
+ toJoin.push(value);
726
+ }
727
+ return toJoin.join(",");
728
+ }
729
+ var canBeAnything = () => null;
730
+ var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
731
+ var mustBeString = (value) => typeof value === "string" ? null : "a string";
732
+ var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
733
+ var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
734
+ var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
735
+ var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
736
+ var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
737
+ var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings";
738
+ var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
739
+ var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
740
+ var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
741
+ var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
742
+ var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
743
+ var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
744
+ var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings";
745
+ var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
746
+ var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
747
+ function getFlag(object, keys, key, mustBeFn) {
748
+ let value = object[key];
749
+ keys[key + ""] = true;
750
+ if (value === void 0) return void 0;
751
+ let mustBe = mustBeFn(value);
752
+ if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`);
753
+ return value;
754
+ }
755
+ function checkForInvalidFlags(object, keys, where) {
756
+ for (let key in object) if (!(key in keys)) throw new Error(`Invalid option ${where}: ${quote(key)}`);
757
+ }
758
+ function validateInitializeOptions(options) {
759
+ let keys = /* @__PURE__ */ Object.create(null);
760
+ let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
761
+ let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
762
+ let worker = getFlag(options, keys, "worker", mustBeBoolean);
763
+ checkForInvalidFlags(options, keys, "in initialize() call");
764
+ return {
765
+ wasmURL,
766
+ wasmModule,
767
+ worker
768
+ };
769
+ }
770
+ function validateMangleCache(mangleCache) {
771
+ let validated;
772
+ if (mangleCache !== void 0) {
773
+ validated = /* @__PURE__ */ Object.create(null);
774
+ for (let key in mangleCache) {
775
+ let value = mangleCache[key];
776
+ if (typeof value === "string" || value === false) validated[key] = value;
777
+ else throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
778
+ }
779
+ }
780
+ return validated;
781
+ }
782
+ function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
783
+ let color = getFlag(options, keys, "color", mustBeBoolean);
784
+ let logLevel = getFlag(options, keys, "logLevel", mustBeString);
785
+ let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
786
+ if (color !== void 0) flags.push(`--color=${color}`);
787
+ else if (isTTY2) flags.push(`--color=true`);
788
+ flags.push(`--log-level=${logLevel || logLevelDefault}`);
789
+ flags.push(`--log-limit=${logLimit || 0}`);
790
+ }
791
+ function validateStringValue(value, what, key) {
792
+ if (typeof value !== "string") throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
793
+ return value;
794
+ }
795
+ function pushCommonFlags(flags, options, keys) {
796
+ let legalComments = getFlag(options, keys, "legalComments", mustBeString);
797
+ let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
798
+ let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
799
+ let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings);
800
+ let format = getFlag(options, keys, "format", mustBeString);
801
+ let globalName = getFlag(options, keys, "globalName", mustBeString);
802
+ let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
803
+ let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
804
+ let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
805
+ let minify = getFlag(options, keys, "minify", mustBeBoolean);
806
+ let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
807
+ let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
808
+ let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
809
+ let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
810
+ let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings);
811
+ let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings);
812
+ let charset = getFlag(options, keys, "charset", mustBeString);
813
+ let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
814
+ let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
815
+ let jsx = getFlag(options, keys, "jsx", mustBeString);
816
+ let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
817
+ let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
818
+ let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
819
+ let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
820
+ let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
821
+ let define = getFlag(options, keys, "define", mustBeObject);
822
+ let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
823
+ let supported = getFlag(options, keys, "supported", mustBeObject);
824
+ let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings);
825
+ let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
826
+ let platform = getFlag(options, keys, "platform", mustBeString);
827
+ let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
828
+ let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings);
829
+ if (legalComments) flags.push(`--legal-comments=${legalComments}`);
830
+ if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`);
831
+ if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`);
832
+ if (target) flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`);
833
+ if (format) flags.push(`--format=${format}`);
834
+ if (globalName) flags.push(`--global-name=${globalName}`);
835
+ if (platform) flags.push(`--platform=${platform}`);
836
+ if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
837
+ if (minify) flags.push("--minify");
838
+ if (minifySyntax) flags.push("--minify-syntax");
839
+ if (minifyWhitespace) flags.push("--minify-whitespace");
840
+ if (minifyIdentifiers) flags.push("--minify-identifiers");
841
+ if (lineLimit) flags.push(`--line-limit=${lineLimit}`);
842
+ if (charset) flags.push(`--charset=${charset}`);
843
+ if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
844
+ if (ignoreAnnotations) flags.push(`--ignore-annotations`);
845
+ if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`);
846
+ if (dropLabels) flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`);
847
+ if (absPaths) flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`);
848
+ if (mangleProps) flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`);
849
+ if (reserveProps) flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`);
850
+ if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`);
851
+ if (jsx) flags.push(`--jsx=${jsx}`);
852
+ if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
853
+ if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`);
854
+ if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`);
855
+ if (jsxDev) flags.push(`--jsx-dev`);
856
+ if (jsxSideEffects) flags.push(`--jsx-side-effects`);
857
+ if (define) for (let key in define) {
858
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`);
859
+ flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
860
+ }
861
+ if (logOverride) for (let key in logOverride) {
862
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`);
863
+ flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
864
+ }
865
+ if (supported) for (let key in supported) {
866
+ if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`);
867
+ const value = supported[key];
868
+ if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
869
+ flags.push(`--supported:${key}=${value}`);
870
+ }
871
+ if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`);
872
+ if (keepNames) flags.push(`--keep-names`);
873
+ }
874
+ function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
875
+ var _a2;
876
+ let flags = [];
877
+ let entries = [];
878
+ let keys = /* @__PURE__ */ Object.create(null);
879
+ let stdinContents = null;
880
+ let stdinResolveDir = null;
881
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
882
+ pushCommonFlags(flags, options, keys);
883
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
884
+ let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
885
+ let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
886
+ let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
887
+ let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
888
+ let outfile = getFlag(options, keys, "outfile", mustBeString);
889
+ let outdir = getFlag(options, keys, "outdir", mustBeString);
890
+ let outbase = getFlag(options, keys, "outbase", mustBeString);
891
+ let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
892
+ let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings);
893
+ let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings);
894
+ let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings);
895
+ let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings);
896
+ let external = getFlag(options, keys, "external", mustBeArrayOfStrings);
897
+ let packages = getFlag(options, keys, "packages", mustBeString);
898
+ let alias = getFlag(options, keys, "alias", mustBeObject);
899
+ let loader = getFlag(options, keys, "loader", mustBeObject);
900
+ let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
901
+ let publicPath = getFlag(options, keys, "publicPath", mustBeString);
902
+ let entryNames = getFlag(options, keys, "entryNames", mustBeString);
903
+ let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
904
+ let assetNames = getFlag(options, keys, "assetNames", mustBeString);
905
+ let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings);
906
+ let banner = getFlag(options, keys, "banner", mustBeObject);
907
+ let footer = getFlag(options, keys, "footer", mustBeObject);
908
+ let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
909
+ let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
910
+ let stdin = getFlag(options, keys, "stdin", mustBeObject);
911
+ let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
912
+ let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
913
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
914
+ keys.plugins = true;
915
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
916
+ if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
917
+ if (bundle) flags.push("--bundle");
918
+ if (allowOverwrite) flags.push("--allow-overwrite");
919
+ if (splitting) flags.push("--splitting");
920
+ if (preserveSymlinks) flags.push("--preserve-symlinks");
921
+ if (metafile) flags.push(`--metafile`);
922
+ if (outfile) flags.push(`--outfile=${outfile}`);
923
+ if (outdir) flags.push(`--outdir=${outdir}`);
924
+ if (outbase) flags.push(`--outbase=${outbase}`);
925
+ if (tsconfig) flags.push(`--tsconfig=${tsconfig}`);
926
+ if (packages) flags.push(`--packages=${packages}`);
927
+ if (resolveExtensions) flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`);
928
+ if (publicPath) flags.push(`--public-path=${publicPath}`);
929
+ if (entryNames) flags.push(`--entry-names=${entryNames}`);
930
+ if (chunkNames) flags.push(`--chunk-names=${chunkNames}`);
931
+ if (assetNames) flags.push(`--asset-names=${assetNames}`);
932
+ if (mainFields) flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`);
933
+ if (conditions) flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`);
934
+ if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`);
935
+ if (alias) for (let old in alias) {
936
+ if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`);
937
+ flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
938
+ }
939
+ if (banner) for (let type in banner) {
940
+ if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`);
941
+ flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
942
+ }
943
+ if (footer) for (let type in footer) {
944
+ if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`);
945
+ flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
946
+ }
947
+ if (inject) for (let path3 of inject) flags.push(`--inject:${validateStringValue(path3, "inject")}`);
948
+ if (loader) for (let ext in loader) {
949
+ if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`);
950
+ flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
951
+ }
952
+ if (outExtension) for (let ext in outExtension) {
953
+ if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
954
+ flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
955
+ }
956
+ if (entryPoints) if (Array.isArray(entryPoints)) for (let i = 0, n = entryPoints.length; i < n; i++) {
957
+ let entryPoint = entryPoints[i];
958
+ if (typeof entryPoint === "object" && entryPoint !== null) {
959
+ let entryPointKeys = /* @__PURE__ */ Object.create(null);
960
+ let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
961
+ let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
962
+ checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
963
+ if (input === void 0) throw new Error("Missing property \"in\" for entry point at index " + i);
964
+ if (output === void 0) throw new Error("Missing property \"out\" for entry point at index " + i);
965
+ entries.push([output, input]);
966
+ } else entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
967
+ }
968
+ else for (let key in entryPoints) entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
969
+ if (stdin) {
970
+ let stdinKeys = /* @__PURE__ */ Object.create(null);
971
+ let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
972
+ let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
973
+ let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
974
+ let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
975
+ checkForInvalidFlags(stdin, stdinKeys, "in \"stdin\" object");
976
+ if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
977
+ if (loader2) flags.push(`--loader=${loader2}`);
978
+ if (resolveDir) stdinResolveDir = resolveDir;
979
+ if (typeof contents === "string") stdinContents = encodeUTF8(contents);
980
+ else if (contents instanceof Uint8Array) stdinContents = contents;
981
+ }
982
+ let nodePaths = [];
983
+ if (nodePathsInput) for (let value of nodePathsInput) {
984
+ value += "";
985
+ nodePaths.push(value);
986
+ }
987
+ return {
988
+ entries,
989
+ flags,
990
+ write,
991
+ stdinContents,
992
+ stdinResolveDir,
993
+ absWorkingDir,
994
+ nodePaths,
995
+ mangleCache: validateMangleCache(mangleCache)
996
+ };
997
+ }
998
+ function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
999
+ let flags = [];
1000
+ let keys = /* @__PURE__ */ Object.create(null);
1001
+ pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
1002
+ pushCommonFlags(flags, options, keys);
1003
+ let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
1004
+ let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
1005
+ let loader = getFlag(options, keys, "loader", mustBeString);
1006
+ let banner = getFlag(options, keys, "banner", mustBeString);
1007
+ let footer = getFlag(options, keys, "footer", mustBeString);
1008
+ let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
1009
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
1010
+ if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
1011
+ if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
1012
+ if (loader) flags.push(`--loader=${loader}`);
1013
+ if (banner) flags.push(`--banner=${banner}`);
1014
+ if (footer) flags.push(`--footer=${footer}`);
1015
+ return {
1016
+ flags,
1017
+ mangleCache: validateMangleCache(mangleCache)
1018
+ };
1019
+ }
1020
+ function createChannel(streamIn) {
1021
+ const requestCallbacksByKey = {};
1022
+ const closeData = {
1023
+ didClose: false,
1024
+ reason: ""
1025
+ };
1026
+ let responseCallbacks = {};
1027
+ let nextRequestID = 0;
1028
+ let nextBuildKey = 0;
1029
+ let stdout = new Uint8Array(16 * 1024);
1030
+ let stdoutUsed = 0;
1031
+ let readFromStdout = (chunk) => {
1032
+ let limit = stdoutUsed + chunk.length;
1033
+ if (limit > stdout.length) {
1034
+ let swap = new Uint8Array(limit * 2);
1035
+ swap.set(stdout);
1036
+ stdout = swap;
1037
+ }
1038
+ stdout.set(chunk, stdoutUsed);
1039
+ stdoutUsed += chunk.length;
1040
+ let offset = 0;
1041
+ while (offset + 4 <= stdoutUsed) {
1042
+ let length = readUInt32LE(stdout, offset);
1043
+ if (offset + 4 + length > stdoutUsed) break;
1044
+ offset += 4;
1045
+ handleIncomingPacket(stdout.subarray(offset, offset + length));
1046
+ offset += length;
1047
+ }
1048
+ if (offset > 0) {
1049
+ stdout.copyWithin(0, offset, stdoutUsed);
1050
+ stdoutUsed -= offset;
1051
+ }
1052
+ };
1053
+ let afterClose = (error) => {
1054
+ closeData.didClose = true;
1055
+ if (error) closeData.reason = ": " + (error.message || error);
1056
+ const text = "The service was stopped" + closeData.reason;
1057
+ for (let id in responseCallbacks) responseCallbacks[id](text, null);
1058
+ responseCallbacks = {};
1059
+ };
1060
+ let sendRequest = (refs, value, callback) => {
1061
+ if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null);
1062
+ let id = nextRequestID++;
1063
+ responseCallbacks[id] = (error, response) => {
1064
+ try {
1065
+ callback(error, response);
1066
+ } finally {
1067
+ if (refs) refs.unref();
1068
+ }
1069
+ };
1070
+ if (refs) refs.ref();
1071
+ streamIn.writeToStdin(encodePacket({
1072
+ id,
1073
+ isRequest: true,
1074
+ value
1075
+ }));
1076
+ };
1077
+ let sendResponse = (id, value) => {
1078
+ if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason);
1079
+ streamIn.writeToStdin(encodePacket({
1080
+ id,
1081
+ isRequest: false,
1082
+ value
1083
+ }));
1084
+ };
1085
+ let handleRequest = async (id, request) => {
1086
+ try {
1087
+ if (request.command === "ping") {
1088
+ sendResponse(id, {});
1089
+ return;
1090
+ }
1091
+ if (typeof request.key === "number") {
1092
+ const requestCallbacks = requestCallbacksByKey[request.key];
1093
+ if (!requestCallbacks) return;
1094
+ const callback = requestCallbacks[request.command];
1095
+ if (callback) {
1096
+ await callback(id, request);
1097
+ return;
1098
+ }
1099
+ }
1100
+ throw new Error(`Invalid command: ` + request.command);
1101
+ } catch (e) {
1102
+ const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")];
1103
+ try {
1104
+ sendResponse(id, { errors });
1105
+ } catch {}
1106
+ }
1107
+ };
1108
+ let isFirstPacket = true;
1109
+ let handleIncomingPacket = (bytes) => {
1110
+ if (isFirstPacket) {
1111
+ isFirstPacket = false;
1112
+ let binaryVersion = String.fromCharCode(...bytes);
1113
+ if (binaryVersion !== "0.27.7") throw new Error(`Cannot start service: Host version "0.27.7" does not match binary version ${quote(binaryVersion)}`);
1114
+ return;
1115
+ }
1116
+ let packet = decodePacket(bytes);
1117
+ if (packet.isRequest) handleRequest(packet.id, packet.value);
1118
+ else {
1119
+ let callback = responseCallbacks[packet.id];
1120
+ delete responseCallbacks[packet.id];
1121
+ if (packet.value.error) callback(packet.value.error, {});
1122
+ else callback(null, packet.value);
1123
+ }
1124
+ };
1125
+ let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
1126
+ let refCount = 0;
1127
+ const buildKey = nextBuildKey++;
1128
+ const requestCallbacks = {};
1129
+ const buildRefs = {
1130
+ ref() {
1131
+ if (++refCount === 1) {
1132
+ if (refs) refs.ref();
1133
+ }
1134
+ },
1135
+ unref() {
1136
+ if (--refCount === 0) {
1137
+ delete requestCallbacksByKey[buildKey];
1138
+ if (refs) refs.unref();
1139
+ }
1140
+ }
1141
+ };
1142
+ requestCallbacksByKey[buildKey] = requestCallbacks;
1143
+ buildRefs.ref();
1144
+ buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, buildRefs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, (err, res) => {
1145
+ try {
1146
+ callback(err, res);
1147
+ } finally {
1148
+ buildRefs.unref();
1149
+ }
1150
+ });
1151
+ };
1152
+ let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
1153
+ const details = createObjectStash();
1154
+ let start = (inputPath) => {
1155
+ try {
1156
+ if (typeof input !== "string" && !(input instanceof Uint8Array)) throw new Error("The input to \"transform\" must be a string or a Uint8Array");
1157
+ let { flags, mangleCache } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
1158
+ let request = {
1159
+ command: "transform",
1160
+ flags,
1161
+ inputFS: inputPath !== null,
1162
+ input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
1163
+ };
1164
+ if (mangleCache) request.mangleCache = mangleCache;
1165
+ sendRequest(refs, request, (error, response) => {
1166
+ if (error) return callback(new Error(error), null);
1167
+ let errors = replaceDetailsInMessages(response.errors, details);
1168
+ let warnings = replaceDetailsInMessages(response.warnings, details);
1169
+ let outstanding = 1;
1170
+ let next = () => {
1171
+ if (--outstanding === 0) {
1172
+ let result = {
1173
+ warnings,
1174
+ code: response.code,
1175
+ map: response.map,
1176
+ mangleCache: void 0,
1177
+ legalComments: void 0
1178
+ };
1179
+ if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments;
1180
+ if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache;
1181
+ callback(null, result);
1182
+ }
1183
+ };
1184
+ if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
1185
+ if (response.codeFS) {
1186
+ outstanding++;
1187
+ fs3.readFile(response.code, (err, contents) => {
1188
+ if (err !== null) callback(err, null);
1189
+ else {
1190
+ response.code = contents;
1191
+ next();
1192
+ }
1193
+ });
1194
+ }
1195
+ if (response.mapFS) {
1196
+ outstanding++;
1197
+ fs3.readFile(response.map, (err, contents) => {
1198
+ if (err !== null) callback(err, null);
1199
+ else {
1200
+ response.map = contents;
1201
+ next();
1202
+ }
1203
+ });
1204
+ }
1205
+ next();
1206
+ });
1207
+ } catch (e) {
1208
+ let flags = [];
1209
+ try {
1210
+ pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
1211
+ } catch {}
1212
+ const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
1213
+ sendRequest(refs, {
1214
+ command: "error",
1215
+ flags,
1216
+ error
1217
+ }, () => {
1218
+ error.detail = details.load(error.detail);
1219
+ callback(failureErrorWithLog("Transform failed", [error], []), null);
1220
+ });
1221
+ }
1222
+ };
1223
+ if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
1224
+ let next = start;
1225
+ start = () => fs3.writeFile(input, next);
1226
+ }
1227
+ start(null);
1228
+ };
1229
+ let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
1230
+ if (!options) throw new Error(`Missing second argument in ${callName}() call`);
1231
+ let keys = {};
1232
+ let kind = getFlag(options, keys, "kind", mustBeString);
1233
+ let color = getFlag(options, keys, "color", mustBeBoolean);
1234
+ let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
1235
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
1236
+ if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`);
1237
+ if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
1238
+ let request = {
1239
+ command: "format-msgs",
1240
+ messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
1241
+ isWarning: kind === "warning"
1242
+ };
1243
+ if (color !== void 0) request.color = color;
1244
+ if (terminalWidth !== void 0) request.terminalWidth = terminalWidth;
1245
+ sendRequest(refs, request, (error, response) => {
1246
+ if (error) return callback(new Error(error), null);
1247
+ callback(null, response.messages);
1248
+ });
1249
+ };
1250
+ let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
1251
+ if (options === void 0) options = {};
1252
+ let keys = {};
1253
+ let color = getFlag(options, keys, "color", mustBeBoolean);
1254
+ let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
1255
+ checkForInvalidFlags(options, keys, `in ${callName}() call`);
1256
+ let request = {
1257
+ command: "analyze-metafile",
1258
+ metafile
1259
+ };
1260
+ if (color !== void 0) request.color = color;
1261
+ if (verbose !== void 0) request.verbose = verbose;
1262
+ sendRequest(refs, request, (error, response) => {
1263
+ if (error) return callback(new Error(error), null);
1264
+ callback(null, response.result);
1265
+ });
1266
+ };
1267
+ return {
1268
+ readFromStdout,
1269
+ afterClose,
1270
+ service: {
1271
+ buildOrContext,
1272
+ transform: transform2,
1273
+ formatMessages: formatMessages2,
1274
+ analyzeMetafile: analyzeMetafile2
1275
+ }
1276
+ };
1277
+ }
1278
+ function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
1279
+ const details = createObjectStash();
1280
+ const isContext = callName === "context";
1281
+ const handleError = (e, pluginName) => {
1282
+ const flags = [];
1283
+ try {
1284
+ pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
1285
+ } catch {}
1286
+ const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
1287
+ sendRequest(refs, {
1288
+ command: "error",
1289
+ flags,
1290
+ error: message
1291
+ }, () => {
1292
+ message.detail = details.load(message.detail);
1293
+ callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
1294
+ });
1295
+ };
1296
+ let plugins;
1297
+ if (typeof options === "object") {
1298
+ const value = options.plugins;
1299
+ if (value !== void 0) {
1300
+ if (!Array.isArray(value)) return handleError(/* @__PURE__ */ new Error(`"plugins" must be an array`), "");
1301
+ plugins = value;
1302
+ }
1303
+ }
1304
+ if (plugins && plugins.length > 0) {
1305
+ if (streamIn.isSync) return handleError(/* @__PURE__ */ new Error("Cannot use plugins in synchronous API calls"), "");
1306
+ handlePlugins(buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, plugins, details).then((result) => {
1307
+ if (!result.ok) return handleError(result.error, result.pluginName);
1308
+ try {
1309
+ buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
1310
+ } catch (e) {
1311
+ handleError(e, "");
1312
+ }
1313
+ }, (e) => handleError(e, ""));
1314
+ return;
1315
+ }
1316
+ try {
1317
+ buildOrContextContinue(null, (result, done) => done([], []), () => {});
1318
+ } catch (e) {
1319
+ handleError(e, "");
1320
+ }
1321
+ function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
1322
+ const writeDefault = streamIn.hasFS;
1323
+ const { entries, flags, write, stdinContents, stdinResolveDir, absWorkingDir, nodePaths, mangleCache } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
1324
+ if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`);
1325
+ const request = {
1326
+ command: "build",
1327
+ key: buildKey,
1328
+ entries,
1329
+ flags,
1330
+ write,
1331
+ stdinContents,
1332
+ stdinResolveDir,
1333
+ absWorkingDir: absWorkingDir || defaultWD2,
1334
+ nodePaths,
1335
+ context: isContext
1336
+ };
1337
+ if (requestPlugins) request.plugins = requestPlugins;
1338
+ if (mangleCache) request.mangleCache = mangleCache;
1339
+ const buildResponseToResult = (response, callback2) => {
1340
+ const result = {
1341
+ errors: replaceDetailsInMessages(response.errors, details),
1342
+ warnings: replaceDetailsInMessages(response.warnings, details),
1343
+ outputFiles: void 0,
1344
+ metafile: void 0,
1345
+ mangleCache: void 0
1346
+ };
1347
+ const originalErrors = result.errors.slice();
1348
+ const originalWarnings = result.warnings.slice();
1349
+ if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles);
1350
+ if (response.metafile && response.metafile.length) result.metafile = parseJSON(response.metafile);
1351
+ if (response.mangleCache) result.mangleCache = response.mangleCache;
1352
+ if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
1353
+ runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
1354
+ if (originalErrors.length > 0 || onEndErrors.length > 0) return callback2(failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings)), null, onEndErrors, onEndWarnings);
1355
+ callback2(null, result, onEndErrors, onEndWarnings);
1356
+ });
1357
+ };
1358
+ let latestResultPromise;
1359
+ let provideLatestResult;
1360
+ if (isContext) requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => {
1361
+ buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
1362
+ const response = {
1363
+ errors: onEndErrors,
1364
+ warnings: onEndWarnings
1365
+ };
1366
+ if (provideLatestResult) provideLatestResult(err, result);
1367
+ latestResultPromise = void 0;
1368
+ provideLatestResult = void 0;
1369
+ sendResponse(id, response);
1370
+ resolve();
1371
+ });
1372
+ });
1373
+ sendRequest(refs, request, (error, response) => {
1374
+ if (error) return callback(new Error(error), null);
1375
+ if (!isContext) return buildResponseToResult(response, (err, res) => {
1376
+ scheduleOnDisposeCallbacks();
1377
+ return callback(err, res);
1378
+ });
1379
+ if (response.errors.length > 0) return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
1380
+ let didDispose = false;
1381
+ const result = {
1382
+ rebuild: () => {
1383
+ if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => {
1384
+ let settlePromise;
1385
+ provideLatestResult = (err, result2) => {
1386
+ if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2);
1387
+ };
1388
+ const triggerAnotherBuild = () => {
1389
+ sendRequest(refs, {
1390
+ command: "rebuild",
1391
+ key: buildKey
1392
+ }, (error2, response2) => {
1393
+ if (error2) reject(new Error(error2));
1394
+ else if (settlePromise) settlePromise();
1395
+ else triggerAnotherBuild();
1396
+ });
1397
+ };
1398
+ triggerAnotherBuild();
1399
+ });
1400
+ return latestResultPromise;
1401
+ },
1402
+ watch: (options2 = {}) => new Promise((resolve, reject) => {
1403
+ if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`);
1404
+ const keys = {};
1405
+ const delay = getFlag(options2, keys, "delay", mustBeInteger);
1406
+ checkForInvalidFlags(options2, keys, `in watch() call`);
1407
+ const request2 = {
1408
+ command: "watch",
1409
+ key: buildKey
1410
+ };
1411
+ if (delay) request2.delay = delay;
1412
+ sendRequest(refs, request2, (error2) => {
1413
+ if (error2) reject(new Error(error2));
1414
+ else resolve(void 0);
1415
+ });
1416
+ }),
1417
+ serve: (options2 = {}) => new Promise((resolve, reject) => {
1418
+ if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`);
1419
+ const keys = {};
1420
+ const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
1421
+ const host = getFlag(options2, keys, "host", mustBeString);
1422
+ const servedir = getFlag(options2, keys, "servedir", mustBeString);
1423
+ const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
1424
+ const certfile = getFlag(options2, keys, "certfile", mustBeString);
1425
+ const fallback = getFlag(options2, keys, "fallback", mustBeString);
1426
+ const cors = getFlag(options2, keys, "cors", mustBeObject);
1427
+ const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
1428
+ checkForInvalidFlags(options2, keys, `in serve() call`);
1429
+ const request2 = {
1430
+ command: "serve",
1431
+ key: buildKey,
1432
+ onRequest: !!onRequest
1433
+ };
1434
+ if (port !== void 0) request2.port = port;
1435
+ if (host !== void 0) request2.host = host;
1436
+ if (servedir !== void 0) request2.servedir = servedir;
1437
+ if (keyfile !== void 0) request2.keyfile = keyfile;
1438
+ if (certfile !== void 0) request2.certfile = certfile;
1439
+ if (fallback !== void 0) request2.fallback = fallback;
1440
+ if (cors) {
1441
+ const corsKeys = {};
1442
+ const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings);
1443
+ checkForInvalidFlags(cors, corsKeys, `on "cors" object`);
1444
+ if (Array.isArray(origin)) request2.corsOrigin = origin;
1445
+ else if (origin !== void 0) request2.corsOrigin = [origin];
1446
+ }
1447
+ sendRequest(refs, request2, (error2, response2) => {
1448
+ if (error2) return reject(new Error(error2));
1449
+ if (onRequest) requestCallbacks["serve-request"] = (id, request3) => {
1450
+ onRequest(request3.args);
1451
+ sendResponse(id, {});
1452
+ };
1453
+ resolve(response2);
1454
+ });
1455
+ }),
1456
+ cancel: () => new Promise((resolve) => {
1457
+ if (didDispose) return resolve();
1458
+ sendRequest(refs, {
1459
+ command: "cancel",
1460
+ key: buildKey
1461
+ }, () => {
1462
+ resolve();
1463
+ });
1464
+ }),
1465
+ dispose: () => new Promise((resolve) => {
1466
+ if (didDispose) return resolve();
1467
+ didDispose = true;
1468
+ sendRequest(refs, {
1469
+ command: "dispose",
1470
+ key: buildKey
1471
+ }, () => {
1472
+ resolve();
1473
+ scheduleOnDisposeCallbacks();
1474
+ refs.unref();
1475
+ });
1476
+ })
1477
+ };
1478
+ refs.ref();
1479
+ callback(null, result);
1480
+ });
1481
+ }
1482
+ }
1483
+ var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
1484
+ let onStartCallbacks = [];
1485
+ let onEndCallbacks = [];
1486
+ let onResolveCallbacks = {};
1487
+ let onLoadCallbacks = {};
1488
+ let onDisposeCallbacks = [];
1489
+ let nextCallbackID = 0;
1490
+ let i = 0;
1491
+ let requestPlugins = [];
1492
+ let isSetupDone = false;
1493
+ plugins = [...plugins];
1494
+ for (let item of plugins) {
1495
+ let keys = {};
1496
+ if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`);
1497
+ const name = getFlag(item, keys, "name", mustBeString);
1498
+ if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`);
1499
+ try {
1500
+ let setup = getFlag(item, keys, "setup", mustBeFunction);
1501
+ if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`);
1502
+ checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
1503
+ let plugin = {
1504
+ name,
1505
+ onStart: false,
1506
+ onEnd: false,
1507
+ onResolve: [],
1508
+ onLoad: []
1509
+ };
1510
+ i++;
1511
+ let resolve = (path3, options = {}) => {
1512
+ if (!isSetupDone) throw new Error("Cannot call \"resolve\" before plugin setup has completed");
1513
+ if (typeof path3 !== "string") throw new Error(`The path to resolve must be a string`);
1514
+ let keys2 = /* @__PURE__ */ Object.create(null);
1515
+ let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
1516
+ let importer = getFlag(options, keys2, "importer", mustBeString);
1517
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1518
+ let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
1519
+ let kind = getFlag(options, keys2, "kind", mustBeString);
1520
+ let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
1521
+ let importAttributes = getFlag(options, keys2, "with", mustBeObject);
1522
+ checkForInvalidFlags(options, keys2, "in resolve() call");
1523
+ return new Promise((resolve2, reject) => {
1524
+ const request = {
1525
+ command: "resolve",
1526
+ path: path3,
1527
+ key: buildKey,
1528
+ pluginName: name
1529
+ };
1530
+ if (pluginName != null) request.pluginName = pluginName;
1531
+ if (importer != null) request.importer = importer;
1532
+ if (namespace != null) request.namespace = namespace;
1533
+ if (resolveDir != null) request.resolveDir = resolveDir;
1534
+ if (kind != null) request.kind = kind;
1535
+ else throw new Error(`Must specify "kind" when calling "resolve"`);
1536
+ if (pluginData != null) request.pluginData = details.store(pluginData);
1537
+ if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with");
1538
+ sendRequest(refs, request, (error, response) => {
1539
+ if (error !== null) reject(new Error(error));
1540
+ else resolve2({
1541
+ errors: replaceDetailsInMessages(response.errors, details),
1542
+ warnings: replaceDetailsInMessages(response.warnings, details),
1543
+ path: response.path,
1544
+ external: response.external,
1545
+ sideEffects: response.sideEffects,
1546
+ namespace: response.namespace,
1547
+ suffix: response.suffix,
1548
+ pluginData: details.load(response.pluginData)
1549
+ });
1550
+ });
1551
+ });
1552
+ };
1553
+ let promise = setup({
1554
+ initialOptions,
1555
+ resolve,
1556
+ onStart(callback) {
1557
+ let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onStart" callback registered here:`), streamIn, "onStart");
1558
+ onStartCallbacks.push({
1559
+ name,
1560
+ callback,
1561
+ note: registeredNote
1562
+ });
1563
+ plugin.onStart = true;
1564
+ },
1565
+ onEnd(callback) {
1566
+ let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onEnd" callback registered here:`), streamIn, "onEnd");
1567
+ onEndCallbacks.push({
1568
+ name,
1569
+ callback,
1570
+ note: registeredNote
1571
+ });
1572
+ plugin.onEnd = true;
1573
+ },
1574
+ onResolve(options, callback) {
1575
+ let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onResolve" callback registered here:`), streamIn, "onResolve");
1576
+ let keys2 = {};
1577
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1578
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1579
+ checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
1580
+ if (filter == null) throw new Error(`onResolve() call is missing a filter`);
1581
+ let id = nextCallbackID++;
1582
+ onResolveCallbacks[id] = {
1583
+ name,
1584
+ callback,
1585
+ note: registeredNote
1586
+ };
1587
+ plugin.onResolve.push({
1588
+ id,
1589
+ filter: jsRegExpToGoRegExp(filter),
1590
+ namespace: namespace || ""
1591
+ });
1592
+ },
1593
+ onLoad(options, callback) {
1594
+ let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onLoad" callback registered here:`), streamIn, "onLoad");
1595
+ let keys2 = {};
1596
+ let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1597
+ let namespace = getFlag(options, keys2, "namespace", mustBeString);
1598
+ checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
1599
+ if (filter == null) throw new Error(`onLoad() call is missing a filter`);
1600
+ let id = nextCallbackID++;
1601
+ onLoadCallbacks[id] = {
1602
+ name,
1603
+ callback,
1604
+ note: registeredNote
1605
+ };
1606
+ plugin.onLoad.push({
1607
+ id,
1608
+ filter: jsRegExpToGoRegExp(filter),
1609
+ namespace: namespace || ""
1610
+ });
1611
+ },
1612
+ onDispose(callback) {
1613
+ onDisposeCallbacks.push(callback);
1614
+ },
1615
+ esbuild: streamIn.esbuild
1616
+ });
1617
+ if (promise) await promise;
1618
+ requestPlugins.push(plugin);
1619
+ } catch (e) {
1620
+ return {
1621
+ ok: false,
1622
+ error: e,
1623
+ pluginName: name
1624
+ };
1625
+ }
1626
+ }
1627
+ requestCallbacks["on-start"] = async (id, request) => {
1628
+ details.clear();
1629
+ let response = {
1630
+ errors: [],
1631
+ warnings: []
1632
+ };
1633
+ await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
1634
+ try {
1635
+ let result = await callback();
1636
+ if (result != null) {
1637
+ if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
1638
+ let keys = {};
1639
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1640
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1641
+ checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
1642
+ if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
1643
+ if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
1644
+ }
1645
+ } catch (e) {
1646
+ response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
1647
+ }
1648
+ }));
1649
+ sendResponse(id, response);
1650
+ };
1651
+ requestCallbacks["on-resolve"] = async (id, request) => {
1652
+ let response = {}, name = "", callback, note;
1653
+ for (let id2 of request.ids) try {
1654
+ ({name, callback, note} = onResolveCallbacks[id2]);
1655
+ let result = await callback({
1656
+ path: request.path,
1657
+ importer: request.importer,
1658
+ namespace: request.namespace,
1659
+ resolveDir: request.resolveDir,
1660
+ kind: request.kind,
1661
+ pluginData: details.load(request.pluginData),
1662
+ with: request.with
1663
+ });
1664
+ if (result != null) {
1665
+ if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
1666
+ let keys = {};
1667
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1668
+ let path3 = getFlag(result, keys, "path", mustBeString);
1669
+ let namespace = getFlag(result, keys, "namespace", mustBeString);
1670
+ let suffix = getFlag(result, keys, "suffix", mustBeString);
1671
+ let external = getFlag(result, keys, "external", mustBeBoolean);
1672
+ let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
1673
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1674
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1675
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1676
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1677
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1678
+ checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
1679
+ response.id = id2;
1680
+ if (pluginName != null) response.pluginName = pluginName;
1681
+ if (path3 != null) response.path = path3;
1682
+ if (namespace != null) response.namespace = namespace;
1683
+ if (suffix != null) response.suffix = suffix;
1684
+ if (external != null) response.external = external;
1685
+ if (sideEffects != null) response.sideEffects = sideEffects;
1686
+ if (pluginData != null) response.pluginData = details.store(pluginData);
1687
+ if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1688
+ if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1689
+ if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1690
+ if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1691
+ break;
1692
+ }
1693
+ } catch (e) {
1694
+ response = {
1695
+ id: id2,
1696
+ errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]
1697
+ };
1698
+ break;
1699
+ }
1700
+ sendResponse(id, response);
1701
+ };
1702
+ requestCallbacks["on-load"] = async (id, request) => {
1703
+ let response = {}, name = "", callback, note;
1704
+ for (let id2 of request.ids) try {
1705
+ ({name, callback, note} = onLoadCallbacks[id2]);
1706
+ let result = await callback({
1707
+ path: request.path,
1708
+ namespace: request.namespace,
1709
+ suffix: request.suffix,
1710
+ pluginData: details.load(request.pluginData),
1711
+ with: request.with
1712
+ });
1713
+ if (result != null) {
1714
+ if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
1715
+ let keys = {};
1716
+ let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1717
+ let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
1718
+ let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
1719
+ let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1720
+ let loader = getFlag(result, keys, "loader", mustBeString);
1721
+ let errors = getFlag(result, keys, "errors", mustBeArray);
1722
+ let warnings = getFlag(result, keys, "warnings", mustBeArray);
1723
+ let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1724
+ let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1725
+ checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
1726
+ response.id = id2;
1727
+ if (pluginName != null) response.pluginName = pluginName;
1728
+ if (contents instanceof Uint8Array) response.contents = contents;
1729
+ else if (contents != null) response.contents = encodeUTF8(contents);
1730
+ if (resolveDir != null) response.resolveDir = resolveDir;
1731
+ if (pluginData != null) response.pluginData = details.store(pluginData);
1732
+ if (loader != null) response.loader = loader;
1733
+ if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1734
+ if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1735
+ if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1736
+ if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1737
+ break;
1738
+ }
1739
+ } catch (e) {
1740
+ response = {
1741
+ id: id2,
1742
+ errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]
1743
+ };
1744
+ break;
1745
+ }
1746
+ sendResponse(id, response);
1747
+ };
1748
+ let runOnEndCallbacks = (result, done) => done([], []);
1749
+ if (onEndCallbacks.length > 0) runOnEndCallbacks = (result, done) => {
1750
+ (async () => {
1751
+ const onEndErrors = [];
1752
+ const onEndWarnings = [];
1753
+ for (const { name, callback, note } of onEndCallbacks) {
1754
+ let newErrors;
1755
+ let newWarnings;
1756
+ try {
1757
+ const value = await callback(result);
1758
+ if (value != null) {
1759
+ if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
1760
+ let keys = {};
1761
+ let errors = getFlag(value, keys, "errors", mustBeArray);
1762
+ let warnings = getFlag(value, keys, "warnings", mustBeArray);
1763
+ checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
1764
+ if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
1765
+ if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1766
+ }
1767
+ } catch (e) {
1768
+ newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
1769
+ }
1770
+ if (newErrors) {
1771
+ onEndErrors.push(...newErrors);
1772
+ try {
1773
+ result.errors.push(...newErrors);
1774
+ } catch {}
1775
+ }
1776
+ if (newWarnings) {
1777
+ onEndWarnings.push(...newWarnings);
1778
+ try {
1779
+ result.warnings.push(...newWarnings);
1780
+ } catch {}
1781
+ }
1782
+ }
1783
+ done(onEndErrors, onEndWarnings);
1784
+ })();
1785
+ };
1786
+ let scheduleOnDisposeCallbacks = () => {
1787
+ for (const cb of onDisposeCallbacks) setTimeout(() => cb(), 0);
1788
+ };
1789
+ isSetupDone = true;
1790
+ return {
1791
+ ok: true,
1792
+ requestPlugins,
1793
+ runOnEndCallbacks,
1794
+ scheduleOnDisposeCallbacks
1795
+ };
1796
+ };
1797
+ function createObjectStash() {
1798
+ const map = /* @__PURE__ */ new Map();
1799
+ let nextID = 0;
1800
+ return {
1801
+ clear() {
1802
+ map.clear();
1803
+ },
1804
+ load(id) {
1805
+ return map.get(id);
1806
+ },
1807
+ store(value) {
1808
+ if (value === void 0) return -1;
1809
+ const id = nextID++;
1810
+ map.set(id, value);
1811
+ return id;
1812
+ }
1813
+ };
1814
+ }
1815
+ function extractCallerV8(e, streamIn, ident) {
1816
+ let note;
1817
+ let tried = false;
1818
+ return () => {
1819
+ if (tried) return note;
1820
+ tried = true;
1821
+ try {
1822
+ let lines = (e.stack + "").split("\n");
1823
+ lines.splice(1, 1);
1824
+ let location = parseStackLinesV8(streamIn, lines, ident);
1825
+ if (location) {
1826
+ note = {
1827
+ text: e.message,
1828
+ location
1829
+ };
1830
+ return note;
1831
+ }
1832
+ } catch {}
1833
+ };
1834
+ }
1835
+ function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
1836
+ let text = "Internal error";
1837
+ let location = null;
1838
+ try {
1839
+ text = (e && e.message || e) + "";
1840
+ } catch {}
1841
+ try {
1842
+ location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
1843
+ } catch {}
1844
+ return {
1845
+ id: "",
1846
+ pluginName,
1847
+ text,
1848
+ location,
1849
+ notes: note ? [note] : [],
1850
+ detail: stash ? stash.store(e) : -1
1851
+ };
1852
+ }
1853
+ function parseStackLinesV8(streamIn, lines, ident) {
1854
+ let at = " at ";
1855
+ if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) for (let i = 1; i < lines.length; i++) {
1856
+ let line = lines[i];
1857
+ if (!line.startsWith(at)) continue;
1858
+ line = line.slice(7);
1859
+ while (true) {
1860
+ let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
1861
+ if (match) {
1862
+ line = match[1];
1863
+ continue;
1864
+ }
1865
+ match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
1866
+ if (match) {
1867
+ line = match[1];
1868
+ continue;
1869
+ }
1870
+ match = /^(\S+):(\d+):(\d+)$/.exec(line);
1871
+ if (match) {
1872
+ let contents;
1873
+ try {
1874
+ contents = streamIn.readFileSync(match[1], "utf8");
1875
+ } catch {
1876
+ break;
1877
+ }
1878
+ let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
1879
+ let column = +match[3] - 1;
1880
+ let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
1881
+ return {
1882
+ file: match[1],
1883
+ namespace: "file",
1884
+ line: +match[2],
1885
+ column: encodeUTF8(lineText.slice(0, column)).length,
1886
+ length: encodeUTF8(lineText.slice(column, column + length)).length,
1887
+ lineText: lineText + "\n" + lines.slice(1).join("\n"),
1888
+ suggestion: ""
1889
+ };
1890
+ }
1891
+ break;
1892
+ }
1893
+ }
1894
+ return null;
1895
+ }
1896
+ function failureErrorWithLog(text, errors, warnings) {
1897
+ let limit = 5;
1898
+ text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, 6).map((e, i) => {
1899
+ if (i === limit) return "\n...";
1900
+ if (!e.location) return `
1901
+ error: ${e.text}`;
1902
+ let { file, line, column } = e.location;
1903
+ return `
1904
+ ${file}:${line}:${column}: ERROR: ${e.pluginName ? `[plugin: ${e.pluginName}] ` : ""}${e.text}`;
1905
+ }).join("");
1906
+ let error = new Error(text);
1907
+ for (const [key, value] of [["errors", errors], ["warnings", warnings]]) Object.defineProperty(error, key, {
1908
+ configurable: true,
1909
+ enumerable: true,
1910
+ get: () => value,
1911
+ set: (value2) => Object.defineProperty(error, key, {
1912
+ configurable: true,
1913
+ enumerable: true,
1914
+ value: value2
1915
+ })
1916
+ });
1917
+ return error;
1918
+ }
1919
+ function replaceDetailsInMessages(messages, stash) {
1920
+ for (const message of messages) message.detail = stash.load(message.detail);
1921
+ return messages;
1922
+ }
1923
+ function sanitizeLocation(location, where, terminalWidth) {
1924
+ if (location == null) return null;
1925
+ let keys = {};
1926
+ let file = getFlag(location, keys, "file", mustBeString);
1927
+ let namespace = getFlag(location, keys, "namespace", mustBeString);
1928
+ let line = getFlag(location, keys, "line", mustBeInteger);
1929
+ let column = getFlag(location, keys, "column", mustBeInteger);
1930
+ let length = getFlag(location, keys, "length", mustBeInteger);
1931
+ let lineText = getFlag(location, keys, "lineText", mustBeString);
1932
+ let suggestion = getFlag(location, keys, "suggestion", mustBeString);
1933
+ checkForInvalidFlags(location, keys, where);
1934
+ if (lineText) {
1935
+ const relevantASCII = lineText.slice(0, (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80));
1936
+ if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) lineText = relevantASCII;
1937
+ }
1938
+ return {
1939
+ file: file || "",
1940
+ namespace: namespace || "",
1941
+ line: line || 0,
1942
+ column: column || 0,
1943
+ length: length || 0,
1944
+ lineText: lineText || "",
1945
+ suggestion: suggestion || ""
1946
+ };
1947
+ }
1948
+ function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
1949
+ let messagesClone = [];
1950
+ let index = 0;
1951
+ for (const message of messages) {
1952
+ let keys = {};
1953
+ let id = getFlag(message, keys, "id", mustBeString);
1954
+ let pluginName = getFlag(message, keys, "pluginName", mustBeString);
1955
+ let text = getFlag(message, keys, "text", mustBeString);
1956
+ let location = getFlag(message, keys, "location", mustBeObjectOrNull);
1957
+ let notes = getFlag(message, keys, "notes", mustBeArray);
1958
+ let detail = getFlag(message, keys, "detail", canBeAnything);
1959
+ let where = `in element ${index} of "${property}"`;
1960
+ checkForInvalidFlags(message, keys, where);
1961
+ let notesClone = [];
1962
+ if (notes) for (const note of notes) {
1963
+ let noteKeys = {};
1964
+ let noteText = getFlag(note, noteKeys, "text", mustBeString);
1965
+ let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
1966
+ checkForInvalidFlags(note, noteKeys, where);
1967
+ notesClone.push({
1968
+ text: noteText || "",
1969
+ location: sanitizeLocation(noteLocation, where, terminalWidth)
1970
+ });
1971
+ }
1972
+ messagesClone.push({
1973
+ id: id || "",
1974
+ pluginName: pluginName || fallbackPluginName,
1975
+ text: text || "",
1976
+ location: sanitizeLocation(location, where, terminalWidth),
1977
+ notes: notesClone,
1978
+ detail: stash ? stash.store(detail) : -1
1979
+ });
1980
+ index++;
1981
+ }
1982
+ return messagesClone;
1983
+ }
1984
+ function sanitizeStringArray(values, property) {
1985
+ const result = [];
1986
+ for (const value of values) {
1987
+ if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`);
1988
+ result.push(value);
1989
+ }
1990
+ return result;
1991
+ }
1992
+ function sanitizeStringMap(map, property) {
1993
+ const result = /* @__PURE__ */ Object.create(null);
1994
+ for (const key in map) {
1995
+ const value = map[key];
1996
+ if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
1997
+ result[key] = value;
1998
+ }
1999
+ return result;
2000
+ }
2001
+ function convertOutputFiles({ path: path3, contents, hash }) {
2002
+ let text = null;
2003
+ return {
2004
+ path: path3,
2005
+ contents,
2006
+ hash,
2007
+ get text() {
2008
+ const binary = this.contents;
2009
+ if (text === null || binary !== contents) {
2010
+ contents = binary;
2011
+ text = decodeUTF8(binary);
2012
+ }
2013
+ return text;
2014
+ }
2015
+ };
2016
+ }
2017
+ function jsRegExpToGoRegExp(regexp) {
2018
+ let result = regexp.source;
2019
+ if (regexp.flags) result = `(?${regexp.flags})${result}`;
2020
+ return result;
2021
+ }
2022
+ function parseJSON(bytes) {
2023
+ let text;
2024
+ try {
2025
+ text = decodeUTF8(bytes);
2026
+ } catch {
2027
+ return JSON_parse(bytes);
2028
+ }
2029
+ return JSON.parse(text);
2030
+ }
2031
+ var fs = __require("fs");
2032
+ var os = __require("os");
2033
+ var path = __require("path");
2034
+ var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
2035
+ var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
2036
+ var packageDarwin_arm64 = "@esbuild/darwin-arm64";
2037
+ var packageDarwin_x64 = "@esbuild/darwin-x64";
2038
+ var knownWindowsPackages = {
2039
+ "win32 arm64 LE": "@esbuild/win32-arm64",
2040
+ "win32 ia32 LE": "@esbuild/win32-ia32",
2041
+ "win32 x64 LE": "@esbuild/win32-x64"
2042
+ };
2043
+ var knownUnixlikePackages = {
2044
+ "aix ppc64 BE": "@esbuild/aix-ppc64",
2045
+ "android arm64 LE": "@esbuild/android-arm64",
2046
+ "darwin arm64 LE": "@esbuild/darwin-arm64",
2047
+ "darwin x64 LE": "@esbuild/darwin-x64",
2048
+ "freebsd arm64 LE": "@esbuild/freebsd-arm64",
2049
+ "freebsd x64 LE": "@esbuild/freebsd-x64",
2050
+ "linux arm LE": "@esbuild/linux-arm",
2051
+ "linux arm64 LE": "@esbuild/linux-arm64",
2052
+ "linux ia32 LE": "@esbuild/linux-ia32",
2053
+ "linux mips64el LE": "@esbuild/linux-mips64el",
2054
+ "linux ppc64 LE": "@esbuild/linux-ppc64",
2055
+ "linux riscv64 LE": "@esbuild/linux-riscv64",
2056
+ "linux s390x BE": "@esbuild/linux-s390x",
2057
+ "linux x64 LE": "@esbuild/linux-x64",
2058
+ "linux loong64 LE": "@esbuild/linux-loong64",
2059
+ "netbsd arm64 LE": "@esbuild/netbsd-arm64",
2060
+ "netbsd x64 LE": "@esbuild/netbsd-x64",
2061
+ "openbsd arm64 LE": "@esbuild/openbsd-arm64",
2062
+ "openbsd x64 LE": "@esbuild/openbsd-x64",
2063
+ "sunos x64 LE": "@esbuild/sunos-x64"
2064
+ };
2065
+ var knownWebAssemblyFallbackPackages = {
2066
+ "android arm LE": "@esbuild/android-arm",
2067
+ "android x64 LE": "@esbuild/android-x64",
2068
+ "openharmony arm64 LE": "@esbuild/openharmony-arm64"
2069
+ };
2070
+ function pkgAndSubpathForCurrentPlatform() {
2071
+ let pkg;
2072
+ let subpath;
2073
+ let isWASM = false;
2074
+ let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
2075
+ if (platformKey in knownWindowsPackages) {
2076
+ pkg = knownWindowsPackages[platformKey];
2077
+ subpath = "esbuild.exe";
2078
+ } else if (platformKey in knownUnixlikePackages) {
2079
+ pkg = knownUnixlikePackages[platformKey];
2080
+ subpath = "bin/esbuild";
2081
+ } else if (platformKey in knownWebAssemblyFallbackPackages) {
2082
+ pkg = knownWebAssemblyFallbackPackages[platformKey];
2083
+ subpath = "bin/esbuild";
2084
+ isWASM = true;
2085
+ } else throw new Error(`Unsupported platform: ${platformKey}`);
2086
+ return {
2087
+ pkg,
2088
+ subpath,
2089
+ isWASM
2090
+ };
2091
+ }
2092
+ function pkgForSomeOtherPlatform() {
2093
+ const libMainJS = __require.resolve("esbuild");
2094
+ const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
2095
+ if (path.basename(nodeModulesDirectory) === "node_modules") {
2096
+ for (const unixKey in knownUnixlikePackages) try {
2097
+ const pkg = knownUnixlikePackages[unixKey];
2098
+ if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
2099
+ } catch {}
2100
+ for (const windowsKey in knownWindowsPackages) try {
2101
+ const pkg = knownWindowsPackages[windowsKey];
2102
+ if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
2103
+ } catch {}
2104
+ }
2105
+ return null;
2106
+ }
2107
+ function downloadedBinPath(pkg, subpath) {
2108
+ const esbuildLibDir = path.dirname(__require.resolve("esbuild"));
2109
+ return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
2110
+ }
2111
+ function generateBinPath() {
2112
+ if (isValidBinaryPath(ESBUILD_BINARY_PATH)) if (!fs.existsSync(ESBUILD_BINARY_PATH)) console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
2113
+ else return {
2114
+ binPath: ESBUILD_BINARY_PATH,
2115
+ isWASM: false
2116
+ };
2117
+ const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
2118
+ let binPath;
2119
+ try {
2120
+ binPath = __require.resolve(`${pkg}/${subpath}`);
2121
+ } catch (e) {
2122
+ binPath = downloadedBinPath(pkg, subpath);
2123
+ if (!fs.existsSync(binPath)) {
2124
+ try {
2125
+ __require.resolve(pkg);
2126
+ } catch {
2127
+ const otherPkg = pkgForSomeOtherPlatform();
2128
+ if (otherPkg) {
2129
+ let suggestions = `
2130
+ Specifically the "${otherPkg}" package is present but this platform
2131
+ needs the "${pkg}" package instead. People often get into this
2132
+ situation by installing esbuild on Windows or macOS and copying "node_modules"
2133
+ into a Docker image that runs Linux, or by copying "node_modules" between
2134
+ Windows and WSL environments.
2135
+
2136
+ If you are installing with npm, you can try not copying the "node_modules"
2137
+ directory when you copy the files over, and running "npm ci" or "npm install"
2138
+ on the destination platform after the copy. Or you could consider using yarn
2139
+ instead of npm which has built-in support for installing a package on multiple
2140
+ platforms simultaneously.
2141
+
2142
+ If you are installing with yarn, you can try listing both this platform and the
2143
+ other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
2144
+ feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
2145
+ Keep in mind that this means multiple copies of esbuild will be present.
2146
+ `;
2147
+ if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) suggestions = `
2148
+ Specifically the "${otherPkg}" package is present but this platform
2149
+ needs the "${pkg}" package instead. People often get into this
2150
+ situation by installing esbuild with npm running inside of Rosetta 2 and then
2151
+ trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
2152
+ 2 is Apple's on-the-fly x86_64-to-arm64 translation service).
2153
+
2154
+ If you are installing with npm, you can try ensuring that both npm and node are
2155
+ not running under Rosetta 2 and then reinstalling esbuild. This likely involves
2156
+ changing how you installed npm and/or node. For example, installing node with
2157
+ the universal installer here should work: https://nodejs.org/en/download/. Or
2158
+ you could consider using yarn instead of npm which has built-in support for
2159
+ installing a package on multiple platforms simultaneously.
2160
+
2161
+ If you are installing with yarn, you can try listing both "arm64" and "x64"
2162
+ in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
2163
+ https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
2164
+ Keep in mind that this means multiple copies of esbuild will be present.
2165
+ `;
2166
+ throw new Error(`
2167
+ You installed esbuild for another platform than the one you're currently using.
2168
+ This won't work because esbuild is written with native code and needs to
2169
+ install a platform-specific binary executable.
2170
+ ${suggestions}
2171
+ Another alternative is to use the "esbuild-wasm" package instead, which works
2172
+ the same way on all platforms. But it comes with a heavy performance cost and
2173
+ can sometimes be 10x slower than the "esbuild" package, so you may also not
2174
+ want to do that.
2175
+ `);
2176
+ }
2177
+ throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
2178
+
2179
+ If you are installing esbuild with npm, make sure that you don't specify the
2180
+ "--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
2181
+ of "package.json" is used by esbuild to install the correct binary executable
2182
+ for your current platform.`);
2183
+ }
2184
+ throw e;
2185
+ }
2186
+ }
2187
+ if (/\.zip\//.test(binPath)) {
2188
+ let pnpapi;
2189
+ try {
2190
+ pnpapi = __require("pnpapi");
2191
+ } catch (e) {}
2192
+ if (pnpapi) {
2193
+ const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
2194
+ const binTargetPath = path.join(root, "node_modules", ".cache", "esbuild", `pnpapi-${pkg.replace("/", "-")}-0.27.7-${path.basename(subpath)}`);
2195
+ if (!fs.existsSync(binTargetPath)) {
2196
+ fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
2197
+ fs.copyFileSync(binPath, binTargetPath);
2198
+ fs.chmodSync(binTargetPath, 493);
2199
+ }
2200
+ return {
2201
+ binPath: binTargetPath,
2202
+ isWASM
2203
+ };
2204
+ }
2205
+ }
2206
+ return {
2207
+ binPath,
2208
+ isWASM
2209
+ };
2210
+ }
2211
+ var child_process = __require("child_process");
2212
+ var crypto = __require("crypto");
2213
+ var path2 = __require("path");
2214
+ var fs2 = __require("fs");
2215
+ var os2 = __require("os");
2216
+ var tty = __require("tty");
2217
+ var worker_threads;
2218
+ if (process.env.ESBUILD_WORKER_THREADS !== "0") {
2219
+ try {
2220
+ worker_threads = __require("worker_threads");
2221
+ } catch {}
2222
+ let [major, minor] = process.versions.node.split(".");
2223
+ if (+major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13) worker_threads = void 0;
2224
+ }
2225
+ var _a;
2226
+ var isInternalWorkerThread = ((_a = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a.esbuildVersion) === "0.27.7";
2227
+ var esbuildCommandAndArgs = () => {
2228
+ if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) throw new Error(`The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
2229
+
2230
+ More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.`);
2231
+ {
2232
+ const { binPath, isWASM } = generateBinPath();
2233
+ if (isWASM) return ["node", [binPath]];
2234
+ else return [binPath, []];
2235
+ }
2236
+ };
2237
+ var isTTY = () => tty.isatty(2);
2238
+ var fsSync = {
2239
+ readFile(tempFile, callback) {
2240
+ try {
2241
+ let contents = fs2.readFileSync(tempFile, "utf8");
2242
+ try {
2243
+ fs2.unlinkSync(tempFile);
2244
+ } catch {}
2245
+ callback(null, contents);
2246
+ } catch (err) {
2247
+ callback(err, null);
2248
+ }
2249
+ },
2250
+ writeFile(contents, callback) {
2251
+ try {
2252
+ let tempFile = randomFileName();
2253
+ fs2.writeFileSync(tempFile, contents);
2254
+ callback(tempFile);
2255
+ } catch {
2256
+ callback(null);
2257
+ }
2258
+ }
2259
+ };
2260
+ var fsAsync = {
2261
+ readFile(tempFile, callback) {
2262
+ try {
2263
+ fs2.readFile(tempFile, "utf8", (err, contents) => {
2264
+ try {
2265
+ fs2.unlink(tempFile, () => callback(err, contents));
2266
+ } catch {
2267
+ callback(err, contents);
2268
+ }
2269
+ });
2270
+ } catch (err) {
2271
+ callback(err, null);
2272
+ }
2273
+ },
2274
+ writeFile(contents, callback) {
2275
+ try {
2276
+ let tempFile = randomFileName();
2277
+ fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
2278
+ } catch {
2279
+ callback(null);
2280
+ }
2281
+ }
2282
+ };
2283
+ var version = "0.27.7";
2284
+ var build = (options) => ensureServiceIsRunning().build(options);
2285
+ var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
2286
+ var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
2287
+ var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
2288
+ var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
2289
+ var buildSync = (options) => {
2290
+ if (worker_threads && !isInternalWorkerThread) {
2291
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2292
+ return workerThreadService.buildSync(options);
2293
+ }
2294
+ let result;
2295
+ runServiceSync((service) => service.buildOrContext({
2296
+ callName: "buildSync",
2297
+ refs: null,
2298
+ options,
2299
+ isTTY: isTTY(),
2300
+ defaultWD,
2301
+ callback: (err, res) => {
2302
+ if (err) throw err;
2303
+ result = res;
2304
+ }
2305
+ }));
2306
+ return result;
2307
+ };
2308
+ var transformSync = (input, options) => {
2309
+ if (worker_threads && !isInternalWorkerThread) {
2310
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2311
+ return workerThreadService.transformSync(input, options);
2312
+ }
2313
+ let result;
2314
+ runServiceSync((service) => service.transform({
2315
+ callName: "transformSync",
2316
+ refs: null,
2317
+ input,
2318
+ options: options || {},
2319
+ isTTY: isTTY(),
2320
+ fs: fsSync,
2321
+ callback: (err, res) => {
2322
+ if (err) throw err;
2323
+ result = res;
2324
+ }
2325
+ }));
2326
+ return result;
2327
+ };
2328
+ var formatMessagesSync = (messages, options) => {
2329
+ if (worker_threads && !isInternalWorkerThread) {
2330
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2331
+ return workerThreadService.formatMessagesSync(messages, options);
2332
+ }
2333
+ let result;
2334
+ runServiceSync((service) => service.formatMessages({
2335
+ callName: "formatMessagesSync",
2336
+ refs: null,
2337
+ messages,
2338
+ options,
2339
+ callback: (err, res) => {
2340
+ if (err) throw err;
2341
+ result = res;
2342
+ }
2343
+ }));
2344
+ return result;
2345
+ };
2346
+ var analyzeMetafileSync = (metafile, options) => {
2347
+ if (worker_threads && !isInternalWorkerThread) {
2348
+ if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2349
+ return workerThreadService.analyzeMetafileSync(metafile, options);
2350
+ }
2351
+ let result;
2352
+ runServiceSync((service) => service.analyzeMetafile({
2353
+ callName: "analyzeMetafileSync",
2354
+ refs: null,
2355
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2356
+ options,
2357
+ callback: (err, res) => {
2358
+ if (err) throw err;
2359
+ result = res;
2360
+ }
2361
+ }));
2362
+ return result;
2363
+ };
2364
+ var stop = () => {
2365
+ if (stopService) stopService();
2366
+ if (workerThreadService) workerThreadService.stop();
2367
+ return Promise.resolve();
2368
+ };
2369
+ var initializeWasCalled = false;
2370
+ var initialize = (options) => {
2371
+ options = validateInitializeOptions(options || {});
2372
+ if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`);
2373
+ if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`);
2374
+ if (options.worker) throw new Error(`The "worker" option only works in the browser`);
2375
+ if (initializeWasCalled) throw new Error("Cannot call \"initialize\" more than once");
2376
+ ensureServiceIsRunning();
2377
+ initializeWasCalled = true;
2378
+ return Promise.resolve();
2379
+ };
2380
+ var defaultWD = process.cwd();
2381
+ var longLivedService;
2382
+ var stopService;
2383
+ var ensureServiceIsRunning = () => {
2384
+ if (longLivedService) return longLivedService;
2385
+ let [command, args] = esbuildCommandAndArgs();
2386
+ let child = child_process.spawn(command, args.concat(`--service=0.27.7`, "--ping"), {
2387
+ windowsHide: true,
2388
+ stdio: [
2389
+ "pipe",
2390
+ "pipe",
2391
+ "inherit"
2392
+ ],
2393
+ cwd: defaultWD
2394
+ });
2395
+ let { readFromStdout, afterClose, service } = createChannel({
2396
+ writeToStdin(bytes) {
2397
+ child.stdin.write(bytes, (err) => {
2398
+ if (err) afterClose(err);
2399
+ });
2400
+ },
2401
+ readFileSync: fs2.readFileSync,
2402
+ isSync: false,
2403
+ hasFS: true,
2404
+ esbuild: node_exports
2405
+ });
2406
+ child.stdin.on("error", afterClose);
2407
+ child.on("error", afterClose);
2408
+ const stdin = child.stdin;
2409
+ const stdout = child.stdout;
2410
+ stdout.on("data", readFromStdout);
2411
+ stdout.on("end", afterClose);
2412
+ stopService = () => {
2413
+ stdin.destroy();
2414
+ stdout.destroy();
2415
+ child.kill();
2416
+ initializeWasCalled = false;
2417
+ longLivedService = void 0;
2418
+ stopService = void 0;
2419
+ };
2420
+ let refCount = 0;
2421
+ child.unref();
2422
+ if (stdin.unref) stdin.unref();
2423
+ if (stdout.unref) stdout.unref();
2424
+ const refs = {
2425
+ ref() {
2426
+ if (++refCount === 1) child.ref();
2427
+ },
2428
+ unref() {
2429
+ if (--refCount === 0) child.unref();
2430
+ }
2431
+ };
2432
+ longLivedService = {
2433
+ build: (options) => new Promise((resolve, reject) => {
2434
+ service.buildOrContext({
2435
+ callName: "build",
2436
+ refs,
2437
+ options,
2438
+ isTTY: isTTY(),
2439
+ defaultWD,
2440
+ callback: (err, res) => err ? reject(err) : resolve(res)
2441
+ });
2442
+ }),
2443
+ context: (options) => new Promise((resolve, reject) => service.buildOrContext({
2444
+ callName: "context",
2445
+ refs,
2446
+ options,
2447
+ isTTY: isTTY(),
2448
+ defaultWD,
2449
+ callback: (err, res) => err ? reject(err) : resolve(res)
2450
+ })),
2451
+ transform: (input, options) => new Promise((resolve, reject) => service.transform({
2452
+ callName: "transform",
2453
+ refs,
2454
+ input,
2455
+ options: options || {},
2456
+ isTTY: isTTY(),
2457
+ fs: fsAsync,
2458
+ callback: (err, res) => err ? reject(err) : resolve(res)
2459
+ })),
2460
+ formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
2461
+ callName: "formatMessages",
2462
+ refs,
2463
+ messages,
2464
+ options,
2465
+ callback: (err, res) => err ? reject(err) : resolve(res)
2466
+ })),
2467
+ analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({
2468
+ callName: "analyzeMetafile",
2469
+ refs,
2470
+ metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2471
+ options,
2472
+ callback: (err, res) => err ? reject(err) : resolve(res)
2473
+ }))
2474
+ };
2475
+ return longLivedService;
2476
+ };
2477
+ var runServiceSync = (callback) => {
2478
+ let [command, args] = esbuildCommandAndArgs();
2479
+ let stdin = new Uint8Array();
2480
+ let { readFromStdout, afterClose, service } = createChannel({
2481
+ writeToStdin(bytes) {
2482
+ if (stdin.length !== 0) throw new Error("Must run at most one command");
2483
+ stdin = bytes;
2484
+ },
2485
+ isSync: true,
2486
+ hasFS: true,
2487
+ esbuild: node_exports
2488
+ });
2489
+ callback(service);
2490
+ readFromStdout(child_process.execFileSync(command, args.concat(`--service=0.27.7`), {
2491
+ cwd: defaultWD,
2492
+ windowsHide: true,
2493
+ input: stdin,
2494
+ maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
2495
+ }));
2496
+ afterClose(null);
2497
+ };
2498
+ var randomFileName = () => {
2499
+ return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
2500
+ };
2501
+ var workerThreadService = null;
2502
+ var startWorkerThreadService = (worker_threads2) => {
2503
+ let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
2504
+ let worker = new worker_threads2.Worker(__filename, {
2505
+ workerData: {
2506
+ workerPort,
2507
+ defaultWD,
2508
+ esbuildVersion: "0.27.7"
2509
+ },
2510
+ transferList: [workerPort],
2511
+ execArgv: []
2512
+ });
2513
+ let nextID = 0;
2514
+ let fakeBuildError = (text) => {
2515
+ let error = /* @__PURE__ */ new Error(`Build failed with 1 error:
2516
+ error: ${text}`);
2517
+ error.errors = [{
2518
+ id: "",
2519
+ pluginName: "",
2520
+ text,
2521
+ location: null,
2522
+ notes: [],
2523
+ detail: void 0
2524
+ }];
2525
+ error.warnings = [];
2526
+ return error;
2527
+ };
2528
+ let validateBuildSyncOptions = (options) => {
2529
+ if (!options) return;
2530
+ let plugins = options.plugins;
2531
+ if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
2532
+ };
2533
+ let applyProperties = (object, properties) => {
2534
+ for (let key in properties) object[key] = properties[key];
2535
+ };
2536
+ let runCallSync = (command, args) => {
2537
+ let id = nextID++;
2538
+ let sharedBuffer = new SharedArrayBuffer(8);
2539
+ let sharedBufferView = new Int32Array(sharedBuffer);
2540
+ let msg = {
2541
+ sharedBuffer,
2542
+ id,
2543
+ command,
2544
+ args
2545
+ };
2546
+ worker.postMessage(msg);
2547
+ let status = Atomics.wait(sharedBufferView, 0, 0);
2548
+ if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status);
2549
+ let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
2550
+ if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
2551
+ if (reject) {
2552
+ applyProperties(reject, properties);
2553
+ throw reject;
2554
+ }
2555
+ return resolve;
2556
+ };
2557
+ worker.unref();
2558
+ return {
2559
+ buildSync(options) {
2560
+ validateBuildSyncOptions(options);
2561
+ return runCallSync("build", [options]);
2562
+ },
2563
+ transformSync(input, options) {
2564
+ return runCallSync("transform", [input, options]);
2565
+ },
2566
+ formatMessagesSync(messages, options) {
2567
+ return runCallSync("formatMessages", [messages, options]);
2568
+ },
2569
+ analyzeMetafileSync(metafile, options) {
2570
+ return runCallSync("analyzeMetafile", [metafile, options]);
2571
+ },
2572
+ stop() {
2573
+ worker.terminate();
2574
+ workerThreadService = null;
2575
+ }
2576
+ };
2577
+ };
2578
+ var startSyncServiceWorker = () => {
2579
+ let workerPort = worker_threads.workerData.workerPort;
2580
+ let parentPort = worker_threads.parentPort;
2581
+ let extractProperties = (object) => {
2582
+ let properties = {};
2583
+ if (object && typeof object === "object") for (let key in object) properties[key] = object[key];
2584
+ return properties;
2585
+ };
2586
+ try {
2587
+ let service = ensureServiceIsRunning();
2588
+ defaultWD = worker_threads.workerData.defaultWD;
2589
+ parentPort.on("message", (msg) => {
2590
+ (async () => {
2591
+ let { sharedBuffer, id, command, args } = msg;
2592
+ let sharedBufferView = new Int32Array(sharedBuffer);
2593
+ try {
2594
+ switch (command) {
2595
+ case "build":
2596
+ workerPort.postMessage({
2597
+ id,
2598
+ resolve: await service.build(args[0])
2599
+ });
2600
+ break;
2601
+ case "transform":
2602
+ workerPort.postMessage({
2603
+ id,
2604
+ resolve: await service.transform(args[0], args[1])
2605
+ });
2606
+ break;
2607
+ case "formatMessages":
2608
+ workerPort.postMessage({
2609
+ id,
2610
+ resolve: await service.formatMessages(args[0], args[1])
2611
+ });
2612
+ break;
2613
+ case "analyzeMetafile":
2614
+ workerPort.postMessage({
2615
+ id,
2616
+ resolve: await service.analyzeMetafile(args[0], args[1])
2617
+ });
2618
+ break;
2619
+ default: throw new Error(`Invalid command: ${command}`);
2620
+ }
2621
+ } catch (reject) {
2622
+ workerPort.postMessage({
2623
+ id,
2624
+ reject,
2625
+ properties: extractProperties(reject)
2626
+ });
2627
+ }
2628
+ Atomics.add(sharedBufferView, 0, 1);
2629
+ Atomics.notify(sharedBufferView, 0, Infinity);
2630
+ })();
2631
+ });
2632
+ } catch (reject) {
2633
+ parentPort.on("message", (msg) => {
2634
+ let { sharedBuffer, id } = msg;
2635
+ let sharedBufferView = new Int32Array(sharedBuffer);
2636
+ workerPort.postMessage({
2637
+ id,
2638
+ reject,
2639
+ properties: extractProperties(reject)
2640
+ });
2641
+ Atomics.add(sharedBufferView, 0, 1);
2642
+ Atomics.notify(sharedBufferView, 0, Infinity);
2643
+ });
2644
+ }
2645
+ };
2646
+ if (isInternalWorkerThread) startSyncServiceWorker();
2647
+ var node_default = node_exports;
2648
+ 0 && (module.exports = {
2649
+ analyzeMetafile,
2650
+ analyzeMetafileSync,
2651
+ build,
2652
+ buildSync,
2653
+ context,
2654
+ formatMessages,
2655
+ formatMessagesSync,
2656
+ initialize,
2657
+ stop,
2658
+ transform,
2659
+ transformSync,
2660
+ version
2661
+ });
2662
+ })))();
2663
+ const viteRawNamespace = "vitehub-vite-raw";
2664
+ const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
2665
+ const markdownTemplateFileSuffix = ".template.md";
2666
+ const markdownTemplateModuleQuery = "markdown-template";
2667
+ const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
2668
+ const skipResolvedAlias = "vitehubSkipResolvedAlias";
2669
+ const encodedAliasPrefixMarker = "\0vitehub-prefix:";
2670
+ const encodedAliasExactMarker = "\0vitehub-exact:";
2671
+ const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
2672
+ function normalizePathSeparators(path) {
2673
+ return path.replaceAll("\\", "/");
2674
+ }
2675
+ function escapeRegExp(value) {
2676
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2677
+ }
2678
+ function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
2679
+ if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
2680
+ if (!Array.isArray(exportsValue) && !isPlainObject(exportsValue)) return [];
2681
+ const candidates = [];
2682
+ const exportEntries = isPlainObject(exportsValue) && Object.keys(exportsValue).some((exportKey) => exportKey.startsWith(".")) ? Object.entries(exportsValue) : [[".", exportsValue]];
2683
+ for (const [exportKey, target] of exportEntries) {
2684
+ const targets = [target];
2685
+ while (targets.length) {
2686
+ const value = targets.shift();
2687
+ if (typeof value === "string") {
2688
+ const normalizedTarget = normalizePathSeparators(value).replace(/^\.\//, "");
2689
+ const targetParts = normalizedTarget.split("*");
2690
+ if (targetParts.length === 1) {
2691
+ if (normalizedTarget === packageRelativePath) candidates.push(`${packageName}${exportKey.slice(1)}`);
2692
+ continue;
2693
+ }
2694
+ const targetPattern = `${escapeRegExp(targetParts[0])}(.*?)${targetParts.slice(1).map((part, index) => `${index ? "\\1" : ""}${escapeRegExp(part)}`).join("")}`;
2695
+ const wildcard = new RegExp(`^${targetPattern}$`).exec(packageRelativePath)?.[1];
2696
+ if (wildcard === void 0) continue;
2697
+ candidates.push(`${packageName}${exportKey.slice(1).replace("*", wildcard)}`);
2698
+ } else if (Array.isArray(value)) targets.push(...value);
2699
+ else if (isPlainObject(value)) targets.push(...Object.values(value));
2700
+ }
2701
+ }
2702
+ return candidates;
2703
+ }
2704
+ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
2705
+ const entries = Object.entries(aliases || {});
2706
+ if (!entries.length) return;
2707
+ const resolvedEntries = Promise.all(entries.map(async ([encodedSpecifier, replacement]) => {
2708
+ const prefixMarkerIndex = encodedSpecifier.lastIndexOf(encodedAliasPrefixMarker);
2709
+ const exactMarkerIndex = encodedSpecifier.lastIndexOf(encodedAliasExactMarker);
2710
+ const explicitlyEncodedPrefix = prefixMarkerIndex !== -1;
2711
+ const markerIndex = Math.max(prefixMarkerIndex, exactMarkerIndex);
2712
+ const specifier = markerIndex === -1 ? encodedSpecifier : encodedSpecifier.slice(0, markerIndex);
2713
+ const prefix = explicitlyEncodedPrefix || specifier.endsWith("/") && !Object.hasOwn(aliases, `${specifier}/`);
2714
+ const resolvedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
2715
+ const canonicalSpecifier = isAbsolute(resolvedSpecifier) ? normalizePathSeparators(await realpath(resolvedSpecifier).catch(() => resolvedSpecifier)) : resolvedSpecifier;
2716
+ const resolvedReplacement = isAbsolute(replacement) ? normalizePathSeparators(resolve(replacement)) : replacement;
2717
+ return {
2718
+ canonicalSpecifier: `${canonicalSpecifier}${prefix && !canonicalSpecifier.endsWith("/") ? "/" : ""}`,
2719
+ prefix,
2720
+ replacement: `${resolvedReplacement}${prefix && !/[\\/]$/.test(resolvedReplacement) ? "/" : ""}`,
2721
+ specifier: `${resolvedSpecifier}${prefix && !resolvedSpecifier.endsWith("/") ? "/" : ""}`
2722
+ };
2723
+ }));
2724
+ return {
2725
+ name: "vitehub-resolved-alias",
2726
+ setup(build) {
2727
+ const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
2728
+ build.onResolve({ filter: /.*/ }, async (args) => {
2729
+ if (args.pluginData?.[skipResolvedAlias]) return;
2730
+ const aliases = await resolvedEntries;
2731
+ let match = aliases.find(({ prefix, specifier }) => /^\.\.?[\\/]/.test(specifier) && (prefix ? args.path.startsWith(specifier) : args.path === specifier));
2732
+ let matchedAlias = match?.specifier;
2733
+ let matchedSpecifier = match ? args.path : void 0;
2734
+ let specifier = args.resolveDir && /^\.\.?[\\/]/.test(args.path) ? resolve(args.resolveDir, args.path) : args.path;
2735
+ let normalizedSpecifier = isAbsolute(specifier) ? normalizePathSeparators(resolve(specifier)) : specifier;
2736
+ let canonicalSpecifier = normalizedSpecifier;
2737
+ const canonicalizeSpecifier = async () => {
2738
+ canonicalSpecifier = normalizePathSeparators(await realpath(normalizedSpecifier).catch(() => normalizedSpecifier));
2739
+ return canonicalSpecifier;
2740
+ };
2741
+ match ||= aliases.find(({ prefix, specifier }) => prefix ? normalizedSpecifier.startsWith(specifier) : normalizedSpecifier === specifier);
2742
+ if (!match && isAbsolute(normalizedSpecifier) && aliases.some((alias) => isAbsolute(alias.specifier))) {
2743
+ await canonicalizeSpecifier();
2744
+ match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
2745
+ }
2746
+ if (!match && isAbsolute(args.path)) for (const alias of aliases) {
2747
+ if (isAbsolute(alias.specifier)) continue;
2748
+ const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
2749
+ const aliasSegments = packageAlias.split("/");
2750
+ if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
2751
+ let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
2752
+ if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
2753
+ const scopeMarker = `/node_modules/${packageAlias}/`;
2754
+ const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
2755
+ const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
2756
+ if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
2757
+ }
2758
+ const packageMarker = `/node_modules/${packageName}/`;
2759
+ const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
2760
+ const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
2761
+ const cacheKey = [
2762
+ alias.specifier,
2763
+ alias.prefix,
2764
+ resolutionScope,
2765
+ args.importer,
2766
+ args.resolveDir,
2767
+ args.kind,
2768
+ args.namespace,
2769
+ JSON.stringify(args.with)
2770
+ ].join("\0");
2771
+ let resolution = args.pluginData ? void 0 : resolvedBareAliasPaths.get(cacheKey);
2772
+ if (!resolution) {
2773
+ resolution = (async () => {
2774
+ let resolvedAliasPath;
2775
+ if (alias.prefix && /^\.\.?[\\/]/.test(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
2776
+ else if (resolutionScope) {
2777
+ const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
2778
+ const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
2779
+ if (!isPlainObject(parsedPackageJson)) return;
2780
+ const packageJson = parsedPackageJson;
2781
+ if (packageJson.exports === void 0 && !alias.prefix) {
2782
+ const resolvedCandidate = await build.resolve(alias.specifier, {
2783
+ importer: args.importer,
2784
+ kind: args.kind,
2785
+ namespace: args.namespace,
2786
+ pluginData: {
2787
+ ...args.pluginData,
2788
+ [skipResolvedAlias]: true
2789
+ },
2790
+ resolveDir: args.resolveDir,
2791
+ with: args.with
2792
+ });
2793
+ if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve(resolvedCandidate.path)) === normalizedSpecifier) return {
2794
+ canonical: alias.specifier,
2795
+ normalized: alias.specifier,
2796
+ publicSpecifier: alias.specifier
2797
+ };
2798
+ return;
2799
+ }
2800
+ const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
2801
+ for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
2802
+ const resolvedCandidate = await build.resolve(publicSpecifier, {
2803
+ importer: args.importer,
2804
+ kind: args.kind,
2805
+ namespace: args.namespace,
2806
+ pluginData: {
2807
+ ...args.pluginData,
2808
+ [skipResolvedAlias]: true
2809
+ },
2810
+ resolveDir: args.resolveDir,
2811
+ with: args.with
2812
+ });
2813
+ if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
2814
+ if (normalizePathSeparators(resolve(resolvedCandidate.path)) !== normalizedSpecifier) continue;
2815
+ matchingPublicSpecifiers.add(publicSpecifier);
2816
+ }
2817
+ if (matchingPublicSpecifiers.size === 1) {
2818
+ const publicSpecifier = [...matchingPublicSpecifiers][0];
2819
+ if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
2820
+ canonical: publicSpecifier,
2821
+ normalized: publicSpecifier,
2822
+ publicSpecifier
2823
+ };
2824
+ }
2825
+ return;
2826
+ } else {
2827
+ const resolvedAlias = await build.resolve(alias.specifier, {
2828
+ importer: args.importer,
2829
+ kind: args.kind,
2830
+ namespace: args.namespace,
2831
+ pluginData: {
2832
+ ...args.pluginData,
2833
+ [skipResolvedAlias]: true
2834
+ },
2835
+ resolveDir: args.resolveDir,
2836
+ with: args.with
2837
+ });
2838
+ if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
2839
+ resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.path));
2840
+ }
2841
+ const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
2842
+ return {
2843
+ canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
2844
+ normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
2845
+ };
2846
+ })();
2847
+ if (!args.pluginData) resolvedBareAliasPaths.set(cacheKey, resolution);
2848
+ }
2849
+ const paths = await resolution;
2850
+ if (!paths) continue;
2851
+ if (paths.publicSpecifier) {
2852
+ match = alias;
2853
+ matchedAlias = alias.specifier;
2854
+ matchedSpecifier = paths.publicSpecifier;
2855
+ break;
2856
+ }
2857
+ const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
2858
+ let canonicalMatch = false;
2859
+ if (!normalizedMatch && paths.canonical !== paths.normalized) {
2860
+ await canonicalizeSpecifier();
2861
+ canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
2862
+ }
2863
+ if (normalizedMatch || canonicalMatch) {
2864
+ match = alias;
2865
+ matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
2866
+ matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
2867
+ break;
2868
+ }
2869
+ }
2870
+ matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
2871
+ matchedSpecifier ||= matchedAlias === match?.canonicalSpecifier ? canonicalSpecifier : normalizedSpecifier;
2872
+ if (!match) return;
2873
+ const target = match?.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match?.replacement ?? "");
2874
+ if (!target) return;
2875
+ const resolvedTarget = /^\.\.?[\\/]/.test(target) ? resolve(aliasResolveDir, target) : target;
2876
+ return build.resolve(resolvedTarget, {
2877
+ importer: args.importer,
2878
+ kind: args.kind,
2879
+ namespace: args.namespace,
2880
+ pluginData: {
2881
+ ...args.pluginData,
2882
+ [skipResolvedAlias]: true
2883
+ },
2884
+ resolveDir: args.resolveDir,
2885
+ with: args.with
2886
+ });
2887
+ });
2888
+ }
2889
+ };
2890
+ }
2891
+ function createViteAliasPlugin(aliases) {
2892
+ if (!Array.isArray(aliases)) return;
2893
+ const resolvingAlias = "vitehubResolvingAlias";
2894
+ return {
2895
+ name: "vitehub-vite-alias",
2896
+ setup(build) {
2897
+ build.onResolve({ filter: /.*/ }, async (args) => {
2898
+ if (args.pluginData?.[resolvingAlias]) return;
2899
+ const alias = aliases.find(({ find }) => {
2900
+ if (typeof find === "string") return args.path === find || args.path.startsWith(`${find}/`);
2901
+ find.lastIndex = 0;
2902
+ return find.test(args.path);
2903
+ });
2904
+ if (!alias) return;
2905
+ if (alias.customResolver) return { errors: [{ text: `[vitehub] Deno Schedule output cannot stage the Vite alias ${JSON.stringify(args.path)} because it uses customResolver.` }] };
2906
+ if (alias.find instanceof RegExp) alias.find.lastIndex = 0;
2907
+ const replacement = typeof alias.find === "string" ? `${alias.replacement}${args.path.slice(alias.find.length)}` : args.path.replace(alias.find, alias.replacement);
2908
+ const result = await build.resolve(replacement, {
2909
+ importer: args.importer,
2910
+ kind: args.kind,
2911
+ namespace: args.namespace,
2912
+ pluginData: Object.assign({}, args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {}, { [resolvingAlias]: true }),
2913
+ resolveDir: args.resolveDir,
2914
+ with: args.with
2915
+ });
2916
+ const pluginData = Object.assign({}, result.pluginData);
2917
+ Reflect.deleteProperty(pluginData, resolvingAlias);
2918
+ return {
2919
+ ...result,
2920
+ pluginData
2921
+ };
2922
+ });
2923
+ }
2924
+ };
2925
+ }
2926
+ function stripMarkdownCode(template) {
2927
+ let fence;
2928
+ let inList = false;
2929
+ let previousLineBlank = true;
2930
+ return template.split("\n").map((line) => {
2931
+ const content = line.replace(/^(?: {0,3}> ?)+/, "");
2932
+ if (!fence) {
2933
+ const listIndented = inList && /^ {4}(?:`{3,}|~{3,})/.test(content);
2934
+ const opening = (listIndented ? content.slice(4) : content).match(/^ {0,3}(`{3,}|~{3,})/);
2935
+ if (!opening) {
2936
+ if (/^ {0,3}(?:[-+*]|\d+[.)])\s+/.test(content)) inList = true;
2937
+ else if (content.trim() && !/^ {2,}/.test(content)) inList = false;
2938
+ const indentedCode = !inList && previousLineBlank && /^(?: {4}|\t)/.test(content) || inList && previousLineBlank && /^(?: {8}| {4}\t|\t{2})/.test(content);
2939
+ previousLineBlank = content.trim() === "";
2940
+ return indentedCode ? "" : line;
2941
+ }
2942
+ fence = {
2943
+ marker: opening[1][0],
2944
+ length: opening[1].length,
2945
+ listIndented
2946
+ };
2947
+ previousLineBlank = false;
2948
+ return "";
2949
+ }
2950
+ const closing = (fence.listIndented ? content.replace(/^ {4}/, "") : content).match(/^ {0,3}(`+|~+)\s*$/)?.[1];
2951
+ if (closing?.[0] === fence.marker && closing.length >= fence.length) fence = void 0;
2952
+ previousLineBlank = false;
2953
+ return "";
2954
+ }).join("\n");
2955
+ }
2956
+ function extractMarkdownTemplateImportSpecifiers(template) {
2957
+ const visible = stripMarkdownCode(template).replace(/(`+)[\s\S]*?\1/g, "").replace(/(!?\[[^\]]*\])\([^)]*\)/g, "$1").replace(/^ {0,3}\[[^\]]+\]:\s*\S+/gm, "").replace(/<[^>]*>/g, "");
2958
+ const specifiers = /* @__PURE__ */ new Set();
2959
+ for (const match of visible.matchAll(/@(\.\.?\/[^\s<>{}[\]]+)/g)) {
2960
+ const token = match[1];
2961
+ const trailing = token.match(/[.,;:!?)]*$/)?.[0] || "";
2962
+ specifiers.add(token.slice(0, token.length - trailing.length));
2963
+ }
2964
+ return [...specifiers];
2965
+ }
2966
+ function parseMarkdownTemplateRequest(id) {
2967
+ const queryIndex = id.indexOf("?");
2968
+ const path = id.split(/[?#]/, 1)[0];
2969
+ if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
2970
+ const query = id.slice(queryIndex + 1).split("#", 1)[0];
2971
+ if (!new URLSearchParams(query).has(markdownTemplateModuleQuery)) return;
2972
+ return { path };
2973
+ }
2974
+ function renderMarkdownTemplateModule(template, sourceId, imports = {}) {
2975
+ return [
2976
+ `import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
2977
+ `const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
2978
+ `const vitehubMarkdownTemplateSourceId = ${JSON.stringify(sourceId)}`,
2979
+ `const vitehubMarkdownTemplateImports = ${JSON.stringify(imports)}`,
2980
+ "export default function render(data = {}) {",
2981
+ " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data, sourceId: vitehubMarkdownTemplateSourceId, resolveImport: (specifier, importer) => vitehubMarkdownTemplateImports[`${importer}\\0${specifier}`] })",
2982
+ "}",
2983
+ ""
2984
+ ].join("\n");
2985
+ }
2986
+ function hasViteRawQuery(path) {
2987
+ const queryIndex = path.indexOf("?");
2988
+ return queryIndex !== -1 && /(?:^|&)raw(?:&|$)/.test(path.slice(queryIndex + 1));
2989
+ }
2990
+ async function resolveViteRawSpecifier(path, rootDir) {
2991
+ if (path.startsWith("/@fs/")) return path.slice(5);
2992
+ if (!rootDir || !path.startsWith("/")) return path;
2993
+ const rootRelativePath = path.slice(1);
2994
+ const publicPath = resolve(rootDir, "public", rootRelativePath);
2995
+ try {
2996
+ await stat(publicPath);
2997
+ return publicPath;
2998
+ } catch (error) {
2999
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
3000
+ return resolve(rootDir, rootRelativePath);
3001
+ }
3002
+ }
3003
+ function createViteRawPlugin(rootDir, frameworkRuntime) {
3004
+ return {
3005
+ name: "vitehub-vite-raw",
3006
+ setup(build) {
3007
+ build.onResolve({
3008
+ filter: /^@vite-hub\/markdown-template$/,
3009
+ namespace: viteMarkdownTemplateNamespace
3010
+ }, async (args) => {
3011
+ if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
3012
+ return build.resolve("vite-hub/_internal/markdown-template", {
3013
+ importer: args.importer,
3014
+ kind: args.kind,
3015
+ resolveDir: args.resolveDir
3016
+ });
3017
+ });
3018
+ build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
3019
+ if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
3020
+ const markdownTemplate = parseMarkdownTemplateRequest(args.path);
3021
+ const raw = hasViteRawQuery(args.path);
3022
+ if (!markdownTemplate && !raw) return;
3023
+ const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
3024
+ let pluginData = args.pluginData;
3025
+ if (markdownTemplate) pluginData = {
3026
+ ...args.pluginData,
3027
+ [skipMarkdownTemplateResolve]: true
3028
+ };
3029
+ const resolved = await build.resolve(specifier, {
3030
+ importer: args.importer,
3031
+ kind: args.kind,
3032
+ namespace: args.namespace,
3033
+ pluginData,
3034
+ resolveDir: args.resolveDir,
3035
+ with: args.with
3036
+ });
3037
+ if (resolved.errors.length) return {
3038
+ errors: resolved.errors,
3039
+ warnings: resolved.warnings
3040
+ };
3041
+ if (resolved.external) return {
3042
+ external: true,
3043
+ namespace: resolved.namespace,
3044
+ path: resolved.path,
3045
+ pluginData: resolved.pluginData,
3046
+ sideEffects: resolved.sideEffects,
3047
+ suffix: resolved.suffix,
3048
+ warnings: resolved.warnings
3049
+ };
3050
+ if (resolved.namespace !== "file") return {
3051
+ 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.` }],
3052
+ warnings: resolved.warnings
3053
+ };
3054
+ return {
3055
+ namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
3056
+ path: resolved.path,
3057
+ pluginData: resolved.pluginData,
3058
+ sideEffects: resolved.sideEffects,
3059
+ suffix: resolved.suffix,
3060
+ warnings: resolved.warnings
3061
+ };
3062
+ });
3063
+ build.onLoad({
3064
+ filter: /.*/,
3065
+ namespace: viteRawNamespace
3066
+ }, async (args) => ({
3067
+ contents: await readFile(args.path),
3068
+ loader: "text"
3069
+ }));
3070
+ build.onLoad({
3071
+ filter: /.*/,
3072
+ namespace: viteMarkdownTemplateNamespace
3073
+ }, async (args) => ({
3074
+ contents: await (async () => {
3075
+ const template = await readFile(args.path, "utf8");
3076
+ const imports = {};
3077
+ const visited = new Set([args.path]);
3078
+ const visit = async (source, importer) => {
3079
+ for (const specifier of extractMarkdownTemplateImportSpecifiers(source)) {
3080
+ const key = `${importer}\0${specifier}`;
3081
+ if (imports[key]) continue;
3082
+ const resolved = await build.resolve(specifier, {
3083
+ importer,
3084
+ kind: "import-statement",
3085
+ pluginData: {
3086
+ ...args.pluginData,
3087
+ [skipMarkdownTemplateResolve]: true
3088
+ },
3089
+ resolveDir: dirname(importer)
3090
+ });
3091
+ if (resolved.errors.length) return Promise.reject(new Error(resolved.errors.map((error) => error.text).join("\n")));
3092
+ 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.`);
3093
+ const imported = {
3094
+ id: resolved.path,
3095
+ template: await readFile(resolved.path, "utf8")
3096
+ };
3097
+ imports[key] = imported;
3098
+ if (!visited.has(imported.id)) {
3099
+ visited.add(imported.id);
3100
+ await visit(imported.template, imported.id);
3101
+ }
3102
+ }
3103
+ };
3104
+ await visit(template, args.path);
3105
+ return renderMarkdownTemplateModule(template, args.path, imports);
3106
+ })(),
3107
+ loader: "js",
3108
+ resolveDir: dirname(args.path)
3109
+ }));
3110
+ }
3111
+ };
3112
+ }
3113
+ function createFileUrlPlugin() {
3114
+ return {
3115
+ name: "vitehub-file-url",
3116
+ setup(build) {
3117
+ build.onResolve({ filter: /^file:/ }, (args) => ({ path: fileURLToPath(args.path) }));
3118
+ }
3119
+ };
3120
+ }
3121
+ async function bundleEsmEntry(entryFile, outfile, options = {}) {
3122
+ options.signal?.throwIfAborted();
3123
+ const format = options.format || "esm";
3124
+ const platform = options.platform || "neutral";
3125
+ const viteAliasPlugin = createViteAliasPlugin(options.alias);
3126
+ 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/"));
3127
+ const plugins = [];
3128
+ const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd());
3129
+ if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
3130
+ plugins.push(...options.plugins ?? [], createFileUrlPlugin());
3131
+ if (viteAliasPlugin) plugins.push(viteAliasPlugin);
3132
+ plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime));
3133
+ const result = await (0, import_main.build)({
3134
+ absWorkingDir: options.workingDir,
3135
+ banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
3136
+ "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
3137
+ " globalThis.require = globalThis.process.getBuiltinModule(\"node:module\").createRequire(import.meta.url);",
3138
+ " globalThis.__filename = globalThis.process.getBuiltinModule(\"node:url\").fileURLToPath(import.meta.url);",
3139
+ " globalThis.__dirname = globalThis.process.getBuiltinModule(\"node:path\").dirname(globalThis.__filename);",
3140
+ "}"
3141
+ ] : []].filter(Boolean).join("\n") } : void 0,
3142
+ bundle: true,
3143
+ conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
3144
+ entryPoints: [entryFile],
3145
+ external: options.external,
3146
+ format,
3147
+ logLevel: "silent",
3148
+ mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
3149
+ resolveExtensions: options.extensions,
3150
+ minifyIdentifiers: options.minifyIdentifiers,
3151
+ minifyWhitespace: options.minifyWhitespace,
3152
+ outfile,
3153
+ packages: options.packages,
3154
+ platform,
3155
+ preserveSymlinks: options.preserveSymlinks,
3156
+ plugins,
3157
+ sourcemap: false,
3158
+ target: "es2022",
3159
+ write: options.signal ? false : true
3160
+ });
3161
+ options.signal?.throwIfAborted();
3162
+ if (options.signal) {
3163
+ await Promise.all((result.outputFiles ?? []).map(async (output) => {
3164
+ await mkdir(dirname(output.path), { recursive: true });
3165
+ options.signal.throwIfAborted();
3166
+ await writeFile(output.path, output.contents, { signal: options.signal });
3167
+ }));
3168
+ options.signal.throwIfAborted();
3169
+ }
3170
+ }
3171
+ //#endregion
3172
+ //#region ../internal/src/build/provider-output-sources.ts
3173
+ /** Removes retained provider output after readers release it, tolerating transient filesystem contention. */
3174
+ async function removeProviderOutputArtifactDir(path) {
3175
+ await rm(path, {
3176
+ force: true,
3177
+ maxRetries: 5,
3178
+ recursive: true,
3179
+ retryDelay: 50
3180
+ });
3181
+ }
3182
+ //#endregion
3183
+ //#region ../internal/src/build/vercel-config.ts
3184
+ function createVercelConfigJson() {
3185
+ return {
3186
+ routes: [{ handle: "filesystem" }, {
3187
+ src: "/(.*)",
3188
+ dest: "/__server"
3189
+ }],
3190
+ version: 3
3191
+ };
3192
+ }
3193
+ function createNodeFunctionConfig(extra = {}) {
3194
+ return {
3195
+ handler: "index.mjs",
3196
+ launcherType: "Nodejs",
3197
+ runtime: "nodejs22.x",
3198
+ shouldAddHelpers: false,
3199
+ supportsResponseStreaming: true,
3200
+ ...extra
3201
+ };
3202
+ }
3203
+ //#endregion
3204
+ //#region ../internal/src/build/provider-output-catalog.ts
3205
+ var ProviderOutputCatalog = class {
3206
+ #appliedCloudflareContributions = /* @__PURE__ */ new Map();
3207
+ #cloudflareContributions = /* @__PURE__ */ new Map();
3208
+ #runtimeContributions = /* @__PURE__ */ new Map();
3209
+ #runtimeContributionsByGeneration = /* @__PURE__ */ new WeakMap();
3210
+ #deploymentContributionSequence = 0;
3211
+ #deploymentContributions = /* @__PURE__ */ new Map();
3212
+ #deploymentGenerationRefs = /* @__PURE__ */ new WeakMap();
3213
+ #deploymentGenerations = /* @__PURE__ */ new Set();
3214
+ #pendingDeploymentDiscards = [];
3215
+ #takenDeploymentContributions = /* @__PURE__ */ new Map();
3216
+ appliedCloudflareContributions() {
3217
+ return this.#appliedCloudflareContributions.values();
3218
+ }
3219
+ appliedCloudflareContributionEntries() {
3220
+ return this.#appliedCloudflareContributions.entries();
3221
+ }
3222
+ clearAppliedCloudflareContributions() {
3223
+ this.#appliedCloudflareContributions.clear();
3224
+ }
3225
+ cloudflareContributions() {
3226
+ return this.#cloudflareContributions.entries();
3227
+ }
3228
+ inheritCloudflareContributions(catalog) {
3229
+ for (const [owner, contribution] of catalog.appliedCloudflareContributionEntries()) this.#appliedCloudflareContributions.set(owner, contribution);
3230
+ for (const [owner, contribution] of [...catalog.cloudflareContributions(), ...this.#cloudflareContributions]) this.#cloudflareContributions.set(owner, contribution);
3231
+ }
3232
+ replaceAppliedCloudflareContribution(owner, contribution) {
3233
+ this.#appliedCloudflareContributions.set(owner, contribution);
3234
+ }
3235
+ replaceCloudflareContribution(owner, contribution) {
3236
+ this.#cloudflareContributions.set(owner, contribution);
3237
+ }
3238
+ replaceRuntimeContribution(contribution, generation) {
3239
+ if (!generation) {
3240
+ this.#runtimeContributions.set(contribution.owner, contribution);
3241
+ return;
3242
+ }
3243
+ let contributions = this.#runtimeContributionsByGeneration.get(generation);
3244
+ if (!contributions) {
3245
+ contributions = /* @__PURE__ */ new Map();
3246
+ this.#runtimeContributionsByGeneration.set(generation, contributions);
3247
+ }
3248
+ contributions.set(contribution.owner, contribution);
3249
+ }
3250
+ runtimeContribution(product, generation) {
3251
+ return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.get(product);
3252
+ }
3253
+ runtimeContributions(generation) {
3254
+ return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.entries() ?? (/* @__PURE__ */ new Map()).entries();
3255
+ }
3256
+ resetRuntimeContributions() {
3257
+ this.#runtimeContributions.clear();
3258
+ }
3259
+ createDeploymentGeneration() {
3260
+ const generation = { valid: true };
3261
+ this.#trackDeploymentGeneration(generation);
3262
+ return generation;
3263
+ }
3264
+ replaceDeploymentContribution(contribution, generation) {
3265
+ const entry = {
3266
+ contribution,
3267
+ generation,
3268
+ sequence: this.#deploymentContributionSequence++
3269
+ };
3270
+ if (generation && !generation.valid) {
3271
+ this.#queueDeploymentDiscard(entry);
3272
+ return;
3273
+ }
3274
+ this.#restoreDeploymentContribution(entry);
3275
+ }
3276
+ resetDeploymentContributions(generation) {
3277
+ if (!generation) {
3278
+ for (const reference of this.#deploymentGenerations) {
3279
+ const current = reference.deref();
3280
+ if (current) current.valid = false;
3281
+ }
3282
+ this.#deploymentGenerations.clear();
3283
+ for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry);
3284
+ for (const taken of this.#takenDeploymentContributions.values()) {
3285
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
3286
+ for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback);
3287
+ }
3288
+ this.#deploymentContributions.clear();
3289
+ this.#takenDeploymentContributions.clear();
3290
+ return;
3291
+ }
3292
+ generation.valid = false;
3293
+ this.#deleteDeploymentGeneration(generation);
3294
+ for (const [owner, entries] of this.#deploymentContributions) {
3295
+ for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry);
3296
+ const remaining = entries.filter((entry) => entry.generation !== generation);
3297
+ if (remaining.length) this.#deploymentContributions.set(owner, remaining);
3298
+ else this.#deploymentContributions.delete(owner);
3299
+ }
3300
+ for (const [contribution, taken] of this.#takenDeploymentContributions) {
3301
+ const invalidatedFallbacks = taken.fallbacks.filter((entry) => entry.generation === generation);
3302
+ taken.fallbacks = taken.fallbacks.filter((entry) => entry.generation !== generation);
3303
+ for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback);
3304
+ if (taken.entry.generation !== generation) continue;
3305
+ this.#takenDeploymentContributions.delete(contribution);
3306
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
3307
+ for (const fallback of taken.fallbacks) if (taken.committed) this.#queueDeploymentDiscard(fallback);
3308
+ else this.#restoreDeploymentContribution(fallback);
3309
+ }
3310
+ }
3311
+ hasDeploymentContributions() {
3312
+ return this.#deploymentContributions.size > 0;
3313
+ }
3314
+ takeDeploymentContributions() {
3315
+ const contributions = [];
3316
+ for (const [owner, entries] of this.#deploymentContributions) {
3317
+ const entry = entries.at(-1);
3318
+ contributions.push(entry.contribution);
3319
+ this.#takenDeploymentContributions.set(entry.contribution, {
3320
+ committed: false,
3321
+ entry,
3322
+ entryDiscarded: false,
3323
+ fallbacks: entries.slice(0, -1)
3324
+ });
3325
+ this.#deploymentContributions.delete(owner);
3326
+ }
3327
+ return contributions;
3328
+ }
3329
+ deploymentContributionGeneration(contribution) {
3330
+ return this.#takenDeploymentContributions.get(contribution)?.entry.generation;
3331
+ }
3332
+ commitDeploymentContributions(contributions) {
3333
+ for (const contribution of contributions) {
3334
+ const taken = this.#takenDeploymentContributions.get(contribution);
3335
+ if (taken) taken.committed = true;
3336
+ }
3337
+ }
3338
+ async prepareDeploymentContributions(contributions) {
3339
+ const discarded = this.#pendingDeploymentDiscards.splice(0);
3340
+ for (const contribution of contributions) {
3341
+ const taken = this.#takenDeploymentContributions.get(contribution);
3342
+ if (!taken || taken.entryDiscarded || !taken.entry.contribution.discard) continue;
3343
+ taken.entryDiscarded = true;
3344
+ discarded.push(Promise.resolve().then(taken.entry.contribution.discard));
3345
+ }
3346
+ const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
3347
+ if (failure) throw failure.reason;
3348
+ }
3349
+ async completeDeploymentContributions(contributions) {
3350
+ const discarded = this.#pendingDeploymentDiscards.splice(0);
3351
+ const completedGenerations = /* @__PURE__ */ new Set();
3352
+ for (const contribution of contributions) {
3353
+ const taken = this.#takenDeploymentContributions.get(contribution);
3354
+ if (!taken) continue;
3355
+ this.#takenDeploymentContributions.delete(contribution);
3356
+ const entries = taken.entryDiscarded ? taken.fallbacks : [...taken.fallbacks, taken.entry];
3357
+ for (const entry of entries) {
3358
+ if (entry.generation) completedGenerations.add(entry.generation);
3359
+ if (entry.contribution.discard) discarded.push(entry.contribution.discard());
3360
+ }
3361
+ }
3362
+ for (const generation of completedGenerations) this.#retireDeploymentGeneration(generation);
3363
+ const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
3364
+ if (failure) throw failure.reason;
3365
+ }
3366
+ rollbackDeploymentContributions(contributions) {
3367
+ for (const contribution of contributions) {
3368
+ const taken = this.#takenDeploymentContributions.get(contribution);
3369
+ if (!taken) continue;
3370
+ this.#takenDeploymentContributions.delete(contribution);
3371
+ for (const entry of [...taken.fallbacks, taken.entry]) this.#restoreDeploymentContribution(entry);
3372
+ }
3373
+ }
3374
+ #restoreDeploymentContribution(entry) {
3375
+ if (entry.generation && !entry.generation.valid) return;
3376
+ if (entry.generation) this.#trackDeploymentGeneration(entry.generation);
3377
+ const entries = this.#deploymentContributions.get(entry.contribution.owner) ?? [];
3378
+ const replaced = entries.findIndex((candidate) => candidate.generation === entry.generation);
3379
+ if (replaced >= 0) {
3380
+ if (entries[replaced].sequence > entry.sequence) return;
3381
+ entries.splice(replaced, 1);
3382
+ }
3383
+ entries.push(entry);
3384
+ entries.sort((left, right) => left.sequence - right.sequence);
3385
+ this.#deploymentContributions.set(entry.contribution.owner, entries);
3386
+ }
3387
+ #retireDeploymentGeneration(generation) {
3388
+ const pending = [...this.#deploymentContributions.values()].some((entries) => entries.some((entry) => entry.generation === generation));
3389
+ const taken = [...this.#takenDeploymentContributions.values()].some((entry) => entry.entry.generation === generation || entry.fallbacks.some((fallback) => fallback.generation === generation));
3390
+ if (!pending && !taken) this.#deleteDeploymentGeneration(generation);
3391
+ }
3392
+ #trackDeploymentGeneration(generation) {
3393
+ if (this.#deploymentGenerationRefs.has(generation)) return;
3394
+ const reference = new WeakRef(generation);
3395
+ this.#deploymentGenerationRefs.set(generation, reference);
3396
+ this.#deploymentGenerations.add(reference);
3397
+ }
3398
+ #deleteDeploymentGeneration(generation) {
3399
+ const reference = this.#deploymentGenerationRefs.get(generation);
3400
+ if (reference) this.#deploymentGenerations.delete(reference);
3401
+ this.#deploymentGenerationRefs.delete(generation);
3402
+ }
3403
+ #queueDeploymentDiscard(entry) {
3404
+ if (!entry.contribution.discard) return;
3405
+ const discard = Promise.resolve().then(entry.contribution.discard);
3406
+ discard.catch(() => {});
3407
+ this.#pendingDeploymentDiscards.push(discard);
3408
+ }
3409
+ };
3410
+ const providerOutputCatalogRegistry = globalThis;
3411
+ const providerOutputCatalogs = providerOutputCatalogRegistry.__vitehubProviderOutputCatalogs ??= /* @__PURE__ */ new WeakMap();
3412
+ const providerOutputCatalog = Symbol.for("vitehub.provider-output-catalog");
3413
+ function createProviderOutputCatalog() {
3414
+ return new ProviderOutputCatalog();
3415
+ }
3416
+ function useProviderOutputCatalog(config) {
3417
+ const owner = config;
3418
+ let catalog = owner[providerOutputCatalog] ?? providerOutputCatalogs.get(config);
3419
+ if (!catalog) catalog = createProviderOutputCatalog();
3420
+ owner[providerOutputCatalog] = catalog;
3421
+ providerOutputCatalogs.set(config, catalog);
3422
+ return catalog;
3423
+ }
3424
+ //#endregion
3425
+ //#region ../internal/src/build/vite.ts
3426
+ function createNoExternalMerger(packageName) {
3427
+ return (current) => {
3428
+ if (current === true) return true;
3429
+ if (!current) return [packageName];
3430
+ const values = Array.isArray(current) ? current : [current];
3431
+ return values.includes(packageName) ? values : [...values, packageName];
3432
+ };
3433
+ }
3434
+ function isServerEnvironment(name, config) {
3435
+ return name === "ssr" || config.consumer === "server";
3436
+ }
3437
+ function includesNitroVitePlugin(value) {
3438
+ if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
3439
+ if (!value || typeof value !== "object") return false;
3440
+ return "name" in value && value.name === "nitro:main";
3441
+ }
3442
+ function hasNitroConfigContext(config) {
3443
+ return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
3444
+ }
3445
+ function shouldSkipViteProviderBuild(command, mode) {
3446
+ return command === "serve" || mode === "e2e";
3447
+ }
3448
+ //#endregion
3449
+ //#region ../internal/src/build/deployment-output.ts
3450
+ const providerDeploymentOutputRegistry = globalThis;
3451
+ const providerDeploymentOutputWrites = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputWrites ??= /* @__PURE__ */ new Map();
3452
+ const providerDeploymentOutputFinalizations = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputFinalizations ??= /* @__PURE__ */ new WeakMap();
3453
+ const providerDeploymentOutputCompletedResets = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputCompletedResets ??= /* @__PURE__ */ new WeakMap();
3454
+ const providerDeploymentOutputRootStates = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputRootStates ??= /* @__PURE__ */ new Map();
3455
+ const providerDeploymentOutputOwnerOrder = [
3456
+ "agent",
3457
+ "database",
3458
+ "blob",
3459
+ "queue",
3460
+ "rate-limit",
3461
+ "schedule",
3462
+ "workflow",
3463
+ "vite-hub",
3464
+ "browser",
3465
+ "kv",
3466
+ "workspace"
3467
+ ];
3468
+ function throwIfProviderOutputAborted(signal) {
3469
+ if (!signal.aborted) return;
3470
+ throw signal.reason ?? new DOMException("Provider Output finalization aborted.", "AbortError");
3471
+ }
3472
+ async function settleWrites(writes) {
3473
+ const failure = (await Promise.allSettled(writes)).find((result) => result.status === "rejected");
3474
+ if (failure) throw failure.reason;
3475
+ }
3476
+ function resolveClientOutput(rootDir, clientOutDir) {
3477
+ const clientDir = resolve(rootDir, clientOutDir);
3478
+ return {
3479
+ clientDir,
3480
+ staticIndex: hasStaticIndex(clientDir)
3481
+ };
3482
+ }
3483
+ function createDefaultCloudflareStaticOutputDir(rootDir) {
3484
+ return resolve(rootDir, "dist", "client");
3485
+ }
3486
+ function resolveProviderOutputOwnershipFile(outputRoot, fileName) {
3487
+ if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") throw new TypeError(`Invalid Provider Output ownership file name: ${JSON.stringify(fileName)}`);
3488
+ return resolve(outputRoot, fileName);
3489
+ }
3490
+ async function readProviderOutputOwnershipFile(outputRoot, fileName) {
3491
+ try {
3492
+ const parsed = JSON.parse(await readFile(resolveProviderOutputOwnershipFile(outputRoot, fileName), "utf8"));
3493
+ if (!Array.isArray(parsed) || !parsed.every((value) => typeof value === "string")) throw new TypeError(`Invalid Provider Output ownership file schema: ${JSON.stringify(fileName)}`);
3494
+ return parsed;
3495
+ } catch (error) {
3496
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
3497
+ throw error;
3498
+ }
3499
+ }
3500
+ async function readCloudflareProviderDeploymentOutputState(rootDir, options) {
3501
+ const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
3502
+ let wranglerConfig = {};
3503
+ try {
3504
+ wranglerConfig = JSON.parse(await readFile(resolve(outputRoot, "wrangler.json"), "utf8"));
3505
+ } catch (error) {
3506
+ if (error.code !== "ENOENT") throw error;
3507
+ }
3508
+ return {
3509
+ wranglerConfig,
3510
+ wranglerConfigOwnership: await resolvePersistedProviderOutputOwnership(outputRoot, options.wranglerConfigOwnership, options.wranglerConfigOwnershipFiles)
3511
+ };
3512
+ }
3513
+ async function resolvePersistedProviderOutputOwnership(outputRoot, ownership, files) {
3514
+ if (!files || !Object.keys(files).length) return ownership;
3515
+ const arrays = { ...ownership?.arrays };
3516
+ await Promise.all(Object.entries(files).map(async ([field, fileName]) => {
3517
+ const current = arrays[field];
3518
+ if (!current) throw new TypeError(`Provider Output ownership file for ${JSON.stringify(field)} requires array ownership.`);
3519
+ arrays[field] = {
3520
+ ...current,
3521
+ values: [...await readProviderOutputOwnershipFile(outputRoot, fileName), ...current.values ?? []]
3522
+ };
3523
+ }));
3524
+ return {
3525
+ ...ownership,
3526
+ arrays
3527
+ };
3528
+ }
3529
+ async function writeProviderOutputOwnershipFiles(outputRoot, ownership, files) {
3530
+ await Promise.all(Object.entries(files ?? {}).map(async ([field, fileName]) => {
3531
+ const file = resolveProviderOutputOwnershipFile(outputRoot, fileName);
3532
+ const values = [...new Set(ownership?.arrays?.[field]?.values ?? [])];
3533
+ if (!values.length) {
3534
+ await rm(file, { force: true });
3535
+ return;
3536
+ }
3537
+ await mkdir(outputRoot, { recursive: true });
3538
+ await writeFile(file, `${JSON.stringify(values, null, 2)}\n`, "utf8");
3539
+ }));
3540
+ }
3541
+ function createDefaultVercelOutputRoot(rootDir) {
3542
+ return resolve(rootDir, ".vercel", "output");
3543
+ }
3544
+ function createDefaultNetlifyOutputRoot(rootDir) {
3545
+ return resolve(rootDir, ".netlify", "v1");
3546
+ }
3547
+ function assertNetlifyFunctionName(functionName) {
3548
+ if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Invalid Netlify function name: ${functionName}`);
3549
+ }
3550
+ function resolveNetlifyFunctionFile(functionsRoot, functionName) {
3551
+ assertNetlifyFunctionName(functionName);
3552
+ return resolve(functionsRoot, `${functionName}.mjs`);
3553
+ }
3554
+ async function appendNetlifyFunctionConfig(outfile, config) {
3555
+ if (!config) return;
3556
+ await writeFile(outfile, `${(await readFile(outfile, "utf8")).trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
3557
+ }
3558
+ async function writeCloudflareDeploymentOutput(options, signal) {
3559
+ signal?.throwIfAborted();
3560
+ const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
3561
+ const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
3562
+ const staticOutputDir = options.staticOutputDir ?? createDefaultCloudflareStaticOutputDir(options.rootDir);
3563
+ const copiesStaticOutput = Boolean(options.bundleEntry && staticIndex && resolve(clientDir) !== resolve(staticOutputDir));
3564
+ const files = Object.entries(options.files ?? {});
3565
+ const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
3566
+ if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw new Error(`Cloudflare output file conflicts with bundle outfile: ${workerOutfile}`);
3567
+ const backupRoot = copiesStaticOutput ? await mkdtemp(resolve(options.rootDir, ".vitehub-cloudflare-output-")) : void 0;
3568
+ const previousOutputRoot = backupRoot ? resolve(backupRoot, "output") : `${outputRoot}.previous`;
3569
+ const previousStaticOutputDir = backupRoot ? resolve(backupRoot, "static") : `${staticOutputDir}.previous`;
3570
+ if (!backupRoot) await rm(previousOutputRoot, {
3571
+ force: true,
3572
+ recursive: true
3573
+ });
3574
+ if (copiesStaticOutput && !backupRoot) await rm(previousStaticOutputDir, {
3575
+ force: true,
3576
+ recursive: true
3577
+ });
3578
+ let hadPreviousOutput = false;
3579
+ let hadPreviousStaticOutput = false;
3580
+ let publicationSucceeded = false;
3581
+ let publicationStarted = false;
3582
+ let outputRestorationSucceeded = false;
3583
+ let staticRestorationSucceeded = false;
3584
+ try {
3585
+ try {
3586
+ await cp(outputRoot, previousOutputRoot, { recursive: true });
3587
+ hadPreviousOutput = true;
3588
+ } catch (error) {
3589
+ if (error.code !== "ENOENT") throw error;
32
3590
  }
33
- return true;
3591
+ if (copiesStaticOutput) try {
3592
+ await cp(staticOutputDir, previousStaticOutputDir, { recursive: true });
3593
+ hadPreviousStaticOutput = true;
3594
+ } catch (error) {
3595
+ if (error.code !== "ENOENT") throw error;
3596
+ }
3597
+ publicationStarted = true;
3598
+ await mkdir(outputRoot, { recursive: true });
3599
+ const wranglerConfigOwnership = await resolvePersistedProviderOutputOwnership(outputRoot, options.wranglerConfigOwnership ?? { keys: options.wranglerConfigKeys }, options.wranglerConfigOwnershipFiles);
3600
+ const writes = [
3601
+ writeCloudflareWranglerConfig({
3602
+ outputRoot,
3603
+ rootDir: options.rootDir,
3604
+ wranglerConfig: options.wranglerConfig,
3605
+ wranglerConfigDefaults: options.wranglerConfigDefaults,
3606
+ wranglerConfigOwnership
3607
+ }),
3608
+ options.bundleEntry && staticIndex ? copyClientOutput(clientDir, staticOutputDir) : Promise.resolve(),
3609
+ ...files.map(([fileName, contents]) => writeFile(resolve(outputRoot, fileName), contents, "utf8"))
3610
+ ];
3611
+ if (options.bundleEntry && workerOutfile) {
3612
+ const stagedWorkerOutfile = `${workerOutfile}.pending`;
3613
+ writes.push((async () => {
3614
+ try {
3615
+ await rm(stagedWorkerOutfile, {
3616
+ force: true,
3617
+ recursive: true
3618
+ });
3619
+ await bundleEsmEntry(options.bundleEntry, stagedWorkerOutfile, {
3620
+ ...options.bundleOptions,
3621
+ rootDir: options.sourceRootDir ?? options.rootDir,
3622
+ signal
3623
+ });
3624
+ signal?.throwIfAborted();
3625
+ await rename(stagedWorkerOutfile, workerOutfile);
3626
+ } catch (error) {
3627
+ await rm(stagedWorkerOutfile, {
3628
+ force: true,
3629
+ recursive: true
3630
+ });
3631
+ throw error;
3632
+ }
3633
+ })());
3634
+ }
3635
+ await settleWrites(writes);
3636
+ await writeProviderOutputOwnershipFiles(outputRoot, options.wranglerConfigOwnership, options.wranglerConfigOwnershipFiles);
3637
+ signal?.throwIfAborted();
3638
+ publicationSucceeded = true;
3639
+ } catch (error) {
3640
+ if (publicationStarted) {
3641
+ await rm(outputRoot, {
3642
+ force: true,
3643
+ recursive: true
3644
+ });
3645
+ if (hadPreviousOutput) {
3646
+ await cp(previousOutputRoot, outputRoot, { recursive: true });
3647
+ outputRestorationSucceeded = true;
3648
+ }
3649
+ if (copiesStaticOutput) {
3650
+ await rm(staticOutputDir, {
3651
+ force: true,
3652
+ recursive: true
3653
+ });
3654
+ if (hadPreviousStaticOutput) {
3655
+ await cp(previousStaticOutputDir, staticOutputDir, { recursive: true });
3656
+ staticRestorationSucceeded = true;
3657
+ }
3658
+ }
3659
+ }
3660
+ throw error;
34
3661
  } finally {
35
- ancestors.delete(value);
3662
+ if (!publicationStarted || publicationSucceeded || outputRestorationSucceeded || !hadPreviousOutput) await rm(previousOutputRoot, {
3663
+ force: true,
3664
+ recursive: true
3665
+ }).catch(() => void 0);
3666
+ if (copiesStaticOutput && (!publicationStarted || publicationSucceeded || staticRestorationSucceeded || !hadPreviousStaticOutput)) await rm(previousStaticOutputDir, {
3667
+ force: true,
3668
+ recursive: true
3669
+ }).catch(() => void 0);
3670
+ if (backupRoot) await rmdir(backupRoot).catch(() => void 0);
36
3671
  }
37
3672
  }
38
- function isProviderJsonRecordValue(value, ancestors) {
39
- const prototype = Object.getPrototypeOf(value);
40
- if (prototype !== Object.prototype && prototype !== null || ancestors.has(value)) return false;
41
- ancestors.add(value);
3673
+ async function copyVercelClientOutput(rootDir, clientDir, staticOutputDir) {
3674
+ const cloudflareOutputRoot = createDefaultCloudflareOutputRoot(rootDir);
3675
+ const outputRelativePath = relative(clientDir, cloudflareOutputRoot);
3676
+ const excludesCloudflareOutput = outputRelativePath && outputRelativePath !== ".." && !outputRelativePath.startsWith(`..${sep}`) && !isAbsolute(outputRelativePath);
3677
+ await copyClientOutput(clientDir, staticOutputDir);
3678
+ if (resolve(clientDir) === resolve(staticOutputDir) || !excludesCloudflareOutput) return;
42
3679
  try {
43
- return Reflect.ownKeys(value).every((key) => {
44
- if (typeof key !== "string") return false;
45
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
46
- return descriptor?.enumerable === true && "value" in descriptor && isProviderJsonValue(descriptor.value, ancestors);
3680
+ await readFile(resolve(cloudflareOutputRoot, "wrangler.json"));
3681
+ } catch (error) {
3682
+ if (error.code === "ENOENT") return;
3683
+ throw error;
3684
+ }
3685
+ await rm(resolve(staticOutputDir, outputRelativePath), {
3686
+ force: true,
3687
+ recursive: true
3688
+ });
3689
+ }
3690
+ async function writeVercelDeploymentOutput(options, signal) {
3691
+ signal?.throwIfAborted();
3692
+ const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
3693
+ const outputRoot = options.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir);
3694
+ const stagedOutputRoot = `${outputRoot}.pending`;
3695
+ const previousOutputRoot = `${outputRoot}.previous`;
3696
+ const functionOutput = options.function ?? { kind: "root" };
3697
+ const serverFunctionName = functionOutput.kind === "root" ? "__server.func" : functionOutput.name;
3698
+ const config = options.config ?? (functionOutput.kind === "root" ? createVercelConfigJson() : {});
3699
+ const serverDir = resolve(stagedOutputRoot, "functions", serverFunctionName);
3700
+ const serverEntry = resolve(serverDir, "index.mjs");
3701
+ const staticOutputDir = options.staticOutputDir ?? resolve(outputRoot, "static");
3702
+ const staticRelativePath = relative(outputRoot, staticOutputDir);
3703
+ const staticInsideOutputRoot = !staticRelativePath.startsWith(`..${sep}`) && !isAbsolute(staticRelativePath);
3704
+ const externalStaticNeedsCommit = staticIndex && !staticInsideOutputRoot && resolve(clientDir) !== resolve(staticOutputDir);
3705
+ const stagedStaticOutputDir = staticInsideOutputRoot ? resolve(stagedOutputRoot, staticRelativePath) : externalStaticNeedsCommit ? `${staticOutputDir}.pending` : staticOutputDir;
3706
+ const previousStaticOutputDir = `${staticOutputDir}.previous`;
3707
+ let replacedOutput = false;
3708
+ let installedOutput = false;
3709
+ let replacedExternalStatic = false;
3710
+ let installedExternalStatic = false;
3711
+ try {
3712
+ await rm(stagedOutputRoot, {
3713
+ force: true,
3714
+ recursive: true
47
3715
  });
48
- } finally {
49
- ancestors.delete(value);
3716
+ try {
3717
+ await cp(outputRoot, stagedOutputRoot, { recursive: true });
3718
+ } catch (error) {
3719
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
3720
+ }
3721
+ await mkdir(serverDir, { recursive: true });
3722
+ await rm(serverDir, {
3723
+ force: true,
3724
+ recursive: true
3725
+ });
3726
+ await mkdir(serverDir, { recursive: true });
3727
+ try {
3728
+ await cp(resolve(outputRoot, "functions", serverFunctionName, "node_modules"), resolve(serverDir, "node_modules"), { recursive: true });
3729
+ } catch (error) {
3730
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
3731
+ }
3732
+ await bundleEsmEntry(options.bundleEntry, serverEntry, {
3733
+ ...options.bundleOptions,
3734
+ rootDir: options.sourceRootDir ?? options.rootDir,
3735
+ signal
3736
+ });
3737
+ await writeFile(resolve(serverDir, ".vc-config.json"), `${stringifyProviderOutputConfig(options.functionConfig ?? createNodeFunctionConfig())}\n`, "utf8");
3738
+ 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");
3739
+ if (failedWrite?.status === "rejected") throw failedWrite.reason;
3740
+ signal?.throwIfAborted();
3741
+ rmSync(previousOutputRoot, {
3742
+ force: true,
3743
+ recursive: true
3744
+ });
3745
+ if (existsSync(outputRoot)) {
3746
+ renameSync(outputRoot, previousOutputRoot);
3747
+ replacedOutput = true;
3748
+ }
3749
+ try {
3750
+ renameSync(stagedOutputRoot, outputRoot);
3751
+ installedOutput = true;
3752
+ } catch (error) {
3753
+ if (replacedOutput && existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
3754
+ replacedOutput = false;
3755
+ throw error;
3756
+ }
3757
+ signal?.throwIfAborted();
3758
+ if (externalStaticNeedsCommit) {
3759
+ rmSync(previousStaticOutputDir, {
3760
+ force: true,
3761
+ recursive: true
3762
+ });
3763
+ if (existsSync(staticOutputDir)) {
3764
+ renameSync(staticOutputDir, previousStaticOutputDir);
3765
+ replacedExternalStatic = true;
3766
+ }
3767
+ try {
3768
+ renameSync(stagedStaticOutputDir, staticOutputDir);
3769
+ installedExternalStatic = true;
3770
+ } catch (error) {
3771
+ if (replacedExternalStatic && existsSync(previousStaticOutputDir)) renameSync(previousStaticOutputDir, staticOutputDir);
3772
+ replacedExternalStatic = false;
3773
+ throw error;
3774
+ }
3775
+ signal?.throwIfAborted();
3776
+ }
3777
+ try {
3778
+ rmSync(previousOutputRoot, {
3779
+ force: true,
3780
+ recursive: true
3781
+ });
3782
+ } catch {}
3783
+ if (replacedExternalStatic) try {
3784
+ rmSync(previousStaticOutputDir, {
3785
+ force: true,
3786
+ recursive: true
3787
+ });
3788
+ } catch {}
3789
+ } catch (error) {
3790
+ await rm(stagedOutputRoot, {
3791
+ force: true,
3792
+ recursive: true
3793
+ });
3794
+ if (externalStaticNeedsCommit) await rm(stagedStaticOutputDir, {
3795
+ force: true,
3796
+ recursive: true
3797
+ });
3798
+ if (installedExternalStatic) rmSync(staticOutputDir, {
3799
+ force: true,
3800
+ recursive: true
3801
+ });
3802
+ if (replacedExternalStatic) {
3803
+ if (existsSync(previousStaticOutputDir)) renameSync(previousStaticOutputDir, staticOutputDir);
3804
+ }
3805
+ if (installedOutput) rmSync(outputRoot, {
3806
+ force: true,
3807
+ recursive: true
3808
+ });
3809
+ if (replacedOutput) {
3810
+ if (existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
3811
+ }
3812
+ throw error;
50
3813
  }
51
3814
  }
52
- function isProviderJsonValue(value, ancestors) {
53
- if (value === null || typeof value === "boolean" || typeof value === "string") return true;
54
- if (typeof value === "number") return Number.isFinite(value);
55
- if (Array.isArray(value)) return isProviderJsonArray(value, ancestors);
56
- return typeof value === "object" && isProviderJsonRecordValue(value, ancestors);
3815
+ async function writeNetlifyDeploymentOutput(options, signal) {
3816
+ signal?.throwIfAborted();
3817
+ const outputRoot = options.outputRoot ?? createDefaultNetlifyOutputRoot(options.rootDir);
3818
+ const stagedOutputRoot = `${outputRoot}.pending`;
3819
+ const previousOutputRoot = `${outputRoot}.previous`;
3820
+ const functionsRoot = resolve(stagedOutputRoot, "functions");
3821
+ let replacedOutput = false;
3822
+ let installedOutput = false;
3823
+ await rm(stagedOutputRoot, {
3824
+ force: true,
3825
+ recursive: true
3826
+ });
3827
+ await rm(previousOutputRoot, {
3828
+ force: true,
3829
+ recursive: true
3830
+ });
3831
+ try {
3832
+ await cp(outputRoot, stagedOutputRoot, { recursive: true });
3833
+ } catch (error) {
3834
+ if (error.code !== "ENOENT") throw error;
3835
+ }
3836
+ const functionWrites = (options.functions ?? []).map(async (func) => {
3837
+ const outfile = resolveNetlifyFunctionFile(functionsRoot, func.functionName);
3838
+ await mkdir(dirname(outfile), { recursive: true });
3839
+ await bundleEsmEntry(func.bundleEntry, outfile, {
3840
+ ...func.bundleOptions,
3841
+ minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers,
3842
+ rootDir: options.sourceRootDir ?? options.rootDir,
3843
+ signal
3844
+ });
3845
+ await appendNetlifyFunctionConfig(outfile, func.config);
3846
+ });
3847
+ try {
3848
+ await mkdir(stagedOutputRoot, { recursive: true });
3849
+ await settleWrites([writeProviderOutputConfig(resolve(stagedOutputRoot, "config.json"), options.config ?? {}, { keys: options.configKeys }), ...functionWrites]);
3850
+ signal?.throwIfAborted();
3851
+ if (existsSync(outputRoot)) {
3852
+ renameSync(outputRoot, previousOutputRoot);
3853
+ replacedOutput = true;
3854
+ }
3855
+ renameSync(stagedOutputRoot, outputRoot);
3856
+ installedOutput = true;
3857
+ signal?.throwIfAborted();
3858
+ } catch (error) {
3859
+ await rm(stagedOutputRoot, {
3860
+ force: true,
3861
+ recursive: true
3862
+ });
3863
+ if (installedOutput) rmSync(outputRoot, {
3864
+ force: true,
3865
+ recursive: true
3866
+ });
3867
+ if (replacedOutput && existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
3868
+ throw error;
3869
+ }
3870
+ try {
3871
+ rmSync(previousOutputRoot, {
3872
+ force: true,
3873
+ recursive: true
3874
+ });
3875
+ } catch {}
57
3876
  }
58
- function isProviderJsonRecord(value) {
3877
+ async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput, signal) {
3878
+ const cleanup = typeof cleanupInput === "function" ? await cleanupInput() : cleanupInput;
3879
+ signal?.throwIfAborted();
3880
+ const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
3881
+ if (!shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup)) return;
3882
+ const wranglerConfigOwnership = await resolvePersistedProviderOutputOwnership(outputRoot, cleanup.wranglerConfigOwnership, cleanup.wranglerConfigOwnershipFiles);
3883
+ const writes = (cleanup.fileNames ?? []).map((fileName) => rm(resolve(outputRoot, fileName), {
3884
+ force: true,
3885
+ recursive: true
3886
+ }));
3887
+ writes.push(writeCloudflareWranglerConfig({
3888
+ outputRoot,
3889
+ rootDir,
3890
+ wranglerConfigOwnership
3891
+ }));
3892
+ await Promise.all(writes);
3893
+ await writeProviderOutputOwnershipFiles(outputRoot, cleanup.wranglerConfigOwnership, cleanup.wranglerConfigOwnershipFiles);
59
3894
  try {
60
- return typeof value === "object" && value !== null && !Array.isArray(value) && isProviderJsonRecordValue(value, /* @__PURE__ */ new Set());
61
- } catch {
62
- return false;
3895
+ await rmdir(outputRoot);
3896
+ } catch (error) {
3897
+ const code = error.code;
3898
+ if (code !== "ENOENT" && code !== "ENOTEMPTY") throw error;
63
3899
  }
64
3900
  }
65
- function assertProviderJsonRecord(value) {
66
- if (!isProviderJsonRecord(value)) throw new TypeError("[vitehub] Provider output config must be a JSON object.");
3901
+ function shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup) {
3902
+ return !cleanup.requirePersistedOwnership || Object.values(cleanup.wranglerConfigOwnershipFiles ?? {}).some((fileName) => existsSync(resolveProviderOutputOwnershipFile(outputRoot, fileName)));
67
3903
  }
68
- function isFileNotFoundError(error) {
69
- return error instanceof Error && "code" in error && error.code === "ENOENT";
3904
+ async function cleanupVercelDeploymentOutput(rootDir, cleanup, signal) {
3905
+ signal?.throwIfAborted();
3906
+ const outputRoot = cleanup.outputRoot ?? createDefaultVercelOutputRoot(rootDir);
3907
+ const writes = [];
3908
+ if (cleanup.serverFunctionName) writes.push(rm(resolve(outputRoot, "functions", cleanup.serverFunctionName), {
3909
+ force: true,
3910
+ recursive: true
3911
+ }));
3912
+ writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
3913
+ await Promise.all(writes);
70
3914
  }
71
- async function readProviderJsonRecord(file) {
72
- try {
73
- const parsed = JSON.parse(await readFile(file, "utf8"));
74
- assertProviderJsonRecord(parsed);
75
- return parsed;
76
- } catch (error) {
77
- if (isFileNotFoundError(error)) return;
78
- throw error;
3915
+ async function cleanupVercelDeploymentOutputs(rootDir, cleanup, signal) {
3916
+ await Promise.all((Array.isArray(cleanup) ? cleanup : [cleanup]).map((item) => cleanupVercelDeploymentOutput(rootDir, item, signal)));
3917
+ }
3918
+ async function cleanupNetlifyDeploymentOutput(rootDir, cleanup, signal) {
3919
+ signal?.throwIfAborted();
3920
+ const outputRoot = cleanup.outputRoot ?? createDefaultNetlifyOutputRoot(rootDir);
3921
+ const functionsRoot = resolve(outputRoot, "functions");
3922
+ const writes = (cleanup.functionNames ?? []).map((functionName) => rm(resolveNetlifyFunctionFile(functionsRoot, functionName), {
3923
+ force: true,
3924
+ recursive: true
3925
+ }));
3926
+ writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
3927
+ await Promise.all(writes);
3928
+ }
3929
+ async function writeProviderDeploymentOutputsNow(options, signal, transaction) {
3930
+ signal?.throwIfAborted();
3931
+ const clientDir = resolve(options.rootDir, options.clientOutDir);
3932
+ await transaction?.snapshot(providerDeploymentOutputPaths(options), [clientDir]);
3933
+ const writes = [];
3934
+ if (options.cloudflare) writes.push(writeCloudflareDeploymentOutput({
3935
+ ...options.cloudflare,
3936
+ clientOutDir: options.clientOutDir,
3937
+ rootDir: options.rootDir,
3938
+ sourceRootDir: options.sourceRootDir
3939
+ }, signal));
3940
+ if (options.netlify) writes.push(writeNetlifyDeploymentOutput({
3941
+ ...options.netlify,
3942
+ clientOutDir: options.clientOutDir,
3943
+ rootDir: options.rootDir,
3944
+ sourceRootDir: options.sourceRootDir
3945
+ }, signal));
3946
+ if (options.vercel) writes.push(writeVercelDeploymentOutput({
3947
+ ...options.vercel,
3948
+ clientOutDir: options.clientOutDir,
3949
+ rootDir: options.rootDir,
3950
+ sourceRootDir: options.sourceRootDir
3951
+ }, signal));
3952
+ await settleWrites(writes);
3953
+ if (options.cloudflare && transaction) transaction.cloudflareWritten = true;
3954
+ signal?.throwIfAborted();
3955
+ await options.afterWrite?.(signal);
3956
+ signal?.throwIfAborted();
3957
+ const cleanups = [];
3958
+ const cleanupPaths = [];
3959
+ if (!options.cloudflare && options.cleanup?.cloudflare) {
3960
+ let cleanup = typeof options.cleanup.cloudflare === "function" ? await options.cleanup.cloudflare() : options.cleanup.cloudflare;
3961
+ const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
3962
+ if (resolve(outputRoot) === clientDir) cleanup = {
3963
+ ...cleanup,
3964
+ fileNames: []
3965
+ };
3966
+ else if (transaction?.cloudflareWritten) cleanup = {
3967
+ ...cleanup,
3968
+ fileNames: []
3969
+ };
3970
+ if (shouldRunCloudflareDeploymentOutputCleanup(outputRoot, cleanup)) {
3971
+ cleanupPaths.push(outputRoot);
3972
+ cleanups.push(async () => await cleanupCloudflareDeploymentOutput(options.rootDir, cleanup, signal));
3973
+ }
3974
+ }
3975
+ if (!options.netlify && options.cleanup?.netlify) {
3976
+ const cleanup = options.cleanup.netlify;
3977
+ cleanupPaths.push(cleanup.outputRoot ?? createDefaultNetlifyOutputRoot(options.rootDir));
3978
+ cleanups.push(async () => await cleanupNetlifyDeploymentOutput(options.rootDir, cleanup, signal));
3979
+ }
3980
+ if (!options.vercel && options.cleanup?.vercel) {
3981
+ const cleanup = typeof options.cleanup.vercel === "function" ? await options.cleanup.vercel() : options.cleanup.vercel;
3982
+ signal?.throwIfAborted();
3983
+ if (cleanup) {
3984
+ const items = Array.isArray(cleanup) ? cleanup : [cleanup];
3985
+ cleanupPaths.push(...items.map((item) => item.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir)));
3986
+ cleanups.push(async () => await cleanupVercelDeploymentOutputs(options.rootDir, cleanup, signal));
3987
+ }
79
3988
  }
3989
+ await transaction?.snapshot(cleanupPaths, [clientDir]);
3990
+ await settleWrites(cleanups.map((cleanup) => cleanup()));
3991
+ signal?.throwIfAborted();
80
3992
  }
81
- function deleteOwnedFields(value, ownership) {
82
- const next = { ...value };
83
- for (const key of ownership.keys ?? []) delete next[key];
84
- for (const field of Object.keys(ownership.arrays ?? {})) delete next[field];
85
- return next;
3993
+ function providerDeploymentOutputPaths(options) {
3994
+ const clientDir = resolve(options.rootDir, options.clientOutDir);
3995
+ return [
3996
+ options.cloudflare && (options.cloudflare.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir)),
3997
+ options.cloudflare?.staticOutputDir,
3998
+ options.netlify?.outputRoot,
3999
+ options.vercel?.outputRoot,
4000
+ options.vercel?.staticOutputDir
4001
+ ].filter((path) => Boolean(path) && resolve(path) !== clientDir);
86
4002
  }
87
- function getKeyedArrayEntryValue(value, key) {
88
- if (key === void 0) return value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string" ? value : void 0;
89
- if (!isProviderJsonRecord(value)) return;
90
- const entryValue = value[key];
91
- return entryValue === null || typeof entryValue === "boolean" || typeof entryValue === "number" || typeof entryValue === "string" ? entryValue : void 0;
4003
+ async function withProviderDeploymentOutputRootLock(rootDir, operation) {
4004
+ const key = resolve(rootDir);
4005
+ const state = providerDeploymentOutputRootStates.get(key) ?? { pending: 0 };
4006
+ providerDeploymentOutputRootStates.set(key, state);
4007
+ state.pending++;
4008
+ const current = (providerDeploymentOutputWrites.get(key) ?? Promise.resolve()).catch(() => void 0).then(async () => await operation(state));
4009
+ providerDeploymentOutputWrites.set(key, current);
4010
+ try {
4011
+ return await current;
4012
+ } finally {
4013
+ if (providerDeploymentOutputWrites.get(key) === current) providerDeploymentOutputWrites.delete(key);
4014
+ state.pending--;
4015
+ if (state.pending === 0 && providerDeploymentOutputRootStates.get(key) === state) providerDeploymentOutputRootStates.delete(key);
4016
+ }
92
4017
  }
93
- function preserveUnownedKeyedArrayEntries(value, ownership, replacements = []) {
94
- const current = Array.isArray(value) ? value : [];
95
- const replacementKeys = replacements.flatMap((entry) => {
96
- const key = getKeyedArrayEntryValue(entry, ownership.key);
97
- return key === void 0 ? [] : [key];
98
- });
99
- const ownedKeys = new Set([...ownership.values ?? [], ...replacementKeys]);
100
- return current.filter((entry) => {
101
- const key = getKeyedArrayEntryValue(entry, ownership.key);
102
- return key === void 0 || !ownedKeys.has(key);
103
- });
4018
+ function pathContains(parent, child) {
4019
+ const nested = relative(parent, child);
4020
+ return !nested || !nested.startsWith(`..${sep}`) && nested !== ".." && !isAbsolute(nested);
104
4021
  }
105
- function mergeOwnedArrays(existing, value, arrays) {
106
- const next = { ...value };
107
- for (const [field, ownership] of Object.entries(arrays ?? {})) {
108
- const incoming = Array.isArray(value[field]) ? value[field] : [];
109
- const merged = [...preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming), ...incoming];
110
- if (merged.length) next[field] = merged;
111
- else delete next[field];
4022
+ async function restoreProviderDeploymentOutputSnapshot(snapshot) {
4023
+ if (snapshot.present) await mkdir(dirname(snapshot.path), { recursive: true });
4024
+ const restoreRoot = await mkdtemp(resolve(snapshot.present ? dirname(snapshot.path) : tmpdir(), "vitehub-provider-output-restore-"));
4025
+ const staged = resolve(restoreRoot, "snapshot");
4026
+ const preservedRoot = resolve(restoreRoot, "preserved");
4027
+ try {
4028
+ await mkdir(preservedRoot, { recursive: true });
4029
+ const preserved = snapshot.preservedPaths.map((path, index) => ({
4030
+ backup: resolve(preservedRoot, String(index)),
4031
+ path,
4032
+ present: existsSync(path)
4033
+ }));
4034
+ await Promise.all(preserved.map(async (entry) => {
4035
+ if (entry.present) await cp(entry.path, entry.backup, { recursive: true });
4036
+ }));
4037
+ if (snapshot.present) await cp(snapshot.backup, staged, { recursive: true });
4038
+ await rm(snapshot.path, {
4039
+ force: true,
4040
+ recursive: true
4041
+ });
4042
+ if (snapshot.present) await rename(staged, snapshot.path);
4043
+ for (const entry of preserved) {
4044
+ await rm(entry.path, {
4045
+ force: true,
4046
+ recursive: true
4047
+ });
4048
+ if (entry.present) {
4049
+ await mkdir(dirname(entry.path), { recursive: true });
4050
+ await cp(entry.backup, entry.path, { recursive: true });
4051
+ }
4052
+ }
4053
+ } finally {
4054
+ await rm(restoreRoot, {
4055
+ force: true,
4056
+ recursive: true
4057
+ });
112
4058
  }
113
- return next;
114
4059
  }
115
- async function persistProviderJsonRecord(file, value, removeIfEmpty) {
116
- if (removeIfEmpty && !Object.keys(value).length) {
117
- await rm(file, { force: true });
118
- return;
4060
+ async function withProviderDeploymentOutputRootTransaction(rootDir, operation, options = {}) {
4061
+ const roots = [
4062
+ createDefaultCloudflareOutputRoot(rootDir),
4063
+ createDefaultNetlifyOutputRoot(rootDir),
4064
+ createDefaultVercelOutputRoot(rootDir),
4065
+ resolve(rootDir, ".vitehub/agent"),
4066
+ resolve(rootDir, ".vitehub/blob/cloudflare-output.json"),
4067
+ resolve(rootDir, ".vitehub/queue/cloudflare-output.json"),
4068
+ resolve(rootDir, ".vitehub/queue/registry.mjs"),
4069
+ resolve(rootDir, ".vitehub/queue/vercel-output.json"),
4070
+ resolve(rootDir, ".vitehub/rate-limit/cloudflare-output.json"),
4071
+ resolve(rootDir, ".vitehub/rate-limit/manifest.json"),
4072
+ resolve(rootDir, ".vitehub/schedule"),
4073
+ resolve(rootDir, ".vitehub/workflow")
4074
+ ];
4075
+ const transactionRoot = await mkdtemp(resolve(tmpdir(), "vitehub-provider-output-"));
4076
+ const snapshots = /* @__PURE__ */ new Map();
4077
+ let snapshotIndex = 0;
4078
+ const transaction = {
4079
+ cloudflareWritten: false,
4080
+ async snapshot(paths, preservedPaths = []) {
4081
+ const resolvedPreservedPaths = [...new Set(preservedPaths.map((path) => resolve(path)))];
4082
+ for (const snapshot of snapshots.values()) {
4083
+ const additions = resolvedPreservedPaths.filter((path) => path !== snapshot.path && pathContains(snapshot.path, path) && !snapshot.preservedPaths.includes(path));
4084
+ snapshot.preservedPaths.push(...additions);
4085
+ if (snapshot.present) await Promise.all(additions.map((path) => rm(resolve(snapshot.backup, relative(snapshot.path, path)), {
4086
+ force: true,
4087
+ recursive: true
4088
+ })));
4089
+ }
4090
+ 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) => ({
4091
+ backup: resolve(transactionRoot, String(snapshotIndex++)),
4092
+ path,
4093
+ present: existsSync(path),
4094
+ preservedPaths: resolvedPreservedPaths.filter((preserved) => preserved !== path && pathContains(path, preserved))
4095
+ }));
4096
+ const failure = (await Promise.allSettled(pending.map(async (snapshot) => {
4097
+ if (snapshot.present) {
4098
+ await cp(snapshot.path, snapshot.backup, { recursive: true });
4099
+ await Promise.all(snapshot.preservedPaths.map((path) => rm(resolve(snapshot.backup, relative(snapshot.path, path)), {
4100
+ force: true,
4101
+ recursive: true
4102
+ })));
4103
+ }
4104
+ }))).find((result) => result.status === "rejected");
4105
+ if (failure) {
4106
+ await Promise.all(pending.map((snapshot) => rm(snapshot.backup, {
4107
+ force: true,
4108
+ recursive: true
4109
+ })));
4110
+ throw failure.reason;
4111
+ }
4112
+ for (const snapshot of pending) {
4113
+ const children = [...snapshots.values()].filter((child) => pathContains(snapshot.path, child.path));
4114
+ if (snapshot.present) for (const child of children) {
4115
+ const nestedBackup = resolve(snapshot.backup, relative(snapshot.path, child.path));
4116
+ await rm(nestedBackup, {
4117
+ force: true,
4118
+ recursive: true
4119
+ });
4120
+ if (child.present) {
4121
+ await mkdir(dirname(nestedBackup), { recursive: true });
4122
+ await cp(child.backup, nestedBackup, { recursive: true });
4123
+ }
4124
+ }
4125
+ for (const child of children) {
4126
+ snapshots.delete(child.path);
4127
+ await rm(child.backup, {
4128
+ force: true,
4129
+ recursive: true
4130
+ });
4131
+ }
4132
+ snapshot.preservedPaths.push(...children.flatMap((child) => child.preservedPaths).filter((path) => !snapshot.preservedPaths.includes(path)));
4133
+ if (snapshot.present) await Promise.all(snapshot.preservedPaths.map((path) => rm(resolve(snapshot.backup, relative(snapshot.path, path)), {
4134
+ force: true,
4135
+ recursive: true
4136
+ })));
4137
+ snapshots.set(snapshot.path, snapshot);
4138
+ }
4139
+ }
4140
+ };
4141
+ try {
4142
+ if (options.snapshotInitialRoots !== false) await transaction.snapshot(roots);
4143
+ const result = await operation(transaction);
4144
+ await removeProviderOutputArtifactDir(transactionRoot).catch(() => void 0);
4145
+ return result;
4146
+ } catch (error) {
4147
+ const restorations = await Promise.allSettled([...snapshots.values()].map(restoreProviderDeploymentOutputSnapshot));
4148
+ if (restorations.every((result) => result.status === "fulfilled")) await rm(transactionRoot, {
4149
+ force: true,
4150
+ recursive: true
4151
+ });
4152
+ const restorationFailure = restorations.find((result) => result.status === "rejected");
4153
+ if (restorationFailure) throw new AggregateError([error, restorationFailure.reason], "Provider Output rollback failed");
4154
+ throw error;
119
4155
  }
120
- await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
121
4156
  }
122
- async function writeProviderOutputConfig(file, value, ownership = {}, options = {}) {
123
- await persistProviderJsonRecord(file, mergeProviderOutputConfig(await readProviderJsonRecord(file) ?? {}, value, ownership), options.removeIfEmpty === true);
4157
+ function contributeProviderDeploymentOutput(catalog, contribution, generation) {
4158
+ closeProviderDeploymentOutputGenerationCapture(generation);
4159
+ catalog?.replaceDeploymentContribution(contribution, generation);
124
4160
  }
125
- function mergeProviderOutputConfig(existing, value, ownership = {}) {
126
- assertProviderJsonRecord(existing);
127
- assertProviderJsonRecord(value);
4161
+ const providerDeploymentOutputEnvironmentGenerations = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputEnvironmentGenerations ??= /* @__PURE__ */ new WeakMap();
4162
+ const providerDeploymentOutputGenerationEnvironments = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputGenerationEnvironments ??= /* @__PURE__ */ new WeakMap();
4163
+ const providerDeploymentOutputFallbackEnvironment = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputFallbackEnvironment ??= {};
4164
+ function closeProviderDeploymentOutputGenerationCapture(generation) {
4165
+ if (!generation) return;
4166
+ const captured = providerDeploymentOutputGenerationEnvironments.get(generation);
4167
+ if (!captured) return;
4168
+ const generations = providerDeploymentOutputEnvironmentGenerations.get(captured.catalog);
4169
+ if (generations?.get(captured.environment) === generation) generations.delete(captured.environment);
4170
+ providerDeploymentOutputGenerationEnvironments.delete(generation);
4171
+ }
4172
+ function createProviderDeploymentOutputGenerationState() {
4173
+ const generations = /* @__PURE__ */ new WeakMap();
4174
+ const readiness = /* @__PURE__ */ new WeakMap();
4175
+ const localEnvironment = (context) => context?.environment ?? context ?? providerDeploymentOutputFallbackEnvironment;
4176
+ const sharedEnvironment = (context) => context?.environment ?? providerDeploymentOutputFallbackEnvironment;
128
4177
  return {
129
- ...deleteOwnedFields(existing, ownership),
130
- ...mergeOwnedArrays(existing, value, ownership.arrays)
4178
+ capture(context, catalog) {
4179
+ const localEnvironmentKey = localEnvironment(context);
4180
+ readiness.delete(localEnvironmentKey);
4181
+ if (!catalog) {
4182
+ generations.set(localEnvironmentKey, void 0);
4183
+ return;
4184
+ }
4185
+ const environmentKey = sharedEnvironment(context);
4186
+ let catalogGenerations = providerDeploymentOutputEnvironmentGenerations.get(catalog);
4187
+ if (!catalogGenerations) {
4188
+ catalogGenerations = /* @__PURE__ */ new WeakMap();
4189
+ providerDeploymentOutputEnvironmentGenerations.set(catalog, catalogGenerations);
4190
+ }
4191
+ const sharedGeneration = catalogGenerations.get(environmentKey);
4192
+ const generation = !sharedGeneration || generations.get(localEnvironmentKey) === sharedGeneration ? catalog.createDeploymentGeneration() : sharedGeneration;
4193
+ catalogGenerations.set(environmentKey, generation);
4194
+ providerDeploymentOutputGenerationEnvironments.set(generation, {
4195
+ catalog,
4196
+ environment: environmentKey
4197
+ });
4198
+ generations.set(localEnvironmentKey, generation);
4199
+ },
4200
+ defer(context, catalog, contribution) {
4201
+ const localEnvironmentKey = localEnvironment(context);
4202
+ const state = { ready: false };
4203
+ readiness.set(localEnvironmentKey, state);
4204
+ contributeProviderDeploymentOutput(catalog, {
4205
+ ...contribution,
4206
+ ready: () => state.ready
4207
+ }, generations.get(localEnvironmentKey));
4208
+ },
4209
+ get(context) {
4210
+ return generations.get(localEnvironment(context));
4211
+ },
4212
+ ready(context) {
4213
+ const state = readiness.get(localEnvironment(context));
4214
+ if (state) state.ready = true;
4215
+ },
4216
+ async reset(context, catalog, failure) {
4217
+ const localEnvironmentKey = localEnvironment(context);
4218
+ const generation = generations.get(localEnvironmentKey);
4219
+ readiness.delete(localEnvironmentKey);
4220
+ closeProviderDeploymentOutputGenerationCapture(generation);
4221
+ await resetProviderDeploymentOutputs(catalog, failure, generation);
4222
+ }
131
4223
  };
132
4224
  }
133
- async function cleanProviderOutputConfig(file, ownership) {
134
- if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
135
- const existing = await readProviderJsonRecord(file);
136
- if (!existing) return;
137
- const next = deleteOwnedFields(existing, ownership);
138
- let changed = (ownership.keys ?? []).some((key) => key in existing);
139
- for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
140
- if (!(field in existing)) continue;
141
- const current = existing[field];
142
- const preserved = preserveUnownedKeyedArrayEntries(current, arrayOwnership);
143
- changed ||= !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
144
- if (preserved.length) next[field] = preserved;
4225
+ async function resetProviderDeploymentOutputs(catalog, failure, generation) {
4226
+ if (!catalog) return;
4227
+ const completedReset = providerDeploymentOutputCompletedResets.get(catalog);
4228
+ if (completedReset && failure !== void 0 && completedReset.failures.has(failure)) {
4229
+ if (generation) catalog.resetDeploymentContributions(generation);
4230
+ await completedReset.promise;
4231
+ return;
145
4232
  }
146
- if (!changed) return;
147
- await persistProviderJsonRecord(file, next, true);
148
- }
149
- //#endregion
150
- //#region ../internal/src/build/user-entry.ts
151
- function toSafeAppName(rootDir) {
152
- return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
153
- }
154
- //#endregion
155
- //#region ../internal/src/build/cloudflare.ts
156
- function createDefaultCloudflareOutputRoot(rootDir) {
157
- return resolve(rootDir, "dist", toSafeAppName(rootDir));
4233
+ if (completedReset) providerDeploymentOutputCompletedResets.delete(catalog);
4234
+ if (generation) catalog.resetDeploymentContributions(generation);
4235
+ const active = providerDeploymentOutputFinalizations.get(catalog);
4236
+ if (active?.reset) {
4237
+ if (failure !== void 0 && !active.reset.failures.has(failure)) {
4238
+ active.reset.failures.add(failure);
4239
+ if (!generation) catalog.resetDeploymentContributions();
4240
+ }
4241
+ providerDeploymentOutputCompletedResets.set(catalog, active.reset);
4242
+ await active.reset.promise;
4243
+ return;
4244
+ }
4245
+ if (!generation) catalog.resetDeploymentContributions();
4246
+ if (active && (!generation || active.state.generations.has(generation))) {
4247
+ active.state.rollback = true;
4248
+ active.controller.abort(/* @__PURE__ */ new Error("Provider Output finalization reset"));
4249
+ active.reset = {
4250
+ failures: new Set([failure]),
4251
+ promise: active.promise.catch(() => void 0)
4252
+ };
4253
+ providerDeploymentOutputCompletedResets.set(catalog, active.reset);
4254
+ await active.reset.promise;
4255
+ } else if (failure !== void 0) providerDeploymentOutputCompletedResets.set(catalog, {
4256
+ failures: new Set([failure]),
4257
+ promise: Promise.resolve()
4258
+ });
158
4259
  }
159
- async function writeCloudflareWranglerConfig(options) {
160
- const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
161
- const configFile = resolve(outputRoot, "wrangler.json");
162
- if (!options.wranglerConfig) {
163
- await cleanProviderOutputConfig(configFile, options.wranglerConfigOwnership ?? {});
4260
+ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
4261
+ if (!catalog) return;
4262
+ const existing = providerDeploymentOutputFinalizations.get(catalog);
4263
+ if (existing) {
4264
+ try {
4265
+ await existing.promise;
4266
+ } catch (error) {
4267
+ if (!catalog.hasDeploymentContributions()) throw error;
4268
+ existing.handoff ??= (async () => {
4269
+ await existing.promise.catch(() => void 0);
4270
+ if (providerDeploymentOutputFinalizations.get(catalog) === existing) providerDeploymentOutputFinalizations.delete(catalog);
4271
+ await finalizeProviderDeploymentOutputs(catalog, options);
4272
+ })();
4273
+ await existing.handoff;
4274
+ return;
4275
+ }
4276
+ if (providerDeploymentOutputFinalizations.get(catalog) === existing) providerDeploymentOutputFinalizations.delete(catalog);
4277
+ if (catalog.hasDeploymentContributions()) await finalizeProviderDeploymentOutputs(catalog, options);
164
4278
  return;
165
4279
  }
166
- await mkdir(outputRoot, { recursive: true });
167
- await writeProviderOutputConfig(configFile, options.wranglerConfig, options.wranglerConfigOwnership, { removeIfEmpty: true });
4280
+ const controller = new AbortController();
4281
+ const state = {
4282
+ generations: /* @__PURE__ */ new Set(),
4283
+ rollback: false
4284
+ };
4285
+ const finalization = (async () => {
4286
+ const order = new Map(providerDeploymentOutputOwnerOrder.map((owner, index) => [owner, index]));
4287
+ const abort = () => controller.abort(options.signal?.reason);
4288
+ if (options.signal?.aborted) abort();
4289
+ else options.signal?.addEventListener("abort", abort, { once: true });
4290
+ try {
4291
+ while (true) {
4292
+ const contributions = catalog.takeDeploymentContributions();
4293
+ if (!contributions.length) return;
4294
+ try {
4295
+ if (contributions.some((contribution) => contribution.ready?.() === false)) {
4296
+ if (controller.signal.aborted) {
4297
+ await catalog.completeDeploymentContributions(contributions);
4298
+ throwIfProviderOutputAborted(controller.signal);
4299
+ }
4300
+ catalog.rollbackDeploymentContributions(contributions);
4301
+ return;
4302
+ }
4303
+ } catch (error) {
4304
+ catalog.rollbackDeploymentContributions(contributions);
4305
+ throw error;
4306
+ }
4307
+ for (const contribution of contributions) {
4308
+ const generation = catalog.deploymentContributionGeneration(contribution);
4309
+ if (generation) state.generations.add(generation);
4310
+ }
4311
+ contributions.sort((left, right) => order.get(left.owner) - order.get(right.owner));
4312
+ const grouped = /* @__PURE__ */ new Map();
4313
+ for (const contribution of contributions) {
4314
+ const rootDir = resolve(contribution.rootDir);
4315
+ const rootContributions = grouped.get(rootDir) ?? [];
4316
+ rootContributions.push(contribution);
4317
+ grouped.set(rootDir, rootContributions);
4318
+ }
4319
+ try {
4320
+ let decideRoots;
4321
+ const rootDecision = new Promise((resolve) => {
4322
+ decideRoots = resolve;
4323
+ });
4324
+ const roots = [...grouped.entries()].map(([rootDir, rootContributions]) => {
4325
+ let ready;
4326
+ let rejectReady;
4327
+ const readiness = new Promise((resolve, reject) => {
4328
+ ready = resolve;
4329
+ rejectReady = reject;
4330
+ });
4331
+ const write = withProviderDeploymentOutputRootLock(rootDir, async () => {
4332
+ await withProviderDeploymentOutputRootTransaction(rootDir, async (transaction) => {
4333
+ try {
4334
+ for (const contribution of rootContributions) {
4335
+ throwIfProviderOutputAborted(controller.signal);
4336
+ await contribution.write({
4337
+ readCloudflareState: async (options) => await readCloudflareProviderDeploymentOutputState(rootDir, options),
4338
+ signal: controller.signal,
4339
+ write: async (writeOptions) => {
4340
+ throwIfProviderOutputAborted(controller.signal);
4341
+ await writeProviderDeploymentOutputsNow(writeOptions, controller.signal, transaction);
4342
+ }
4343
+ });
4344
+ throwIfProviderOutputAborted(controller.signal);
4345
+ }
4346
+ ready();
4347
+ const rollback = await rootDecision;
4348
+ if (rollback !== void 0) throw rollback;
4349
+ throwIfProviderOutputAborted(controller.signal);
4350
+ } catch (error) {
4351
+ controller.abort(error);
4352
+ rejectReady(error);
4353
+ throw error;
4354
+ }
4355
+ }, { snapshotInitialRoots: rootContributions.some((contribution) => contribution.owner !== "kv") });
4356
+ });
4357
+ write.catch(rejectReady);
4358
+ return {
4359
+ readiness,
4360
+ write
4361
+ };
4362
+ });
4363
+ const failedRoot = (await Promise.allSettled(roots.map((root) => root.readiness))).find((result) => result.status === "rejected");
4364
+ if (failedRoot) {
4365
+ decideRoots(failedRoot.reason);
4366
+ await settleWrites(roots.map((root) => root.write));
4367
+ }
4368
+ try {
4369
+ await catalog.prepareDeploymentContributions(contributions);
4370
+ throwIfProviderOutputAborted(controller.signal);
4371
+ } catch (error) {
4372
+ decideRoots(error);
4373
+ await settleWrites(roots.map((root) => root.write));
4374
+ throw error;
4375
+ }
4376
+ catalog.commitDeploymentContributions(contributions);
4377
+ state.generations.clear();
4378
+ decideRoots(void 0);
4379
+ await settleWrites(roots.map((root) => root.write));
4380
+ await catalog.completeDeploymentContributions(contributions);
4381
+ } catch (error) {
4382
+ if (state.rollback) catalog.rollbackDeploymentContributions(contributions);
4383
+ else await catalog.completeDeploymentContributions(contributions);
4384
+ throw error;
4385
+ } finally {
4386
+ state.generations.clear();
4387
+ }
4388
+ }
4389
+ } finally {
4390
+ options.signal?.removeEventListener("abort", abort);
4391
+ }
4392
+ })();
4393
+ const active = {
4394
+ controller,
4395
+ promise: finalization,
4396
+ state
4397
+ };
4398
+ providerDeploymentOutputFinalizations.set(catalog, active);
4399
+ try {
4400
+ await finalization;
4401
+ } finally {
4402
+ if (providerDeploymentOutputFinalizations.get(catalog) === active) providerDeploymentOutputFinalizations.delete(catalog);
4403
+ }
168
4404
  }
169
4405
  const VITEHUB_MODES = {
170
4406
  e2e: "e2e",
@@ -194,28 +4430,6 @@ function getViteCliMode(argv = process.argv) {
194
4430
  function getViteMode(env = process.env) {
195
4431
  return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
196
4432
  }
197
- [
198
- ".ts",
199
- ".mts",
200
- ".cts",
201
- ".js",
202
- ".mjs",
203
- ".cjs"
204
- ].flatMap((extension) => [["server", `email${extension}`], [`server.email${extension}`]]);
205
- function createNoExternalMerger(packageName) {
206
- return (current) => {
207
- if (current === true) return true;
208
- if (!current) return [packageName];
209
- const values = Array.isArray(current) ? current : [current];
210
- return values.includes(packageName) ? values : [...values, packageName];
211
- };
212
- }
213
- function isServerEnvironment(name, config) {
214
- return name === "ssr" || config.consumer === "server";
215
- }
216
- function shouldSkipViteProviderBuild(command, mode) {
217
- return command === "serve" || mode === "e2e";
218
- }
219
4433
  //#endregion
220
4434
  //#region ../internal/src/arrays.ts
221
4435
  function pushUnique(arr, item, key = (value) => value) {
@@ -227,14 +4441,14 @@ function pushUnique(arr, item, key = (value) => value) {
227
4441
  //#region src/integrations/cloudflare.ts
228
4442
  function configureCloudflareKV(target, config) {
229
4443
  for (const store of Object.values(config.stores || { default: config.store })) {
230
- if (store.driver !== "cloudflare-kv-binding" || !store.namespaceId) continue;
4444
+ if (store.driver !== "cloudflare-kv-binding") continue;
231
4445
  const { binding, namespaceId } = store;
232
4446
  target.cloudflare ||= {};
233
4447
  target.cloudflare.wrangler ||= {};
234
4448
  target.cloudflare.wrangler.kv_namespaces ||= [];
235
4449
  pushUnique(target.cloudflare.wrangler.kv_namespaces, {
236
4450
  binding,
237
- id: namespaceId
4451
+ ...namespaceId ? { id: namespaceId } : {}
238
4452
  }, (entry) => entry.binding);
239
4453
  }
240
4454
  }
@@ -244,8 +4458,7 @@ const RESOLVED_KV_VIRTUAL_CONFIG_ID = `\0${KV_VIRTUAL_CONFIG_ID}`;
244
4458
  const RESOLVED_KV_RUNTIME_ID = `\0#vitehub/kv/runtime`;
245
4459
  const KV_ERRORS_IMPORT_ID = new URL(import.meta.url.endsWith(".ts") ? "./errors.ts" : "./errors.js", import.meta.url).href;
246
4460
  const UPSTASH_DRIVER_IMPORT_ID = "@vite-hub/kv/runtime/upstash-driver";
247
- const UNSTORAGE_IMPORT_ID = import.meta.resolve("unstorage");
248
- const CLOUDFLARE_KV_DRIVER_IMPORT_ID = import.meta.resolve("unstorage/drivers/cloudflare-kv-binding");
4461
+ const CLOUDFLARE_KV_RUNTIME_IMPORT_ID = import.meta.url.endsWith(".ts") ? "@vite-hub/kv/runtime/cloudflare-kv" : new URL("./runtime/cloudflare-kv.js", import.meta.url).href;
249
4462
  const mergeNoExternal = createNoExternalMerger("@vite-hub/kv");
250
4463
  const KV_CLOUDFLARE_BINDINGS_FILE = ".vitehub-kv-bindings.json";
251
4464
  function hubKvOptionalPeerResolver() {
@@ -269,7 +4482,8 @@ function serializeVirtualConfig(config) {
269
4482
  ].join("\n");
270
4483
  }
271
4484
  function isCloudflareKVConfig(kv) {
272
- return Boolean(kv) && Object.values(kv.stores || { default: kv.store }).every((store) => store.driver === "cloudflare-kv-binding");
4485
+ if (!kv) return false;
4486
+ return Object.values(kv.stores || { default: kv.store }).every((store) => store.driver === "cloudflare-kv-binding");
273
4487
  }
274
4488
  function hasUpstashStore(kv) {
275
4489
  if (!kv) return false;
@@ -286,31 +4500,9 @@ function createCloudflareKVWranglerConfig(kv) {
286
4500
  configureCloudflareKV(target, kv);
287
4501
  return target.cloudflare?.wrangler?.kv_namespaces?.length ? target.cloudflare.wrangler : void 0;
288
4502
  }
289
- function cloudflareBindingsFile(rootDir) {
290
- return join(createDefaultCloudflareOutputRoot(rootDir), KV_CLOUDFLARE_BINDINGS_FILE);
291
- }
292
- async function readOwnedCloudflareKVBindings(rootDir) {
293
- try {
294
- const parsed = JSON.parse(await readFile(cloudflareBindingsFile(rootDir), "utf8"));
295
- return Array.isArray(parsed) ? parsed.filter((value) => typeof value === "string") : [];
296
- } catch (error) {
297
- if (error.code === "ENOENT") return [];
298
- throw error;
299
- }
300
- }
301
- async function writeOwnedCloudflareKVBindings(rootDir, bindings) {
302
- const file = cloudflareBindingsFile(rootDir);
303
- if (!bindings.length) {
304
- await rm(file, { force: true });
305
- return;
306
- }
307
- await mkdir(createDefaultCloudflareOutputRoot(rootDir), { recursive: true });
308
- await writeFile(file, `${JSON.stringify([...new Set(bindings)], null, 2)}\n`, "utf8");
309
- }
310
4503
  function serializeCloudflareRuntime(config) {
311
4504
  return [
312
- `import { createStorage } from ${JSON.stringify(UNSTORAGE_IMPORT_ID)};`,
313
- `import createDriver from ${JSON.stringify(CLOUDFLARE_KV_DRIVER_IMPORT_ID)};`,
4505
+ `import { createCloudflareKVStorage } from ${JSON.stringify(CLOUDFLARE_KV_RUNTIME_IMPORT_ID)};`,
314
4506
  `import { kvResult } from ${JSON.stringify(KV_ERRORS_IMPORT_ID)};`,
315
4507
  "",
316
4508
  `const kvConfig = ${JSON.stringify(config, null, 2)}`,
@@ -327,7 +4519,7 @@ function serializeCloudflareRuntime(config) {
327
4519
  " const store = resolveStoreConfig(name);",
328
4520
  " const existing = storages.get(name);",
329
4521
  " if (existing) return existing;",
330
- " const storage = createStorage({ driver: createDriver(store) });",
4522
+ " const storage = createCloudflareKVStorage(store);",
331
4523
  " storages.set(name, storage);",
332
4524
  " return storage;",
333
4525
  "}",
@@ -342,8 +4534,11 @@ function serializeCloudflareRuntime(config) {
342
4534
  " async clear(base, options) { const [error, storage] = await resolveStorageResult(name, \"clear\"); return error ? [error, undefined] : kvResult(\"clear\", name, async () => { await storage.clear(base, options); }); },",
343
4535
  " async del(key, options) { const [error, storage] = await resolveStorageResult(name, \"del\"); return error ? [error, undefined] : kvResult(\"del\", name, async () => { await storage.removeItem(key, options); }); },",
344
4536
  " async get(key, options) { const [error, storage] = await resolveStorageResult(name, \"get\"); return error ? [error, undefined] : kvResult(\"get\", name, () => storage.getItem(key, options)); },",
4537
+ " async getAndDelete() { resolveStoreConfig(name); throw new Error(\"[vitehub] Cloudflare KV does not support atomic operations. Use Upstash.\"); },",
345
4538
  " async has(key, options) { const [error, storage] = await resolveStorageResult(name, \"has\"); return error ? [error, undefined] : kvResult(\"has\", name, () => storage.hasItem(key, options)); },",
4539
+ " async increment() { resolveStoreConfig(name); throw new Error(\"[vitehub] Cloudflare KV does not support atomic operations. Use Upstash.\"); },",
346
4540
  " async keys(base, options) { const [error, storage] = await resolveStorageResult(name, \"keys\"); return error ? [error, undefined] : kvResult(\"keys\", name, () => storage.getKeys(base, options)); },",
4541
+ " async list(options) { if (!Number.isInteger(options.limit) || options.limit <= 0) throw new TypeError(\"`limit` must be a positive integer.\"); const [error, storage] = await resolveStorageResult(name, \"list\"); return error ? [error, undefined] : kvResult(\"list\", name, () => storage.listKeys(options)); },",
347
4542
  " async set(key, value, options) { const [error, storage] = await resolveStorageResult(name, \"set\"); return error ? [error, undefined] : kvResult(\"set\", name, async () => { await storage.setItem(key, value, options); }); },",
348
4543
  " store(storeName) { return createKVStorage(storeName); },",
349
4544
  " };",
@@ -353,55 +4548,178 @@ function serializeCloudflareRuntime(config) {
353
4548
  ""
354
4549
  ].join("\n");
355
4550
  }
4551
+ function getNitroCloudflareKVNamespaces(target) {
4552
+ if (!isPlainObject(target)) return [];
4553
+ const cloudflare = Reflect.get(target, "cloudflare");
4554
+ if (!isPlainObject(cloudflare)) return [];
4555
+ const wrangler = Reflect.get(cloudflare, "wrangler");
4556
+ if (!isPlainObject(wrangler)) return [];
4557
+ const namespaces = Reflect.get(wrangler, "kv_namespaces");
4558
+ if (!Array.isArray(namespaces)) return [];
4559
+ return namespaces.flatMap((namespace) => {
4560
+ let normalized;
4561
+ try {
4562
+ normalized = JSON.parse(JSON.stringify(namespace));
4563
+ } catch {
4564
+ return [];
4565
+ }
4566
+ if (!isProviderJsonRecord(normalized)) return [];
4567
+ const binding = Reflect.get(normalized, "binding");
4568
+ const id = Reflect.get(normalized, "id");
4569
+ const previewId = Reflect.get(normalized, "preview_id");
4570
+ const experimentalRemote = Reflect.get(normalized, "experimental_remote");
4571
+ if (typeof binding !== "string") return [];
4572
+ if (id !== void 0 && typeof id !== "string") return [];
4573
+ if (previewId !== void 0 && typeof previewId !== "string") return [];
4574
+ if (experimentalRemote !== void 0 && typeof experimentalRemote !== "boolean") return [];
4575
+ return [normalized];
4576
+ });
4577
+ }
4578
+ function getResolvedNitroConfig(config) {
4579
+ return Reflect.get(config, "nitro");
4580
+ }
4581
+ function reconcileNitroCloudflareKV(target, kv, ownedNamespaces) {
4582
+ const namespaces = target.cloudflare?.wrangler?.kv_namespaces;
4583
+ if (namespaces?.length && ownedNamespaces.size) for (const owned of ownedNamespaces) {
4584
+ const ownedIndex = namespaces.findIndex((namespace) => namespace.binding === owned.binding && namespace.id === owned.id);
4585
+ if (ownedIndex !== -1) namespaces.splice(ownedIndex, 1);
4586
+ }
4587
+ if (kv) configureCloudflareKV(target, kv);
4588
+ }
4589
+ function configureNitroCloudflareKV(config, options, ownedNamespaces) {
4590
+ const { nitro } = config;
4591
+ if (!isPlainObject(nitro)) return false;
4592
+ const target = nitro;
4593
+ const namespaces = target.cloudflare?.wrangler?.kv_namespaces;
4594
+ if (namespaces && ownedNamespaces.size) target.cloudflare.wrangler.kv_namespaces = namespaces.filter((namespace) => !ownedNamespaces.has(namespace));
4595
+ ownedNamespaces.clear();
4596
+ const kv = resolveKVViteConfig(config.kv ?? options).kv;
4597
+ if (kv) {
4598
+ const existingNamespaces = new Set(target.cloudflare?.wrangler?.kv_namespaces);
4599
+ configureCloudflareKV(target, kv);
4600
+ for (const namespace of target.cloudflare?.wrangler?.kv_namespaces ?? []) if (!existingNamespaces.has(namespace)) ownedNamespaces.add(namespace);
4601
+ }
4602
+ return true;
4603
+ }
356
4604
  function hubKv(options) {
4605
+ let nitroOwned = false;
4606
+ let nitroOptions;
4607
+ const ownedNitroNamespaces = /* @__PURE__ */ new Set();
357
4608
  let resolved;
4609
+ let providerOutput;
358
4610
  let runtimeConfig;
359
4611
  const getConfig = () => runtimeConfig ??= resolveKVViteConfig(options);
4612
+ const providerOutputGenerations = createProviderDeploymentOutputGenerationState();
360
4613
  return {
361
4614
  name: KV_VITE_PLUGIN_NAME,
362
- enforce: "pre",
4615
+ enforce: "post",
363
4616
  api: { getConfig },
364
- configResolved(config) {
365
- resolved = config;
366
- runtimeConfig = resolveKVViteConfig(config.kv ?? options);
4617
+ nitro: {
4618
+ name: "@vite-hub/kv/cloudflare-bindings",
4619
+ setup(nitro) {
4620
+ nitroOptions = nitro.options;
4621
+ if (runtimeConfig) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces);
4622
+ }
367
4623
  },
368
- configEnvironment(name, config) {
369
- if (!isServerEnvironment(name, config)) return;
370
- return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
4624
+ config: {
4625
+ order: "pre",
4626
+ handler(config) {
4627
+ nitroOwned = configureNitroCloudflareKV(config, options, ownedNitroNamespaces);
4628
+ }
371
4629
  },
372
- resolveId(id, importer, resolveOptions) {
373
- if (id === UPSTASH_DRIVER_IMPORT_ID && resolveOptions?.ssr && !hasUpstashStore(getConfig().kv) && isKVOptionalUpstashImport(id, importer)) return {
374
- external: true,
375
- id
376
- };
377
- if (id === "@vite-hub/kv" && isCloudflareKVConfig(getConfig().kv)) return RESOLVED_KV_RUNTIME_ID;
378
- if (id === "#vitehub/kv/config") return RESOLVED_KV_VIRTUAL_CONFIG_ID;
4630
+ configResolved: {
4631
+ order: "pre",
4632
+ handler(config) {
4633
+ resolved = config;
4634
+ providerOutput = useProviderOutputCatalog(config);
4635
+ runtimeConfig = resolveKVViteConfig(config.kv ?? options);
4636
+ if (nitroOptions) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces);
4637
+ if (hasNitroConfigContext(config) || isPlainObject(getResolvedNitroConfig(config))) nitroOwned = configureNitroCloudflareKV(config, options, ownedNitroNamespaces);
4638
+ }
4639
+ },
4640
+ configEnvironment: {
4641
+ order: "pre",
4642
+ handler(name, config) {
4643
+ if (!isServerEnvironment(name, config)) return;
4644
+ return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
4645
+ }
4646
+ },
4647
+ resolveId: {
4648
+ order: "pre",
4649
+ handler(id, importer, resolveOptions) {
4650
+ if (id === UPSTASH_DRIVER_IMPORT_ID && resolveOptions?.ssr && !hasUpstashStore(getConfig().kv) && isKVOptionalUpstashImport(id, importer)) return {
4651
+ external: true,
4652
+ id
4653
+ };
4654
+ if (id === "@vite-hub/kv" && isCloudflareKVConfig(getConfig().kv)) return RESOLVED_KV_RUNTIME_ID;
4655
+ if (id === "#vitehub/kv/config") return RESOLVED_KV_VIRTUAL_CONFIG_ID;
4656
+ }
4657
+ },
4658
+ load: {
4659
+ order: "pre",
4660
+ handler(id) {
4661
+ if (id === RESOLVED_KV_RUNTIME_ID) {
4662
+ const kv = getConfig().kv;
4663
+ if (isCloudflareKVConfig(kv)) return serializeCloudflareRuntime(kv);
4664
+ }
4665
+ if (id === RESOLVED_KV_VIRTUAL_CONFIG_ID) return serializeVirtualConfig(getConfig());
4666
+ }
379
4667
  },
380
- load(id) {
381
- if (id === RESOLVED_KV_RUNTIME_ID) {
382
- const kv = getConfig().kv;
383
- if (isCloudflareKVConfig(kv)) return serializeCloudflareRuntime(kv);
4668
+ buildStart: {
4669
+ order: "pre",
4670
+ handler() {
4671
+ providerOutputGenerations.capture(this, providerOutput);
4672
+ }
4673
+ },
4674
+ buildEnd: {
4675
+ order: "pre",
4676
+ async handler(error) {
4677
+ if (error) {
4678
+ await providerOutputGenerations.reset(this, providerOutput, error);
4679
+ return;
4680
+ }
4681
+ if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
4682
+ const rootDir = resolved.root;
4683
+ const clientOutDir = resolved.build.outDir;
4684
+ const wranglerConfig = nitroOwned ? void 0 : createCloudflareKVWranglerConfig(getConfig().kv);
4685
+ const nextBindings = wranglerConfig?.kv_namespaces?.map((binding) => binding.binding) ?? [];
4686
+ const wranglerConfigOwnership = { arrays: { kv_namespaces: {
4687
+ key: "binding",
4688
+ retainOnCleanup: nitroOwned ? [...new Map([...getNitroCloudflareKVNamespaces(nitroOptions), ...getNitroCloudflareKVNamespaces(getResolvedNitroConfig(resolved))].map((namespace) => [namespace.binding, namespace])).values()] : [],
4689
+ values: nextBindings
4690
+ } } };
4691
+ const wranglerConfigOwnershipFiles = { kv_namespaces: KV_CLOUDFLARE_BINDINGS_FILE };
4692
+ contributeProviderDeploymentOutput(providerOutput, {
4693
+ owner: "kv",
4694
+ rootDir,
4695
+ write: async ({ write }) => await write({
4696
+ clientOutDir,
4697
+ rootDir,
4698
+ ...wranglerConfig ? { cloudflare: {
4699
+ wranglerConfig,
4700
+ wranglerConfigOwnership,
4701
+ wranglerConfigOwnershipFiles
4702
+ } } : { cleanup: { cloudflare: {
4703
+ requirePersistedOwnership: true,
4704
+ wranglerConfigOwnership,
4705
+ wranglerConfigOwnershipFiles
4706
+ } } }
4707
+ })
4708
+ }, providerOutputGenerations.get(this));
4709
+ }
4710
+ },
4711
+ renderError: {
4712
+ order: "pre",
4713
+ async handler(error) {
4714
+ await providerOutputGenerations.reset(this, providerOutput, error);
384
4715
  }
385
- if (id === RESOLVED_KV_VIRTUAL_CONFIG_ID) return serializeVirtualConfig(getConfig());
386
4716
  },
387
4717
  closeBundle: {
388
4718
  order: "post",
389
4719
  sequential: true,
390
4720
  async handler() {
391
4721
  if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
392
- const wranglerConfig = createCloudflareKVWranglerConfig(getConfig().kv);
393
- const nextBindings = wranglerConfig?.kv_namespaces?.map((binding) => binding.binding) ?? [];
394
- const previousBindings = await readOwnedCloudflareKVBindings(resolved.root);
395
- if (!wranglerConfig && !previousBindings.length) return;
396
- await writeCloudflareWranglerConfig({
397
- rootDir: resolved.root,
398
- wranglerConfigOwnership: { arrays: { kv_namespaces: {
399
- key: "binding",
400
- values: [...previousBindings, ...nextBindings]
401
- } } },
402
- ...wranglerConfig ? { wranglerConfig } : {}
403
- });
404
- await writeOwnedCloudflareKVBindings(resolved.root, nextBindings);
4722
+ await finalizeProviderDeploymentOutputs(providerOutput);
405
4723
  }
406
4724
  }
407
4725
  };