vite 6.0.0-alpha.2 → 6.0.0-alpha.20

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.
@@ -1,248 +1,246 @@
1
1
  import '@vite/env';
2
2
 
3
3
  class HMRContext {
4
- constructor(hmrClient, ownerPath) {
5
- this.hmrClient = hmrClient;
6
- this.ownerPath = ownerPath;
7
- if (!hmrClient.dataMap.has(ownerPath)) {
8
- hmrClient.dataMap.set(ownerPath, {});
4
+ constructor(hmrClient, ownerPath) {
5
+ this.hmrClient = hmrClient;
6
+ this.ownerPath = ownerPath;
7
+ if (!hmrClient.dataMap.has(ownerPath)) {
8
+ hmrClient.dataMap.set(ownerPath, {});
9
+ }
10
+ const mod = hmrClient.hotModulesMap.get(ownerPath);
11
+ if (mod) {
12
+ mod.callbacks = [];
13
+ }
14
+ const staleListeners = hmrClient.ctxToListenersMap.get(ownerPath);
15
+ if (staleListeners) {
16
+ for (const [event, staleFns] of staleListeners) {
17
+ const listeners = hmrClient.customListenersMap.get(event);
18
+ if (listeners) {
19
+ hmrClient.customListenersMap.set(
20
+ event,
21
+ listeners.filter((l) => !staleFns.includes(l))
22
+ );
9
23
  }
10
- // when a file is hot updated, a new context is created
11
- // clear its stale callbacks
12
- const mod = hmrClient.hotModulesMap.get(ownerPath);
13
- if (mod) {
14
- mod.callbacks = [];
15
- }
16
- // clear stale custom event listeners
17
- const staleListeners = hmrClient.ctxToListenersMap.get(ownerPath);
18
- if (staleListeners) {
19
- for (const [event, staleFns] of staleListeners) {
20
- const listeners = hmrClient.customListenersMap.get(event);
21
- if (listeners) {
22
- hmrClient.customListenersMap.set(event, listeners.filter((l) => !staleFns.includes(l)));
23
- }
24
- }
25
- }
26
- this.newListeners = new Map();
27
- hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
28
- }
29
- get data() {
30
- return this.hmrClient.dataMap.get(this.ownerPath);
31
- }
32
- accept(deps, callback) {
33
- if (typeof deps === 'function' || !deps) {
34
- // self-accept: hot.accept(() => {})
35
- this.acceptDeps([this.ownerPath], ([mod]) => deps === null || deps === void 0 ? void 0 : deps(mod));
36
- }
37
- else if (typeof deps === 'string') {
38
- // explicit deps
39
- this.acceptDeps([deps], ([mod]) => callback === null || callback === void 0 ? void 0 : callback(mod));
40
- }
41
- else if (Array.isArray(deps)) {
42
- this.acceptDeps(deps, callback);
43
- }
44
- else {
45
- throw new Error(`invalid hot.accept() usage.`);
46
- }
47
- }
48
- // export names (first arg) are irrelevant on the client side, they're
49
- // extracted in the server for propagation
50
- acceptExports(_, callback) {
51
- this.acceptDeps([this.ownerPath], ([mod]) => callback === null || callback === void 0 ? void 0 : callback(mod));
52
- }
53
- dispose(cb) {
54
- this.hmrClient.disposeMap.set(this.ownerPath, cb);
55
- }
56
- prune(cb) {
57
- this.hmrClient.pruneMap.set(this.ownerPath, cb);
58
- }
59
- // Kept for backward compatibility (#11036)
60
- // eslint-disable-next-line @typescript-eslint/no-empty-function
61
- decline() { }
62
- invalidate(message) {
63
- this.hmrClient.notifyListeners('vite:invalidate', {
64
- path: this.ownerPath,
65
- message,
66
- });
67
- this.send('vite:invalidate', {
68
- path: this.ownerPath,
69
- message,
70
- });
71
- this.hmrClient.logger.debug(`[vite] invalidate ${this.ownerPath}${message ? `: ${message}` : ''}`);
72
- }
73
- on(event, cb) {
74
- const addToMap = (map) => {
75
- const existing = map.get(event) || [];
76
- existing.push(cb);
77
- map.set(event, existing);
78
- };
79
- addToMap(this.hmrClient.customListenersMap);
80
- addToMap(this.newListeners);
81
- }
82
- off(event, cb) {
83
- const removeFromMap = (map) => {
84
- const existing = map.get(event);
85
- if (existing === undefined) {
86
- return;
87
- }
88
- const pruned = existing.filter((l) => l !== cb);
89
- if (pruned.length === 0) {
90
- map.delete(event);
91
- return;
92
- }
93
- map.set(event, pruned);
94
- };
95
- removeFromMap(this.hmrClient.customListenersMap);
96
- removeFromMap(this.newListeners);
97
- }
98
- send(event, data) {
99
- this.hmrClient.messenger.send(JSON.stringify({ type: 'custom', event, data }));
100
- }
101
- acceptDeps(deps, callback = () => { }) {
102
- const mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
103
- id: this.ownerPath,
104
- callbacks: [],
105
- };
106
- mod.callbacks.push({
107
- deps,
108
- fn: callback,
109
- });
110
- this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
111
- }
24
+ }
25
+ }
26
+ this.newListeners = /* @__PURE__ */ new Map();
27
+ hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners);
28
+ }
29
+ get data() {
30
+ return this.hmrClient.dataMap.get(this.ownerPath);
31
+ }
32
+ accept(deps, callback) {
33
+ if (typeof deps === "function" || !deps) {
34
+ this.acceptDeps([this.ownerPath], ([mod]) => deps?.(mod));
35
+ } else if (typeof deps === "string") {
36
+ this.acceptDeps([deps], ([mod]) => callback?.(mod));
37
+ } else if (Array.isArray(deps)) {
38
+ this.acceptDeps(deps, callback);
39
+ } else {
40
+ throw new Error(`invalid hot.accept() usage.`);
41
+ }
42
+ }
43
+ // export names (first arg) are irrelevant on the client side, they're
44
+ // extracted in the server for propagation
45
+ acceptExports(_, callback) {
46
+ this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod));
47
+ }
48
+ dispose(cb) {
49
+ this.hmrClient.disposeMap.set(this.ownerPath, cb);
50
+ }
51
+ prune(cb) {
52
+ this.hmrClient.pruneMap.set(this.ownerPath, cb);
53
+ }
54
+ // Kept for backward compatibility (#11036)
55
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
56
+ decline() {
57
+ }
58
+ invalidate(message) {
59
+ this.hmrClient.notifyListeners("vite:invalidate", {
60
+ path: this.ownerPath,
61
+ message
62
+ });
63
+ this.send("vite:invalidate", {
64
+ path: this.ownerPath,
65
+ message
66
+ });
67
+ this.hmrClient.logger.debug(
68
+ `invalidate ${this.ownerPath}${message ? `: ${message}` : ""}`
69
+ );
70
+ }
71
+ on(event, cb) {
72
+ const addToMap = (map) => {
73
+ const existing = map.get(event) || [];
74
+ existing.push(cb);
75
+ map.set(event, existing);
76
+ };
77
+ addToMap(this.hmrClient.customListenersMap);
78
+ addToMap(this.newListeners);
79
+ }
80
+ off(event, cb) {
81
+ const removeFromMap = (map) => {
82
+ const existing = map.get(event);
83
+ if (existing === void 0) {
84
+ return;
85
+ }
86
+ const pruned = existing.filter((l) => l !== cb);
87
+ if (pruned.length === 0) {
88
+ map.delete(event);
89
+ return;
90
+ }
91
+ map.set(event, pruned);
92
+ };
93
+ removeFromMap(this.hmrClient.customListenersMap);
94
+ removeFromMap(this.newListeners);
95
+ }
96
+ send(event, data) {
97
+ this.hmrClient.messenger.send(
98
+ JSON.stringify({ type: "custom", event, data })
99
+ );
100
+ }
101
+ acceptDeps(deps, callback = () => {
102
+ }) {
103
+ const mod = this.hmrClient.hotModulesMap.get(this.ownerPath) || {
104
+ id: this.ownerPath,
105
+ callbacks: []
106
+ };
107
+ mod.callbacks.push({
108
+ deps,
109
+ fn: callback
110
+ });
111
+ this.hmrClient.hotModulesMap.set(this.ownerPath, mod);
112
+ }
112
113
  }
