@voidzero-dev/vite-plus-core 0.2.7 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/LICENSE +65 -1
  2. package/dist/rolldown/cli.mjs +17 -14
  3. package/dist/rolldown/config.d.mts +1 -1
  4. package/dist/rolldown/config.mjs +2 -2
  5. package/dist/rolldown/experimental-default-runtime.mjs +116 -0
  6. package/dist/rolldown/experimental-index.d.mts +10 -4
  7. package/dist/rolldown/experimental-index.mjs +32 -16
  8. package/dist/rolldown/experimental-runtime-base.mjs +95 -0
  9. package/dist/rolldown/experimental-runtime.d.ts +177 -0
  10. package/dist/rolldown/experimental-runtime.mjs +257 -0
  11. package/dist/rolldown/filter-index.d.mts +1 -1
  12. package/dist/rolldown/filter-index.mjs +1 -3
  13. package/dist/rolldown/index.d.mts +3 -3
  14. package/dist/rolldown/index.mjs +4 -4
  15. package/dist/rolldown/parallel-plugin-worker.mjs +3 -3
  16. package/dist/rolldown/parallel-plugin.d.mts +1 -1
  17. package/dist/rolldown/parse-ast-index.d.mts +1 -1
  18. package/dist/rolldown/parse-ast-index.mjs +2 -2
  19. package/dist/rolldown/plugins-index.d.mts +3 -3
  20. package/dist/rolldown/plugins-index.mjs +2 -2
  21. package/dist/rolldown/shared/binding-CKyeQZen.mjs +673 -0
  22. package/dist/rolldown/shared/{binding-Dbbi0RbO.d.mts → binding-CVtkJvyl.d.mts} +11 -0
  23. package/dist/rolldown/shared/{bindingify-input-options-DVQ4K-zY.mjs → bindingify-input-options-44iPAymO.mjs} +449 -273
  24. package/dist/rolldown/shared/{constructors-CuGa75s-.mjs → constructors-6Zc-JFd7.mjs} +10 -6
  25. package/dist/rolldown/shared/{constructors-CSWbNgBZ.d.mts → constructors-XaIbWpwJ.d.mts} +2 -2
  26. package/dist/rolldown/shared/{rolldown-build-BGXNOfvH.mjs → create-bundler-option-e1FU0w0P.mjs} +72 -179
  27. package/dist/rolldown/shared/{define-config-B-IDOhDz.d.mts → define-config-DVsXPNaU.d.mts} +85 -26
  28. package/dist/rolldown/shared/{error-DFGNOCle.mjs → error-BzLGqhSQ.mjs} +1 -1
  29. package/dist/rolldown/shared/{load-config-R0z2olkB.mjs → load-config-C6QXSnoS.mjs} +2 -2
  30. package/dist/rolldown/shared/{logs-ZGEh6uhb.mjs → logs-DmYCAKcW.mjs} +8 -1
  31. package/dist/rolldown/shared/{misc-CoQm4NHO.mjs → misc-DOSKtd97.mjs} +9 -1
  32. package/dist/rolldown/shared/{normalize-string-or-regex-SiXbePVH.mjs → normalize-string-or-regex-DYjJ67tj.mjs} +2 -2
  33. package/dist/rolldown/shared/{parse-D5dkElpf.mjs → parse-uDDyc1el.mjs} +2 -2
  34. package/dist/rolldown/shared/{prompt-pZFoa1TT.mjs → prompt-uaCPq0_A.mjs} +2 -6
  35. package/dist/rolldown/shared/{resolve-tsconfig-2TXRF_zr.mjs → resolve-tsconfig-Bcd82vVT.mjs} +2 -2
  36. package/dist/rolldown/shared/rolldown-CCbQNGZt.mjs +178 -0
  37. package/dist/rolldown/shared/{transform-Cs2bUDRH.d.mts → transform-WmU_cI8e.d.mts} +1 -1
  38. package/dist/rolldown/shared/{watch-DVucf-VG.mjs → watch-vuOCmvFs.mjs} +17 -14
  39. package/dist/rolldown/utils-index.d.mts +3 -3
  40. package/dist/rolldown/utils-index.mjs +15 -13
  41. package/dist/tsdown/{build-D_enfyvD-DX5mX46j.js → build-D_enfyvD-Dg1eKRD4.js} +22 -19
  42. package/dist/tsdown/{debug-CKcBYQLP-GQrJ--dM.js → debug-CKcBYQLP-C3NhYhrk.js} +4 -6
  43. package/dist/tsdown/{detect-DGhJGEqb-Cz6qOZuP.js → detect-DGhJGEqb-6CTf16BW.js} +1 -1
  44. package/dist/tsdown/{dist-DCMiHFrJ.js → dist-CMKwGGNp.js} +1 -3
  45. package/dist/tsdown/{dist-CWolxbYK.js → dist-DyXLnzyh.js} +43 -10
  46. package/dist/tsdown/index-types.d.ts +6 -6
  47. package/dist/tsdown/index.js +4 -4
  48. package/dist/tsdown/internal-DKworeK4.js +3 -0
  49. package/dist/tsdown/{main-DI8qthUB.js → main-DiierkER.js} +211 -197
  50. package/dist/tsdown/npm_entry_picomatch.cjs +11 -7
  51. package/dist/tsdown/npm_entry_tree-kill.cjs +15 -15
  52. package/dist/tsdown/{resolver-cwLsPb2o-DvUqSYux.js → resolver-cwLsPb2o-Dk4xdAGE.js} +3 -3
  53. package/dist/tsdown/run.js +6 -6
  54. package/dist/tsdown/{src-CPDzmpAq.js → src-drVPfX63.js} +5 -5
  55. package/dist/tsdown/{target-Bab3CUeB-Di6tCARH.js → target-Bab3CUeB-DQ0pKhCv.js} +6 -6
  56. package/dist/tsdown/{tsc-BQoNcjeB.js → tsc-JnMl2z7d.js} +4 -5
  57. package/dist/tsdown/tsdown-css.js +7 -9
  58. package/dist/tsdown/tsdown-exe.js +4 -4
  59. package/dist/vite/client/bundledDevClient.mjs +1781 -0
  60. package/dist/vite/client/client.mjs +67 -92
  61. package/dist/vite/node/chunks/build.js +98 -88
  62. package/dist/vite/node/chunks/dist.js +62 -114
  63. package/dist/vite/node/chunks/dist2.js +198 -159
  64. package/dist/vite/node/chunks/node.js +3690 -3135
  65. package/dist/vite/node/chunks/postcss-import.js +20 -19
  66. package/dist/vite/node/index.d.ts +73 -17
  67. package/dist/vite/node/module-runner.js +42 -26
  68. package/dist/vite/types/customEvent.d.ts +3 -1
  69. package/dist/vite/types/hmrPayload.d.ts +20 -6
  70. package/package.json +36 -16
  71. package/dist/rolldown/shared/binding-Dby9rwGk.mjs +0 -588
  72. package/dist/rolldown/shared/rolldown-BnV7isAX.mjs +0 -40
  73. package/dist/tsdown/internal-DAh_SWnB.js +0 -3
  74. package/dist/tsdown/load-tsc-BKULZsrs-Bha6Vsu1.js +0 -18
  75. package/dist/tsdown/tsc-context-BhMGQ9Qr.js +0 -23
