@ohos-ports/vite 8.3.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1864 @@
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 ../../node_modules/.pnpm/rolldown@1.2.6/node_modules/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.147.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.147.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.147.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.147.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 ../../node_modules/.pnpm/rolldown@1.2.6/node_modules/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 = { exports: {} }) {
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 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 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
+ this.applyQueue = Promise.resolve();
555
+ this.lastSeq = 0;
556
+ 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({
589
+ boundary: id,
590
+ acceptedVia: id,
591
+ isWithinCircularImport: this.isNodeWithinCircularImports(id, stack)
592
+ });
593
+ return;
594
+ }
595
+ const parents = this.runtime.getImporters(id).filter((p) => this.runtime.isExecuted(p));
596
+ if (!parents.length) return {
597
+ type: "full-reload",
598
+ reason: `no hmr boundary found for module \`${id}\``
599
+ };
600
+ for (const parent of parents) {
601
+ const subChain = [...stack, parent];
602
+ if (this.acceptsDep(parent, id)) {
603
+ boundaries.push({
604
+ boundary: parent,
605
+ acceptedVia: id,
606
+ isWithinCircularImport: this.isNodeWithinCircularImports(parent, subChain)
607
+ });
608
+ continue;
609
+ }
610
+ if (!stack.includes(parent)) {
611
+ const fullReload = this.bubble(parent, subChain, updateSet, boundaries, firstInvalidatedBy, traversedModules);
612
+ if (fullReload) return fullReload;
613
+ }
614
+ }
615
+ }
616
+ /**
617
+ * Check importers recursively if it's an import loop. An accepted module within
618
+ * an import loop cannot recover its execution order and should be reloaded.
619
+ *
620
+ * @param node The node that accepts HMR and is a boundary
621
+ * @param nodeChain The chain of nodes/imports that lead to the node.
622
+ * (The last node in the chain imports the `node` parameter)
623
+ * @param currentChain The current chain tracked from the `node` parameter
624
+ * @param traversedModules The set of modules that have traversed
625
+ */
626
+ isNodeWithinCircularImports(node, nodeChain, currentChain = [node], traversedModules = /* @__PURE__ */ new Set()) {
627
+ if (traversedModules.has(node)) return false;
628
+ traversedModules.add(node);
629
+ for (const importer of this.runtime.getImporters(node)) {
630
+ if (importer === node) continue;
631
+ const importerIndex = nodeChain.indexOf(importer);
632
+ if (importerIndex > -1) {
633
+ const importChain = [
634
+ importer,
635
+ ...currentChain.toReversed(),
636
+ ...nodeChain.slice(importerIndex, -1).reverse()
637
+ ];
638
+ this.logger.debug(`circular imports detected: ${importChain.join(" -> ")}`);
639
+ return true;
640
+ }
641
+ if (!currentChain.includes(importer)) {
642
+ const result = this.isNodeWithinCircularImports(importer, nodeChain, [...currentChain, importer], traversedModules);
643
+ if (result) return result;
644
+ }
645
+ }
646
+ return false;
647
+ }
648
+ handlePush(payload) {
649
+ this.applyQueue = this.applyQueue.then(() => this.applyPush(payload)).catch((err) => {
650
+ this.warnFailedUpdate(err, payload.changedIds);
651
+ });
652
+ }
653
+ invalidateLocally(id, message) {
654
+ this.logger.debug(`invalidate ${id}${message ? `: ${message}` : ""}`);
655
+ this.applyQueue = this.applyQueue.then(() => this.applyInvalidate(id)).catch((err) => {
656
+ this.warnFailedUpdate(err, id);
657
+ });
658
+ }
659
+ handleModuleCacheRemoval(id) {
660
+ const disposer = this.disposeMap.get(id);
661
+ if (disposer) disposer(this.dataMap.get(id));
662
+ }
663
+ async applyPush({ changedIds, url, seq }) {
664
+ if (this.reloadPending) return;
665
+ if (seq !== this.lastSeq + 1) {
666
+ this.requestFullReload(`hmr update sequence gap (expected ${this.lastSeq + 1}, got ${seq})`);
667
+ return;
668
+ }
669
+ this.lastSeq = seq;
670
+ const update = this.computeHmrUpdate(changedIds);
671
+ if (update.type === "noop") return;
672
+ if (update.type === "full-reload") {
673
+ this.requestFullReload(update.reason);
674
+ return;
675
+ }
676
+ const listenerPayload = this.toUpdatePayload(update.boundaries, void 0);
677
+ await this.notifyListeners("vite:beforeUpdate", listenerPayload);
678
+ if (this.options.beforeApply() === "reload") return;
679
+ try {
680
+ await import(
681
+ /* @vite-ignore */
682
+ this.options.base + url
683
+ );
684
+ } catch {
685
+ this.requestFullReload(`failed to import hmr patch ${url}`);
686
+ return;
687
+ }
688
+ await this.applyUpdate(update);
689
+ await this.notifyListeners("vite:afterUpdate", listenerPayload);
690
+ }
691
+ async applyInvalidate(id) {
692
+ if (this.reloadPending) return;
693
+ const firstInvalidatedBy = this.currentFirstInvalidatedBy ?? id;
694
+ const importers = this.runtime.getImporters(id).filter((p) => this.runtime.isExecuted(p));
695
+ if (!importers.length) {
696
+ this.requestFullReload(`no importers to handle \`import.meta.hot.invalidate()\` called by \`${id}\``);
697
+ return;
698
+ }
699
+ const update = this.computeHmrUpdate(importers, { firstInvalidatedBy });
700
+ if (update.type === "noop") return;
701
+ if (update.type === "full-reload") {
702
+ this.requestFullReload(update.reason);
703
+ return;
704
+ }
705
+ const listenerPayload = this.toUpdatePayload(update.boundaries, firstInvalidatedBy);
706
+ await this.notifyListeners("vite:beforeUpdate", listenerPayload);
707
+ if (this.options.beforeApply() === "reload") return;
708
+ await this.applyUpdate(update, firstInvalidatedBy);
709
+ await this.notifyListeners("vite:afterUpdate", listenerPayload);
710
+ }
711
+ async applyUpdate(update, firstInvalidatedBy) {
712
+ for (const id of update.updateSet) if (!this.runtime.hasFactory(id)) {
713
+ this.requestFullReload(`no factory for module \`${id}\``);
714
+ return;
715
+ }
716
+ const applies = update.boundaries.map(({ boundary, acceptedVia, isWithinCircularImport }) => ({
717
+ boundary,
718
+ acceptedVia,
719
+ isWithinCircularImport,
720
+ callbacks: this.hotModulesMap.get(boundary)?.callbacks.filter((c) => c.deps.includes(acceptedVia)) ?? []
721
+ }));
722
+ for (const id of update.updateSet) this.runtime.removeModuleCache(id);
723
+ for (const { boundary, acceptedVia, isWithinCircularImport, callbacks } of applies) {
724
+ let fresh;
725
+ try {
726
+ this.runtime.initModule(acceptedVia);
727
+ fresh = this.runtime.loadExports(acceptedVia);
728
+ } catch (err) {
729
+ if (isWithinCircularImport) {
730
+ this.requestFullReload(`${acceptedVia} failed to apply HMR as it's within a circular import. Reloading page to reset the execution order.`);
731
+ return;
732
+ }
733
+ throw err;
734
+ }
735
+ try {
736
+ this.currentFirstInvalidatedBy = firstInvalidatedBy;
737
+ for (const { deps, fn } of callbacks) fn(deps.map((dep) => dep === acceptedVia ? fresh : void 0));
738
+ } finally {
739
+ this.currentFirstInvalidatedBy = void 0;
740
+ }
741
+ this.logger.debug(`hot updated: ${boundary === acceptedVia ? boundary : `${acceptedVia} via ${boundary}`}`);
742
+ }
743
+ }
744
+ toUpdatePayload(boundaries, firstInvalidatedBy) {
745
+ return {
746
+ type: "update",
747
+ updates: boundaries.map(({ boundary, acceptedVia, isWithinCircularImport }) => ({
748
+ type: "js-update",
749
+ path: boundary,
750
+ acceptedPath: acceptedVia,
751
+ timestamp: Date.now(),
752
+ isWithinCircularImport,
753
+ firstInvalidatedBy
754
+ }))
755
+ };
756
+ }
757
+ requestFullReload(reason) {
758
+ if (this.reloadPending) return;
759
+ this.reloadPending = true;
760
+ this.logger.debug(`full reload needed: ${reason}`);
761
+ this.send({
762
+ type: "custom",
763
+ event: "vite:bundled-dev:reload-needed",
764
+ data: { reason }
765
+ });
766
+ }
767
+ };
768
+ var BundledDevHMRContext = class extends HMRContext {
769
+ constructor(bundledDevClient, owner) {
770
+ super(bundledDevClient, owner);
771
+ this.bundledDevClient = bundledDevClient;
772
+ this.owner = owner;
773
+ }
774
+ invalidate(message) {
775
+ this.bundledDevClient.notifyListeners("vite:invalidate", {
776
+ path: this.owner,
777
+ message,
778
+ firstInvalidatedBy: this.bundledDevClient.currentFirstInvalidatedBy ?? this.owner
779
+ });
780
+ this.bundledDevClient.invalidateLocally(this.owner, message);
781
+ }
782
+ };
783
+ //#endregion
784
+ //#region src/shared/constants.ts
785
+ /**
786
+ * Prefix for resolved Ids that are not valid browser import specifiers
787
+ */
788
+ const VALID_ID_PREFIX = `/@id/`;
789
+ /**
790
+ * Plugins that use 'virtual modules' (e.g. for helper functions), prefix the
791
+ * module ID with `\0`, a convention from the rollup ecosystem.
792
+ * This prevents other plugins from trying to process the id (like node resolution),
793
+ * and core features like sourcemaps can use this info to differentiate between
794
+ * virtual modules and regular files.
795
+ * `\0` is not a permitted char in import URLs so we have to replace them during
796
+ * import analysis. The id will be decoded back before entering the plugins pipeline.
797
+ * These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual
798
+ * modules in the browser end up encoded as `/@id/__x00__{id}`
799
+ */
800
+ const NULL_BYTE_PLACEHOLDER = `__x00__`;
801
+ let SOURCEMAPPING_URL = "sourceMa";
802
+ SOURCEMAPPING_URL += "ppingURL";
803
+ typeof process !== "undefined" && process.platform;
804
+ /**
805
+ * Prepend `/@id/` and replace null byte so the id is URL-safe.
806
+ * This is prepended to resolved ids that are not valid browser
807
+ * import specifiers by the importAnalysis plugin.
808
+ */
809
+ function wrapId(id) {
810
+ return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
811
+ }
812
+ (async function() {}).constructor;
813
+ function promiseWithResolvers() {
814
+ let resolve;
815
+ let reject;
816
+ return {
817
+ promise: new Promise((_resolve, _reject) => {
818
+ resolve = _resolve;
819
+ reject = _reject;
820
+ }),
821
+ resolve,
822
+ reject
823
+ };
824
+ }
825
+ //#endregion
826
+ //#region src/shared/moduleRunnerTransport.ts
827
+ function reviveInvokeError(e) {
828
+ const error = new Error(e.message || "Unknown invoke error");
829
+ Object.assign(error, e, { runnerError: /* @__PURE__ */ new Error("RunnerError") });
830
+ return error;
831
+ }
832
+ const createInvokeableTransport = (transport) => {
833
+ if (transport.invoke) return {
834
+ ...transport,
835
+ async invoke(name, data) {
836
+ const result = await transport.invoke({
837
+ type: "custom",
838
+ event: "vite:invoke",
839
+ data: {
840
+ id: "send",
841
+ name,
842
+ data
843
+ }
844
+ });
845
+ if ("error" in result) throw reviveInvokeError(result.error);
846
+ return result.result;
847
+ }
848
+ };
849
+ if (!transport.send || !transport.connect) throw new Error("transport must implement send and connect when invoke is not implemented");
850
+ const rpcPromises = /* @__PURE__ */ new Map();
851
+ return {
852
+ ...transport,
853
+ connect({ onMessage, onDisconnection }) {
854
+ return transport.connect({
855
+ onMessage(payload) {
856
+ if (payload.type === "custom" && payload.event === "vite:invoke") {
857
+ const data = payload.data;
858
+ if (data.id.startsWith("response:")) {
859
+ const invokeId = data.id.slice(9);
860
+ const promise = rpcPromises.get(invokeId);
861
+ if (!promise) return;
862
+ if (promise.timeoutId) clearTimeout(promise.timeoutId);
863
+ rpcPromises.delete(invokeId);
864
+ const { error, result } = data.data;
865
+ if (error) promise.reject(error);
866
+ else promise.resolve(result);
867
+ return;
868
+ }
869
+ }
870
+ onMessage(payload);
871
+ },
872
+ onDisconnection
873
+ });
874
+ },
875
+ disconnect() {
876
+ rpcPromises.forEach((promise) => {
877
+ promise.reject(/* @__PURE__ */ new Error(`transport was disconnected, cannot call ${JSON.stringify(promise.name)}`));
878
+ });
879
+ rpcPromises.clear();
880
+ return transport.disconnect?.();
881
+ },
882
+ send(data) {
883
+ return transport.send(data);
884
+ },
885
+ async invoke(name, data) {
886
+ const promiseId = nanoid();
887
+ const wrappedData = {
888
+ type: "custom",
889
+ event: "vite:invoke",
890
+ data: {
891
+ name,
892
+ id: `send:${promiseId}`,
893
+ data
894
+ }
895
+ };
896
+ const sendPromise = transport.send(wrappedData);
897
+ const { promise, resolve, reject } = promiseWithResolvers();
898
+ const timeout = transport.timeout ?? 6e4;
899
+ let timeoutId;
900
+ if (timeout > 0) {
901
+ timeoutId = setTimeout(() => {
902
+ rpcPromises.delete(promiseId);
903
+ reject(/* @__PURE__ */ new Error(`transport invoke timed out after ${timeout}ms (data: ${JSON.stringify(wrappedData)})`));
904
+ }, timeout);
905
+ timeoutId?.unref?.();
906
+ }
907
+ rpcPromises.set(promiseId, {
908
+ resolve,
909
+ reject,
910
+ name,
911
+ timeoutId
912
+ });
913
+ if (sendPromise) sendPromise.catch((err) => {
914
+ clearTimeout(timeoutId);
915
+ rpcPromises.delete(promiseId);
916
+ reject(err);
917
+ });
918
+ try {
919
+ return await promise;
920
+ } catch (err) {
921
+ throw reviveInvokeError(err);
922
+ }
923
+ }
924
+ };
925
+ };
926
+ const normalizeModuleRunnerTransport = (transport) => {
927
+ const invokeableTransport = createInvokeableTransport(transport);
928
+ let isConnected = !invokeableTransport.connect;
929
+ let connectingPromise;
930
+ return {
931
+ ...transport,
932
+ ...invokeableTransport.connect ? { async connect(onMessage) {
933
+ if (isConnected) return;
934
+ if (connectingPromise) {
935
+ await connectingPromise;
936
+ return;
937
+ }
938
+ const maybePromise = invokeableTransport.connect({
939
+ onMessage: onMessage ?? (() => {}),
940
+ onDisconnection() {
941
+ isConnected = false;
942
+ }
943
+ });
944
+ if (maybePromise) {
945
+ connectingPromise = maybePromise;
946
+ await connectingPromise;
947
+ connectingPromise = void 0;
948
+ }
949
+ isConnected = true;
950
+ } } : {},
951
+ ...invokeableTransport.disconnect ? { async disconnect() {
952
+ if (!isConnected) return;
953
+ if (connectingPromise) await connectingPromise;
954
+ isConnected = false;
955
+ await invokeableTransport.disconnect();
956
+ } } : {},
957
+ async send(data) {
958
+ if (!invokeableTransport.send) return;
959
+ if (!isConnected) {
960
+ if (connectingPromise) await connectingPromise;
961
+ else throw new SendBeforeConnectError("send was called before connect");
962
+ }
963
+ await invokeableTransport.send(data);
964
+ },
965
+ async invoke(name, data) {
966
+ if (!isConnected) {
967
+ if (connectingPromise) await connectingPromise;
968
+ else throw new SendBeforeConnectError("invoke was called before connect");
969
+ }
970
+ return invokeableTransport.invoke(name, data);
971
+ }
972
+ };
973
+ };
974
+ var SendBeforeConnectError = class extends Error {
975
+ constructor(message) {
976
+ super(message);
977
+ this.name = "SendBeforeConnectError";
978
+ }
979
+ };
980
+ const createWebSocketModuleRunnerTransport = (options) => {
981
+ const pingInterval = options.pingInterval ?? 3e4;
982
+ let ws;
983
+ let pingIntervalId;
984
+ return {
985
+ async connect({ onMessage, onDisconnection }) {
986
+ const socket = options.createConnection();
987
+ socket.addEventListener("message", ({ data }) => {
988
+ onMessage(JSON.parse(data));
989
+ });
990
+ let isOpened = socket.readyState === socket.OPEN;
991
+ if (!isOpened) await new Promise((resolve, reject) => {
992
+ socket.addEventListener("open", () => {
993
+ isOpened = true;
994
+ resolve();
995
+ }, { once: true });
996
+ socket.addEventListener("close", () => {
997
+ if (!isOpened) {
998
+ reject(/* @__PURE__ */ new Error("WebSocket closed without opened."));
999
+ return;
1000
+ }
1001
+ onMessage({
1002
+ type: "custom",
1003
+ event: "vite:ws:disconnect",
1004
+ data: { webSocket: socket }
1005
+ });
1006
+ onDisconnection();
1007
+ });
1008
+ });
1009
+ onMessage({
1010
+ type: "custom",
1011
+ event: "vite:ws:connect",
1012
+ data: { webSocket: socket }
1013
+ });
1014
+ ws = socket;
1015
+ pingIntervalId = setInterval(() => {
1016
+ if (socket.readyState === socket.OPEN) socket.send(JSON.stringify({ type: "ping" }));
1017
+ }, pingInterval);
1018
+ },
1019
+ disconnect() {
1020
+ clearInterval(pingIntervalId);
1021
+ ws?.close();
1022
+ },
1023
+ send(data) {
1024
+ ws.send(JSON.stringify(data));
1025
+ }
1026
+ };
1027
+ };
1028
+ //#endregion
1029
+ //#region src/shared/forwardConsole.ts
1030
+ function setupForwardConsoleHandler(transport, options, console = globalThis.console) {
1031
+ if (!options.enabled) return;
1032
+ async function sendError(type, error) {
1033
+ await transport.send({
1034
+ type: "custom",
1035
+ event: "vite:forward-console",
1036
+ data: {
1037
+ type,
1038
+ data: {
1039
+ name: error?.name || "Unknown Error",
1040
+ message: error?.message || String(error),
1041
+ stack: error?.stack
1042
+ }
1043
+ }
1044
+ });
1045
+ }
1046
+ async function sendLog(level, args) {
1047
+ try {
1048
+ await transport.send({
1049
+ type: "custom",
1050
+ event: "vite:forward-console",
1051
+ data: {
1052
+ type: "log",
1053
+ data: {
1054
+ level,
1055
+ message: formatConsoleArgs(args)
1056
+ }
1057
+ }
1058
+ });
1059
+ } catch (err) {
1060
+ try {
1061
+ await sendError("unhandled-rejection", err);
1062
+ } catch (err) {
1063
+ if (!(err instanceof SendBeforeConnectError)) originalConsoleError("Failed to send error to Vite server:", err);
1064
+ }
1065
+ }
1066
+ }
1067
+ const originalConsoleError = console.error;
1068
+ for (const level of options.logLevels) {
1069
+ const original = console[level];
1070
+ if (typeof original !== "function") continue;
1071
+ console[level] = (...args) => {
1072
+ original(...args);
1073
+ sendLog(level, args);
1074
+ };
1075
+ }
1076
+ if (options.unhandledErrors && typeof window !== "undefined") {
1077
+ window.addEventListener("error", async (event) => {
1078
+ const error = event.error ?? (event.message ? new Error(event.message) : event);
1079
+ try {
1080
+ await sendError("error", error);
1081
+ } catch (err) {
1082
+ if (!(err instanceof SendBeforeConnectError)) originalConsoleError("Failed to send error to Vite server:", err);
1083
+ }
1084
+ });
1085
+ window.addEventListener("unhandledrejection", async (event) => {
1086
+ try {
1087
+ await sendError("unhandled-rejection", event.reason);
1088
+ } catch (err) {
1089
+ if (!(err instanceof SendBeforeConnectError)) originalConsoleError("Failed to send error to Vite server:", err);
1090
+ }
1091
+ });
1092
+ }
1093
+ }
1094
+ function formatConsoleArgs(args) {
1095
+ if (args.length === 0) return "";
1096
+ if (typeof args[0] !== "string") return args.map((arg) => stringifyConsoleArg(arg)).join(" ");
1097
+ const len = args.length;
1098
+ let i = 1;
1099
+ let message = args[0].replace(/%[sdjifoOc%]/g, (specifier) => {
1100
+ if (specifier === "%%") return "%";
1101
+ if (i >= len) return specifier;
1102
+ const arg = args[i++];
1103
+ switch (specifier) {
1104
+ case "%s":
1105
+ if (typeof arg === "bigint") return `${arg.toString()}n`;
1106
+ return typeof arg === "object" && arg != null ? stringifyConsoleArg(arg) : String(arg);
1107
+ case "%d":
1108
+ if (typeof arg === "bigint") return `${arg.toString()}n`;
1109
+ if (typeof arg === "symbol") return "NaN";
1110
+ return Number(arg).toString();
1111
+ case "%i":
1112
+ if (typeof arg === "bigint") return `${arg.toString()}n`;
1113
+ return Number.parseInt(String(arg), 10).toString();
1114
+ case "%f": return Number.parseFloat(String(arg)).toString();
1115
+ case "%o":
1116
+ case "%O": return stringifyConsoleArg(arg);
1117
+ case "%j": try {
1118
+ return JSON.stringify(arg) ?? "undefined";
1119
+ } catch {
1120
+ return "[Circular]";
1121
+ }
1122
+ case "%c": return "";
1123
+ default: return specifier;
1124
+ }
1125
+ });
1126
+ for (let arg = args[i]; i < len; arg = args[++i]) if (arg == null || typeof arg !== "object") message += ` ${typeof arg === "symbol" ? arg.toString() : String(arg)}`;
1127
+ else message += ` ${stringifyConsoleArg(arg)}`;
1128
+ return message;
1129
+ }
1130
+ function stringifyConsoleArg(value) {
1131
+ if (typeof value === "string") return value;
1132
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "undefined") return String(value);
1133
+ if (typeof value === "symbol") return value.toString();
1134
+ if (typeof value === "function") return value.name ? `[Function: ${value.name}]` : "[Function]";
1135
+ if (value instanceof Error) return value.stack || `${value.name}: ${value.message}`;
1136
+ if (typeof value === "bigint") return `${value}n`;
1137
+ const seen = /* @__PURE__ */ new WeakSet();
1138
+ try {
1139
+ return JSON.stringify(value, (_, nested) => {
1140
+ if (typeof nested === "bigint") return `${nested}n`;
1141
+ if (nested instanceof Error) return {
1142
+ name: nested.name,
1143
+ message: nested.message,
1144
+ stack: nested.stack
1145
+ };
1146
+ if (nested && typeof nested === "object") {
1147
+ if (seen.has(nested)) return "[Circular]";
1148
+ seen.add(nested);
1149
+ }
1150
+ return nested;
1151
+ }) ?? String(value);
1152
+ } catch {
1153
+ return String(value);
1154
+ }
1155
+ }
1156
+ //#endregion
1157
+ //#region src/shared/hmrHandler.ts
1158
+ function createHMRHandler(handler) {
1159
+ const queue = new Queue();
1160
+ return (payload) => queue.enqueue(() => handler(payload));
1161
+ }
1162
+ var Queue = class {
1163
+ constructor() {
1164
+ _defineProperty(this, "queue", []);
1165
+ _defineProperty(this, "pending", false);
1166
+ }
1167
+ enqueue(promise) {
1168
+ return new Promise((resolve, reject) => {
1169
+ this.queue.push({
1170
+ promise,
1171
+ resolve,
1172
+ reject
1173
+ });
1174
+ this.dequeue();
1175
+ });
1176
+ }
1177
+ dequeue() {
1178
+ if (this.pending) return false;
1179
+ const item = this.queue.shift();
1180
+ if (!item) return false;
1181
+ this.pending = true;
1182
+ item.promise().then(item.resolve).catch(item.reject).finally(() => {
1183
+ this.pending = false;
1184
+ this.dequeue();
1185
+ });
1186
+ return true;
1187
+ }
1188
+ };
1189
+ //#endregion
1190
+ //#region src/client/overlay.ts
1191
+ const hmrConfigName = __HMR_CONFIG_NAME__;
1192
+ const base$1 = __BASE__ || "/";
1193
+ const cspNonce = "document" in globalThis ? document.querySelector("meta[property=csp-nonce]")?.nonce : void 0;
1194
+ function h(e, attrs = {}, ...children) {
1195
+ const elem = document.createElement(e);
1196
+ for (const [k, v] of Object.entries(attrs)) if (v !== void 0) elem.setAttribute(k, v);
1197
+ elem.append(...children);
1198
+ return elem;
1199
+ }
1200
+ const templateStyle = `
1201
+ :host {
1202
+ position: fixed;
1203
+ top: 0;
1204
+ left: 0;
1205
+ width: 100%;
1206
+ height: 100%;
1207
+ z-index: 99999;
1208
+ --monospace: 'SFMono-Regular', Consolas,
1209
+ 'Liberation Mono', Menlo, Courier, monospace;
1210
+ --red: #ff5555;
1211
+ --yellow: #e2aa53;
1212
+ --purple: #cfa4ff;
1213
+ --cyan: #2dd9da;
1214
+ --dim: #c9c9c9;
1215
+
1216
+ --window-background: #181818;
1217
+ --window-color: #d8d8d8;
1218
+ }
1219
+
1220
+ .backdrop {
1221
+ position: fixed;
1222
+ z-index: 99999;
1223
+ top: 0;
1224
+ left: 0;
1225
+ width: 100%;
1226
+ height: 100%;
1227
+ overflow-y: scroll;
1228
+ margin: 0;
1229
+ background: rgba(0, 0, 0, 0.66);
1230
+ }
1231
+
1232
+ .window {
1233
+ font-family: var(--monospace);
1234
+ line-height: 1.5;
1235
+ max-width: 80vw;
1236
+ color: var(--window-color);
1237
+ box-sizing: border-box;
1238
+ margin: 30px auto;
1239
+ padding: 2.5vh 4vw;
1240
+ position: relative;
1241
+ background: var(--window-background);
1242
+ border-radius: 6px 6px 8px 8px;
1243
+ box-shadow: 0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0,0,0,0.22);
1244
+ overflow: hidden;
1245
+ border-top: 8px solid var(--red);
1246
+ direction: ltr;
1247
+ text-align: left;
1248
+ }
1249
+
1250
+ pre {
1251
+ font-family: var(--monospace);
1252
+ font-size: 16px;
1253
+ margin-top: 0;
1254
+ margin-bottom: 1em;
1255
+ overflow-x: scroll;
1256
+ scrollbar-width: none;
1257
+ }
1258
+
1259
+ pre::-webkit-scrollbar {
1260
+ display: none;
1261
+ }
1262
+
1263
+ pre.frame::-webkit-scrollbar {
1264
+ display: block;
1265
+ height: 5px;
1266
+ }
1267
+
1268
+ pre.frame::-webkit-scrollbar-thumb {
1269
+ background: #999;
1270
+ border-radius: 5px;
1271
+ }
1272
+
1273
+ pre.frame {
1274
+ scrollbar-width: thin;
1275
+ }
1276
+
1277
+ .message {
1278
+ line-height: 1.3;
1279
+ font-weight: 400;
1280
+ white-space: pre-wrap;
1281
+ }
1282
+
1283
+ .message-body {
1284
+ color: var(--red);
1285
+ }
1286
+
1287
+ .plugin {
1288
+ color: var(--purple);
1289
+ }
1290
+
1291
+ .file {
1292
+ color: var(--cyan);
1293
+ margin-bottom: 0;
1294
+ white-space: pre-wrap;
1295
+ word-break: break-all;
1296
+ }
1297
+
1298
+ .frame {
1299
+ color: var(--yellow);
1300
+ }
1301
+
1302
+ .stack {
1303
+ font-size: 13px;
1304
+ color: var(--dim);
1305
+ }
1306
+
1307
+ .tip {
1308
+ font-size: 13px;
1309
+ color: #999;
1310
+ border-top: 1px dotted #999;
1311
+ padding-top: 13px;
1312
+ line-height: 1.8;
1313
+ }
1314
+
1315
+ code {
1316
+ font-size: 13px;
1317
+ font-family: var(--monospace);
1318
+ color: var(--yellow);
1319
+ }
1320
+
1321
+ .file-link {
1322
+ text-decoration: underline;
1323
+ cursor: pointer;
1324
+ }
1325
+
1326
+ kbd {
1327
+ line-height: 1.5;
1328
+ font-family: ui-monospace, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
1329
+ font-size: 0.75rem;
1330
+ font-weight: 700;
1331
+ background-color: rgb(38, 40, 44);
1332
+ color: rgb(166, 167, 171);
1333
+ padding: 0.15rem 0.3rem;
1334
+ border-radius: 0.25rem;
1335
+ border-width: 0.0625rem 0.0625rem 0.1875rem;
1336
+ border-style: solid;
1337
+ border-color: rgb(54, 57, 64);
1338
+ border-image: initial;
1339
+ }
1340
+ `;
1341
+ const createTemplate = () => h("div", {
1342
+ class: "backdrop",
1343
+ part: "backdrop"
1344
+ }, h("div", {
1345
+ class: "window",
1346
+ part: "window"
1347
+ }, h("pre", {
1348
+ class: "message",
1349
+ part: "message"
1350
+ }, h("span", {
1351
+ class: "plugin",
1352
+ part: "plugin"
1353
+ }), h("span", {
1354
+ class: "message-body",
1355
+ part: "message-body"
1356
+ })), h("pre", {
1357
+ class: "file",
1358
+ part: "file"
1359
+ }), h("pre", {
1360
+ class: "frame",
1361
+ part: "frame"
1362
+ }), h("pre", {
1363
+ class: "stack",
1364
+ part: "stack"
1365
+ }), h("div", {
1366
+ class: "tip",
1367
+ part: "tip"
1368
+ }, "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));
1369
+ const fileRE = /(?:file:\/\/)?(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g;
1370
+ const codeframeRE = /^(?:>?\s*\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm;
1371
+ const { HTMLElement = class {} } = globalThis;
1372
+ var ErrorOverlay = class extends HTMLElement {
1373
+ constructor(err, links = true) {
1374
+ super();
1375
+ this.root = this.attachShadow({ mode: "open" });
1376
+ this.root.appendChild(createTemplate());
1377
+ codeframeRE.lastIndex = 0;
1378
+ const hasFrame = err.frame && codeframeRE.test(err.frame);
1379
+ const message = hasFrame ? err.message.replace(codeframeRE, "") : err.message;
1380
+ if (err.plugin) this.text(".plugin", `[plugin:${err.plugin}] `);
1381
+ this.text(".message-body", message.trim());
1382
+ const [file] = (err.loc?.file || err.id || "unknown file").split(`?`);
1383
+ if (err.loc) this.text(".file", `${file}:${err.loc.line}:${err.loc.column}`, links);
1384
+ else if (err.id) this.text(".file", file);
1385
+ if (hasFrame) this.text(".frame", err.frame.trim());
1386
+ this.text(".stack", err.stack, links);
1387
+ this.root.querySelector(".window").addEventListener("click", (e) => {
1388
+ e.stopPropagation();
1389
+ });
1390
+ this.addEventListener("click", () => {
1391
+ this.close();
1392
+ });
1393
+ this.closeOnEsc = (e) => {
1394
+ if (e.key === "Escape" || e.code === "Escape") this.close();
1395
+ };
1396
+ document.addEventListener("keydown", this.closeOnEsc);
1397
+ }
1398
+ text(selector, text, linkFiles = false) {
1399
+ const el = this.root.querySelector(selector);
1400
+ if (!linkFiles) el.textContent = text;
1401
+ else {
1402
+ let curIndex = 0;
1403
+ let match;
1404
+ fileRE.lastIndex = 0;
1405
+ while (match = fileRE.exec(text)) {
1406
+ const { 0: file, index } = match;
1407
+ const frag = text.slice(curIndex, index);
1408
+ el.appendChild(document.createTextNode(frag));
1409
+ const link = document.createElement("a");
1410
+ link.textContent = file;
1411
+ link.className = "file-link";
1412
+ link.onclick = () => {
1413
+ fetch(new URL(`${base$1}__open-in-editor?file=${encodeURIComponent(file)}`, import.meta.url));
1414
+ };
1415
+ el.appendChild(link);
1416
+ curIndex += frag.length + file.length;
1417
+ }
1418
+ if (curIndex < text.length) el.appendChild(document.createTextNode(text.slice(curIndex)));
1419
+ }
1420
+ }
1421
+ close() {
1422
+ this.parentNode?.removeChild(this);
1423
+ document.removeEventListener("keydown", this.closeOnEsc);
1424
+ }
1425
+ };
1426
+ const overlayId = "vite-error-overlay";
1427
+ const { customElements } = globalThis;
1428
+ if (customElements && !customElements.get("vite-error-overlay")) customElements.define(overlayId, ErrorOverlay);
1429
+ //#endregion
1430
+ //#region src/client/client.ts
1431
+ console.debug("[vite] connecting...");
1432
+ const importMetaUrl = new URL(import.meta.url);
1433
+ const serverHost = __SERVER_HOST__;
1434
+ const socketProtocol = __HMR_PROTOCOL__ || (importMetaUrl.protocol === "https:" ? "wss" : "ws");
1435
+ const hmrPort = __HMR_PORT__;
1436
+ const socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${hmrPort || importMetaUrl.port}${__HMR_BASE__}`;
1437
+ const directSocketHost = __HMR_DIRECT_TARGET__;
1438
+ const base = __BASE__ || "/";
1439
+ const hmrTimeout = __HMR_TIMEOUT__;
1440
+ const wsToken = __WS_TOKEN__;
1441
+ const forwardConsole = __SERVER_FORWARD_CONSOLE__;
1442
+ const transport = normalizeModuleRunnerTransport((() => {
1443
+ let wsTransport = createWebSocketModuleRunnerTransport({
1444
+ createConnection: () => new WebSocket(`${socketProtocol}://${socketHost}?token=${wsToken}`, "vite-hmr"),
1445
+ pingInterval: hmrTimeout
1446
+ });
1447
+ return {
1448
+ async connect(handlers) {
1449
+ try {
1450
+ await wsTransport.connect(handlers);
1451
+ } catch (e) {
1452
+ if (!hmrPort) {
1453
+ wsTransport = createWebSocketModuleRunnerTransport({
1454
+ createConnection: () => new WebSocket(`${socketProtocol}://${directSocketHost}?token=${wsToken}`, "vite-hmr"),
1455
+ pingInterval: hmrTimeout
1456
+ });
1457
+ try {
1458
+ await wsTransport.connect(handlers);
1459
+ console.info("[vite] Direct websocket connection fallback. Check out https://vite.dev/config/server-options.html#server-hmr to remove the previous connection error.");
1460
+ } catch (e) {
1461
+ if (e instanceof Error && e.message.includes("WebSocket closed without opened.")) {
1462
+ const currentScriptHostURL = new URL(import.meta.url);
1463
+ const currentScriptHost = currentScriptHostURL.host + currentScriptHostURL.pathname.replace(/@vite\/client$/, "");
1464
+ console.error(`[vite] failed to connect to websocket.
1465
+ your current setup:
1466
+ (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 .`);
1467
+ }
1468
+ }
1469
+ return;
1470
+ }
1471
+ console.error(`[vite] failed to connect to websocket (${e}). `);
1472
+ throw e;
1473
+ }
1474
+ },
1475
+ async disconnect() {
1476
+ await wsTransport.disconnect();
1477
+ },
1478
+ send(data) {
1479
+ wsTransport.send(data);
1480
+ }
1481
+ };
1482
+ })());
1483
+ let willUnload = false;
1484
+ if (typeof window !== "undefined") window.addEventListener?.("beforeunload", () => {
1485
+ willUnload = true;
1486
+ });
1487
+ function cleanUrl(pathname) {
1488
+ const url = new URL(pathname, "http://vite.dev");
1489
+ url.searchParams.delete("direct");
1490
+ return url.pathname + url.search;
1491
+ }
1492
+ let isFirstUpdate = true;
1493
+ const outdatedLinkTags = /* @__PURE__ */ new WeakSet();
1494
+ const debounceReload = (time) => {
1495
+ let timer;
1496
+ return () => {
1497
+ if (timer) {
1498
+ clearTimeout(timer);
1499
+ timer = null;
1500
+ }
1501
+ timer = setTimeout(() => {
1502
+ location.reload();
1503
+ }, time);
1504
+ };
1505
+ };
1506
+ const pageReload = debounceReload(20);
1507
+ function wrapIdIfNeeded(id) {
1508
+ return id[0] === "." || id[0] === "/" ? id : wrapId(id);
1509
+ }
1510
+ const hmrClient = new HMRClient({
1511
+ error: (err) => console.error("[vite]", err),
1512
+ debug: (...msg) => console.debug("[vite]", ...msg)
1513
+ }, transport, async function importUpdatedModule({ acceptedPath, timestamp, explicitImportRequired, isWithinCircularImport }) {
1514
+ const [acceptedPathWithoutQuery, query] = acceptedPath.split(`?`);
1515
+ const browserPath = wrapIdIfNeeded(acceptedPathWithoutQuery);
1516
+ const importPromise = import(
1517
+ /* @vite-ignore */
1518
+ base + browserPath.slice(1) + `?${explicitImportRequired ? "import&" : ""}t=${timestamp}${query ? `&${query}` : ""}`
1519
+ );
1520
+ if (isWithinCircularImport) importPromise.catch(() => {
1521
+ 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.`);
1522
+ pageReload();
1523
+ });
1524
+ return await importPromise;
1525
+ });
1526
+ let bundledDevClient;
1527
+ function registerBundledDevClient(client) {
1528
+ bundledDevClient = client;
1529
+ }
1530
+ transport.connect(createHMRHandler(handleMessage));
1531
+ setupForwardConsoleHandler(transport, forwardConsole);
1532
+ function clearOverlayOrReloadOnFirstUpdate() {
1533
+ if (hasDocument) {
1534
+ if (isFirstUpdate && hasErrorOverlay()) {
1535
+ location.reload();
1536
+ return "reload";
1537
+ }
1538
+ if (enableOverlay) clearErrorOverlay();
1539
+ isFirstUpdate = false;
1540
+ }
1541
+ return "continue";
1542
+ }
1543
+ async function handleMessage(payload) {
1544
+ const activeHmrClient = bundledDevClient ?? hmrClient;
1545
+ switch (payload.type) {
1546
+ case "connected":
1547
+ console.debug(`[vite] connected.`);
1548
+ break;
1549
+ case "bundled-dev-update":
1550
+ bundledDevClient.handlePush(payload);
1551
+ break;
1552
+ case "update":
1553
+ await activeHmrClient.notifyListeners("vite:beforeUpdate", payload);
1554
+ if (clearOverlayOrReloadOnFirstUpdate() === "reload") return;
1555
+ await Promise.all(payload.updates.map(async (update) => {
1556
+ if (update.type === "js-update") return hmrClient.queueUpdate(update);
1557
+ const { path, timestamp } = update;
1558
+ const searchUrl = cleanUrl(path);
1559
+ const el = Array.from(document.querySelectorAll("link")).find((e) => !outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl));
1560
+ if (!el) return;
1561
+ const newPath = `${base}${searchUrl.slice(1)}${searchUrl.includes("?") ? "&" : "?"}t=${timestamp}`;
1562
+ return new Promise((resolve) => {
1563
+ const newLinkTag = el.cloneNode();
1564
+ newLinkTag.href = new URL(newPath, el.href).href;
1565
+ const removeOldEl = () => {
1566
+ el.remove();
1567
+ console.debug(`[vite] css hot updated: ${searchUrl}`);
1568
+ resolve();
1569
+ };
1570
+ newLinkTag.addEventListener("load", removeOldEl);
1571
+ newLinkTag.addEventListener("error", removeOldEl);
1572
+ outdatedLinkTags.add(el);
1573
+ el.after(newLinkTag);
1574
+ });
1575
+ }));
1576
+ await activeHmrClient.notifyListeners("vite:afterUpdate", payload);
1577
+ break;
1578
+ case "custom":
1579
+ await activeHmrClient.notifyListeners(payload.event, payload.data);
1580
+ if (payload.event === "vite:ws:disconnect") {
1581
+ if (hasDocument && !willUnload) {
1582
+ console.log(`[vite] server connection lost. Polling for restart...`);
1583
+ const socket = payload.data.webSocket;
1584
+ const url = new URL(socket.url);
1585
+ url.search = "";
1586
+ await waitForSuccessfulPing(url.href);
1587
+ location.reload();
1588
+ }
1589
+ }
1590
+ break;
1591
+ case "full-reload":
1592
+ if (payload.ifFallback && !globalThis.__vite_is_fallback_page__) break;
1593
+ await activeHmrClient.notifyListeners("vite:beforeFullReload", payload);
1594
+ if (hasDocument) {
1595
+ if (payload.path && payload.path.endsWith(".html")) {
1596
+ const pagePath = decodeURI(location.pathname);
1597
+ const payloadPath = base + payload.path.slice(1);
1598
+ if (pagePath === payloadPath || payload.path === "/index.html" || pagePath.endsWith("/") && pagePath + "index.html" === payloadPath) pageReload();
1599
+ return;
1600
+ } else pageReload();
1601
+ }
1602
+ break;
1603
+ case "prune":
1604
+ await activeHmrClient.notifyListeners("vite:beforePrune", payload);
1605
+ await activeHmrClient.prunePaths(payload.paths);
1606
+ break;
1607
+ case "error":
1608
+ await activeHmrClient.notifyListeners("vite:error", payload);
1609
+ if (hasDocument) {
1610
+ const err = payload.err;
1611
+ if (enableOverlay) createErrorOverlay(err);
1612
+ else console.error(`[vite] Internal Server Error\n${err.message}\n${err.stack}`);
1613
+ }
1614
+ break;
1615
+ case "ping": break;
1616
+ default: return payload;
1617
+ }
1618
+ }
1619
+ const enableOverlay = __HMR_ENABLE_OVERLAY__;
1620
+ const hasDocument = "document" in globalThis;
1621
+ function createErrorOverlay(err) {
1622
+ clearErrorOverlay();
1623
+ const { customElements } = globalThis;
1624
+ if (customElements) {
1625
+ const ErrorOverlayConstructor = customElements.get(overlayId);
1626
+ document.body.appendChild(new ErrorOverlayConstructor(err));
1627
+ }
1628
+ }
1629
+ function clearErrorOverlay() {
1630
+ document.querySelectorAll(overlayId).forEach((n) => n.close());
1631
+ }
1632
+ function hasErrorOverlay() {
1633
+ return document.querySelectorAll(overlayId).length;
1634
+ }
1635
+ function waitForSuccessfulPing(socketUrl) {
1636
+ if (typeof SharedWorker === "undefined") {
1637
+ const visibilityManager = {
1638
+ currentState: document.visibilityState,
1639
+ listeners: /* @__PURE__ */ new Set()
1640
+ };
1641
+ const onVisibilityChange = () => {
1642
+ visibilityManager.currentState = document.visibilityState;
1643
+ for (const listener of visibilityManager.listeners) listener(visibilityManager.currentState);
1644
+ };
1645
+ document.addEventListener("visibilitychange", onVisibilityChange);
1646
+ return waitForSuccessfulPingInternal(socketUrl, visibilityManager);
1647
+ }
1648
+ const blob = new Blob([
1649
+ "\"use strict\";",
1650
+ `const waitForSuccessfulPingInternal = ${waitForSuccessfulPingInternal.toString()};`,
1651
+ `const fn = ${pingWorkerContentMain.toString()};`,
1652
+ `fn(${JSON.stringify(socketUrl)})`
1653
+ ], { type: "application/javascript" });
1654
+ const objURL = URL.createObjectURL(blob);
1655
+ const sharedWorker = new SharedWorker(objURL);
1656
+ return new Promise((resolve, reject) => {
1657
+ const onVisibilityChange = () => {
1658
+ sharedWorker.port.postMessage({ visibility: document.visibilityState });
1659
+ };
1660
+ document.addEventListener("visibilitychange", onVisibilityChange);
1661
+ sharedWorker.port.addEventListener("message", (event) => {
1662
+ document.removeEventListener("visibilitychange", onVisibilityChange);
1663
+ sharedWorker.port.close();
1664
+ const data = event.data;
1665
+ if (data.type === "error") {
1666
+ reject(data.error);
1667
+ return;
1668
+ }
1669
+ resolve();
1670
+ });
1671
+ onVisibilityChange();
1672
+ sharedWorker.port.start();
1673
+ });
1674
+ }
1675
+ function pingWorkerContentMain(socketUrl) {
1676
+ self.addEventListener("connect", (_event) => {
1677
+ const port = _event.ports[0];
1678
+ if (!socketUrl) {
1679
+ port.postMessage({
1680
+ type: "error",
1681
+ error: /* @__PURE__ */ new Error("socketUrl not found")
1682
+ });
1683
+ return;
1684
+ }
1685
+ const visibilityManager = {
1686
+ currentState: "visible",
1687
+ listeners: /* @__PURE__ */ new Set()
1688
+ };
1689
+ port.addEventListener("message", (event) => {
1690
+ const { visibility } = event.data;
1691
+ visibilityManager.currentState = visibility;
1692
+ console.debug("[vite] new window visibility", visibility);
1693
+ for (const listener of visibilityManager.listeners) listener(visibility);
1694
+ });
1695
+ port.start();
1696
+ console.debug("[vite] connected from window");
1697
+ waitForSuccessfulPingInternal(socketUrl, visibilityManager).then(() => {
1698
+ console.debug("[vite] ping successful");
1699
+ try {
1700
+ port.postMessage({ type: "success" });
1701
+ } catch (error) {
1702
+ port.postMessage({
1703
+ type: "error",
1704
+ error
1705
+ });
1706
+ }
1707
+ }, (error) => {
1708
+ console.debug("[vite] error happened", error);
1709
+ try {
1710
+ port.postMessage({
1711
+ type: "error",
1712
+ error
1713
+ });
1714
+ } catch (error) {
1715
+ port.postMessage({
1716
+ type: "error",
1717
+ error
1718
+ });
1719
+ }
1720
+ });
1721
+ });
1722
+ }
1723
+ async function waitForSuccessfulPingInternal(socketUrl, visibilityManager, ms = 1e3) {
1724
+ function wait(ms) {
1725
+ return new Promise((resolve) => setTimeout(resolve, ms));
1726
+ }
1727
+ async function ping() {
1728
+ try {
1729
+ const socket = new WebSocket(socketUrl, "vite-ping");
1730
+ return new Promise((resolve) => {
1731
+ function onOpen() {
1732
+ resolve(true);
1733
+ close();
1734
+ }
1735
+ function onError() {
1736
+ resolve(false);
1737
+ close();
1738
+ }
1739
+ function close() {
1740
+ socket.removeEventListener("open", onOpen);
1741
+ socket.removeEventListener("error", onError);
1742
+ socket.close();
1743
+ }
1744
+ socket.addEventListener("open", onOpen);
1745
+ socket.addEventListener("error", onError);
1746
+ });
1747
+ } catch {
1748
+ return false;
1749
+ }
1750
+ }
1751
+ function waitForWindowShow(visibilityManager) {
1752
+ return new Promise((resolve) => {
1753
+ const onChange = (newVisibility) => {
1754
+ if (newVisibility === "visible") {
1755
+ resolve();
1756
+ visibilityManager.listeners.delete(onChange);
1757
+ }
1758
+ };
1759
+ visibilityManager.listeners.add(onChange);
1760
+ });
1761
+ }
1762
+ if (await ping()) return;
1763
+ await wait(ms);
1764
+ while (true) if (visibilityManager.currentState === "visible") {
1765
+ if (await ping()) break;
1766
+ await wait(ms);
1767
+ } else await waitForWindowShow(visibilityManager);
1768
+ }
1769
+ const sheetsMap = /* @__PURE__ */ new Map();
1770
+ const linkSheetsMap = /* @__PURE__ */ new Map();
1771
+ if ("document" in globalThis) {
1772
+ document.querySelectorAll("style[data-vite-dev-id]").forEach((el) => {
1773
+ sheetsMap.set(el.getAttribute("data-vite-dev-id"), el);
1774
+ });
1775
+ document.querySelectorAll("link[rel=\"stylesheet\"][data-vite-dev-id]").forEach((el) => {
1776
+ linkSheetsMap.set(el.getAttribute("data-vite-dev-id"), el);
1777
+ });
1778
+ }
1779
+ let lastInsertedStyle;
1780
+ function updateStyle(id, content) {
1781
+ if (linkSheetsMap.has(id)) return;
1782
+ let style = sheetsMap.get(id);
1783
+ if (!style) {
1784
+ style = document.createElement("style");
1785
+ style.setAttribute("type", "text/css");
1786
+ style.setAttribute("data-vite-dev-id", id);
1787
+ style.textContent = content;
1788
+ if (cspNonce) style.setAttribute("nonce", cspNonce);
1789
+ if (!lastInsertedStyle) {
1790
+ document.head.appendChild(style);
1791
+ setTimeout(() => {
1792
+ lastInsertedStyle = void 0;
1793
+ }, 0);
1794
+ } else lastInsertedStyle.insertAdjacentElement("afterend", style);
1795
+ lastInsertedStyle = style;
1796
+ } else style.textContent = content;
1797
+ sheetsMap.set(id, style);
1798
+ }
1799
+ function removeStyle(id) {
1800
+ if (linkSheetsMap.has(id)) {
1801
+ document.querySelectorAll(`link[rel="stylesheet"][data-vite-dev-id="${CSS.escape(id)}"]`).forEach((el) => el.remove());
1802
+ linkSheetsMap.delete(id);
1803
+ }
1804
+ const style = sheetsMap.get(id);
1805
+ if (style) {
1806
+ document.head.removeChild(style);
1807
+ sheetsMap.delete(id);
1808
+ }
1809
+ }
1810
+ function createHotContext(ownerPath) {
1811
+ return new HMRContext(hmrClient, ownerPath);
1812
+ }
1813
+ /**
1814
+ * urls here are dynamic import() urls that couldn't be statically analyzed
1815
+ */
1816
+ function injectQuery(url, queryToInject) {
1817
+ if (url[0] !== "." && url[0] !== "/") return url;
1818
+ const pathname = url.replace(/[?#].*$/, "");
1819
+ const { search, hash } = new URL(url, "http://vite.dev");
1820
+ return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ""}${hash || ""}`;
1821
+ }
1822
+ //#endregion
1823
+ //#region src/client/bundledDevClient.ts
1824
+ if (typeof DevRuntime !== "undefined") {
1825
+ var _ref;
1826
+ class ViteDevRuntime extends DevRuntime {
1827
+ payloadDelivered(filename) {
1828
+ transport.send({
1829
+ type: "custom",
1830
+ event: "vite:bundled-dev:payload-delivered",
1831
+ data: { filename }
1832
+ });
1833
+ }
1834
+ createModuleHotContext(moduleId) {
1835
+ const ctx = new BundledDevHMRContext(bundledDevHmrClient, moduleId);
1836
+ ctx._internal = {
1837
+ updateStyle,
1838
+ removeStyle
1839
+ };
1840
+ return ctx;
1841
+ }
1842
+ }
1843
+ const clientId = nanoid();
1844
+ transport.send({
1845
+ type: "custom",
1846
+ event: "vite:client-connected",
1847
+ data: { clientId }
1848
+ });
1849
+ const runtime = (_ref = globalThis).__rolldown_runtime__ ?? (_ref.__rolldown_runtime__ = new ViteDevRuntime(clientId));
1850
+ const bundledDevHmrClient = new BundledDevHMRClient({
1851
+ error: (err) => console.error("[vite]", err),
1852
+ debug: (...msg) => console.debug("[vite]", ...msg)
1853
+ }, transport, runtime, {
1854
+ base,
1855
+ beforeApply: clearOverlayOrReloadOnFirstUpdate
1856
+ });
1857
+ registerBundledDevClient(bundledDevHmrClient);
1858
+ runtime.hooks = {
1859
+ createModuleHotContext: (id) => runtime.createModuleHotContext(id),
1860
+ onModuleCacheRemoval: (id) => bundledDevHmrClient.handleModuleCacheRemoval(id)
1861
+ };
1862
+ }
1863
+ //#endregion
1864
+ export { ErrorOverlay, createHotContext, injectQuery, removeStyle, updateStyle };