113
114
  class HMRMessenger {
114
- constructor(connection) {
115
- this.connection = connection;
116
- this.queue = [];
117
- }
118
- send(message) {
119
- this.queue.push(message);
120
- this.flush();
121
- }
122
- flush() {
123
- if (this.connection.isReady()) {
124
- this.queue.forEach((msg) => this.connection.send(msg));
125
- this.queue = [];
126
- }
127
- }
115
+ constructor(connection) {
116
+ this.connection = connection;
117
+ this.queue = [];
118
+ }
119
+ send(message) {
120
+ this.queue.push(message);
121
+ this.flush();
122
+ }
123
+ flush() {
124
+ if (this.connection.isReady()) {
125
+ this.queue.forEach((msg) => this.connection.send(msg));
126
+ this.queue = [];
127
+ }
128
+ }
128
129
  }
129
130
  class HMRClient {
130
- constructor(logger, connection,
131
- // This allows implementing reloading via different methods depending on the environment
132
- importUpdatedModule) {
133
- this.logger = logger;
134
- this.importUpdatedModule = importUpdatedModule;
135
- this.hotModulesMap = new Map();
136
- this.disposeMap = new Map();
137
- this.pruneMap = new Map();
138
- this.dataMap = new Map();
139
- this.customListenersMap = new Map();
140
- this.ctxToListenersMap = new Map();
141
- this.updateQueue = [];
142
- this.pendingUpdateQueue = false;
143
- this.messenger = new HMRMessenger(connection);
144
- }
145
- async notifyListeners(event, data) {
146
- const cbs = this.customListenersMap.get(event);
147
- if (cbs) {
148
- await Promise.allSettled(cbs.map((cb) => cb(data)));
149
- }
150
- }
151
- clear() {
152
- this.hotModulesMap.clear();
153
- this.disposeMap.clear();
154
- this.pruneMap.clear();
155
- this.dataMap.clear();
156
- this.customListenersMap.clear();
157
- this.ctxToListenersMap.clear();
158
- }
159
- // After an HMR update, some modules are no longer imported on the page
160
- // but they may have left behind side effects that need to be cleaned up
161
- // (.e.g style injections)
162
- async prunePaths(paths) {
163
- await Promise.all(paths.map((path) => {
164
- const disposer = this.disposeMap.get(path);
165
- if (disposer)
166
- return disposer(this.dataMap.get(path));
167
- }));
168
- paths.forEach((path) => {
169
- const fn = this.pruneMap.get(path);
170
- if (fn) {
171
- fn(this.dataMap.get(path));
172
- }
173
- });
174
- }
175
- warnFailedUpdate(err, path) {
176
- if (!err.message.includes('fetch')) {
177
- this.logger.error(err);
178
- }
179
- this.logger.error(`[hmr] Failed to reload ${path}. ` +
180
- `This could be due to syntax errors or importing non-existent ` +
181
- `modules. (see errors above)`);
182
- }
183
- /**
184
- * buffer multiple hot updates triggered by the same src change
185
- * so that they are invoked in the same order they were sent.
186
- * (otherwise the order may be inconsistent because of the http request round trip)
187
- */
188
- async queueUpdate(payload) {
189
- this.updateQueue.push(this.fetchUpdate(payload));
190
- if (!this.pendingUpdateQueue) {
191
- this.pendingUpdateQueue = true;
192
- await Promise.resolve();
193
- this.pendingUpdateQueue = false;
194
- const loading = [...this.updateQueue];
195
- this.updateQueue = [];
196
- (await Promise.all(loading)).forEach((fn) => fn && fn());
197
- }
198
- }
199
- async fetchUpdate(update) {
200
- const { path, acceptedPath } = update;
201
- const mod = this.hotModulesMap.get(path);
202
- if (!mod) {
203
- // In a code-splitting project,
204
- // it is common that the hot-updating module is not loaded yet.
205
- // https://github.com/vitejs/vite/issues/721
206
- return;
207
- }
208
- let fetchedModule;
209
- const isSelfUpdate = path === acceptedPath;
210
- // determine the qualified callbacks before we re-import the modules
211
- const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => deps.includes(acceptedPath));
212
- if (isSelfUpdate || qualifiedCallbacks.length > 0) {
213
- const disposer = this.disposeMap.get(acceptedPath);
214
- if (disposer)
215
- await disposer(this.dataMap.get(acceptedPath));
216
- try {
217
- fetchedModule = await this.importUpdatedModule(update);
218
- }
219
- catch (e) {
220
- this.warnFailedUpdate(e, acceptedPath);
221
- }
222
- }
223
- return () => {
224
- for (const { deps, fn } of qualifiedCallbacks) {
225
- fn(deps.map((dep) => (dep === acceptedPath ? fetchedModule : undefined)));
226
- }
227
- const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
228
- this.logger.debug(`[vite] hot updated: ${loggedPath}`);
229
- };
131
+ constructor(logger, connection, importUpdatedModule) {
132
+ this.logger = logger;
133
+ this.importUpdatedModule = importUpdatedModule;
134
+ this.hotModulesMap = /* @__PURE__ */ new Map();
135
+ this.disposeMap = /* @__PURE__ */ new Map();
136
+ this.pruneMap = /* @__PURE__ */ new Map();
137
+ this.dataMap = /* @__PURE__ */ new Map();
138
+ this.customListenersMap = /* @__PURE__ */ new Map();
139
+ this.ctxToListenersMap = /* @__PURE__ */ new Map();
140
+ this.updateQueue = [];
141
+ this.pendingUpdateQueue = false;
142
+ this.messenger = new HMRMessenger(connection);
143
+ }
144
+ async notifyListeners(event, data) {
145
+ const cbs = this.customListenersMap.get(event);
146
+ if (cbs) {
147
+ await Promise.allSettled(cbs.map((cb) => cb(data)));
148
+ }
149
+ }
150
+ clear() {
151
+ this.hotModulesMap.clear();
152
+ this.disposeMap.clear();
153
+ this.pruneMap.clear();
154
+ this.dataMap.clear();
155
+ this.customListenersMap.clear();
156
+ this.ctxToListenersMap.clear();
157
+ }
158
+ // After an HMR update, some modules are no longer imported on the page
159
+ // but they may have left behind side effects that need to be cleaned up
160
+ // (.e.g style injections)
161
+ async prunePaths(paths) {
162
+ await Promise.all(
163
+ paths.map((path) => {
164
+ const disposer = this.disposeMap.get(path);
165
+ if (disposer) return disposer(this.dataMap.get(path));
166
+ })
167
+ );
168
+ paths.forEach((path) => {
169
+ const fn = this.pruneMap.get(path);
170
+ if (fn) {
171
+ fn(this.dataMap.get(path));
172
+ }
173
+ });
174
+ }
175
+ warnFailedUpdate(err, path) {
176
+ if (!err.message.includes("fetch")) {
177
+ this.logger.error(err);
178
+ }
179
+ this.logger.error(
180
+ `Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
181
+ );
182
+ }
183
+ /**
184
+ * buffer multiple hot updates triggered by the same src change
185
+ * so that they are invoked in the same order they were sent.
186
+ * (otherwise the order may be inconsistent because of the http request round trip)
187
+ */
188
+ async queueUpdate(payload) {
189
+ this.updateQueue.push(this.fetchUpdate(payload));
190
+ if (!this.pendingUpdateQueue) {
191
+ this.pendingUpdateQueue = true;
192
+ await Promise.resolve();
193
+ this.pendingUpdateQueue = false;
194
+ const loading = [...this.updateQueue];
195
+ this.updateQueue = [];
196
+ (await Promise.all(loading)).forEach((fn) => fn && fn());
197
+ }
198
+ }
199
+ async fetchUpdate(update) {
200
+ const { path, acceptedPath } = update;
201
+ const mod = this.hotModulesMap.get(path);
202
+ if (!mod) {
203
+ return;
204
+ }
205
+ let fetchedModule;
206
+ const isSelfUpdate = path === acceptedPath;
207
+ const qualifiedCallbacks = mod.callbacks.filter(
208
+ ({ deps }) => deps.includes(acceptedPath)
209
+ );
210
+ if (isSelfUpdate || qualifiedCallbacks.length > 0) {
211
+ const disposer = this.disposeMap.get(acceptedPath);
212
+ if (disposer) await disposer(this.dataMap.get(acceptedPath));
213
+ try {
214
+ fetchedModule = await this.importUpdatedModule(update);
215
+ } catch (e) {
216
+ this.warnFailedUpdate(e, acceptedPath);
217
+ }
230
218
  }
219
+ return () => {
220
+ for (const { deps, fn } of qualifiedCallbacks) {
221
+ fn(
222
+ deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0)
223
+ );
224
+ }
225
+ const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
226
+ this.logger.debug(`hot updated: ${loggedPath}`);
227
+ };
228
+ }
231
229
  }
232
230
 
233
231
  const hmrConfigName = __HMR_CONFIG_NAME__;
234
- const base$1 = __BASE__ || '/';
235
- // Create an element with provided attributes and optional children
232
+ const base$1 = __BASE__ || "/";
236
233
  function h(e, attrs = {}, ...children) {
237
- const elem = document.createElement(e);
238
- for (const [k, v] of Object.entries(attrs)) {
239
- elem.setAttribute(k, v);
240
- }
241
- elem.append(...children);
242
- return elem;
243
- }
244
- // set :host styles to make playwright detect the element as visible
245
- const templateStyle = /*css*/ `
234
+ const elem = document.createElement(e);
235
+ for (const [k, v] of Object.entries(attrs)) {
236
+ elem.setAttribute(k, v);
237
+ }
238
+ elem.append(...children);
239
+ return elem;
240
+ }
241
+ const templateStyle = (
242
+ /*css*/
243
+ `
246
244
  :host {
247
245
  position: fixed;
248
246
  top: 0;
@@ -382,447 +380,452 @@ kbd {
382
380
  border-color: rgb(54, 57, 64);
383
381
  border-image: initial;
384
382
  }
385
- `;
386
- // Error Template
387
- let template;
388
- const createTemplate = () => h('div', { class: 'backdrop', part: 'backdrop' }, h('div', { class: 'window', part: 'window' }, h('pre', { class: 'message', part: 'message' }, h('span', { class: 'plugin', part: 'plugin' }), h('span', { class: 'message-body', part: 'message-body' })), h('pre', { class: 'file', part: 'file' }), h('pre', { class: 'frame', part: 'frame' }), h('pre', { class: 'stack', part: 'stack' }), h('div', { class: 'tip', part: 'tip' }, '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', {}, templateStyle));
383
+ `
384
+ );
385
+ const createTemplate = () => h(
386
+ "div",
387
+ { class: "backdrop", part: "backdrop" },
388
+ h(
389
+ "div",
390
+ { class: "window", part: "window" },
391
+ h(
392
+ "pre",
393
+ { class: "message", part: "message" },
394
+ h("span", { class: "plugin", part: "plugin" }),
395
+ h("span", { class: "message-body", part: "message-body" })
396
+ ),
397
+ h("pre", { class: "file", part: "file" }),
398
+ h("pre", { class: "frame", part: "frame" }),
399
+ h("pre", { class: "stack", part: "stack" }),
400
+ h(
401
+ "div",
402
+ { class: "tip", part: "tip" },
403
+ "Click outside, press ",
404
+ h("kbd", {}, "Esc"),
405
+ " key, or fix the code to dismiss.",
406
+ h("br"),
407
+ "You can also disable this overlay by setting ",
408
+ h("code", { part: "config-option-name" }, "server.hmr.overlay"),
409
+ " to ",
410
+ h("code", { part: "config-option-value" }, "false"),
411
+ " in ",
412
+ h("code", { part: "config-file-name" }, hmrConfigName),
413
+ "."
414
+ )
415
+ ),
416
+ h("style", {}, templateStyle)
417
+ );
389
418
  const fileRE = /(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g;
390
419
  const codeframeRE = /^(?:>?\s*\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm;
391
- // Allow `ErrorOverlay` to extend `HTMLElement` even in environments where
392
- // `HTMLElement` was not originally defined.
393
420
  const { HTMLElement = class {
394
421
  } } = globalThis;
395
422
  class ErrorOverlay extends HTMLElement {
396
- constructor(err, links = true) {
397
- var _a;
398
- super();
399
- this.root = this.attachShadow({ mode: 'open' });
400
- template !== null && template !== void 0 ? template : (template = createTemplate());
401
- this.root.appendChild(template);
402
- codeframeRE.lastIndex = 0;
403
- const hasFrame = err.frame && codeframeRE.test(err.frame);
404
- const message = hasFrame
405
- ? err.message.replace(codeframeRE, '')
406
- : err.message;
407
- if (err.plugin) {
408
- this.text('.plugin', `[plugin:${err.plugin}] `);
409
- }
410
- this.text('.message-body', message.trim());
411
- const [file] = (((_a = err.loc) === null || _a === void 0 ? void 0 : _a.file) || err.id || 'unknown file').split(`?`);
412
- if (err.loc) {
413
- this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, links);
414
- }
415
- else if (err.id) {
416
- this.text('.file', file);
417
- }
418
- if (hasFrame) {
419
- this.text('.frame', err.frame.trim());
420
- }
421
- this.text('.stack', err.stack, links);
422
- this.root.querySelector('.window').addEventListener('click', (e) => {
423
- e.stopPropagation();
424
- });
425
- this.addEventListener('click', () => {
426
- this.close();
427
- });
428
- this.closeOnEsc = (e) => {
429
- if (e.key === 'Escape' || e.code === 'Escape') {
430
- this.close();
431
- }
432
- };
433
- document.addEventListener('keydown', this.closeOnEsc);
434
- }
435
- text(selector, text, linkFiles = false) {
436
- const el = this.root.querySelector(selector);
437
- if (!linkFiles) {
438
- el.textContent = text;
439
- }
440
- else {
441
- let curIndex = 0;
442
- let match;
443
- fileRE.lastIndex = 0;
444
- while ((match = fileRE.exec(text))) {
445
- const { 0: file, index } = match;
446
- if (index != null) {
447
- const frag = text.slice(curIndex, index);
448
- el.appendChild(document.createTextNode(frag));
449
- const link = document.createElement('a');
450
- link.textContent = file;
451
- link.className = 'file-link';
452
- link.onclick = () => {
453
- fetch(new URL(`${base$1}__open-in-editor?file=${encodeURIComponent(file)}`, import.meta.url));
454
- };
455
- el.appendChild(link);
456
- curIndex += frag.length + file.length;
457
- }
458
- }
423
+ constructor(err, links = true) {
424
+ super();
425
+ this.root = this.attachShadow({ mode: "open" });
426
+ this.root.appendChild(createTemplate());
427
+ codeframeRE.lastIndex = 0;
428
+ const hasFrame = err.frame && codeframeRE.test(err.frame);
429
+ const message = hasFrame ? err.message.replace(codeframeRE, "") : err.message;
430
+ if (err.plugin) {
431
+ this.text(".plugin", `[plugin:${err.plugin}] `);
432
+ }
433
+ this.text(".message-body", message.trim());
434
+ const [file] = (err.loc?.file || err.id || "unknown file").split(`?`);
435
+ if (err.loc) {
436
+ this.text(".file", `${file}:${err.loc.line}:${err.loc.column}`, links);
437
+ } else if (err.id) {
438
+ this.text(".file", file);
439
+ }
440
+ if (hasFrame) {
441
+ this.text(".frame", err.frame.trim());
442
+ }
443
+ this.text(".stack", err.stack, links);
444
+ this.root.querySelector(".window").addEventListener("click", (e) => {
445
+ e.stopPropagation();
446
+ });
447
+ this.addEventListener("click", () => {
448
+ this.close();
449
+ });
450
+ this.closeOnEsc = (e) => {
451
+ if (e.key === "Escape" || e.code === "Escape") {
452
+ this.close();
453
+ }
454
+ };
455
+ document.addEventListener("keydown", this.closeOnEsc);
456
+ }
457
+ text(selector, text, linkFiles = false) {
458
+ const el = this.root.querySelector(selector);
459
+ if (!linkFiles) {
460
+ el.textContent = text;
461
+ } else {
462
+ let curIndex = 0;
463
+ let match;
464
+ fileRE.lastIndex = 0;
465
+ while (match = fileRE.exec(text)) {
466
+ const { 0: file, index } = match;
467
+ if (index != null) {
468
+ const frag = text.slice(curIndex, index);
469
+ el.appendChild(document.createTextNode(frag));
470
+ const link = document.createElement("a");
471
+ link.textContent = file;
472
+ link.className = "file-link";
473
+ link.onclick = () => {
474
+ fetch(
475
+ new URL(
476
+ `${base$1}__open-in-editor?file=${encodeURIComponent(file)}`,
477
+ import.meta.url
478
+ )
479
+ );
480
+ };
481
+ el.appendChild(link);
482
+ curIndex += frag.length + file.length;
459
483
  }
484
+ }
460
485
  }
461
- close() {
462
- var _a;
463
- (_a = this.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this);
464
- document.removeEventListener('keydown', this.closeOnEsc);
465
- }
486
+ }
487
+ close() {
488
+ this.parentNode?.removeChild(this);
489
+ document.removeEventListener("keydown", this.closeOnEsc);
490
+ }
466
491
  }
467
- const overlayId = 'vite-error-overlay';
468
- const { customElements } = globalThis; // Ensure `customElements` is defined before the next line.
492
+ const overlayId = "vite-error-overlay";
493
+ const { customElements } = globalThis;
469
494
  if (customElements && !customElements.get(overlayId)) {
470
- customElements.define(overlayId, ErrorOverlay);
495
+ customElements.define(overlayId, ErrorOverlay);
471
496
  }
472
497
 
473
- var _a;
474
- console.debug('[vite] connecting...');
498
+ console.debug("[vite] connecting...");
475
499
  const importMetaUrl = new URL(import.meta.url);
476
- // use server configuration, then fallback to inference
477
500
  const serverHost = __SERVER_HOST__;
478
- const socketProtocol = __HMR_PROTOCOL__ || (importMetaUrl.protocol === 'https:' ? 'wss' : 'ws');
501
+ const socketProtocol = __HMR_PROTOCOL__ || (importMetaUrl.protocol === "https:" ? "wss" : "ws");
479
502
  const hmrPort = __HMR_PORT__;
480
503
  const socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${hmrPort || importMetaUrl.port}${__HMR_BASE__}`;
481
504
  const directSocketHost = __HMR_DIRECT_TARGET__;
482
- const base = __BASE__ || '/';
505
+ const base = __BASE__ || "/";
483
506
  let socket;
484
507
  try {
485
- let fallback;
486
- // only use fallback when port is inferred to prevent confusion
487
- if (!hmrPort) {
488
- fallback = () => {
489
- // fallback to connecting directly to the hmr server
490
- // for servers which does not support proxying websocket
491
- socket = setupWebSocket(socketProtocol, directSocketHost, () => {
492
- const currentScriptHostURL = new URL(import.meta.url);
493
- const currentScriptHost = currentScriptHostURL.host +
494
- currentScriptHostURL.pathname.replace(/@vite\/client$/, '');
495
- console.error('[vite] failed to connect to websocket.\n' +
496
- 'your current setup:\n' +
497
- ` (browser) ${currentScriptHost} <--[HTTP]--> ${serverHost} (server)\n` +
498
- ` (browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)\n` +
499
- 'Check out your Vite / network configuration and https://vitejs.dev/config/server-options.html#server-hmr .');
500
- });
501
- socket.addEventListener('open', () => {
502
- console.info('[vite] Direct websocket connection fallback. Check out https://vitejs.dev/config/server-options.html#server-hmr to remove the previous connection error.');
503
- }, { once: true });
504
- };
505
- }
506
- socket = setupWebSocket(socketProtocol, socketHost, fallback);
507
- }
508
- catch (error) {
509
- console.error(`[vite] failed to connect to websocket (${error}). `);
508
+ let fallback;
509
+ if (!hmrPort) {
510
+ fallback = () => {
511
+ socket = setupWebSocket(socketProtocol, directSocketHost, () => {
512
+ const currentScriptHostURL = new URL(import.meta.url);
513
+ const currentScriptHost = currentScriptHostURL.host + currentScriptHostURL.pathname.replace(/@vite\/client$/, "");
514
+ console.error(
515
+ `[vite] failed to connect to websocket.
516
+ your current setup:
517
+ (browser) ${currentScriptHost} <--[HTTP]--> ${serverHost} (server)
518
+ (browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)
519
+ Check out your Vite / network configuration and https://vitejs.dev/config/server-options.html#server-hmr .`
520
+ );
521
+ });
522
+ socket.addEventListener(
523
+ "open",
524
+ () => {
525
+ console.info(
526
+ "[vite] Direct websocket connection fallback. Check out https://vitejs.dev/config/server-options.html#server-hmr to remove the previous connection error."
527
+ );
528
+ },
529
+ { once: true }
530
+ );
531
+ };
532
+ }
533
+ socket = setupWebSocket(socketProtocol, socketHost, fallback);
534
+ } catch (error) {
535
+ console.error(`[vite] failed to connect to websocket (${error}). `);
510
536
  }
511
537
  function setupWebSocket(protocol, hostAndPath, onCloseWithoutOpen) {
512
- const socket = new WebSocket(`${protocol}://${hostAndPath}`, 'vite-hmr');
513
- let isOpened = false;
514
- socket.addEventListener('open', () => {
515
- isOpened = true;
516
- notifyListeners('vite:ws:connect', { webSocket: socket });
517
- }, { once: true });
518
- // Listen for messages
519
- socket.addEventListener('message', async ({ data }) => {
520
- handleMessage(JSON.parse(data));
521
- });
522
- // ping server
523
- socket.addEventListener('close', async ({ wasClean }) => {
524
- if (wasClean)
525
- return;
526
- if (!isOpened && onCloseWithoutOpen) {
527
- onCloseWithoutOpen();
528
- return;
529
- }
530
- notifyListeners('vite:ws:disconnect', { webSocket: socket });
531
- if (hasDocument) {
532
- console.log(`[vite] server connection lost. polling for restart...`);
533
- await waitForSuccessfulPing(protocol, hostAndPath);
534
- location.reload();
535
- }
536
- });
537
- return socket;
538
+ const socket2 = new WebSocket(`${protocol}://${hostAndPath}`, "vite-hmr");
539
+ let isOpened = false;
540
+ socket2.addEventListener(
541
+ "open",
542
+ () => {
543
+ isOpened = true;
544
+ notifyListeners("vite:ws:connect", { webSocket: socket2 });
545
+ },
546
+ { once: true }
547
+ );
548
+ socket2.addEventListener("message", async ({ data }) => {
549
+ handleMessage(JSON.parse(data));
550
+ });
551
+ socket2.addEventListener("close", async ({ wasClean }) => {
552
+ if (wasClean) return;
553
+ if (!isOpened && onCloseWithoutOpen) {
554
+ onCloseWithoutOpen();
555
+ return;
556
+ }
557
+ notifyListeners("vite:ws:disconnect", { webSocket: socket2 });
558
+ if (hasDocument) {
559
+ console.log(`[vite] server connection lost. Polling for restart...`);
560
+ await waitForSuccessfulPing(protocol, hostAndPath);
561
+ location.reload();
562
+ }
563
+ });
564
+ return socket2;
538
565
  }
539
566
  function cleanUrl(pathname) {
540
- const url = new URL(pathname, 'http://vitejs.dev');
541
- url.searchParams.delete('direct');
542
- return url.pathname + url.search;
567
+ const url = new URL(pathname, "http://vitejs.dev");
568
+ url.searchParams.delete("direct");
569
+ return url.pathname + url.search;
543
570
  }
544
571
  let isFirstUpdate = true;
545
- const outdatedLinkTags = new WeakSet();
572
+ const outdatedLinkTags = /* @__PURE__ */ new WeakSet();
546
573
  const debounceReload = (time) => {
547
- let timer;
548
- return () => {
549
- if (timer) {
550
- clearTimeout(timer);
551
- timer = null;
552
- }
553
- timer = setTimeout(() => {
554
- location.reload();
555
- }, time);
556
- };
574
+ let timer;
575
+ return () => {
576
+ if (timer) {
577
+ clearTimeout(timer);
578
+ timer = null;
579
+ }
580
+ timer = setTimeout(() => {
581
+ location.reload();
582
+ }, time);
583
+ };
557
584
  };
558
585
  const pageReload = debounceReload(50);
559
- const hmrClient = new HMRClient(console, {
586
+ const hmrClient = new HMRClient(
587
+ {
588
+ error: (err) => console.error("[vite]", err),
589
+ debug: (...msg) => console.debug("[vite]", ...msg)
590
+ },
591
+ {
560
592
  isReady: () => socket && socket.readyState === 1,
561
- send: (message) => socket.send(message),
562
- }, async function importUpdatedModule({ acceptedPath, timestamp, explicitImportRequired, isWithinCircularImport, }) {
593
+ send: (message) => socket.send(message)
594
+ },
595
+ async function importUpdatedModule({
596
+ acceptedPath,
597
+ timestamp,
598
+ explicitImportRequired,
599
+ isWithinCircularImport
600
+ }) {
563
601
  const [acceptedPathWithoutQuery, query] = acceptedPath.split(`?`);
564
602
  const importPromise = import(
565
- /* @vite-ignore */
566
- base +
567
- acceptedPathWithoutQuery.slice(1) +
568
- `?${explicitImportRequired ? 'import&' : ''}t=${timestamp}${query ? `&${query}` : ''}`);
603
+ /* @vite-ignore */
604
+ base + acceptedPathWithoutQuery.slice(1) + `?${explicitImportRequired ? "import&" : ""}t=${timestamp}${query ? `&${query}` : ""}`
605
+ );
569
606
  if (isWithinCircularImport) {
570
- importPromise.catch(() => {
571
- console.info(`[hmr] ${acceptedPath} failed to apply HMR as it's within a circular import. Reloading page to reset the execution order. ` +
572
- `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.`);
573
- pageReload();
574
- });
607
+ importPromise.catch(() => {
608
+ console.info(
609
+ `[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.`
610
+ );
611
+ pageReload();
612
+ });
575
613
  }
576
614
  return await importPromise;
577
- });
615
+ }
616
+ );
578
617
  async function handleMessage(payload) {
579
- switch (payload.type) {
580
- case 'connected':
581
- console.debug(`[vite] connected.`);
582
- hmrClient.messenger.flush();
583
- // proxy(nginx, docker) hmr ws maybe caused timeout,
584
- // so send ping package let ws keep alive.
585
- setInterval(() => {
586
- if (socket.readyState === socket.OPEN) {
587
- socket.send('{"type":"ping"}');
588
- }
589
- }, __HMR_TIMEOUT__);
590
- break;
591
- case 'update':
592
- notifyListeners('vite:beforeUpdate', payload);
593
- if (hasDocument) {
594
- // if this is the first update and there's already an error overlay, it
595
- // means the page opened with existing server compile error and the whole
596
- // module script failed to load (since one of the nested imports is 500).
597
- // in this case a normal update won't work and a full reload is needed.
598
- if (isFirstUpdate && hasErrorOverlay()) {
599
- window.location.reload();
600
- return;
601
- }
602
- else {
603
- if (enableOverlay) {
604
- clearErrorOverlay();
605
- }
606
- isFirstUpdate = false;
607
- }
608
- }
609
- await Promise.all(payload.updates.map(async (update) => {
610
- if (update.type === 'js-update') {
611
- return hmrClient.queueUpdate(update);
612
- }
613
- // css-update
614
- // this is only sent when a css file referenced with <link> is updated
615
- const { path, timestamp } = update;
616
- const searchUrl = cleanUrl(path);
617
- // can't use querySelector with `[href*=]` here since the link may be
618
- // using relative paths so we need to use link.href to grab the full
619
- // URL for the include check.
620
- const el = Array.from(document.querySelectorAll('link')).find((e) => !outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl));
621
- if (!el) {
622
- return;
623
- }
624
- const newPath = `${base}${searchUrl.slice(1)}${searchUrl.includes('?') ? '&' : '?'}t=${timestamp}`;
625
- // rather than swapping the href on the existing tag, we will
626
- // create a new link tag. Once the new stylesheet has loaded we
627
- // will remove the existing link tag. This removes a Flash Of
628
- // Unstyled Content that can occur when swapping out the tag href
629
- // directly, as the new stylesheet has not yet been loaded.
630
- return new Promise((resolve) => {
631
- const newLinkTag = el.cloneNode();
632
- newLinkTag.href = new URL(newPath, el.href).href;
633
- const removeOldEl = () => {
634
- el.remove();
635
- console.debug(`[vite] css hot updated: ${searchUrl}`);
636
- resolve();
637
- };
638
- newLinkTag.addEventListener('load', removeOldEl);
639
- newLinkTag.addEventListener('error', removeOldEl);
640
- outdatedLinkTags.add(el);
641
- el.after(newLinkTag);
642
- });
643
- }));
644
- notifyListeners('vite:afterUpdate', payload);
645
- break;
646
- case 'custom': {
647
- notifyListeners(payload.event, payload.data);
648
- break;
618
+ switch (payload.type) {
619
+ case "connected":
620
+ console.debug(`[vite] connected.`);
621
+ hmrClient.messenger.flush();
622
+ setInterval(() => {
623
+ if (socket.readyState === socket.OPEN) {
624
+ socket.send('{"type":"ping"}');
625
+ }
626
+ }, __HMR_TIMEOUT__);
627
+ break;
628
+ case "update":
629
+ notifyListeners("vite:beforeUpdate", payload);
630
+ if (hasDocument) {
631
+ if (isFirstUpdate && hasErrorOverlay()) {
632
+ location.reload();
633
+ return;
634
+ } else {
635
+ if (enableOverlay) {
636
+ clearErrorOverlay();
637
+ }
638
+ isFirstUpdate = false;
649
639
  }
650
- case 'full-reload':
651
- notifyListeners('vite:beforeFullReload', payload);
652
- if (hasDocument) {
653
- if (payload.path && payload.path.endsWith('.html')) {
654
- // if html file is edited, only reload the page if the browser is
655
- // currently on that page.
656
- const pagePath = decodeURI(location.pathname);
657
- const payloadPath = base + payload.path.slice(1);
658
- if (pagePath === payloadPath ||
659
- payload.path === '/index.html' ||
660
- (pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)) {
661
- pageReload();
662
- }
663
- return;
664
- }
665
- else {
666
- pageReload();
667
- }
668
- }
669
- break;
670
- case 'prune':
671
- notifyListeners('vite:beforePrune', payload);
672
- await hmrClient.prunePaths(payload.paths);
673
- break;
674
- case 'error': {
675
- notifyListeners('vite:error', payload);
676
- if (hasDocument) {
677
- const err = payload.err;
678
- if (enableOverlay) {
679
- createErrorOverlay(err);
680
- }
681
- else {
682
- console.error(`[vite] Internal Server Error\n${err.message}\n${err.stack}`);
683
- }
684
- }
685
- break;
640
+ }
641
+ await Promise.all(
642
+ payload.updates.map(async (update) => {
643
+ if (update.type === "js-update") {
644
+ return hmrClient.queueUpdate(update);
645
+ }
646
+ const { path, timestamp } = update;
647
+ const searchUrl = cleanUrl(path);
648
+ const el = Array.from(
649
+ document.querySelectorAll("link")
650
+ ).find(
651
+ (e) => !outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl)
652
+ );
653
+ if (!el) {
654
+ return;
655
+ }
656
+ const newPath = `${base}${searchUrl.slice(1)}${searchUrl.includes("?") ? "&" : "?"}t=${timestamp}`;
657
+ return new Promise((resolve) => {
658
+ const newLinkTag = el.cloneNode();
659
+ newLinkTag.href = new URL(newPath, el.href).href;
660
+ const removeOldEl = () => {
661
+ el.remove();
662
+ console.debug(`[vite] css hot updated: ${searchUrl}`);
663
+ resolve();
664
+ };
665
+ newLinkTag.addEventListener("load", removeOldEl);
666
+ newLinkTag.addEventListener("error", removeOldEl);
667
+ outdatedLinkTags.add(el);
668
+ el.after(newLinkTag);
669
+ });
670
+ })
671
+ );
672
+ notifyListeners("vite:afterUpdate", payload);
673
+ break;
674
+ case "custom": {
675
+ notifyListeners(payload.event, payload.data);
676
+ break;
677
+ }
678
+ case "full-reload":
679
+ notifyListeners("vite:beforeFullReload", payload);
680
+ if (hasDocument) {
681
+ if (payload.path && payload.path.endsWith(".html")) {
682
+ const pagePath = decodeURI(location.pathname);
683
+ const payloadPath = base + payload.path.slice(1);
684
+ if (pagePath === payloadPath || payload.path === "/index.html" || pagePath.endsWith("/") && pagePath + "index.html" === payloadPath) {
685
+ pageReload();
686
+ }
687
+ return;
688
+ } else {
689
+ pageReload();
686
690
  }
687
- default: {
688
- const check = payload;
689
- return check;
691
+ }
692
+ break;
693
+ case "prune":
694
+ notifyListeners("vite:beforePrune", payload);
695
+ await hmrClient.prunePaths(payload.paths);
696
+ break;
697
+ case "error": {
698
+ notifyListeners("vite:error", payload);
699
+ if (hasDocument) {
700
+ const err = payload.err;
701
+ if (enableOverlay) {
702
+ createErrorOverlay(err);
703
+ } else {
704
+ console.error(
705
+ `[vite] Internal Server Error
706
+ ${err.message}
707
+ ${err.stack}`
708
+ );
690
709
  }
710
+ }
711
+ break;
712
+ }
713
+ default: {
714
+ const check = payload;
715
+ return check;
691
716
  }
717
+ }
692
718
  }
693
719
  function notifyListeners(event, data) {
694
- hmrClient.notifyListeners(event, data);
720
+ hmrClient.notifyListeners(event, data);
695
721
  }
696
722
  const enableOverlay = __HMR_ENABLE_OVERLAY__;
697
- const hasDocument = 'document' in globalThis;
723
+ const hasDocument = "document" in globalThis;
698
724
  function createErrorOverlay(err) {
699
- clearErrorOverlay();
700
- document.body.appendChild(new ErrorOverlay(err));
725
+ clearErrorOverlay();
726
+ document.body.appendChild(new ErrorOverlay(err));
701
727
  }
702
728
  function clearErrorOverlay() {
703
- document.querySelectorAll(overlayId).forEach((n) => n.close());
729
+ document.querySelectorAll(overlayId).forEach((n) => n.close());
704
730
  }
705
731
  function hasErrorOverlay() {
706
- return document.querySelectorAll(overlayId).length;
707
- }
708
- async function waitForSuccessfulPing(socketProtocol, hostAndPath, ms = 1000) {
709
- const pingHostProtocol = socketProtocol === 'wss' ? 'https' : 'http';
710
- const ping = async () => {
711
- // A fetch on a websocket URL will return a successful promise with status 400,
712
- // but will reject a networking error.
713
- // When running on middleware mode, it returns status 426, and an cors error happens if mode is not no-cors
714
- try {
715
- await fetch(`${pingHostProtocol}://${hostAndPath}`, {
716
- mode: 'no-cors',
717
- headers: {
718
- // Custom headers won't be included in a request with no-cors so (ab)use one of the
719
- // safelisted headers to identify the ping request
720
- Accept: 'text/x-vite-ping',
721
- },
722
- });
723
- return true;
724
- }
725
- catch { }
726
- return false;
727
- };
728
- if (await ping()) {
729
- return;
730
- }
731
- await wait(ms);
732
- // eslint-disable-next-line no-constant-condition
733
- while (true) {
734
- if (document.visibilityState === 'visible') {
735
- if (await ping()) {
736
- break;
737
- }
738
- await wait(ms);
739
- }
740
- else {
741
- await waitForWindowShow();
732
+ return document.querySelectorAll(overlayId).length;
733
+ }
734
+ async function waitForSuccessfulPing(socketProtocol2, hostAndPath, ms = 1e3) {
735
+ const pingHostProtocol = socketProtocol2 === "wss" ? "https" : "http";
736
+ const ping = async () => {
737
+ try {
738
+ await fetch(`${pingHostProtocol}://${hostAndPath}`, {
739
+ mode: "no-cors",
740
+ headers: {
741
+ // Custom headers won't be included in a request with no-cors so (ab)use one of the
742
+ // safelisted headers to identify the ping request
743
+ Accept: "text/x-vite-ping"
742
744
  }
743
- }
745
+ });
746
+ return true;
747
+ } catch {
748
+ }
749
+ return false;
750
+ };
751
+ if (await ping()) {
752
+ return;
753
+ }
754
+ await wait(ms);
755
+ while (true) {
756
+ if (document.visibilityState === "visible") {
757
+ if (await ping()) {
758
+ break;
759
+ }
760
+ await wait(ms);
761
+ } else {
762
+ await waitForWindowShow();
763
+ }
764
+ }
744
765
  }
745
766
  function wait(ms) {
746
- return new Promise((resolve) => setTimeout(resolve, ms));
767
+ return new Promise((resolve) => setTimeout(resolve, ms));
747
768
  }
748
769
  function waitForWindowShow() {
749
- return new Promise((resolve) => {
750
- const onChange = async () => {
751
- if (document.visibilityState === 'visible') {
752
- resolve();
753
- document.removeEventListener('visibilitychange', onChange);
754
- }
755
- };
756
- document.addEventListener('visibilitychange', onChange);
757
- });
770
+ return new Promise((resolve) => {
771
+ const onChange = async () => {
772
+ if (document.visibilityState === "visible") {
773
+ resolve();
774
+ document.removeEventListener("visibilitychange", onChange);
775
+ }
776
+ };
777
+ document.addEventListener("visibilitychange", onChange);
778
+ });
758
779
  }
759
- const sheetsMap = new Map();
760
- // collect existing style elements that may have been inserted during SSR
761
- // to avoid FOUC or duplicate styles
762
- if ('document' in globalThis) {
763
- document
764
- .querySelectorAll('style[data-vite-dev-id]')
765
- .forEach((el) => {
766
- sheetsMap.set(el.getAttribute('data-vite-dev-id'), el);
767
- });
780
+ const sheetsMap = /* @__PURE__ */ new Map();
781
+ if ("document" in globalThis) {
782
+ document.querySelectorAll("style[data-vite-dev-id]").forEach((el) => {
783
+ sheetsMap.set(el.getAttribute("data-vite-dev-id"), el);
784
+ });
768
785
  }
769
- const cspNonce = 'document' in globalThis
770
- ? (_a = document.querySelector('meta[property=csp-nonce]')) === null || _a === void 0 ? void 0 : _a.nonce
771
- : undefined;
772
- // all css imports should be inserted at the same position
773
- // because after build it will be a single css file
786
+ const cspNonce = "document" in globalThis ? document.querySelector("meta[property=csp-nonce]")?.nonce : void 0;
774
787
  let lastInsertedStyle;
775
788
  function updateStyle(id, content) {
776
- let style = sheetsMap.get(id);
777
- if (!style) {
778
- style = document.createElement('style');
779
- style.setAttribute('type', 'text/css');
780
- style.setAttribute('data-vite-dev-id', id);
781
- style.textContent = content;
782
- if (cspNonce) {
783
- style.setAttribute('nonce', cspNonce);
784
- }
785
- if (!lastInsertedStyle) {
786
- document.head.appendChild(style);
787
- // reset lastInsertedStyle after async
788
- // because dynamically imported css will be splitted into a different file
789
- setTimeout(() => {
790
- lastInsertedStyle = undefined;
791
- }, 0);
792
- }
793
- else {
794
- lastInsertedStyle.insertAdjacentElement('afterend', style);
795
- }
796
- lastInsertedStyle = style;
797
- }
798
- else {
799
- style.textContent = content;
800
- }
801
- sheetsMap.set(id, style);
789
+ let style = sheetsMap.get(id);
790
+ if (!style) {
791
+ style = document.createElement("style");
792
+ style.setAttribute("type", "text/css");
793
+ style.setAttribute("data-vite-dev-id", id);
794
+ style.textContent = content;
795
+ if (cspNonce) {
796
+ style.setAttribute("nonce", cspNonce);
797
+ }
798
+ if (!lastInsertedStyle) {
799
+ document.head.appendChild(style);
800
+ setTimeout(() => {
801
+ lastInsertedStyle = void 0;
802
+ }, 0);
803
+ } else {
804
+ lastInsertedStyle.insertAdjacentElement("afterend", style);
805
+ }
806
+ lastInsertedStyle = style;
807
+ } else {
808
+ style.textContent = content;
809
+ }
810
+ sheetsMap.set(id, style);
802
811
  }
803
812
  function removeStyle(id) {
804
- const style = sheetsMap.get(id);
805
- if (style) {
806
- document.head.removeChild(style);
807
- sheetsMap.delete(id);
808
- }
813
+ const style = sheetsMap.get(id);
814
+ if (style) {
815
+ document.head.removeChild(style);
816
+ sheetsMap.delete(id);
817
+ }
809
818
  }
810
819
  function createHotContext(ownerPath) {
811
- return new HMRContext(hmrClient, ownerPath);
820
+ return new HMRContext(hmrClient, ownerPath);
812
821
  }
813
- /**
814
- * urls here are dynamic import() urls that couldn't be statically analyzed
815
- */
816
822
  function injectQuery(url, queryToInject) {
817
- // skip urls that won't be handled by vite
818
- if (url[0] !== '.' && url[0] !== '/') {
819
- return url;
820
- }
821
- // can't use pathname from URL since it may be relative like ../
822
- const pathname = url.replace(/[?#].*$/, '');
823
- const { search, hash } = new URL(url, 'http://vitejs.dev');
824
- return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash || ''}`;
823
+ if (url[0] !== "." && url[0] !== "/") {
824
+ return url;
825
+ }
826
+ const pathname = url.replace(/[?#].*$/, "");
827
+ const { search, hash } = new URL(url, "http://vitejs.dev");
828
+ return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ""}${hash || ""}`;
825
829
  }
826
830
 
827
831
  export { ErrorOverlay, createHotContext, injectQuery, removeStyle, updateStyle };
828
- //# sourceMappingURL=client.mjs.map