@@ -0,0 +1,1781 @@
1
+ import "@vite/env";
2
+ //#region ../../node_modules/.pnpm/nanoid@5.1.16/node_modules/nanoid/non-secure/index.js
3
+ let urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
4
+ let nanoid = (size = 21) => {
5
+ let id = "";
6
+ let i = size | 0;
7
+ while (i-- > 0) id += urlAlphabet[Math.random() * 64 | 0];
8
+ return id;
9
+ };
10
+ //#endregion
11
+ //#region ../../rolldown/packages/rolldown/dist/experimental-runtime-base.mjs
12
+ var __create = Object.create;
13
+ var __defProp = Object.defineProperty;
14
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
15
+ var __getOwnPropNames = Object.getOwnPropertyNames;
16
+ var __getProtoOf = Object.getPrototypeOf;
17
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
18
+ var __exportAll = (all, no_symbols) => {
19
+ let target = {};
20
+ for (var name in all) __defProp(target, name, {
21
+ get: all[name],
22
+ enumerable: true
23
+ });
24
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
25
+ return target;
26
+ };
27
+ var __copyProps = (to, from, except, desc) => {
28
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
29
+ key = keys[i];
30
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
31
+ get: ((k) => from[k]).bind(null, key),
32
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
33
+ });
34
+ }
35
+ return to;
36
+ };
37
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
38
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
39
+ value: mod,
40
+ enumerable: true
41
+ }) : target, mod));
42
+ var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
43
+ //#endregion
44
+ //#region \0@oxc-project+runtime@0.143.0/helpers/esm/typeof.js
45
+ function _typeof(o) {
46
+ "@babel/helpers - typeof";
47
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
48
+ return typeof o;
49
+ } : function(o) {
50
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
51
+ }, _typeof(o);
52
+ }
53
+ //#endregion
54
+ //#region \0@oxc-project+runtime@0.143.0/helpers/esm/toPrimitive.js
55
+ function toPrimitive(t, r) {
56
+ if ("object" != _typeof(t) || !t) return t;
57
+ var e = t[Symbol.toPrimitive];
58
+ if (void 0 !== e) {
59
+ var i = e.call(t, r || "default");
60
+ if ("object" != _typeof(i)) return i;
61
+ throw new TypeError("@@toPrimitive must return a primitive value.");
62
+ }
63
+ return ("string" === r ? String : Number)(t);
64
+ }
65
+ //#endregion
66
+ //#region \0@oxc-project+runtime@0.143.0/helpers/esm/toPropertyKey.js
67
+ function toPropertyKey(t) {
68
+ var i = toPrimitive(t, "string");
69
+ return "symbol" == _typeof(i) ? i : i + "";
70
+ }
71
+ //#endregion
72
+ //#region \0@oxc-project+runtime@0.143.0/helpers/esm/defineProperty.js
73
+ function _defineProperty(e, r, t) {
74
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
75
+ value: t,
76
+ enumerable: !0,
77
+ configurable: !0,
78
+ writable: !0
79
+ }) : e[r] = t, e;
80
+ }
81
+ //#endregion
82
+ //#region ../../rolldown/packages/rolldown/dist/experimental-runtime.mjs
83
+ var Module = class {
84
+ /**
85
+ * @param {string} id
86
+ */
87
+ constructor(id) {
88
+ _defineProperty(
89
+ this,
90
+ /**
91
+ * @type {{ exports: any }}
92
+ */
93
+ "exportsHolder",
94
+ { exports: null }
95
+ );
96
+ _defineProperty(
97
+ this,
98
+ /**
99
+ * @type {string}
100
+ */
101
+ "id",
102
+ void 0
103
+ );
104
+ this.id = id;
105
+ }
106
+ get exports() {
107
+ return this.exportsHolder.exports;
108
+ }
109
+ };
110
+ /**
111
+ * Compiler-emitted module-graph delta — pure topology (static + dynamic edges).
112
+ * `ids[0, localCount)` are the modules this payload carries; `ids[localCount, …)` are foreign edge targets.
113
+ * `edges[i]` / `dynamicEdges[i]` are the static / dynamic-`import()` out-edges of `ids[i]`.
114
+ * @typedef {{ ids: string[], localCount: number, edges: number[][], dynamicEdges?: number[][] }} ModuleGraphDelta
115
+ * @typedef {{ createModuleHotContext(moduleId: string): any, onModuleCacheRemoval(moduleId: string): void }} DevRuntimeHooks
116
+ */
117
+ var MissingFactoryError = class extends Error {
118
+ /**
119
+ * @param {string} id
120
+ */
121
+ constructor(id) {
122
+ super(`No factory registered for module ${id}`);
123
+ this.id = id;
124
+ }
125
+ };
126
+ var DevRuntime = class {
127
+ /**
128
+ * @param {string} clientId
129
+ */
130
+ constructor(clientId) {
131
+ _defineProperty(
132
+ this,
133
+ /**
134
+ * Client ID generated at runtime initialization, used for lazy compilation requests.
135
+ * @type {string}
136
+ */
137
+ "clientId",
138
+ void 0
139
+ );
140
+ _defineProperty(
141
+ this,
142
+ /**
143
+ * Static import edges from `registerGraph` — entries persist across `removeModuleCache`
144
+ * and change only by replacement from a newer payload (last write wins).
145
+ * @type {Map<string, { edges: string[] }>}
146
+ */
147
+ "staticImports",
148
+ /* @__PURE__ */ new Map()
149
+ );
150
+ _defineProperty(
151
+ this,
152
+ /**
153
+ * Reverse index over the static imports.
154
+ * @type {Map<string, Set<string>>}
155
+ */
156
+ "importers",
157
+ /* @__PURE__ */ new Map()
158
+ );
159
+ _defineProperty(
160
+ this,
161
+ /**
162
+ * Dynamic `import()` edges from `registerGraph`, keyed by importer — mirror of
163
+ * `staticImports` for the dynamic reverse index.
164
+ * @type {Map<string, { edges: string[] }>}
165
+ */
166
+ "dynamicImports",
167
+ /* @__PURE__ */ new Map()
168
+ );
169
+ _defineProperty(
170
+ this,
171
+ /**
172
+ * Reverse index over the dynamic imports.
173
+ * @type {Map<string, Set<string>>}
174
+ */
175
+ "dynamicImporters",
176
+ /* @__PURE__ */ new Map()
177
+ );
178
+ _defineProperty(
179
+ this,
180
+ /**
181
+ * The module cache. Membership means "this module's side effects ran in this tab" —
182
+ * registration is emitted ahead of every module body, and nothing un-registers on
183
+ * unwind, so a factory that throws mid-body stays registered. A `Map` rather than a
184
+ * plain object: HMR eviction deletes entries, and a `delete` on an object drops V8
185
+ * into dictionary mode, taxing every later lookup on the hottest read path.
186
+ * @type {Map<string, Module>}
187
+ */
188
+ "moduleCache",
189
+ /* @__PURE__ */ new Map()
190
+ );
191
+ _defineProperty(
192
+ this,
193
+ /**
194
+ * Re-runnable factories from HMR patches and lazy chunks. The initial bundle stays
195
+ * scope-hoisted and contributes none.
196
+ * @type {Map<string, { kind: 'esm' | 'cjs', fn: (id: string) => void }>}
197
+ */
198
+ "factories",
199
+ /* @__PURE__ */ new Map()
200
+ );
201
+ _defineProperty(
202
+ this,
203
+ /**
204
+ * Installed by the dev client at boot. The runtime is a store + executor and makes
205
+ * no HMR decisions; accepting, disposing, and reloading live behind these hooks.
206
+ * @type {DevRuntimeHooks | null}
207
+ */
208
+ "hooks",
209
+ null
210
+ );
211
+ _defineProperty(
212
+ this,
213
+ /** @internal */
214
+ "__toESM",
215
+ __toESM
216
+ );
217
+ _defineProperty(
218
+ this,
219
+ /** @internal */
220
+ "__toCommonJS",
221
+ __toCommonJS
222
+ );
223
+ _defineProperty(
224
+ this,
225
+ /** @internal */
226
+ "__exportAll",
227
+ __exportAll
228
+ );
229
+ _defineProperty(
230
+ this,
231
+ /**
232
+ * @param {boolean} [isNodeMode]
233
+ * @returns {(mod: any) => any}
234
+ * @internal
235
+ */
236
+ "__toDynamicImportESM",
237
+ (isNodeMode) => (mod) => __toESM(mod.default, isNodeMode)
238
+ );
239
+ _defineProperty(
240
+ this,
241
+ /** @internal */
242
+ "__reExport",
243
+ __reExport
244
+ );
245
+ this.clientId = clientId;
246
+ }
247
+ /**
248
+ * @param {ModuleGraphDelta} delta
249
+ */
250
+ registerGraph(delta) {
251
+ for (let i = 0; i < delta.localCount; i++) {
252
+ const id = delta.ids[i];
253
+ const edges = delta.edges[i].map((j) => delta.ids[j]);
254
+ for (const target of this.staticImports.get(id)?.edges ?? []) this.importers.get(target)?.delete(id);
255
+ for (const target of edges) {
256
+ let importerSet = this.importers.get(target);
257
+ if (!importerSet) {
258
+ importerSet = /* @__PURE__ */ new Set();
259
+ this.importers.set(target, importerSet);
260
+ }
261
+ importerSet.add(id);
262
+ }
263
+ this.staticImports.set(id, { edges });
264
+ const dynamicEdges = (delta.dynamicEdges?.[i] ?? []).map((j) => delta.ids[j]);
265
+ for (const target of this.dynamicImports.get(id)?.edges ?? []) this.dynamicImporters.get(target)?.delete(id);
266
+ for (const target of dynamicEdges) {
267
+ let importerSet = this.dynamicImporters.get(target);
268
+ if (!importerSet) {
269
+ importerSet = /* @__PURE__ */ new Set();
270
+ this.dynamicImporters.set(target, importerSet);
271
+ }
272
+ importerSet.add(id);
273
+ }
274
+ this.dynamicImports.set(id, { edges: dynamicEdges });
275
+ }
276
+ }
277
+ /**
278
+ * @param {string} id
279
+ * @param {'esm' | 'cjs'} kind
280
+ * @param {(id: string) => void} fn
281
+ */
282
+ registerFactory(id, kind, fn) {
283
+ this.factories.set(id, {
284
+ kind,
285
+ fn
286
+ });
287
+ }
288
+ /**
289
+ * @param {string} id
290
+ * @param {{ exports: any }} exportsHolder
291
+ */
292
+ registerModule(id, exportsHolder) {
293
+ const module = new Module(id);
294
+ module.exportsHolder = exportsHolder;
295
+ this.moduleCache.set(id, module);
296
+ }
297
+ /**
298
+ * @param {string} id
299
+ * @returns {string[]}
300
+ */
301
+ getImporters(id) {
302
+ const dynamic = this.dynamicImporters.get(id);
303
+ if (!dynamic || dynamic.size === 0) return [...this.importers.get(id) ?? []];
304
+ return [.../* @__PURE__ */ new Set([...this.importers.get(id) ?? [], ...dynamic])];
305
+ }
306
+ /**
307
+ * @param {string} id
308
+ */
309
+ isExecuted(id) {
310
+ return this.moduleCache.has(id);
311
+ }
312
+ /**
313
+ * @param {string} id
314
+ */
315
+ hasFactory(id) {
316
+ return this.factories.has(id);
317
+ }
318
+ /**
319
+ * Module-cache delete only — static imports and factories persist. Removal is what
320
+ * re-arms a cache-gated factory for `initModule`.
321
+ * @param {string} id
322
+ */
323
+ removeModuleCache(id) {
324
+ this.moduleCache.delete(id);
325
+ this.hooks?.onModuleCacheRemoval(id);
326
+ }
327
+ /**
328
+ * The one re-execution gate: registered → return the live exports; otherwise run the
329
+ * mapped factory (which registers itself first, then runs the body).
330
+ * @param {string} id
331
+ */
332
+ initModule(id) {
333
+ if (this.moduleCache.has(id)) return this.loadExports(id);
334
+ const factory = this.factories.get(id);
335
+ if (!factory) throw new MissingFactoryError(id);
336
+ factory.fn(id);
337
+ return this.loadExports(id);
338
+ }
339
+ /**
340
+ * @param {string} id
341
+ */
342
+ loadExports(id) {
343
+ const module = this.moduleCache.get(id);
344
+ if (module) return module.exportsHolder.exports;
345
+ else {
346
+ console.warn(`Module ${id} not found`);
347
+ return {};
348
+ }
349
+ }
350
+ /**
351
+ * @param {string} moduleId
352
+ */
353
+ createModuleHotContext(moduleId) {
354
+ if (this.hooks) return this.hooks.createModuleHotContext(moduleId);
355
+ throw new Error("createModuleHotContext requires installed hooks or an override");
356
+ }
357
+ };
358
+ //#endregion
359
+ //#region ../../vite/packages/vite/src/shared/hmr.ts
360
+ var HMRContext = class {
361
+ constructor(hmrClient, ownerPath) {
362
+ this.hmrClient = hmrClient;
363
+ this.ownerPath = ownerPath;
364
+ _defineProperty(this, "newListeners", void 0);
365
+ if (!hmrClient.dataMap.has(ownerPath)) hmrClient.dataMap.set(ownerPath, {});
366
+ const mod = hmrClient.hotModulesMap.get(ownerPath);
367
+ if (mod) mod.callbacks = [];
368
+ const staleListeners = hmrClient.ctxToListenersMap.get(ownerPath);
369
+ if (staleListeners) for (const [event, staleFns] of staleListeners) {
370
+ const listeners = hmrClient.customListenersMap.get(event);
371
+ if (listeners) hmrClient.customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l)));
372
+ }
373
+ this.newListeners = /* @__PURE__ */ new Map();
374
+ hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
375
+ }
376
+ get data() {
377
+ return this.hmrClient.dataMap.get(this.ownerPath);
378
+ }
379
+ accept(deps, callback) {
380
+ if (typeof deps === "function" || !deps) this.acceptDeps([this.ownerPath], ([mod]) => deps?.(mod));
381
+ else if (typeof deps === "string") this.acceptDeps([deps], ([mod]) => callback?.(mod));
382
+ else if (Array.isArray(deps)) this.acceptDeps(deps, callback);
383
+ else throw new Error(`invalid hot.accept() usage.`);
384
+ }
385
+ acceptExports(_, callback) {
386
+ this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod));
387
+ }
388
+ dispose(cb) {
389
+ this.hmrClient.disposeMap.set(this.ownerPath, cb);
390
+ }
391
+ prune(cb) {
392
+ this.hmrClient.pruneMap.set(this.ownerPath, cb);
393
+ }
394
+ decline() {}
395
+ invalidate(message) {
396
+ const firstInvalidatedBy = this.hmrClient.currentFirstInvalidatedBy ?? this.ownerPath;
397
+ this.hmrClient.notifyListeners("vite:invalidate", {
398
+ path: this.ownerPath,
399
+ message,
400
+ firstInvalidatedBy
401
+ });
402
+ this.send("vite:invalidate", {
403
+ path: this.ownerPath,
404
+ message,
405
+ firstInvalidatedBy
406
+ });
407
+ this.hmrClient.logger.debug(`invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`);
408
+ }
409
+ on(event, cb) {
410
+ const addToMap = (map) => {
411
+ const existing = map.get(event) || [];
412
+ existing.push(cb);
413
+ map.set(event, existing);
414
+ };
415
+ addToMap(this.hmrClient.customListenersMap);
416
+ addToMap(this.newListeners);
417
+ }
418
+ off(event, cb) {
419
+ const removeFromMap = (map) => {
420
+ const existing = map.get(event);
421
+ if (existing === void 0) return;
422
+ const pruned = existing.filter((l) => l !== cb);
423
+ if (pruned.length === 0) {
424
+ map.delete(event);
425
+ return;
426
+ }
427
+ map.set(event, pruned);
428
+ };
429
+ removeFromMap(this.hmrClient.customListenersMap);
430
+ removeFromMap(this.newListeners);
431
+ }
432
+ send(event, data) {
433
+ this.hmrClient.send({
434
+ type: "custom",
435
+ event,
436
+ data
437
+ });
438
+ }
439
+ acceptDeps(deps, callback = () => {}) {
440
+ const mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
441
+ id: this.ownerPath,
442
+ callbacks: []
443
+ };
444
+ mod.callbacks.push({
445
+ deps,
446
+ fn: callback
447
+ });
448
+ this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
449
+ }
450
+ };
451
+ var HMRClient = class {
452
+ constructor(logger, transport, importUpdatedModule) {
453
+ this.logger = logger;
454
+ this.transport = transport;
455
+ this.importUpdatedModule = importUpdatedModule;
456
+ _defineProperty(this, "hotModulesMap", /* @__PURE__ */ new Map());
457
+ _defineProperty(this, "disposeMap", /* @__PURE__ */ new Map());
458
+ _defineProperty(this, "pruneMap", /* @__PURE__ */ new Map());
459
+ _defineProperty(this, "dataMap", /* @__PURE__ */ new Map());
460
+ _defineProperty(this, "customListenersMap", /* @__PURE__ */ new Map());
461
+ _defineProperty(this, "ctxToListenersMap", /* @__PURE__ */ new Map());
462
+ _defineProperty(this, "currentFirstInvalidatedBy", void 0);
463
+ _defineProperty(this, "updateQueue", []);
464
+ _defineProperty(this, "pendingUpdateQueue", false);
465
+ }
466
+ async notifyListeners(event, data) {
467
+ const cbs = this.customListenersMap.get(event);
468
+ if (cbs) await Promise.allSettled(cbs.map((cb) => cb(data)));
469
+ }
470
+ send(payload) {
471
+ this.transport.send(payload).catch((err) => {
472
+ this.logger.error(err);
473
+ });
474
+ }
475
+ clear() {
476
+ this.hotModulesMap.clear();
477
+ this.disposeMap.clear();
478
+ this.pruneMap.clear();
479
+ this.dataMap.clear();
480
+ this.customListenersMap.clear();
481
+ this.ctxToListenersMap.clear();
482
+ }
483
+ async prunePaths(paths) {
484
+ try {
485
+ await Promise.all(paths.map((path) => {
486
+ const disposer = this.disposeMap.get(path);
487
+ if (disposer) return disposer(this.dataMap.get(path));
488
+ }));
489
+ await Promise.all(paths.map((path) => {
490
+ const fn = this.pruneMap.get(path);
491
+ if (fn) return fn(this.dataMap.get(path));
492
+ }));
493
+ } finally {
494
+ paths.forEach((path) => this.dataMap.delete(path));
495
+ }
496
+ }
497
+ warnFailedUpdate(err, path) {
498
+ if (!(err instanceof Error) || !err.message.includes("fetch")) this.logger.error(err);
499
+ this.logger.error(`Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`);
500
+ }
501
+ /**
502
+ * buffer multiple hot updates triggered by the same src change
503
+ * so that they are invoked in the same order they were sent.
504
+ * (otherwise the order may be inconsistent because of the http request round trip)
505
+ */
506
+ async queueUpdate(payload) {
507
+ this.updateQueue.push(this.fetchUpdate(payload));
508
+ if (!this.pendingUpdateQueue) {
509
+ this.pendingUpdateQueue = true;
510
+ await Promise.resolve();
511
+ this.pendingUpdateQueue = false;
512
+ const loading = [...this.updateQueue];
513
+ this.updateQueue = [];
514
+ (await Promise.all(loading)).forEach((fn) => fn && fn());
515
+ }
516
+ }
517
+ async fetchUpdate(update) {
518
+ const { path, acceptedPath, firstInvalidatedBy } = update;
519
+ const mod = this.hotModulesMap.get(path);
520
+ if (!mod) return;
521
+ let fetchedModule;
522
+ const isSelfUpdate = path === acceptedPath;
523
+ const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => deps.includes(acceptedPath));
524
+ if (isSelfUpdate || qualifiedCallbacks.length > 0) {
525
+ const disposer = this.disposeMap.get(acceptedPath);
526
+ if (disposer) await disposer(this.dataMap.get(acceptedPath));
527
+ try {
528
+ fetchedModule = await this.importUpdatedModule(update);
529
+ } catch (e) {
530
+ this.warnFailedUpdate(e, acceptedPath);
531
+ }
532
+ }
533
+ return () => {
534
+ try {
535
+ this.currentFirstInvalidatedBy = firstInvalidatedBy;
536
+ for (const { deps, fn } of qualifiedCallbacks) fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
537
+ const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
538
+ this.logger.debug(`hot updated: ${loggedPath}`);
539
+ } finally {
540
+ this.currentFirstInvalidatedBy = void 0;
541
+ }
542
+ };
543
+ }
544
+ };
545
+ //#endregion
546
+ //#region ../../vite/packages/vite/src/client/bundledDevHmrClient.ts
547
+ var BundledDevHMRClient = class extends HMRClient {
548
+ constructor(logger, transport, runtime, options) {
549
+ super(logger, transport, async () => {
550
+ throw new Error("unreachable: full-bundle mode applies patches through its own queue");
551
+ });
552
+ this.runtime = runtime;
553
+ this.options = options;
554
+ _defineProperty(this, "applyQueue", Promise.resolve());
555
+ _defineProperty(this, "lastSeq", 0);
556
+ _defineProperty(this, "reloadPending", false);
557
+ }
558
+ isSelfAccepted(id) {
559
+ return this.hotModulesMap.get(id)?.callbacks.some((c) => c.deps.includes(id)) ?? false;
560
+ }
561
+ acceptsDep(parent, id) {
562
+ return this.hotModulesMap.get(parent)?.callbacks.some((c) => c.deps.includes(id)) ?? false;
563
+ }
564
+ computeHmrUpdate(changedIds, opts) {
565
+ const boundaries = [];
566
+ const updateSet = /* @__PURE__ */ new Set();
567
+ const traversedModules = /* @__PURE__ */ new Set();
568
+ for (const changed of changedIds) {
569
+ if (!this.runtime.isExecuted(changed)) continue;
570
+ const fullReload = this.bubble(changed, [changed], updateSet, boundaries, opts?.firstInvalidatedBy, traversedModules);
571
+ if (fullReload) return fullReload;
572
+ }
573
+ return boundaries.length ? {
574
+ type: "boundaries",
575
+ boundaries,
576
+ updateSet: [...updateSet]
577
+ } : { type: "noop" };
578
+ }
579
+ bubble(id, stack, updateSet, boundaries, firstInvalidatedBy, traversedModules) {
580
+ if (traversedModules.has(id)) return;
581
+ traversedModules.add(id);
582
+ updateSet.add(id);
583
+ if (firstInvalidatedBy !== void 0 && id === firstInvalidatedBy) return {
584
+ type: "full-reload",
585
+ reason: `update propagated back to ${firstInvalidatedBy}, which already called \`import.meta.hot.invalidate()\``
586
+ };
587
+ if (this.isSelfAccepted(id)) {
588
+ boundaries.push([id, id]);
589
+ return;
590
+ }
591
+ const parents = this.runtime.getImporters(id).filter((p) => this.runtime.isExecuted(p));
592
+ if (!parents.length) return {
593
+ type: "full-reload",
594
+ reason: `no hmr boundary found for module \`${id}\``
595
+ };
596
+ for (const parent of parents) {
597
+ if (this.acceptsDep(parent, id)) {
598
+ boundaries.push([parent, id]);
599
+ continue;
600
+ }
601
+ if (stack.includes(parent)) return {
602
+ type: "full-reload",
603
+ reason: `circular import chain between \`${id}\` and \`${parent}\``
604
+ };
605
+ const fullReload = this.bubble(parent, [...stack, parent], updateSet, boundaries, firstInvalidatedBy, traversedModules);
606
+ if (fullReload) return fullReload;
607
+ }
608
+ }
609
+ handlePush(payload) {
610
+ this.applyQueue = this.applyQueue.then(() => this.applyPush(payload)).catch((err) => {
611
+ this.warnFailedUpdate(err, payload.changedIds);
612
+ });
613
+ }
614
+ invalidateLocally(id, message) {
615
+ this.logger.debug(`invalidate ${id}${message ? `: ${message}` : ""}`);
616
+ this.applyQueue = this.applyQueue.then(() => this.applyInvalidate(id)).catch((err) => {
617
+ this.warnFailedUpdate(err, id);
618
+ });
619
+ }
620
+ handleModuleCacheRemoval(id) {
621
+ const disposer = this.disposeMap.get(id);
622
+ if (disposer) disposer(this.dataMap.get(id));
623
+ }
624
+ async applyPush({ changedIds, url, seq }) {
625
+ if (this.reloadPending) return;
626
+ if (seq !== this.lastSeq + 1) {
627
+ this.requestFullReload(`hmr update sequence gap (expected ${this.lastSeq + 1}, got ${seq})`);
628
+ return;
629
+ }
630
+ this.lastSeq = seq;
631
+ const update = this.computeHmrUpdate(changedIds);
632
+ if (update.type === "noop") return;
633
+ if (update.type === "full-reload") {
634
+ this.requestFullReload(update.reason);
635
+ return;
636
+ }
637
+ const listenerPayload = this.toUpdatePayload(update.boundaries, void 0);
638
+ await this.notifyListeners("vite:beforeUpdate", listenerPayload);
639
+ if (this.options.beforeApply() === "reload") return;
640
+ try {
641
+ await import(
642
+ /* @vite-ignore */
643
+ this.options.base + url
644
+ );
645
+ } catch {
646
+ this.requestFullReload(`failed to import hmr patch ${url}`);
647
+ return;
648
+ }
649
+ await this.applyUpdate(update);
650
+ await this.notifyListeners("vite:afterUpdate", listenerPayload);
651
+ }
652
+ async applyInvalidate(id) {
653
+ if (this.reloadPending) return;
654
+ const firstInvalidatedBy = this.currentFirstInvalidatedBy ?? id;
655
+ const importers = this.runtime.getImporters(id).filter((p) => this.runtime.isExecuted(p));
656
+ if (!importers.length) {
657
+ this.requestFullReload(`no importers to handle \`import.meta.hot.invalidate()\` called by \`${id}\``);
658
+ return;
659
+ }
660
+ const update = this.computeHmrUpdate(importers, { firstInvalidatedBy });
661
+ if (update.type === "noop") return;
662
+ if (update.type === "full-reload") {
663
+ this.requestFullReload(update.reason);
664
+ return;
665
+ }
666
+ const listenerPayload = this.toUpdatePayload(update.boundaries, firstInvalidatedBy);
667
+ await this.notifyListeners("vite:beforeUpdate", listenerPayload);
668
+ if (this.options.beforeApply() === "reload") return;
669
+ await this.applyUpdate(update, firstInvalidatedBy);
670
+ await this.notifyListeners("vite:afterUpdate", listenerPayload);
671
+ }
672
+ async applyUpdate(update, firstInvalidatedBy) {
673
+ for (const id of update.updateSet) if (!this.runtime.hasFactory(id)) {
674
+ this.requestFullReload(`no factory for module \`${id}\``);
675
+ return;
676
+ }
677
+ const applies = update.boundaries.map(([boundary, acceptedVia]) => ({
678
+ boundary,
679
+ acceptedVia,
680
+ callbacks: this.hotModulesMap.get(boundary)?.callbacks.filter((c) => c.deps.includes(acceptedVia)) ?? []
681
+ }));
682
+ for (const id of update.updateSet) this.runtime.removeModuleCache(id);
683
+ for (const { boundary, acceptedVia, callbacks } of applies) {
684
+ this.runtime.initModule(acceptedVia);
685
+ const fresh = this.runtime.loadExports(acceptedVia);
686
+ try {
687
+ this.currentFirstInvalidatedBy = firstInvalidatedBy;
688
+ for (const { deps, fn } of callbacks) fn(deps.map((dep) => dep === acceptedVia ? fresh : void 0));
689
+ } finally {
690
+ this.currentFirstInvalidatedBy = void 0;
691
+ }
692
+ this.logger.debug(`hot updated: ${boundary === acceptedVia ? boundary : `${acceptedVia} via ${boundary}`}`);
693
+ }
694
+ }
695
+ toUpdatePayload(boundaries, firstInvalidatedBy) {
696
+ return {
697
+ type: "update",
698
+ updates: boundaries.map(([boundary, acceptedVia]) => ({
699
+ type: "js-update",
700
+ path: boundary,
701
+ acceptedPath: acceptedVia,
702
+ timestamp: Date.now(),
703
+ firstInvalidatedBy
704
+ }))
705
+ };
706
+ }
707
+ requestFullReload(reason) {
708
+ if (this.reloadPending) return;
709
+ this.reloadPending = true;
710
+ this.logger.debug(`full reload needed: ${reason}`);
711
+ this.send({
712
+ type: "custom",
713
+ event: "vite:bundled-dev:reload-needed",
714
+ data: { reason }
715
+ });
716
+ }
717
+ };
718
+ var BundledDevHMRContext = class extends HMRContext {
719
+ constructor(bundledDevClient, owner) {
720
+ super(bundledDevClient, owner);
721
+ this.bundledDevClient = bundledDevClient;
722
+ this.owner = owner;
723
+ }
724
+ invalidate(message) {
725
+ this.bundledDevClient.notifyListeners("vite:invalidate", {
726
+ path: this.owner,
727
+ message,
728
+ firstInvalidatedBy: this.bundledDevClient.currentFirstInvalidatedBy ?? this.owner
729
+ });
730
+ this.bundledDevClient.invalidateLocally(this.owner, message);
731
+ }
732
+ };
733
+ //#endregion
734
+ //#region ../../vite/packages/vite/src/shared/constants.ts
735
+ let SOURCEMAPPING_URL = "sourceMa";
736
+ SOURCEMAPPING_URL += "ppingURL";
737
+ typeof process !== "undefined" && process.platform;
738
+ (async function() {}).constructor;
739
+ function promiseWithResolvers() {
740
+ let resolve;
741
+ let reject;
742
+ return {
743
+ promise: new Promise((_resolve, _reject) => {
744
+ resolve = _resolve;
745
+ reject = _reject;
746
+ }),
747
+ resolve,
748
+ reject
749
+ };
750
+ }
751
+ //#endregion
752
+ //#region ../../vite/packages/vite/src/shared/moduleRunnerTransport.ts
753
+ function reviveInvokeError(e) {
754
+ const error = new Error(e.message || "Unknown invoke error");
755
+ Object.assign(error, e, { runnerError: /* @__PURE__ */ new Error("RunnerError") });
756
+ return error;
757
+ }
758
+ const createInvokeableTransport = (transport) => {
759
+ if (transport.invoke) return {
760
+ ...transport,
761
+ async invoke(name, data) {
762
+ const result = await transport.invoke({
763
+ type: "custom",
764
+ event: "vite:invoke",
765
+ data: {
766
+ id: "send",
767
+ name,
768
+ data
769
+ }
770
+ });
771
+ if ("error" in result) throw reviveInvokeError(result.error);
772
+ return result.result;
773
+ }
774
+ };
775
+ if (!transport.send || !transport.connect) throw new Error("transport must implement send and connect when invoke is not implemented");
776
+ const rpcPromises = /* @__PURE__ */ new Map();
777
+ return {
778
+ ...transport,
779
+ connect({ onMessage, onDisconnection }) {
780
+ return transport.connect({
781
+ onMessage(payload) {
782
+ if (payload.type === "custom" && payload.event === "vite:invoke") {
783
+ const data = payload.data;
784
+ if (data.id.startsWith("response:")) {
785
+ const invokeId = data.id.slice(9);
786
+ const promise = rpcPromises.get(invokeId);
787
+ if (!promise) return;
788
+ if (promise.timeoutId) clearTimeout(promise.timeoutId);
789
+ rpcPromises.delete(invokeId);
790
+ const { error, result } = data.data;
791
+ if (error) promise.reject(error);
792
+ else promise.resolve(result);
793
+ return;
794
+ }
795
+ }
796
+ onMessage(payload);
797
+ },
798
+ onDisconnection
799
+ });
800
+ },
801
+ disconnect() {
802
+ rpcPromises.forEach((promise) => {
803
+ promise.reject(/* @__PURE__ */ new Error(`transport was disconnected, cannot call ${JSON.stringify(promise.name)}`));
804
+ });
805
+ rpcPromises.clear();
806
+ return transport.disconnect?.();
807
+ },
808
+ send(data) {
809
+ return transport.send(data);
810
+ },
811
+ async invoke(name, data) {
812
+ const promiseId = nanoid();
813
+ const wrappedData = {
814
+ type: "custom",
815
+ event: "vite:invoke",
816
+ data: {
817
+ name,
818
+ id: `send:${promiseId}`,
819
+ data
820
+ }
821
+ };
822
+ const sendPromise = transport.send(wrappedData);
823
+ const { promise, resolve, reject } = promiseWithResolvers();
824
+ const timeout = transport.timeout ?? 6e4;
825
+ let timeoutId;
826
+ if (timeout > 0) {
827
+ timeoutId = setTimeout(() => {
828
+ rpcPromises.delete(promiseId);
829
+ reject(/* @__PURE__ */ new Error(`transport invoke timed out after ${timeout}ms (data: ${JSON.stringify(wrappedData)})`));
830
+ }, timeout);
831
+ timeoutId?.unref?.();
832
+ }
833
+ rpcPromises.set(promiseId, {
834
+ resolve,
835
+ reject,
836
+ name,
837
+ timeoutId
838
+ });
839
+ if (sendPromise) sendPromise.catch((err) => {
840
+ clearTimeout(timeoutId);
841
+ rpcPromises.delete(promiseId);
842
+ reject(err);
843
+ });
844
+ try {
845
+ return await promise;
846
+ } catch (err) {
847
+ throw reviveInvokeError(err);
848
+ }
849
+ }
850
+ };
851
+ };
852
+ const normalizeModuleRunnerTransport = (transport) => {
853
+ const invokeableTransport = createInvokeableTransport(transport);
854
+ let isConnected = !invokeableTransport.connect;
855
+ let connectingPromise;
856
+ return {
857
+ ...transport,
858
+ ...invokeableTransport.connect ? { async connect(onMessage) {
859
+ if (isConnected) return;
860
+ if (connectingPromise) {
861
+ await connectingPromise;
862
+ return;
863
+ }
864
+ const maybePromise = invokeableTransport.connect({
865
+ onMessage: onMessage ?? (() => {}),
866
+ onDisconnection() {
867
+ isConnected = false;
868
+ }
869
+ });
870
+ if (maybePromise) {
871
+ connectingPromise = maybePromise;
872
+ await connectingPromise;
873
+ connectingPromise = void 0;
874
+ }
875
+ isConnected = true;
876
+ } } : {},
877
+ ...invokeableTransport.disconnect ? { async disconnect() {
878
+ if (!isConnected) return;
879
+ if (connectingPromise) await connectingPromise;
880
+ isConnected = false;
881
+ await invokeableTransport.disconnect();
882
+ } } : {},
883
+ async send(data) {
884
+ if (!invokeableTransport.send) return;
885
+ if (!isConnected) {
886
+ if (connectingPromise) await connectingPromise;
887
+ else throw new SendBeforeConnectError("send was called before connect");
888
+ }
889
+ await invokeableTransport.send(data);
890
+ },
891
+ async invoke(name, data) {
892
+ if (!isConnected) {
893
+ if (connectingPromise) await connectingPromise;
894
+ else throw new SendBeforeConnectError("invoke was called before connect");
895
+ }
896
+ return invokeableTransport.invoke(name, data);
897
+ }
898
+ };
899
+ };
900
+ var SendBeforeConnectError = class extends Error {
901
+ constructor(message) {
902
+ super(message);
903
+ this.name = "SendBeforeConnectError";
904
+ }
905
+ };
906
+ const createWebSocketModuleRunnerTransport = (options) => {
907
+ const pingInterval = options.pingInterval ?? 3e4;
908
+ let ws;
909
+ let pingIntervalId;
910
+ return {
911
+ async connect({ onMessage, onDisconnection }) {
912
+ const socket = options.createConnection();
913
+ socket.addEventListener("message", ({ data }) => {
914
+ onMessage(JSON.parse(data));
915
+ });
916
+ let isOpened = socket.readyState === socket.OPEN;
917
+ if (!isOpened) await new Promise((resolve, reject) => {
918
+ socket.addEventListener("open", () => {
919
+ isOpened = true;
920
+ resolve();
921
+ }, { once: true });
922
+ socket.addEventListener("close", () => {
923
+ if (!isOpened) {
924
+ reject(/* @__PURE__ */ new Error("WebSocket closed without opened."));
925
+ return;
926
+ }
927
+ onMessage({
928
+ type: "custom",
929
+ event: "vite:ws:disconnect",
930
+ data: { webSocket: socket }
931
+ });
932
+ onDisconnection();
933
+ });
934
+ });
935
+ onMessage({
936
+ type: "custom",
937
+ event: "vite:ws:connect",
938
+ data: { webSocket: socket }
939
+ });
940
+ ws = socket;
941
+ pingIntervalId = setInterval(() => {
942
+ if (socket.readyState === socket.OPEN) socket.send(JSON.stringify({ type: "ping" }));
943
+ }, pingInterval);
944
+ },
945
+ disconnect() {
946
+ clearInterval(pingIntervalId);
947
+ ws?.close();
948
+ },
949
+ send(data) {
950
+ ws.send(JSON.stringify(data));
951
+ }
952
+ };
953
+ };
954
+ //#endregion
955
+ //#region ../../vite/packages/vite/src/shared/hmrHandler.ts
956
+ function createHMRHandler(handler) {
957
+ const queue = new Queue();
958
+ return (payload) => queue.enqueue(() => handler(payload));
959
+ }
960
+ var Queue = class {
961
+ constructor() {
962
+ _defineProperty(this, "queue", []);
963
+ _defineProperty(this, "pending", false);
964
+ }
965
+ enqueue(promise) {
966
+ return new Promise((resolve, reject) => {
967
+ this.queue.push({
968
+ promise,
969
+ resolve,
970
+ reject
971
+ });
972
+ this.dequeue();
973
+ });
974
+ }
975
+ dequeue() {
976
+ if (this.pending) return false;
977
+ const item = this.queue.shift();
978
+ if (!item) return false;
979
+ this.pending = true;
980
+ item.promise().then(item.resolve).catch(item.reject).finally(() => {
981
+ this.pending = false;
982
+ this.dequeue();
983
+ });
984
+ return true;
985
+ }
986
+ };
987
+ //#endregion
988
+ //#region ../../vite/packages/vite/src/shared/forwardConsole.ts
989
+ function setupForwardConsoleHandler(transport, options, console = globalThis.console) {
990
+ if (!options.enabled) return;
991
+ async function sendError(type, error) {
992
+ await transport.send({
993
+ type: "custom",
994
+ event: "vite:forward-console",
995
+ data: {
996
+ type,
997
+ data: {
998
+ name: error?.name || "Unknown Error",
999
+ message: error?.message || String(error),
1000
+ stack: error?.stack
1001
+ }
1002
+ }
1003
+ });
1004
+ }
1005
+ async function sendLog(level, args) {
1006
+ try {
1007
+ await transport.send({
1008
+ type: "custom",
1009
+ event: "vite:forward-console",
1010
+ data: {
1011
+ type: "log",
1012
+ data: {
1013
+ level,
1014
+ message: formatConsoleArgs(args)
1015
+ }
1016
+ }
1017
+ });
1018
+ } catch (err) {
1019
+ try {
1020
+ await sendError("unhandled-rejection", err);
1021
+ } catch (err) {
1022
+ if (!(err instanceof SendBeforeConnectError)) originalConsoleError("Failed to send error to Vite server:", err);
1023
+ }
1024
+ }
1025
+ }
1026
+ const originalConsoleError = console.error;
1027
+ for (const level of options.logLevels) {
1028
+ const original = console[level];
1029
+ if (typeof original !== "function") continue;
1030
+ console[level] = (...args) => {
1031
+ original(...args);
1032
+ sendLog(level, args);
1033
+ };
1034
+ }
1035
+ if (options.unhandledErrors && typeof window !== "undefined") {
1036
+ window.addEventListener("error", async (event) => {
1037
+ const error = event.error ?? (event.message ? new Error(event.message) : event);
1038
+ try {
1039
+ await sendError("error", error);
1040
+ } catch (err) {
1041
+ if (!(err instanceof SendBeforeConnectError)) originalConsoleError("Failed to send error to Vite server:", err);
1042
+ }
1043
+ });
1044
+ window.addEventListener("unhandledrejection", async (event) => {
1045
+ try {
1046
+ await sendError("unhandled-rejection", event.reason);
1047
+ } catch (err) {
1048
+ if (!(err instanceof SendBeforeConnectError)) originalConsoleError("Failed to send error to Vite server:", err);
1049
+ }
1050
+ });
1051
+ }
1052
+ }
1053
+ function formatConsoleArgs(args) {
1054
+ if (args.length === 0) return "";
1055
+ if (typeof args[0] !== "string") return args.map((arg) => stringifyConsoleArg(arg)).join(" ");
1056
+ const len = args.length;
1057
+ let i = 1;
1058
+ let message = args[0].replace(/%[sdjifoOc%]/g, (specifier) => {
1059
+ if (specifier === "%%") return "%";
1060
+ if (i >= len) return specifier;
1061
+ const arg = args[i++];
1062
+ switch (specifier) {
1063
+ case "%s":
1064
+ if (typeof arg === "bigint") return `${arg.toString()}n`;
1065
+ return typeof arg === "object" && arg != null ? stringifyConsoleArg(arg) : String(arg);
1066
+ case "%d":
1067
+ if (typeof arg === "bigint") return `${arg.toString()}n`;
1068
+ if (typeof arg === "symbol") return "NaN";
1069
+ return Number(arg).toString();
1070
+ case "%i":
1071
+ if (typeof arg === "bigint") return `${arg.toString()}n`;
1072
+ return Number.parseInt(String(arg), 10).toString();
1073
+ case "%f": return Number.parseFloat(String(arg)).toString();
1074
+ case "%o":
1075
+ case "%O": return stringifyConsoleArg(arg);
1076
+ case "%j": try {
1077
+ return JSON.stringify(arg) ?? "undefined";
1078
+ } catch {
1079
+ return "[Circular]";
1080
+ }
1081
+ case "%c": return "";
1082
+ default: return specifier;
1083
+ }
1084
+ });
1085
+ for (let arg = args[i]; i < len; arg = args[++i]) if (arg == null || typeof arg !== "object") message += ` ${typeof arg === "symbol" ? arg.toString() : String(arg)}`;
1086
+ else message += ` ${stringifyConsoleArg(arg)}`;
1087
+ return message;
1088
+ }
1089
+ function stringifyConsoleArg(value) {
1090
+ if (typeof value === "string") return value;
1091
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "undefined") return String(value);
1092
+ if (typeof value === "symbol") return value.toString();
1093
+ if (typeof value === "function") return value.name ? `[Function: ${value.name}]` : "[Function]";
1094
+ if (value instanceof Error) return value.stack || `${value.name}: ${value.message}`;
1095
+ if (typeof value === "bigint") return `${value}n`;
1096
+ const seen = /* @__PURE__ */ new WeakSet();
1097
+ try {
1098
+ return JSON.stringify(value, (_, nested) => {
1099
+ if (typeof nested === "bigint") return `${nested}n`;
1100
+ if (nested instanceof Error) return {
1101
+ name: nested.name,
1102
+ message: nested.message,
1103
+ stack: nested.stack
1104
+ };
1105
+ if (nested && typeof nested === "object") {
1106
+ if (seen.has(nested)) return "[Circular]";
1107
+ seen.add(nested);
1108
+ }
1109
+ return nested;
1110
+ }) ?? String(value);
1111
+ } catch {
1112
+ return String(value);
1113
+ }
1114
+ }
1115
+ //#endregion
1116
+ //#region ../../vite/packages/vite/src/client/overlay.ts
1117
+ const hmrConfigName = __HMR_CONFIG_NAME__;
1118
+ const base$1 = __BASE__ || "/";
1119
+ const cspNonce = "document" in globalThis ? document.querySelector("meta[property=csp-nonce]")?.nonce : void 0;
1120
+ function h(e, attrs = {}, ...children) {
1121
+ const elem = document.createElement(e);
1122
+ for (const [k, v] of Object.entries(attrs)) if (v !== void 0) elem.setAttribute(k, v);
1123
+ elem.append(...children);
1124
+ return elem;
1125
+ }
1126
+ const templateStyle = `
1127
+ :host {
1128
+ position: fixed;
1129
+ top: 0;
1130
+ left: 0;
1131
+ width: 100%;
1132
+ height: 100%;
1133
+ z-index: 99999;
1134
+ --monospace: 'SFMono-Regular', Consolas,
1135
+ 'Liberation Mono', Menlo, Courier, monospace;
1136
+ --red: #ff5555;
1137
+ --yellow: #e2aa53;
1138
+ --purple: #cfa4ff;
1139
+ --cyan: #2dd9da;
1140
+ --dim: #c9c9c9;
1141
+
1142
+ --window-background: #181818;
1143
+ --window-color: #d8d8d8;
1144
+ }
1145
+
1146
+ .backdrop {
1147
+ position: fixed;
1148
+ z-index: 99999;
1149
+ top: 0;
1150
+ left: 0;
1151
+ width: 100%;
1152
+ height: 100%;
1153
+ overflow-y: scroll;
1154
+ margin: 0;
1155
+ background: rgba(0, 0, 0, 0.66);
1156
+ }
1157
+
1158
+ .window {
1159
+ font-family: var(--monospace);
1160
+ line-height: 1.5;
1161
+ max-width: 80vw;
1162
+ color: var(--window-color);
1163
+ box-sizing: border-box;
1164
+ margin: 30px auto;
1165
+ padding: 2.5vh 4vw;
1166
+ position: relative;
1167
+ background: var(--window-background);
1168
+ border-radius: 6px 6px 8px 8px;
1169
+ box-shadow: 0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0,0,0,0.22);
1170
+ overflow: hidden;
1171
+ border-top: 8px solid var(--red);
1172
+ direction: ltr;
1173
+ text-align: left;
1174
+ }
1175
+
1176
+ pre {
1177
+ font-family: var(--monospace);
1178
+ font-size: 16px;
1179
+ margin-top: 0;
1180
+ margin-bottom: 1em;
1181
+ overflow-x: scroll;
1182
+ scrollbar-width: none;
1183
+ }
1184
+
1185
+ pre::-webkit-scrollbar {
1186
+ display: none;
1187
+ }
1188
+
1189
+ pre.frame::-webkit-scrollbar {
1190
+ display: block;
1191
+ height: 5px;
1192
+ }
1193
+
1194
+ pre.frame::-webkit-scrollbar-thumb {
1195
+ background: #999;
1196
+ border-radius: 5px;
1197
+ }
1198
+
1199
+ pre.frame {
1200
+ scrollbar-width: thin;
1201
+ }
1202
+
1203
+ .message {
1204
+ line-height: 1.3;
1205
+ font-weight: 400;
1206
+ white-space: pre-wrap;
1207
+ }
1208
+
1209
+ .message-body {
1210
+ color: var(--red);
1211
+ }
1212
+
1213
+ .plugin {
1214
+ color: var(--purple);
1215
+ }
1216
+
1217
+ .file {
1218
+ color: var(--cyan);
1219
+ margin-bottom: 0;
1220
+ white-space: pre-wrap;
1221
+ word-break: break-all;
1222
+ }
1223
+
1224
+ .frame {
1225
+ color: var(--yellow);
1226
+ }
1227
+
1228
+ .stack {
1229
+ font-size: 13px;
1230
+ color: var(--dim);
1231
+ }
1232
+
1233
+ .tip {
1234
+ font-size: 13px;
1235
+ color: #999;
1236
+ border-top: 1px dotted #999;
1237
+ padding-top: 13px;
1238
+ line-height: 1.8;
1239
+ }
1240
+
1241
+ code {
1242
+ font-size: 13px;
1243
+ font-family: var(--monospace);
1244
+ color: var(--yellow);
1245
+ }
1246
+
1247
+ .file-link {
1248
+ text-decoration: underline;
1249
+ cursor: pointer;
1250
+ }
1251
+
1252
+ kbd {
1253
+ line-height: 1.5;
1254
+ font-family: ui-monospace, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
1255
+ font-size: 0.75rem;
1256
+ font-weight: 700;
1257
+ background-color: rgb(38, 40, 44);
1258
+ color: rgb(166, 167, 171);
1259
+ padding: 0.15rem 0.3rem;
1260
+ border-radius: 0.25rem;
1261
+ border-width: 0.0625rem 0.0625rem 0.1875rem;
1262
+ border-style: solid;
1263
+ border-color: rgb(54, 57, 64);
1264
+ border-image: initial;
1265
+ }
1266
+ `;
1267
+ const createTemplate = () => h("div", {
1268
+ class: "backdrop",
1269
+ part: "backdrop"
1270
+ }, h("div", {
1271
+ class: "window",
1272
+ part: "window"
1273
+ }, h("pre", {
1274
+ class: "message",
1275
+ part: "message"
1276
+ }, h("span", {
1277
+ class: "plugin",
1278
+ part: "plugin"
1279
+ }), h("span", {
1280
+ class: "message-body",
1281
+ part: "message-body"
1282
+ })), h("pre", {
1283
+ class: "file",
1284
+ part: "file"
1285
+ }), h("pre", {
1286
+ class: "frame",
1287
+ part: "frame"
1288
+ }), h("pre", {
1289
+ class: "stack",
1290
+ part: "stack"
1291
+ }), h("div", {
1292
+ class: "tip",
1293
+ part: "tip"
1294
+ }, "Click outside, press ", h("kbd", {}, "Esc"), " key, or fix the code to dismiss.", h("br"), "You can also disable this overlay by setting ", h("code", { part: "config-option-name" }, "server.hmr.overlay"), " to ", h("code", { part: "config-option-value" }, "false"), " in ", h("code", { part: "config-file-name" }, hmrConfigName), ".")), h("style", { nonce: cspNonce }, templateStyle));
1295
+ const fileRE = /(?:file:\/\/)?(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g;
1296
+ const codeframeRE = /^(?:>?\s*\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm;
1297
+ const { HTMLElement = class {} } = globalThis;
1298
+ var ErrorOverlay = class extends HTMLElement {
1299
+ constructor(err, links = true) {
1300
+ super();
1301
+ _defineProperty(this, "root", void 0);
1302
+ _defineProperty(this, "closeOnEsc", void 0);
1303
+ this.root = this.attachShadow({ mode: "open" });
1304
+ this.root.appendChild(createTemplate());
1305
+ codeframeRE.lastIndex = 0;
1306
+ const hasFrame = err.frame && codeframeRE.test(err.frame);
1307
+ const message = hasFrame ? err.message.replace(codeframeRE, "") : err.message;
1308
+ if (err.plugin) this.text(".plugin", `[plugin:${err.plugin}] `);
1309
+ this.text(".message-body", message.trim());
1310
+ const [file] = (err.loc?.file || err.id || "unknown file").split(`?`);
1311
+ if (err.loc) this.text(".file", `${file}:${err.loc.line}:${err.loc.column}`, links);
1312
+ else if (err.id) this.text(".file", file);
1313
+ if (hasFrame) this.text(".frame", err.frame.trim());
1314
+ this.text(".stack", err.stack, links);
1315
+ this.root.querySelector(".window").addEventListener("click", (e) => {
1316
+ e.stopPropagation();
1317
+ });
1318
+ this.addEventListener("click", () => {
1319
+ this.close();
1320
+ });
1321
+ this.closeOnEsc = (e) => {
1322
+ if (e.key === "Escape" || e.code === "Escape") this.close();
1323
+ };
1324
+ document.addEventListener("keydown", this.closeOnEsc);
1325
+ }
1326
+ text(selector, text, linkFiles = false) {
1327
+ const el = this.root.querySelector(selector);
1328
+ if (!linkFiles) el.textContent = text;
1329
+ else {
1330
+ let curIndex = 0;
1331
+ let match;
1332
+ fileRE.lastIndex = 0;
1333
+ while (match = fileRE.exec(text)) {
1334
+ const { 0: file, index } = match;
1335
+ const frag = text.slice(curIndex, index);
1336
+ el.appendChild(document.createTextNode(frag));
1337
+ const link = document.createElement("a");
1338
+ link.textContent = file;
1339
+ link.className = "file-link";
1340
+ link.onclick = () => {
1341
+ fetch(new URL(`${base$1}__open-in-editor?file=${encodeURIComponent(file)}`, import.meta.url));
1342
+ };
1343
+ el.appendChild(link);
1344
+ curIndex += frag.length + file.length;
1345
+ }
1346
+ if (curIndex < text.length) el.appendChild(document.createTextNode(text.slice(curIndex)));
1347
+ }
1348
+ }
1349
+ close() {
1350
+ this.parentNode?.removeChild(this);
1351
+ document.removeEventListener("keydown", this.closeOnEsc);
1352
+ }
1353
+ };
1354
+ const overlayId = "vite-error-overlay";
1355
+ const { customElements } = globalThis;
1356
+ if (customElements && !customElements.get("vite-error-overlay")) customElements.define(overlayId, ErrorOverlay);
1357
+ //#endregion
1358
+ //#region ../../vite/packages/vite/src/client/client.ts
1359
+ console.debug("[vite] connecting...");
1360
+ const importMetaUrl = new URL(import.meta.url);
1361
+ const serverHost = __SERVER_HOST__;
1362
+ const socketProtocol = __HMR_PROTOCOL__ || (importMetaUrl.protocol === "https:" ? "wss" : "ws");
1363
+ const hmrPort = __HMR_PORT__;
1364
+ const socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${hmrPort || importMetaUrl.port}${__HMR_BASE__}`;
1365
+ const directSocketHost = __HMR_DIRECT_TARGET__;
1366
+ const base = __BASE__ || "/";
1367
+ const hmrTimeout = __HMR_TIMEOUT__;
1368
+ const wsToken = __WS_TOKEN__;
1369
+ const forwardConsole = __SERVER_FORWARD_CONSOLE__;
1370
+ const transport = normalizeModuleRunnerTransport((() => {
1371
+ let wsTransport = createWebSocketModuleRunnerTransport({
1372
+ createConnection: () => new WebSocket(`${socketProtocol}://${socketHost}?token=${wsToken}`, "vite-hmr"),
1373
+ pingInterval: hmrTimeout
1374
+ });
1375
+ return {
1376
+ async connect(handlers) {
1377
+ try {
1378
+ await wsTransport.connect(handlers);
1379
+ } catch (e) {
1380
+ if (!hmrPort) {
1381
+ wsTransport = createWebSocketModuleRunnerTransport({
1382
+ createConnection: () => new WebSocket(`${socketProtocol}://${directSocketHost}?token=${wsToken}`, "vite-hmr"),
1383
+ pingInterval: hmrTimeout
1384
+ });
1385
+ try {
1386
+ await wsTransport.connect(handlers);
1387
+ console.info("[vite] Direct websocket connection fallback. Check out https://vite.dev/config/server-options.html#server-hmr to remove the previous connection error.");
1388
+ } catch (e) {
1389
+ if (e instanceof Error && e.message.includes("WebSocket closed without opened.")) {
1390
+ const currentScriptHostURL = new URL(import.meta.url);
1391
+ const currentScriptHost = currentScriptHostURL.host + currentScriptHostURL.pathname.replace(/@vite\/client$/, "");
1392
+ console.error(`[vite] failed to connect to websocket.
1393
+ your current setup:
1394
+ (browser) ${currentScriptHost} <--[HTTP]--> ${serverHost} (server)\n (browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)\nCheck out your Vite / network configuration and https://vite.dev/config/server-options.html#server-hmr .`);
1395
+ }
1396
+ }
1397
+ return;
1398
+ }
1399
+ console.error(`[vite] failed to connect to websocket (${e}). `);
1400
+ throw e;
1401
+ }
1402
+ },
1403
+ async disconnect() {
1404
+ await wsTransport.disconnect();
1405
+ },
1406
+ send(data) {
1407
+ wsTransport.send(data);
1408
+ }
1409
+ };
1410
+ })());
1411
+ let willUnload = false;
1412
+ if (typeof window !== "undefined") window.addEventListener?.("beforeunload", () => {
1413
+ willUnload = true;
1414
+ });
1415
+ function cleanUrl(pathname) {
1416
+ const url = new URL(pathname, "http://vite.dev");
1417
+ url.searchParams.delete("direct");
1418
+ return url.pathname + url.search;
1419
+ }
1420
+ let isFirstUpdate = true;
1421
+ const outdatedLinkTags = /* @__PURE__ */ new WeakSet();
1422
+ const debounceReload = (time) => {
1423
+ let timer;
1424
+ return () => {
1425
+ if (timer) {
1426
+ clearTimeout(timer);
1427
+ timer = null;
1428
+ }
1429
+ timer = setTimeout(() => {
1430
+ location.reload();
1431
+ }, time);
1432
+ };
1433
+ };
1434
+ const pageReload = debounceReload(20);
1435
+ const hmrClient = new HMRClient({
1436
+ error: (err) => console.error("[vite]", err),
1437
+ debug: (...msg) => console.debug("[vite]", ...msg)
1438
+ }, transport, async function importUpdatedModule({ acceptedPath, timestamp, explicitImportRequired, isWithinCircularImport }) {
1439
+ const [acceptedPathWithoutQuery, query] = acceptedPath.split(`?`);
1440
+ const importPromise = import(
1441
+ /* @vite-ignore */
1442
+ base + acceptedPathWithoutQuery.slice(1) + `?${explicitImportRequired ? "import&" : ""}t=${timestamp}${query ? `&${query}` : ""}`
1443
+ );
1444
+ if (isWithinCircularImport) importPromise.catch(() => {
1445
+ console.info(`[hmr] ${acceptedPath} failed to apply HMR as it's within a circular import. Reloading page to reset the execution order. To debug and break the circular import, you can run \`vite --debug hmr\` to log the circular dependency path if a file change triggered it.`);
1446
+ pageReload();
1447
+ });
1448
+ return await importPromise;
1449
+ });
1450
+ let bundledDevClient;
1451
+ function registerBundledDevClient(client) {
1452
+ bundledDevClient = client;
1453
+ }
1454
+ transport.connect(createHMRHandler(handleMessage));
1455
+ setupForwardConsoleHandler(transport, forwardConsole);
1456
+ function clearOverlayOrReloadOnFirstUpdate() {
1457
+ if (hasDocument) {
1458
+ if (isFirstUpdate && hasErrorOverlay()) {
1459
+ location.reload();
1460
+ return "reload";
1461
+ }
1462
+ if (enableOverlay) clearErrorOverlay();
1463
+ isFirstUpdate = false;
1464
+ }
1465
+ return "continue";
1466
+ }
1467
+ async function handleMessage(payload) {
1468
+ const activeHmrClient = bundledDevClient ?? hmrClient;
1469
+ switch (payload.type) {
1470
+ case "connected":
1471
+ console.debug(`[vite] connected.`);
1472
+ break;
1473
+ case "bundled-dev-update":
1474
+ bundledDevClient.handlePush(payload);
1475
+ break;
1476
+ case "update":
1477
+ await activeHmrClient.notifyListeners("vite:beforeUpdate", payload);
1478
+ if (clearOverlayOrReloadOnFirstUpdate() === "reload") return;
1479
+ await Promise.all(payload.updates.map(async (update) => {
1480
+ if (update.type === "js-update") return hmrClient.queueUpdate(update);
1481
+ const { path, timestamp } = update;
1482
+ const searchUrl = cleanUrl(path);
1483
+ const el = Array.from(document.querySelectorAll("link")).find((e) => !outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl));
1484
+ if (!el) return;
1485
+ const newPath = `${base}${searchUrl.slice(1)}${searchUrl.includes("?") ? "&" : "?"}t=${timestamp}`;
1486
+ return new Promise((resolve) => {
1487
+ const newLinkTag = el.cloneNode();
1488
+ newLinkTag.href = new URL(newPath, el.href).href;
1489
+ const removeOldEl = () => {
1490
+ el.remove();
1491
+ console.debug(`[vite] css hot updated: ${searchUrl}`);
1492
+ resolve();
1493
+ };
1494
+ newLinkTag.addEventListener("load", removeOldEl);
1495
+ newLinkTag.addEventListener("error", removeOldEl);
1496
+ outdatedLinkTags.add(el);
1497
+ el.after(newLinkTag);
1498
+ });
1499
+ }));
1500
+ await activeHmrClient.notifyListeners("vite:afterUpdate", payload);
1501
+ break;
1502
+ case "custom":
1503
+ await activeHmrClient.notifyListeners(payload.event, payload.data);
1504
+ if (payload.event === "vite:ws:disconnect") {
1505
+ if (hasDocument && !willUnload) {
1506
+ console.log(`[vite] server connection lost. Polling for restart...`);
1507
+ const socket = payload.data.webSocket;
1508
+ const url = new URL(socket.url);
1509
+ url.search = "";
1510
+ await waitForSuccessfulPing(url.href);
1511
+ location.reload();
1512
+ }
1513
+ }
1514
+ break;
1515
+ case "full-reload":
1516
+ if (payload.ifFallback && !globalThis.__vite_is_fallback_page__) break;
1517
+ await activeHmrClient.notifyListeners("vite:beforeFullReload", payload);
1518
+ if (hasDocument) {
1519
+ if (payload.path && payload.path.endsWith(".html")) {
1520
+ const pagePath = decodeURI(location.pathname);
1521
+ const payloadPath = base + payload.path.slice(1);
1522
+ if (pagePath === payloadPath || payload.path === "/index.html" || pagePath.endsWith("/") && pagePath + "index.html" === payloadPath) pageReload();
1523
+ return;
1524
+ } else pageReload();
1525
+ }
1526
+ break;
1527
+ case "prune":
1528
+ await activeHmrClient.notifyListeners("vite:beforePrune", payload);
1529
+ await activeHmrClient.prunePaths(payload.paths);
1530
+ break;
1531
+ case "error":
1532
+ await activeHmrClient.notifyListeners("vite:error", payload);
1533
+ if (hasDocument) {
1534
+ const err = payload.err;
1535
+ if (enableOverlay) createErrorOverlay(err);
1536
+ else console.error(`[vite] Internal Server Error\n${err.message}\n${err.stack}`);
1537
+ }
1538
+ break;
1539
+ case "ping": break;
1540
+ default: return payload;
1541
+ }
1542
+ }
1543
+ const enableOverlay = __HMR_ENABLE_OVERLAY__;
1544
+ const hasDocument = "document" in globalThis;
1545
+ function createErrorOverlay(err) {
1546
+ clearErrorOverlay();
1547
+ const { customElements } = globalThis;
1548
+ if (customElements) {
1549
+ const ErrorOverlayConstructor = customElements.get(overlayId);
1550
+ document.body.appendChild(new ErrorOverlayConstructor(err));
1551
+ }
1552
+ }
1553
+ function clearErrorOverlay() {
1554
+ document.querySelectorAll(overlayId).forEach((n) => n.close());
1555
+ }
1556
+ function hasErrorOverlay() {
1557
+ return document.querySelectorAll(overlayId).length;
1558
+ }
1559
+ function waitForSuccessfulPing(socketUrl) {
1560
+ if (typeof SharedWorker === "undefined") {
1561
+ const visibilityManager = {
1562
+ currentState: document.visibilityState,
1563
+ listeners: /* @__PURE__ */ new Set()
1564
+ };
1565
+ const onVisibilityChange = () => {
1566
+ visibilityManager.currentState = document.visibilityState;
1567
+ for (const listener of visibilityManager.listeners) listener(visibilityManager.currentState);
1568
+ };
1569
+ document.addEventListener("visibilitychange", onVisibilityChange);
1570
+ return waitForSuccessfulPingInternal(socketUrl, visibilityManager);
1571
+ }
1572
+ const blob = new Blob([
1573
+ "\"use strict\";",
1574
+ `const waitForSuccessfulPingInternal = ${waitForSuccessfulPingInternal.toString()};`,
1575
+ `const fn = ${pingWorkerContentMain.toString()};`,
1576
+ `fn(${JSON.stringify(socketUrl)})`
1577
+ ], { type: "application/javascript" });
1578
+ const objURL = URL.createObjectURL(blob);
1579
+ const sharedWorker = new SharedWorker(objURL);
1580
+ return new Promise((resolve, reject) => {
1581
+ const onVisibilityChange = () => {
1582
+ sharedWorker.port.postMessage({ visibility: document.visibilityState });
1583
+ };
1584
+ document.addEventListener("visibilitychange", onVisibilityChange);
1585
+ sharedWorker.port.addEventListener("message", (event) => {
1586
+ document.removeEventListener("visibilitychange", onVisibilityChange);
1587
+ sharedWorker.port.close();
1588
+ const data = event.data;
1589
+ if (data.type === "error") {
1590
+ reject(data.error);
1591
+ return;
1592
+ }
1593
+ resolve();
1594
+ });
1595
+ onVisibilityChange();
1596
+ sharedWorker.port.start();
1597
+ });
1598
+ }
1599
+ function pingWorkerContentMain(socketUrl) {
1600
+ self.addEventListener("connect", (_event) => {
1601
+ const port = _event.ports[0];
1602
+ if (!socketUrl) {
1603
+ port.postMessage({
1604
+ type: "error",
1605
+ error: /* @__PURE__ */ new Error("socketUrl not found")
1606
+ });
1607
+ return;
1608
+ }
1609
+ const visibilityManager = {
1610
+ currentState: "visible",
1611
+ listeners: /* @__PURE__ */ new Set()
1612
+ };
1613
+ port.addEventListener("message", (event) => {
1614
+ const { visibility } = event.data;
1615
+ visibilityManager.currentState = visibility;
1616
+ console.debug("[vite] new window visibility", visibility);
1617
+ for (const listener of visibilityManager.listeners) listener(visibility);
1618
+ });
1619
+ port.start();
1620
+ console.debug("[vite] connected from window");
1621
+ waitForSuccessfulPingInternal(socketUrl, visibilityManager).then(() => {
1622
+ console.debug("[vite] ping successful");
1623
+ try {
1624
+ port.postMessage({ type: "success" });
1625
+ } catch (error) {
1626
+ port.postMessage({
1627
+ type: "error",
1628
+ error
1629
+ });
1630
+ }
1631
+ }, (error) => {
1632
+ console.debug("[vite] error happened", error);
1633
+ try {
1634
+ port.postMessage({
1635
+ type: "error",
1636
+ error
1637
+ });
1638
+ } catch (error) {
1639
+ port.postMessage({
1640
+ type: "error",
1641
+ error
1642
+ });
1643
+ }
1644
+ });
1645
+ });
1646
+ }
1647
+ async function waitForSuccessfulPingInternal(socketUrl, visibilityManager, ms = 1e3) {
1648
+ function wait(ms) {
1649
+ return new Promise((resolve) => setTimeout(resolve, ms));
1650
+ }
1651
+ async function ping() {
1652
+ try {
1653
+ const socket = new WebSocket(socketUrl, "vite-ping");
1654
+ return new Promise((resolve) => {
1655
+ function onOpen() {
1656
+ resolve(true);
1657
+ close();
1658
+ }
1659
+ function onError() {
1660
+ resolve(false);
1661
+ close();
1662
+ }
1663
+ function close() {
1664
+ socket.removeEventListener("open", onOpen);
1665
+ socket.removeEventListener("error", onError);
1666
+ socket.close();
1667
+ }
1668
+ socket.addEventListener("open", onOpen);
1669
+ socket.addEventListener("error", onError);
1670
+ });
1671
+ } catch {
1672
+ return false;
1673
+ }
1674
+ }
1675
+ function waitForWindowShow(visibilityManager) {
1676
+ return new Promise((resolve) => {
1677
+ const onChange = (newVisibility) => {
1678
+ if (newVisibility === "visible") {
1679
+ resolve();
1680
+ visibilityManager.listeners.delete(onChange);
1681
+ }
1682
+ };
1683
+ visibilityManager.listeners.add(onChange);
1684
+ });
1685
+ }
1686
+ if (await ping()) return;
1687
+ await wait(ms);
1688
+ while (true) if (visibilityManager.currentState === "visible") {
1689
+ if (await ping()) break;
1690
+ await wait(ms);
1691
+ } else await waitForWindowShow(visibilityManager);
1692
+ }
1693
+ const sheetsMap = /* @__PURE__ */ new Map();
1694
+ const linkSheetsMap = /* @__PURE__ */ new Map();
1695
+ if ("document" in globalThis) {
1696
+ document.querySelectorAll("style[data-vite-dev-id]").forEach((el) => {
1697
+ sheetsMap.set(el.getAttribute("data-vite-dev-id"), el);
1698
+ });
1699
+ document.querySelectorAll("link[rel=\"stylesheet\"][data-vite-dev-id]").forEach((el) => {
1700
+ linkSheetsMap.set(el.getAttribute("data-vite-dev-id"), el);
1701
+ });
1702
+ }
1703
+ let lastInsertedStyle;
1704
+ function updateStyle(id, content) {
1705
+ if (linkSheetsMap.has(id)) return;
1706
+ let style = sheetsMap.get(id);
1707
+ if (!style) {
1708
+ style = document.createElement("style");
1709
+ style.setAttribute("type", "text/css");
1710
+ style.setAttribute("data-vite-dev-id", id);
1711
+ style.textContent = content;
1712
+ if (cspNonce) style.setAttribute("nonce", cspNonce);
1713
+ if (!lastInsertedStyle) {
1714
+ document.head.appendChild(style);
1715
+ setTimeout(() => {
1716
+ lastInsertedStyle = void 0;
1717
+ }, 0);
1718
+ } else lastInsertedStyle.insertAdjacentElement("afterend", style);
1719
+ lastInsertedStyle = style;
1720
+ } else style.textContent = content;
1721
+ sheetsMap.set(id, style);
1722
+ }
1723
+ function removeStyle(id) {
1724
+ if (linkSheetsMap.has(id)) {
1725
+ document.querySelectorAll(`link[rel="stylesheet"][data-vite-dev-id="${CSS.escape(id)}"]`).forEach((el) => el.remove());
1726
+ linkSheetsMap.delete(id);
1727
+ }
1728
+ const style = sheetsMap.get(id);
1729
+ if (style) {
1730
+ document.head.removeChild(style);
1731
+ sheetsMap.delete(id);
1732
+ }
1733
+ }
1734
+ function createHotContext(ownerPath) {
1735
+ return new HMRContext(hmrClient, ownerPath);
1736
+ }
1737
+ /**
1738
+ * urls here are dynamic import() urls that couldn't be statically analyzed
1739
+ */
1740
+ function injectQuery(url, queryToInject) {
1741
+ if (url[0] !== "." && url[0] !== "/") return url;
1742
+ const pathname = url.replace(/[?#].*$/, "");
1743
+ const { search, hash } = new URL(url, "http://vite.dev");
1744
+ return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ""}${hash || ""}`;
1745
+ }
1746
+ //#endregion
1747
+ //#region ../../vite/packages/vite/src/client/bundledDevClient.ts
1748
+ if (typeof DevRuntime !== "undefined") {
1749
+ var _ref;
1750
+ class ViteDevRuntime extends DevRuntime {
1751
+ createModuleHotContext(moduleId) {
1752
+ const ctx = new BundledDevHMRContext(bundledDevHmrClient, moduleId);
1753
+ ctx._internal = {
1754
+ updateStyle,
1755
+ removeStyle
1756
+ };
1757
+ return ctx;
1758
+ }
1759
+ }
1760
+ const clientId = nanoid();
1761
+ transport.send({
1762
+ type: "custom",
1763
+ event: "vite:client-connected",
1764
+ data: { clientId }
1765
+ });
1766
+ const runtime = (_ref = globalThis).__rolldown_runtime__ ?? (_ref.__rolldown_runtime__ = new ViteDevRuntime(clientId));
1767
+ const bundledDevHmrClient = new BundledDevHMRClient({
1768
+ error: (err) => console.error("[vite]", err),
1769
+ debug: (...msg) => console.debug("[vite]", ...msg)
1770
+ }, transport, runtime, {
1771
+ base,
1772
+ beforeApply: clearOverlayOrReloadOnFirstUpdate
1773
+ });
1774
+ registerBundledDevClient(bundledDevHmrClient);
1775
+ runtime.hooks = {
1776
+ createModuleHotContext: (id) => runtime.createModuleHotContext(id),
1777
+ onModuleCacheRemoval: (id) => bundledDevHmrClient.handleModuleCacheRemoval(id)
1778
+ };
1779
+ }
1780
+ //#endregion
1781
+ export { ErrorOverlay, createHotContext, injectQuery, removeStyle, updateStyle };