@oxog/devinspector 1.4.1 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/chunk-5QIYNQ4C.js +19 -0
  3. package/dist/chunk-5QIYNQ4C.js.map +1 -0
  4. package/dist/{chunk-LNBLBFDA.js → chunk-NP2SAIEA.js} +23 -19
  5. package/dist/chunk-NP2SAIEA.js.map +1 -0
  6. package/dist/{chunk-KZ4SDSBO.js → chunk-WUYUDBSC.js} +5 -1
  7. package/dist/chunk-WUYUDBSC.js.map +1 -0
  8. package/dist/{console-monitor-AVTNZCED.js → console-monitor-AO67CSAK.js} +17 -10
  9. package/dist/console-monitor-AO67CSAK.js.map +1 -0
  10. package/dist/devinspector.umd.cjs +772 -491
  11. package/dist/devinspector.umd.cjs.map +1 -1
  12. package/dist/devinspector.umd.js +772 -491
  13. package/dist/devinspector.umd.js.map +1 -1
  14. package/dist/devinspector.umd.min.cjs +2 -2
  15. package/dist/devinspector.umd.min.cjs.map +1 -1
  16. package/dist/devinspector.umd.min.js +2 -2
  17. package/dist/devinspector.umd.min.js.map +1 -1
  18. package/dist/{dom-monitor-JHJVZYS4.js → dom-monitor-D6GHCDBP.js} +1 -1
  19. package/dist/{dom-monitor-JHJVZYS4.js.map → dom-monitor-D6GHCDBP.js.map} +1 -1
  20. package/dist/{error-monitor-3CRFREH3.js → error-monitor-AVTYBTS7.js} +27 -52
  21. package/dist/error-monitor-AVTYBTS7.js.map +1 -0
  22. package/dist/index.cjs +515 -287
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +4 -2
  25. package/dist/index.d.ts +4 -2
  26. package/dist/index.js +269 -99
  27. package/dist/index.js.map +1 -1
  28. package/dist/{inspector-ui-C7WSILKC.js → inspector-ui-TEAZXDPM.js} +17 -7
  29. package/dist/inspector-ui-TEAZXDPM.js.map +1 -0
  30. package/dist/{network-monitor-WNRL2JI7.js → network-monitor-QHVMB5F3.js} +154 -115
  31. package/dist/network-monitor-QHVMB5F3.js.map +1 -0
  32. package/dist/{performance-monitor-UKQFA7ZR.js → performance-monitor-ULNHXBYX.js} +8 -6
  33. package/dist/performance-monitor-ULNHXBYX.js.map +1 -0
  34. package/dist/{state-monitor-JGJLBAD7.js → state-monitor-UNAVEOGH.js} +1 -1
  35. package/dist/{state-monitor-JGJLBAD7.js.map → state-monitor-UNAVEOGH.js.map} +1 -1
  36. package/dist/{storage-monitor-3NPTWRTY.js → storage-monitor-5RCRXYMX.js} +1 -1
  37. package/dist/{storage-monitor-3NPTWRTY.js.map → storage-monitor-5RCRXYMX.js.map} +1 -1
  38. package/package.json +9 -3
  39. package/dist/chunk-KZ4SDSBO.js.map +0 -1
  40. package/dist/chunk-LNBLBFDA.js.map +0 -1
  41. package/dist/console-monitor-AVTNZCED.js.map +0 -1
  42. package/dist/error-monitor-3CRFREH3.js.map +0 -1
  43. package/dist/inspector-ui-C7WSILKC.js.map +0 -1
  44. package/dist/network-monitor-WNRL2JI7.js.map +0 -1
  45. package/dist/performance-monitor-UKQFA7ZR.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @oxog/devinspector v1.4.1
2
+ * @oxog/devinspector v1.5.1
3
3
  * (c) Ersin Koc <ersinkoc@gmail.com>
4
4
  * Released under the MIT License
5
5
  */
@@ -32,6 +32,15 @@
32
32
  function defaultEnabled() {
33
33
  return readNodeEnv() !== 'production';
34
34
  }
35
+ /**
36
+ * A size limit from user config: non-negative finite numbers are floored (0 keeps
37
+ * nothing); anything else falls back to the default.
38
+ */
39
+ function normalizeLimit(value, fallback) {
40
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0
41
+ ? Math.floor(value)
42
+ : fallback;
43
+ }
35
44
  /** True when a DOM is available (browser, jsdom), false during SSR/Node. */
36
45
  function hasDom() {
37
46
  return typeof window !== 'undefined' && typeof document !== 'undefined';
@@ -46,7 +55,7 @@
46
55
  };
47
56
  /** Escapes a value for use in HTML text or a quoted attribute. */
48
57
  function escapeHtml(value) {
49
- return String(value).replace(/[&<>"'`]/g, ch => HTML_ESCAPES[ch]);
58
+ return String(value).replace(/[&<>"'`]/g, (ch) => HTML_ESCAPES[ch]);
50
59
  }
51
60
 
52
61
  class EventEmitter {
@@ -87,7 +96,7 @@
87
96
  return false;
88
97
  }
89
98
  const data = args[0];
90
- listeners.forEach(listener => {
99
+ listeners.forEach((listener) => {
91
100
  try {
92
101
  listener(data);
93
102
  }
@@ -139,6 +148,30 @@
139
148
  }
140
149
  }
141
150
 
151
+ /**
152
+ * Restoring monkey patches when several wrappers are stacked on one API.
153
+ *
154
+ * A wrapper that cannot be removed (something else wrapped it since) stays in
155
+ * place and passes straight through; it is remembered here with the value it
156
+ * wraps, so whoever restores the wrapper on top of it skips over it. Destroying
157
+ * inspectors or monitors in any order then still ends at the original API.
158
+ */
159
+ const retired = new WeakMap();
160
+ function unwrapRetired(value) {
161
+ let current = value;
162
+ while (current !== null && typeof current === 'function' && retired.has(current))
163
+ current = retired.get(current);
164
+ return current;
165
+ }
166
+ /** Puts `original` back on `target[key]` if `replacement` is still installed there. */
167
+ function restorePatch(target, key, replacement, original) {
168
+ const record = target;
169
+ if (record[key] === replacement)
170
+ record[key] = unwrapRetired(original);
171
+ else if (replacement !== null && typeof replacement === 'function')
172
+ retired.set(replacement, original);
173
+ }
174
+
142
175
  class PluginSystem {
143
176
  constructor(context) {
144
177
  this.plugins = new Map();
@@ -163,7 +196,7 @@
163
196
  }
164
197
  this.context.events.emit('plugin:registered', {
165
198
  name: plugin.name,
166
- version: plugin.version
199
+ version: plugin.version,
167
200
  });
168
201
  }
169
202
  catch (error) {
@@ -178,17 +211,23 @@
178
211
  if (!plugin) {
179
212
  throw new Error(`Plugin "${pluginName}" is not registered`);
180
213
  }
181
- if (plugin.disable) {
182
- plugin.disable();
214
+ try {
215
+ if (plugin.disable) {
216
+ plugin.disable();
217
+ }
218
+ if (plugin.uninstall) {
219
+ await plugin.uninstall();
220
+ }
183
221
  }
184
- if (plugin.uninstall) {
185
- await plugin.uninstall();
222
+ finally {
223
+ // Removed even when disable()/uninstall() throws (the error still reaches the
224
+ // caller), so a broken plugin is not left registered and active.
225
+ this.plugins.delete(pluginName);
226
+ this.activePlugins.delete(pluginName);
227
+ this.context.events.emit('plugin:unregistered', {
228
+ name: pluginName,
229
+ });
186
230
  }
187
- this.plugins.delete(pluginName);
188
- this.activePlugins.delete(pluginName);
189
- this.context.events.emit('plugin:unregistered', {
190
- name: pluginName
191
- });
192
231
  }
193
232
  enable(pluginName) {
194
233
  const plugin = this.plugins.get(pluginName);
@@ -203,7 +242,7 @@
203
242
  }
204
243
  this.activePlugins.add(pluginName);
205
244
  this.context.events.emit('plugin:enabled', {
206
- name: pluginName
245
+ name: pluginName,
207
246
  });
208
247
  }
209
248
  disable(pluginName) {
@@ -219,7 +258,7 @@
219
258
  }
220
259
  this.activePlugins.delete(pluginName);
221
260
  this.context.events.emit('plugin:disabled', {
222
- name: pluginName
261
+ name: pluginName,
223
262
  });
224
263
  }
225
264
  get(pluginName) {
@@ -235,7 +274,7 @@
235
274
  return Array.from(this.plugins.values());
236
275
  }
237
276
  getActive() {
238
- return Array.from(this.activePlugins).map(name => this.plugins.get(name));
277
+ return Array.from(this.activePlugins).map((name) => this.plugins.get(name));
239
278
  }
240
279
  getMetadata(pluginName) {
241
280
  const plugin = this.plugins.get(pluginName);
@@ -245,14 +284,14 @@
245
284
  return {
246
285
  name: plugin.name,
247
286
  version: plugin.version,
248
- description: plugin.description
287
+ description: plugin.description,
249
288
  };
250
289
  }
251
290
  getAllMetadata() {
252
- return this.getAll().map(plugin => ({
291
+ return this.getAll().map((plugin) => ({
253
292
  name: plugin.name,
254
293
  version: plugin.version,
255
- description: plugin.description
294
+ description: plugin.description,
256
295
  }));
257
296
  }
258
297
  }
@@ -296,7 +335,7 @@
296
335
  }
297
336
 
298
337
  /** Package version, kept in sync with package.json (checked by tests). */
299
- const VERSION = '1.4.1';
338
+ const VERSION = '1.5.1';
300
339
 
301
340
  /**
302
341
  * DevInspector - the default inspector: floating widget plus a panel with
@@ -312,38 +351,71 @@
312
351
  const ASSET_PATTERN = /\.(?:css|js|mjs|map|png|jpe?g|gif|svg|webp|avif|ico|woff2?|ttf|otf|eot)(?:[?#]|$)/i;
313
352
  const POSITIONS = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
314
353
  const PALETTES = {
315
- dark: { bg: '#1a1a1a', header: '#262626', toolbar: '#1e1e1e', border: '#333', row: '#2a2a2a', text: '#e4e4e7', muted: '#9ca3af', code: '#0f0f0f' },
316
- light: { bg: '#ffffff', header: '#f3f4f6', toolbar: '#f9fafb', border: '#d1d5db', row: '#e5e7eb', text: '#111827', muted: '#4b5563', code: '#f3f4f6' },
354
+ dark: {
355
+ bg: '#1a1a1a',
356
+ header: '#262626',
357
+ toolbar: '#1e1e1e',
358
+ border: '#333',
359
+ row: '#2a2a2a',
360
+ text: '#e4e4e7',
361
+ muted: '#9ca3af',
362
+ code: '#0f0f0f',
363
+ },
364
+ light: {
365
+ bg: '#ffffff',
366
+ header: '#f3f4f6',
367
+ toolbar: '#f9fafb',
368
+ border: '#d1d5db',
369
+ row: '#e5e7eb',
370
+ text: '#111827',
371
+ muted: '#4b5563',
372
+ code: '#f3f4f6',
373
+ },
317
374
  };
318
375
  let idCounter = 0;
319
376
  function nextId() {
320
377
  idCounter = (idCounter + 1) % Number.MAX_SAFE_INTEGER;
321
378
  return `${Date.now().toString(36)}-${idCounter.toString(36)}`;
322
379
  }
323
- function limit(value, fallback) {
324
- return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
325
- }
326
380
  function normalizeCombo(combo) {
327
381
  if (typeof combo !== 'string')
328
382
  return '';
329
- const parts = combo.toLowerCase().split('+').map(part => part.trim()).filter(Boolean);
330
- const key = parts.filter(part => !['ctrl', 'control', 'alt', 'shift', 'meta', 'cmd'].includes(part));
383
+ const parts = combo
384
+ .toLowerCase()
385
+ .split('+')
386
+ .map((part) => part.trim())
387
+ .filter(Boolean);
388
+ const key = parts.filter((part) => !['ctrl', 'control', 'alt', 'shift', 'meta', 'cmd'].includes(part));
331
389
  if (key.length !== 1)
332
390
  return '';
333
- const has = (...names) => names.some(name => parts.includes(name));
334
- return [has('ctrl', 'control') && 'ctrl', has('alt') && 'alt', has('shift') && 'shift', has('meta', 'cmd') && 'meta', key[0]]
391
+ const has = (...names) => names.some((name) => parts.includes(name));
392
+ return [
393
+ has('ctrl', 'control') && 'ctrl',
394
+ has('alt') && 'alt',
395
+ has('shift') && 'shift',
396
+ has('meta', 'cmd') && 'meta',
397
+ key[0],
398
+ ]
335
399
  .filter(Boolean)
336
400
  .join('+');
337
401
  }
338
402
  function eventCombo(event) {
339
403
  if (typeof event.key !== 'string')
340
404
  return '';
341
- return [event.ctrlKey && 'ctrl', event.altKey && 'alt', event.shiftKey && 'shift', event.metaKey && 'meta', event.key.toLowerCase()]
405
+ return [
406
+ event.ctrlKey && 'ctrl',
407
+ event.altKey && 'alt',
408
+ event.shiftKey && 'shift',
409
+ event.metaKey && 'meta',
410
+ event.key.toLowerCase(),
411
+ ]
342
412
  .filter(Boolean)
343
413
  .join('+');
344
414
  }
345
415
  function truncate(text) {
346
- return text.length > MAX_MESSAGE_LENGTH ? `${text.slice(0, MAX_MESSAGE_LENGTH)}… (${text.length - MAX_MESSAGE_LENGTH} more characters)` : text;
416
+ return text.length > MAX_MESSAGE_LENGTH
417
+ ? `${text.slice(0, MAX_MESSAGE_LENGTH)}… (${text.length - MAX_MESSAGE_LENGTH} more characters)`
418
+ : text;
347
419
  }
348
420
  function stringifyArg(arg) {
349
421
  if (typeof arg === 'string')
@@ -465,7 +537,11 @@
465
537
  this.setupHotkeys();
466
538
  this.mountWhenReady();
467
539
  for (const plugin of (_a = config.plugins) !== null && _a !== void 0 ? _a : []) {
468
- this.use(plugin).catch(error => this.reportInternal('Failed to register plugin', error));
540
+ this.use(plugin).catch((error) => {
541
+ // After destroy() the plugin was uninstalled again; nothing to report.
542
+ if (!this.destroyed)
543
+ this.reportInternal('Failed to register plugin', error);
544
+ });
469
545
  }
470
546
  this.events.emit('inspector:ready');
471
547
  }
@@ -491,7 +567,9 @@
491
567
  const hotkeys = (_b = config.hotkeys) !== null && _b !== void 0 ? _b : {};
492
568
  return {
493
569
  enabled: typeof config.enabled === 'boolean' ? config.enabled : defaultEnabled(),
494
- position: POSITIONS.includes(config.position) ? config.position : 'bottom-right',
570
+ position: POSITIONS.includes(config.position)
571
+ ? config.position
572
+ : 'bottom-right',
495
573
  theme: theme === 'auto' ? (prefersDark ? 'dark' : 'light') : theme,
496
574
  hotkeys: {
497
575
  toggle: normalizeCombo((_c = hotkeys.toggle) !== null && _c !== void 0 ? _c : 'ctrl+shift+d'),
@@ -503,12 +581,12 @@
503
581
  performance: features.performance !== false,
504
582
  errors: features.errors !== false,
505
583
  },
506
- maxNetworkEntries: limit(config.maxNetworkEntries, 1000),
507
- maxConsoleEntries: limit(config.maxConsoleEntries, 500),
508
- maxErrorEntries: limit(config.maxErrorEntries, 100),
584
+ maxNetworkEntries: normalizeLimit(config.maxNetworkEntries, 1000),
585
+ maxConsoleEntries: normalizeLimit(config.maxConsoleEntries, 500),
586
+ maxErrorEntries: normalizeLimit(config.maxErrorEntries, 100),
509
587
  captureStackTraces: config.captureStackTraces !== false,
510
588
  hideAssets: ((_e = config.networkFilters) === null || _e === void 0 ? void 0 : _e.hideAssets) === true,
511
- slowRequestThreshold: limit(config.slowRequestThreshold, 3000),
589
+ slowRequestThreshold: normalizeLimit(config.slowRequestThreshold, 3000),
512
590
  onError: typeof config.onError === 'function' ? config.onError : undefined,
513
591
  onPerformanceIssue: typeof config.onPerformanceIssue === 'function' ? config.onPerformanceIssue : undefined,
514
592
  };
@@ -554,8 +632,9 @@
554
632
  if (!this.isEnabled)
555
633
  return;
556
634
  this.isMinimized = !this.isMinimized;
635
+ // Minimized, the panel is as tall as its header (a fixed height clipped it).
557
636
  if (this.panel)
558
- this.panel.style.height = this.isMinimized ? '48px' : '650px';
637
+ this.panel.style.height = this.isMinimized ? 'auto' : '650px';
559
638
  this.render();
560
639
  this.events.emit('inspector:minimize', this.isMinimized);
561
640
  }
@@ -584,20 +663,25 @@
584
663
  getEntries(type) {
585
664
  switch (type) {
586
665
  case 'network':
587
- return this.network.map(entry => ({ ...entry }));
666
+ return this.network.map((entry) => ({ ...entry }));
588
667
  case 'console':
589
- return this.consoleEntries.map(entry => ({ ...entry }));
668
+ return this.consoleEntries.map((entry) => ({ ...entry }));
590
669
  case 'errors':
591
- return this.errors.map(entry => ({ ...entry }));
670
+ return this.errors.map((entry) => ({ ...entry }));
592
671
  default:
593
- return this.metrics.map(entry => ({ ...entry }));
672
+ return this.metrics.map((entry) => ({ ...entry }));
594
673
  }
595
674
  }
596
675
  /** Records a custom metric and emits `performance:metric`. */
597
676
  track(name, data) {
598
677
  if (!this.isEnabled)
599
678
  return;
600
- const entry = { id: nextId(), name: String(name), data, timestamp: Date.now() };
679
+ const entry = {
680
+ id: nextId(),
681
+ name: String(name),
682
+ data,
683
+ timestamp: Date.now(),
684
+ };
601
685
  this.pushBounded(this.metrics, entry, MAX_METRIC_ENTRIES);
602
686
  this.emitSafely('performance:metric', entry);
603
687
  this.scheduleRender();
@@ -632,7 +716,12 @@
632
716
  catch (_c) {
633
717
  // See markStart().
634
718
  }
635
- const entry = { id: nextId(), name: key, duration, timestamp: Date.now() };
719
+ const entry = {
720
+ id: nextId(),
721
+ name: key,
722
+ duration,
723
+ timestamp: Date.now(),
724
+ };
636
725
  this.pushBounded(this.metrics, entry, MAX_METRIC_ENTRIES);
637
726
  this.emitSafely('performance:mark', entry);
638
727
  this.scheduleRender();
@@ -642,7 +731,15 @@
642
731
  use(plugin) {
643
732
  if (this.destroyed)
644
733
  return Promise.reject(new Error('DevInspector has been destroyed'));
645
- return this.pluginSystem.register(plugin);
734
+ return this.pluginSystem.register(plugin).then(async () => {
735
+ if (!this.destroyed)
736
+ return;
737
+ // destroy() ran while install() was pending and could not see the plugin yet.
738
+ await this.pluginSystem
739
+ .unregister(plugin.name)
740
+ .catch((error) => this.reportInternal(`Failed to uninstall plugin "${plugin.name}"`, error));
741
+ throw new Error('DevInspector has been destroyed');
742
+ });
646
743
  }
647
744
  on(event, listener) {
648
745
  return this.events.on(event, listener);
@@ -675,19 +772,25 @@
675
772
  if (!data || typeof data !== 'object')
676
773
  throw new TypeError('DevInspector.import() expects an object produced by export()');
677
774
  const source = data;
678
- const list = (value) => Array.isArray(value) ? value.filter((item) => !!item && typeof item === 'object') : [];
679
- const str = (value, fallback = '') => (typeof value === 'string' ? value : fallback);
680
- const num = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined);
775
+ const list = (value) => Array.isArray(value)
776
+ ? value.filter((item) => !!item && typeof item === 'object')
777
+ : [];
778
+ const str = (value, fallback = '') => typeof value === 'string' ? value : fallback;
779
+ const num = (value) => typeof value === 'number' && Number.isFinite(value) ? value : undefined;
681
780
  this.network = list(source.network)
682
781
  .slice(0, this.config.maxNetworkEntries)
683
- .map(item => {
782
+ .map((item) => {
684
783
  var _a;
685
784
  return ({
686
785
  id: str(item.id, nextId()),
687
786
  type: item.type === 'xhr' ? 'xhr' : 'fetch',
688
787
  url: str(item.url),
689
788
  method: str(item.method, 'GET'),
690
- status: typeof item.status === 'number' ? item.status : item.status === 'pending' ? 'pending' : 'error',
789
+ status: typeof item.status === 'number'
790
+ ? item.status
791
+ : item.status === 'pending'
792
+ ? 'pending'
793
+ : 'error',
691
794
  timestamp: (_a = num(item.timestamp)) !== null && _a !== void 0 ? _a : Date.now(),
692
795
  duration: num(item.duration),
693
796
  error: typeof item.error === 'string' ? item.error : undefined,
@@ -695,18 +798,20 @@
695
798
  });
696
799
  this.consoleEntries = list(source.console)
697
800
  .slice(0, this.config.maxConsoleEntries)
698
- .map(item => {
801
+ .map((item) => {
699
802
  var _a;
700
803
  return ({
701
804
  id: str(item.id, nextId()),
702
- level: CONSOLE_METHODS.includes(item.level) ? item.level : 'log',
805
+ level: CONSOLE_METHODS.includes(item.level)
806
+ ? item.level
807
+ : 'log',
703
808
  message: truncate(str(item.message)),
704
809
  timestamp: (_a = num(item.timestamp)) !== null && _a !== void 0 ? _a : Date.now(),
705
810
  });
706
811
  });
707
812
  this.errors = list(source.errors)
708
813
  .slice(0, this.config.maxErrorEntries)
709
- .map(item => {
814
+ .map((item) => {
710
815
  var _a;
711
816
  return ({
712
817
  id: str(item.id, nextId()),
@@ -718,7 +823,7 @@
718
823
  });
719
824
  this.metrics = list(source.metrics)
720
825
  .slice(0, MAX_METRIC_ENTRIES)
721
- .map(item => {
826
+ .map((item) => {
722
827
  var _a;
723
828
  return ({
724
829
  id: str(item.id, nextId()),
@@ -741,10 +846,9 @@
741
846
  return;
742
847
  this.destroyed = true;
743
848
  for (const patch of this.patches.reverse()) {
744
- // Only restore when nobody has wrapped our replacement since; otherwise the
849
+ // Only restored when nobody has wrapped our replacement since; otherwise the
745
850
  // replacement stays in place but passes straight through (destroyed flag).
746
- if (patch.target[patch.key] === patch.replacement)
747
- patch.target[patch.key] = patch.original;
851
+ restorePatch(patch.target, patch.key, patch.replacement, patch.original);
748
852
  }
749
853
  this.patches = [];
750
854
  for (const cleanup of this.cleanups.splice(0)) {
@@ -761,7 +865,9 @@
761
865
  this.widget = null;
762
866
  this.panel = null;
763
867
  for (const plugin of this.pluginSystem.getAll()) {
764
- this.pluginSystem.unregister(plugin.name).catch(error => this.reportInternal(`Failed to uninstall plugin "${plugin.name}"`, error));
868
+ this.pluginSystem
869
+ .unregister(plugin.name)
870
+ .catch((error) => this.reportInternal(`Failed to uninstall plugin "${plugin.name}"`, error));
765
871
  }
766
872
  this.emitSafely('inspector:destroy', undefined);
767
873
  this.events.removeAllListeners();
@@ -770,7 +876,7 @@
770
876
  this.errors = [];
771
877
  this.metrics = [];
772
878
  this.marks.clear();
773
- EnhancedDevInspector.instances = EnhancedDevInspector.instances.filter(instance => instance !== this);
879
+ EnhancedDevInspector.instances = EnhancedDevInspector.instances.filter((instance) => instance !== this);
774
880
  }
775
881
  // ---------------------------------------------------------------------------
776
882
  // Capture
@@ -822,7 +928,12 @@
822
928
  entry.error = error;
823
929
  this.emitSafely(status === 'error' ? 'network:error' : 'network:response', { ...entry });
824
930
  if (duration > this.config.slowRequestThreshold) {
825
- const issue = { type: 'slow-network', message: `Slow network request: ${entry.url}`, url: entry.url, duration: entry.duration };
931
+ const issue = {
932
+ type: 'slow-network',
933
+ message: `Slow network request: ${entry.url}`,
934
+ url: entry.url,
935
+ duration: entry.duration,
936
+ };
826
937
  this.emitSafely('performance:issue', issue);
827
938
  this.callUser(this.config.onPerformanceIssue, issue);
828
939
  }
@@ -839,7 +950,14 @@
839
950
  let entry = null;
840
951
  const start = performance.now();
841
952
  self.capture(() => {
842
- entry = { id: nextId(), type: 'fetch', url: requestUrl(args[0]), method: requestMethod(args[0], args[1]), status: 'pending', timestamp: Date.now() };
953
+ entry = {
954
+ id: nextId(),
955
+ type: 'fetch',
956
+ url: requestUrl(args[0]),
957
+ method: requestMethod(args[0], args[1]),
958
+ status: 'pending',
959
+ timestamp: Date.now(),
960
+ };
843
961
  self.addNetworkEntry(entry);
844
962
  });
845
963
  if (!entry)
@@ -854,7 +972,7 @@
854
972
  self.capture(() => self.finishNetworkEntry(tracked, 'error', performance.now() - start, error instanceof Error ? error.message : String(error)));
855
973
  throw error;
856
974
  }
857
- return Promise.resolve(result).then(response => {
975
+ return Promise.resolve(result).then((response) => {
858
976
  self.capture(() => self.finishNetworkEntry(tracked, response.status, performance.now() - start));
859
977
  return response;
860
978
  }, (error) => {
@@ -878,24 +996,56 @@
878
996
  // Patch the prototype rather than replacing the constructor, so
879
997
  // `instanceof XMLHttpRequest` and constants such as XMLHttpRequest.DONE keep working.
880
998
  const open = function (...args) {
999
+ var _a, _b;
1000
+ const result = Reflect.apply(originalOpen, this, args);
881
1001
  if (!self.destroyed) {
882
- self.xhrState.set(this, { method: typeof args[0] === 'string' ? args[0].toUpperCase() : 'GET', url: requestUrl(args[1]) });
1002
+ // open() on a request in flight terminates it without abort/loadend events.
1003
+ (_b = (_a = self.xhrState.get(this)) === null || _a === void 0 ? void 0 : _a.terminate) === null || _b === void 0 ? void 0 : _b.call(_a);
1004
+ self.xhrState.set(this, {
1005
+ method: typeof args[0] === 'string' ? args[0].toUpperCase() : 'GET',
1006
+ url: requestUrl(args[1]),
1007
+ });
883
1008
  }
884
- return Reflect.apply(originalOpen, this, args);
1009
+ return result;
885
1010
  };
886
1011
  const send = function (...args) {
1012
+ var _a;
887
1013
  const state = self.xhrState.get(this);
1014
+ const tracking = {};
888
1015
  if (state)
889
- self.capture(() => self.trackXhr(this, state));
890
- return Reflect.apply(originalSend, this, args);
1016
+ self.capture(() => (tracking.fail = self.trackXhr(this, state)));
1017
+ try {
1018
+ return Reflect.apply(originalSend, this, args);
1019
+ }
1020
+ catch (error) {
1021
+ // send() threw (e.g. InvalidStateError on a second send(), or a synchronous
1022
+ // NetworkError): no request was started by this call.
1023
+ (_a = tracking.fail) === null || _a === void 0 ? void 0 : _a.call(tracking, error);
1024
+ throw error;
1025
+ }
891
1026
  };
892
1027
  this.patch(proto, 'open', open);
893
1028
  this.patch(proto, 'send', send);
894
1029
  }
895
1030
  trackXhr(xhr, state) {
896
- const entry = { id: nextId(), type: 'xhr', url: state.url, method: state.method, status: 'pending', timestamp: Date.now() };
1031
+ const previous = {
1032
+ entry: state.entry,
1033
+ start: state.start,
1034
+ failure: state.failure,
1035
+ terminate: state.terminate,
1036
+ };
1037
+ let settled = false;
1038
+ const entry = {
1039
+ id: nextId(),
1040
+ type: 'xhr',
1041
+ url: state.url,
1042
+ method: state.method,
1043
+ status: 'pending',
1044
+ timestamp: Date.now(),
1045
+ };
1046
+ const startedAt = performance.now();
897
1047
  state.entry = entry;
898
- state.start = performance.now();
1048
+ state.start = startedAt;
899
1049
  state.failure = undefined;
900
1050
  const fail = (reason) => () => {
901
1051
  state.failure = reason;
@@ -903,23 +1053,50 @@
903
1053
  const onError = fail('Network error');
904
1054
  const onAbort = fail('Request aborted');
905
1055
  const onTimeout = fail('Request timed out');
906
- const onLoadEnd = () => {
907
- var _a;
1056
+ const detach = () => {
908
1057
  xhr.removeEventListener('error', onError);
909
1058
  xhr.removeEventListener('abort', onAbort);
910
1059
  xhr.removeEventListener('timeout', onTimeout);
911
1060
  xhr.removeEventListener('loadend', onLoadEnd);
912
- if (state.entry !== entry || this.destroyed)
1061
+ };
1062
+ const onLoadEnd = () => {
1063
+ var _a;
1064
+ detach();
1065
+ if (settled || state.entry !== entry || this.destroyed)
913
1066
  return;
1067
+ settled = true;
914
1068
  const duration = performance.now() - ((_a = state.start) !== null && _a !== void 0 ? _a : performance.now());
915
1069
  const failed = state.failure !== undefined || xhr.status === 0;
916
- this.capture(() => { var _a; return this.finishNetworkEntry(entry, failed ? 'error' : xhr.status, duration, failed ? (_a = state.failure) !== null && _a !== void 0 ? _a : 'Network error' : undefined); });
1070
+ this.capture(() => {
1071
+ var _a;
1072
+ return this.finishNetworkEntry(entry, failed ? 'error' : xhr.status, duration, failed ? ((_a = state.failure) !== null && _a !== void 0 ? _a : 'Network error') : undefined);
1073
+ });
917
1074
  };
918
1075
  xhr.addEventListener('error', onError);
919
1076
  xhr.addEventListener('abort', onAbort);
920
1077
  xhr.addEventListener('timeout', onTimeout);
921
1078
  xhr.addEventListener('loadend', onLoadEnd);
1079
+ state.terminate = () => {
1080
+ detach();
1081
+ if (settled || this.destroyed)
1082
+ return;
1083
+ settled = true;
1084
+ this.capture(() => this.finishNetworkEntry(entry, 'error', performance.now() - startedAt, 'Request aborted'));
1085
+ };
922
1086
  this.addNetworkEntry(entry);
1087
+ // Called when send() throws: the request already in flight (if any) keeps its
1088
+ // own entry, and this attempt is recorded as failed.
1089
+ return (error) => {
1090
+ detach();
1091
+ if (settled)
1092
+ return;
1093
+ settled = true;
1094
+ if (state.entry === entry)
1095
+ Object.assign(state, previous);
1096
+ if (this.destroyed)
1097
+ return;
1098
+ this.capture(() => this.finishNetworkEntry(entry, 'error', performance.now() - startedAt, error instanceof Error ? error.message : String(error)));
1099
+ };
923
1100
  }
924
1101
  interceptConsole() {
925
1102
  // eslint-disable-next-line @typescript-eslint/no-this-alias
@@ -957,7 +1134,9 @@
957
1134
  this.listen(window, 'error', (event) => {
958
1135
  this.capture(() => {
959
1136
  var _a;
960
- const error = event.error instanceof Error ? event.error : new Error(String((_a = event.message) !== null && _a !== void 0 ? _a : 'Unknown error'));
1137
+ const error = event.error instanceof Error
1138
+ ? event.error
1139
+ : new Error(String((_a = event.message) !== null && _a !== void 0 ? _a : 'Unknown error'));
961
1140
  record({
962
1141
  id: nextId(),
963
1142
  type: 'JavaScript Error',
@@ -979,7 +1158,9 @@
979
1158
  type: 'Promise Rejection',
980
1159
  message: truncate(error.message),
981
1160
  timestamp: Date.now(),
982
- stack: this.config.captureStackTraces && reason instanceof Error && reason.stack ? truncate(reason.stack) : undefined,
1161
+ stack: this.config.captureStackTraces && reason instanceof Error && reason.stack
1162
+ ? truncate(reason.stack)
1163
+ : undefined,
983
1164
  }, error);
984
1165
  });
985
1166
  });
@@ -1015,7 +1196,7 @@
1015
1196
  }
1016
1197
  reportInternal(message, error) {
1017
1198
  // Use the unpatched console so internal problems are visible but never captured.
1018
- const patched = this.patches.find(patch => patch.target === console && patch.key === 'error');
1199
+ const patched = this.patches.find((patch) => patch.target === console && patch.key === 'error');
1019
1200
  const log = (patched ? patched.original : console.error);
1020
1201
  try {
1021
1202
  log.call(console, `[DevInspector] ${message}:`, error);
@@ -1028,7 +1209,9 @@
1028
1209
  // Performance loop (runs only while the panel is visible)
1029
1210
  // ---------------------------------------------------------------------------
1030
1211
  startPerformanceLoop() {
1031
- if (!this.config.features.performance || this.rafId !== null || typeof requestAnimationFrame !== 'function')
1212
+ if (!this.config.features.performance ||
1213
+ this.rafId !== null ||
1214
+ typeof requestAnimationFrame !== 'function')
1032
1215
  return;
1033
1216
  let last = performance.now();
1034
1217
  let frames = 0;
@@ -1104,7 +1287,7 @@
1104
1287
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; font-size: 13px;
1105
1288
  color: ${this.colors.text}; overflow: hidden;`;
1106
1289
  // One delegated listener survives every re-render (no per-render listener churn).
1107
- panel.addEventListener('click', event => this.handlePanelClick(event));
1290
+ panel.addEventListener('click', (event) => this.handlePanelClick(event));
1108
1291
  this.widget = widget;
1109
1292
  this.panel = panel;
1110
1293
  document.body.appendChild(widget);
@@ -1187,7 +1370,7 @@
1187
1370
  return;
1188
1371
  }
1189
1372
  const tabBar = tabs
1190
- .map(tab => `<button type="button" data-action="tab" data-tab="${tab.id}" style="padding: 12px 16px; border: none; cursor: pointer;
1373
+ .map((tab) => `<button type="button" data-action="tab" data-tab="${tab.id}" style="padding: 12px 16px; border: none; cursor: pointer;
1191
1374
  background: ${this.activeTab === tab.id ? c.bg : 'transparent'}; color: ${this.activeTab === tab.id ? '#3b82f6' : c.muted};
1192
1375
  border-bottom: 2px solid ${this.activeTab === tab.id ? '#3b82f6' : 'transparent'};">${tab.label}${tab.count !== undefined
1193
1376
  ? ` <span style="background: #374151; color: white; padding: 2px 6px; border-radius: 10px; font-size: 11px; margin-left: 4px;">${tab.count}</span>`
@@ -1223,9 +1406,11 @@
1223
1406
  renderNetwork(button) {
1224
1407
  var _a;
1225
1408
  const c = this.colors;
1226
- const visible = this.config.hideAssets ? this.network.filter(entry => !ASSET_PATTERN.test(entry.url)) : this.network;
1409
+ const visible = this.config.hideAssets
1410
+ ? this.network.filter((entry) => !ASSET_PATTERN.test(entry.url))
1411
+ : this.network;
1227
1412
  const rows = visible
1228
- .map(entry => {
1413
+ .map((entry) => {
1229
1414
  var _a;
1230
1415
  const selected = entry.id === this.selectedRequestId;
1231
1416
  return `<div data-action="select-request" data-id="${escapeHtml(entry.id)}" style="padding: 10px 16px; border-bottom: 1px solid ${c.row}; cursor: pointer; ${selected ? 'background: rgba(59, 130, 246, 0.25);' : ''}">
@@ -1241,7 +1426,9 @@
1241
1426
  </div>`;
1242
1427
  })
1243
1428
  .join('');
1244
- const selected = this.selectedRequestId ? this.network.find(entry => entry.id === this.selectedRequestId) : undefined;
1429
+ const selected = this.selectedRequestId
1430
+ ? this.network.find((entry) => entry.id === this.selectedRequestId)
1431
+ : undefined;
1245
1432
  const details = selected
1246
1433
  ? `<div style="border-top: 1px solid ${c.border}; max-height: 200px; overflow-y: auto; background: ${c.toolbar}; padding: 12px 16px; font-size: 12px;">
1247
1434
  <div style="display: flex; justify-content: space-between; margin-bottom: 8px;"><strong>Request details</strong>
@@ -1261,7 +1448,7 @@
1261
1448
  renderConsole(button) {
1262
1449
  const c = this.colors;
1263
1450
  const rows = this.consoleEntries
1264
- .map(entry => `<div style="padding: 8px 16px; border-bottom: 1px solid ${c.row}; font-size: 12px;">
1451
+ .map((entry) => `<div style="padding: 8px 16px; border-bottom: 1px solid ${c.row}; font-size: 12px;">
1265
1452
  <span style="color: ${levelColor(entry.level)}; text-transform: uppercase; font-weight: 600;">[${escapeHtml(entry.level)}]</span>
1266
1453
  <span style="color: ${c.muted}; margin: 0 8px;">${escapeHtml(new Date(entry.timestamp).toLocaleTimeString())}</span>
1267
1454
  <span style="white-space: pre-wrap; word-break: break-word;">${escapeHtml(entry.message)}</span>
@@ -1275,7 +1462,7 @@
1275
1462
  const { fps, memory } = this.performanceStats;
1276
1463
  const rows = this.metrics
1277
1464
  .slice(0, 100)
1278
- .map(metric => `<div style="padding: 6px 0; border-bottom: 1px solid ${c.row}; font-size: 12px;">
1465
+ .map((metric) => `<div style="padding: 6px 0; border-bottom: 1px solid ${c.row}; font-size: 12px;">
1279
1466
  <strong>${escapeHtml(metric.name)}</strong>
1280
1467
  ${metric.duration !== undefined ? `<span style="color: ${c.muted};"> ${metric.duration.toFixed(1)}ms</span>` : ''}
1281
1468
  ${metric.data !== undefined ? `<span style="color: ${c.muted};"> ${escapeHtml(truncate(stringifyArg(metric.data)))}</span>` : ''}
@@ -1299,7 +1486,7 @@
1299
1486
  renderErrors(button) {
1300
1487
  const c = this.colors;
1301
1488
  const rows = this.errors
1302
- .map(error => `<div style="padding: 12px 16px; border-bottom: 1px solid ${c.row};">
1489
+ .map((error) => `<div style="padding: 12px 16px; border-bottom: 1px solid ${c.row};">
1303
1490
  <div style="display: flex; justify-content: space-between; margin-bottom: 6px;">
1304
1491
  <span style="color: #ef4444; font-weight: 600;">${escapeHtml(error.type)}</span>
1305
1492
  <span style="color: ${c.muted}; font-size: 11px;">${escapeHtml(new Date(error.timestamp).toLocaleTimeString())}</span>
@@ -1361,17 +1548,25 @@
1361
1548
  this.tail = 0;
1362
1549
  this.size = 0;
1363
1550
  this.idCounter = 0;
1364
- this.maxSize = options.maxSize;
1551
+ const { maxSize } = options;
1552
+ if (typeof maxSize !== 'number' || !Number.isFinite(maxSize) || maxSize < 0) {
1553
+ throw new RangeError(`CircularStorage maxSize must be a non-negative finite number, got ${String(maxSize)}`);
1554
+ }
1555
+ // Fractions are floored; 0 keeps nothing (as the inspectors' entry limits do).
1556
+ this.maxSize = Math.floor(maxSize);
1365
1557
  this.ttl = options.ttl;
1366
1558
  this.onEvict = options.onEvict;
1367
1559
  this.buffer = new Array(this.maxSize);
1368
1560
  }
1369
1561
  push(data) {
1370
1562
  const id = `${Date.now()}-${++this.idCounter}`;
1563
+ // maxSize 0 stores nothing (and the ring arithmetic below would divide by zero).
1564
+ if (this.maxSize === 0)
1565
+ return id;
1371
1566
  const entry = {
1372
1567
  id,
1373
1568
  timestamp: Date.now(),
1374
- data
1569
+ data,
1375
1570
  };
1376
1571
  if (this.size === this.maxSize) {
1377
1572
  const evictedEntry = this.buffer[this.tail];
@@ -1395,7 +1590,7 @@
1395
1590
  return undefined;
1396
1591
  }
1397
1592
  getAll() {
1398
- return this.getAllEntries().map(entry => entry.data);
1593
+ return this.getAllEntries().map((entry) => entry.data);
1399
1594
  }
1400
1595
  getAllEntries() {
1401
1596
  const entries = [];
@@ -1420,8 +1615,8 @@
1420
1615
  }
1421
1616
  filter(predicate) {
1422
1617
  return this.getAllEntries()
1423
- .filter(entry => predicate(entry.data))
1424
- .map(entry => entry.data);
1618
+ .filter((entry) => predicate(entry.data))
1619
+ .map((entry) => entry.data);
1425
1620
  }
1426
1621
  clear() {
1427
1622
  this.buffer = new Array(this.maxSize);
@@ -1451,6 +1646,7 @@
1451
1646
  return now - entry.timestamp > this.ttl;
1452
1647
  }
1453
1648
  removeExpired() {
1649
+ var _a;
1454
1650
  if (!this.ttl)
1455
1651
  return 0;
1456
1652
  const now = Date.now();
@@ -1462,8 +1658,8 @@
1462
1658
  if (entry && !this.isExpired(entry, now)) {
1463
1659
  validEntries.push(entry);
1464
1660
  }
1465
- else if (entry && this.onEvict) {
1466
- this.onEvict(entry);
1661
+ else if (entry) {
1662
+ (_a = this.onEvict) === null || _a === void 0 ? void 0 : _a.call(this, entry);
1467
1663
  removedCount++;
1468
1664
  }
1469
1665
  }
@@ -1489,7 +1685,7 @@
1489
1685
  const entry = {
1490
1686
  id: key,
1491
1687
  timestamp: Date.now(),
1492
- data
1688
+ data,
1493
1689
  };
1494
1690
  if (this.storage.has(key)) {
1495
1691
  // Optimize: use splice instead of filter to avoid creating new array
@@ -1539,14 +1735,14 @@
1539
1735
  this.onEvict(entry);
1540
1736
  }
1541
1737
  this.storage.delete(key);
1542
- this.accessOrder = this.accessOrder.filter(k => k !== key);
1738
+ this.accessOrder = this.accessOrder.filter((k) => k !== key);
1543
1739
  return true;
1544
1740
  }
1545
1741
  return false;
1546
1742
  }
1547
1743
  clear() {
1548
1744
  if (this.onEvict) {
1549
- this.storage.forEach(entry => this.onEvict(entry));
1745
+ this.storage.forEach((entry) => this.onEvict(entry));
1550
1746
  }
1551
1747
  this.storage.clear();
1552
1748
  this.accessOrder = [];
@@ -1559,8 +1755,8 @@
1559
1755
  }
1560
1756
  getAllValues() {
1561
1757
  return Array.from(this.storage.values())
1562
- .filter(entry => !this.isExpired(entry))
1563
- .map(entry => entry.data);
1758
+ .filter((entry) => !this.isExpired(entry))
1759
+ .map((entry) => entry.data);
1564
1760
  }
1565
1761
  updateAccessOrder(key) {
1566
1762
  // Optimize: use splice instead of filter to avoid creating new array
@@ -1583,7 +1779,7 @@
1583
1779
  expiredKeys.push(key);
1584
1780
  }
1585
1781
  });
1586
- expiredKeys.forEach(key => {
1782
+ expiredKeys.forEach((key) => {
1587
1783
  if (this.delete(key)) {
1588
1784
  removedCount++;
1589
1785
  }
@@ -1606,6 +1802,7 @@
1606
1802
  this.cleanupFunctions = [];
1607
1803
  this.initPromise = null;
1608
1804
  this.destroyed = false;
1805
+ this.uninstallingPlugins = new Set();
1609
1806
  if (DevInspector.instance) {
1610
1807
  console.warn('DevInspector instance already exists. Returning existing instance.');
1611
1808
  return DevInspector.instance;
@@ -1614,19 +1811,19 @@
1614
1811
  this.events = new EventEmitter({ maxListeners: 100 });
1615
1812
  this.networkStorage = new CircularStorage({
1616
1813
  maxSize: this.config.maxNetworkEntries,
1617
- onEvict: (entry) => this.events.emit('network:evict', entry)
1814
+ onEvict: (entry) => this.events.emit('network:evict', entry),
1618
1815
  });
1619
1816
  this.consoleStorage = new CircularStorage({
1620
1817
  maxSize: this.config.maxConsoleEntries,
1621
- onEvict: (entry) => this.events.emit('console:evict', entry)
1818
+ onEvict: (entry) => this.events.emit('console:evict', entry),
1622
1819
  });
1623
1820
  this.performanceStorage = new IndexedStorage({
1624
1821
  maxSize: 1000,
1625
- ttl: 60 * 60 * 1000 // 1 hour
1822
+ ttl: 60 * 60 * 1000, // 1 hour
1626
1823
  });
1627
1824
  this.errorStorage = new CircularStorage({
1628
1825
  maxSize: this.config.maxErrorEntries,
1629
- onEvict: (entry) => this.events.emit('error:evict', entry)
1826
+ onEvict: (entry) => this.events.emit('error:evict', entry),
1630
1827
  });
1631
1828
  this.pluginSystem = new PluginSystem({
1632
1829
  inspector: this,
@@ -1634,10 +1831,10 @@
1634
1831
  network: this.networkStorage,
1635
1832
  console: this.consoleStorage,
1636
1833
  performance: this.performanceStorage,
1637
- error: this.errorStorage
1834
+ error: this.errorStorage,
1638
1835
  },
1639
1836
  events: this.events,
1640
- config: this.config
1837
+ config: this.config,
1641
1838
  });
1642
1839
  if (this.config.enabled) {
1643
1840
  void this.init();
@@ -1651,7 +1848,7 @@
1651
1848
  theme: 'auto',
1652
1849
  hotkeys: {
1653
1850
  toggle: 'ctrl+shift+d',
1654
- minimize: 'ctrl+shift+m'
1851
+ minimize: 'ctrl+shift+m',
1655
1852
  },
1656
1853
  features: {
1657
1854
  network: true,
@@ -1660,7 +1857,7 @@
1660
1857
  errors: true,
1661
1858
  state: true,
1662
1859
  dom: true,
1663
- storage: true
1860
+ storage: true,
1664
1861
  },
1665
1862
  plugins: [],
1666
1863
  maxNetworkEntries: 1000,
@@ -1668,21 +1865,25 @@
1668
1865
  captureStackTraces: true,
1669
1866
  networkFilters: {
1670
1867
  hideAssets: false,
1671
- hideCached: false
1868
+ hideCached: false,
1672
1869
  },
1673
1870
  onError: () => { },
1674
1871
  onPerformanceIssue: () => { },
1675
1872
  maxErrorEntries: 100,
1676
1873
  slowRequestThreshold: 3000,
1677
1874
  workerUrl: undefined,
1678
- remoteConfig: null
1875
+ remoteConfig: null,
1679
1876
  };
1680
1877
  return {
1681
1878
  ...defaultConfig,
1682
1879
  ...config,
1683
1880
  hotkeys: { ...defaultConfig.hotkeys, ...config.hotkeys },
1684
1881
  features: { ...defaultConfig.features, ...config.features },
1685
- networkFilters: { ...defaultConfig.networkFilters, ...config.networkFilters }
1882
+ networkFilters: { ...defaultConfig.networkFilters, ...config.networkFilters },
1883
+ // Invalid limits (negative, NaN, Infinity) fall back to the defaults, as in DevInspector.
1884
+ maxNetworkEntries: normalizeLimit(config.maxNetworkEntries, defaultConfig.maxNetworkEntries),
1885
+ maxConsoleEntries: normalizeLimit(config.maxConsoleEntries, defaultConfig.maxConsoleEntries),
1886
+ maxErrorEntries: normalizeLimit(config.maxErrorEntries, defaultConfig.maxErrorEntries),
1686
1887
  };
1687
1888
  }
1688
1889
  init() {
@@ -1707,7 +1908,6 @@
1707
1908
  if (this.destroyed)
1708
1909
  return this.teardown();
1709
1910
  this.setupHotkeys();
1710
- this.setupErrorHandlers();
1711
1911
  this.initialized = true;
1712
1912
  this.events.emit('inspector:ready');
1713
1913
  }
@@ -1795,34 +1995,6 @@
1795
1995
  document.addEventListener('keydown', handleKeydown);
1796
1996
  this.cleanupFunctions.push(() => document.removeEventListener('keydown', handleKeydown));
1797
1997
  }
1798
- setupErrorHandlers() {
1799
- if (!this.config.features.errors)
1800
- return;
1801
- const handleError = (event) => {
1802
- this.events.emit('error:uncaught', {
1803
- message: event.message,
1804
- filename: event.filename,
1805
- lineno: event.lineno,
1806
- colno: event.colno,
1807
- error: event.error,
1808
- timestamp: Date.now()
1809
- });
1810
- };
1811
- const handleRejection = (event) => {
1812
- this.events.emit('error:uncaught', {
1813
- message: 'Unhandled promise rejection',
1814
- reason: event.reason,
1815
- promise: event.promise,
1816
- timestamp: Date.now()
1817
- });
1818
- };
1819
- window.addEventListener('error', handleError);
1820
- window.addEventListener('unhandledrejection', handleRejection);
1821
- this.cleanupFunctions.push(() => {
1822
- window.removeEventListener('error', handleError);
1823
- window.removeEventListener('unhandledrejection', handleRejection);
1824
- });
1825
- }
1826
1998
  getKeyCombo(event) {
1827
1999
  const parts = [];
1828
2000
  if (event.ctrlKey)
@@ -1841,11 +2013,13 @@
1841
2013
  if (this.destroyed)
1842
2014
  return;
1843
2015
  if (!this.initialized) {
1844
- this.init().then(() => {
2016
+ this.init()
2017
+ .then(() => {
1845
2018
  // Only retry show() once init has actually succeeded (no retry loop on failure).
1846
2019
  if (this.initialized && !this.destroyed)
1847
2020
  this.show();
1848
- }).catch(err => {
2021
+ })
2022
+ .catch((err) => {
1849
2023
  var _a, _b;
1850
2024
  console.error('Failed to show inspector:', err);
1851
2025
  (_b = (_a = this.config).onError) === null || _b === void 0 ? void 0 : _b.call(_a, err);
@@ -1879,7 +2053,7 @@
1879
2053
  }
1880
2054
  teardown() {
1881
2055
  var _a;
1882
- this.monitors.forEach(monitor => {
2056
+ this.monitors.forEach((monitor) => {
1883
2057
  var _a;
1884
2058
  try {
1885
2059
  (_a = monitor.stop) === null || _a === void 0 ? void 0 : _a.call(monitor);
@@ -1891,8 +2065,24 @@
1891
2065
  this.monitors.clear();
1892
2066
  (_a = this.ui) === null || _a === void 0 ? void 0 : _a.destroy();
1893
2067
  this.ui = null;
1894
- this.cleanupFunctions.forEach(cleanup => cleanup());
2068
+ this.cleanupFunctions.forEach((cleanup) => cleanup());
1895
2069
  this.cleanupFunctions = [];
2070
+ this.uninstallPlugins();
2071
+ }
2072
+ /** Disables and uninstalls every registered plugin; failures are reported, not thrown. */
2073
+ uninstallPlugins(names = this.pluginSystem.getAll().map((plugin) => plugin.name)) {
2074
+ for (const name of names) {
2075
+ // teardown() can run twice (destroy() during init); uninstall each plugin once.
2076
+ if (this.uninstallingPlugins.has(name))
2077
+ continue;
2078
+ this.uninstallingPlugins.add(name);
2079
+ this.pluginSystem
2080
+ .unregister(name)
2081
+ .catch((error) => {
2082
+ console.error(`DevInspector: failed to uninstall plugin "${name}"`, error);
2083
+ })
2084
+ .finally(() => this.uninstallingPlugins.delete(name));
2085
+ }
1896
2086
  }
1897
2087
  destroy() {
1898
2088
  // A destroy() during the asynchronous init is honoured once init resumes.
@@ -1906,7 +2096,7 @@
1906
2096
  this.events.emit('performance:metric', {
1907
2097
  name,
1908
2098
  data,
1909
- timestamp: Date.now()
2099
+ timestamp: Date.now(),
1910
2100
  });
1911
2101
  }
1912
2102
  markStart(name) {
@@ -1922,7 +2112,14 @@
1922
2112
  }
1923
2113
  }
1924
2114
  async use(plugin) {
2115
+ if (this.destroyed)
2116
+ throw new Error('DevInspector has been destroyed');
1925
2117
  await this.pluginSystem.register(plugin);
2118
+ if (this.destroyed) {
2119
+ // destroy() ran while install() was pending and could not see the plugin yet.
2120
+ this.uninstallPlugins([plugin.name]);
2121
+ throw new Error('DevInspector has been destroyed');
2122
+ }
1926
2123
  }
1927
2124
  export() {
1928
2125
  return {
@@ -1933,8 +2130,8 @@
1933
2130
  network: this.networkStorage.getAll(),
1934
2131
  console: this.consoleStorage.getAll(),
1935
2132
  performance: this.performanceStorage.getAllValues(),
1936
- errors: this.errorStorage.getAll()
1937
- }
2133
+ errors: this.errorStorage.getAll(),
2134
+ },
1938
2135
  };
1939
2136
  }
1940
2137
  import(data) {
@@ -1952,10 +2149,14 @@
1952
2149
  }
1953
2150
  getStorage(type) {
1954
2151
  switch (type) {
1955
- case 'network': return this.networkStorage;
1956
- case 'console': return this.consoleStorage;
1957
- case 'performance': return this.performanceStorage;
1958
- case 'error': return this.errorStorage;
2152
+ case 'network':
2153
+ return this.networkStorage;
2154
+ case 'console':
2155
+ return this.consoleStorage;
2156
+ case 'performance':
2157
+ return this.performanceStorage;
2158
+ case 'error':
2159
+ return this.errorStorage;
1959
2160
  }
1960
2161
  }
1961
2162
  getConfig() {
@@ -1992,7 +2193,7 @@
1992
2193
  enabled: defaultEnabled(),
1993
2194
  position: 'bottom-right',
1994
2195
  theme: 'dark',
1995
- ...config
2196
+ ...config,
1996
2197
  };
1997
2198
  if (this.config.enabled && hasDom()) {
1998
2199
  this.init();
@@ -2239,7 +2440,7 @@
2239
2440
  return {
2240
2441
  name: value.name,
2241
2442
  message: value.message,
2242
- stack: value.stack
2443
+ stack: value.stack,
2243
2444
  };
2244
2445
  }
2245
2446
  return value;
@@ -2250,8 +2451,8 @@
2250
2451
  return stack
2251
2452
  .split('\n')
2252
2453
  .slice(1)
2253
- .map(line => line.trim())
2254
- .filter(line => line.startsWith('at '));
2454
+ .map((line) => line.trim())
2455
+ .filter((line) => line.startsWith('at '));
2255
2456
  }
2256
2457
  function parseStackFrame(frame) {
2257
2458
  const match = frame.match(/at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);
@@ -2263,7 +2464,7 @@
2263
2464
  functionName: functionName || '<anonymous>',
2264
2465
  fileName: fileName || '<unknown>',
2265
2466
  lineNumber: parseInt(lineNumber || '0', 10),
2266
- columnNumber: parseInt(columnNumber || '0', 10)
2467
+ columnNumber: parseInt(columnNumber || '0', 10),
2267
2468
  };
2268
2469
  }
2269
2470
 
@@ -2282,26 +2483,28 @@
2282
2483
  if (this.installed || typeof this.originalFetch !== 'function')
2283
2484
  return;
2284
2485
  const instrumented = async function (input, init) {
2285
- var _a, _b, _c, _d;
2486
+ // Uninstalled but still wrapped by someone else: pass straight through.
2487
+ if (self.installed !== instrumented)
2488
+ return self.originalFetch.apply(this !== null && this !== void 0 ? this : window, [input, init]);
2286
2489
  const id = generateId();
2287
2490
  const startTime = performance.now();
2288
2491
  let url;
2289
2492
  let method;
2290
2493
  let headers = {};
2291
2494
  let body;
2495
+ let bodyPreview;
2496
+ let stopPreview;
2497
+ const previewStopped = new Promise((resolve) => (stopPreview = resolve));
2292
2498
  if (typeof Request !== 'undefined' && input instanceof Request) {
2293
2499
  url = input.url;
2294
2500
  method = input.method;
2295
2501
  input.headers.forEach((value, key) => {
2296
2502
  headers[key] = value;
2297
2503
  });
2298
- // Try to extract body, but handle cases where request is locked/used
2299
- try {
2300
- body = await self.extractBody(input);
2301
- }
2302
- catch (e) {
2303
- body = '[Body unavailable - request already used]';
2304
- }
2504
+ // The clone is taken synchronously (before the real fetch reads the body);
2505
+ // the preview is read from it in the background, so the real fetch starts
2506
+ // at once even for a streaming upload whose next chunk is not ready yet.
2507
+ bodyPreview = self.extractBody(input, previewStopped);
2305
2508
  }
2306
2509
  else {
2307
2510
  // eslint-disable-next-line @typescript-eslint/no-base-to-string -- a URL object here
@@ -2324,43 +2527,67 @@
2324
2527
  }
2325
2528
  body = init === null || init === void 0 ? void 0 : init.body;
2326
2529
  }
2327
- const request = {
2328
- id,
2329
- method,
2330
- url,
2331
- headers,
2332
- body: self.sanitizeBody(body),
2333
- timestamp: Date.now(),
2334
- type: 'fetch'
2335
- };
2336
- self.requestMap.set(id, request);
2337
- (_b = (_a = self.handlers).onRequest) === null || _b === void 0 ? void 0 : _b.call(_a, request);
2338
- let response;
2530
+ let pending;
2339
2531
  try {
2340
- response = await self.originalFetch.apply(this !== null && this !== void 0 ? this : window, [input, init]);
2532
+ pending = Promise.resolve(self.originalFetch.apply(this !== null && this !== void 0 ? this : window, [input, init]));
2341
2533
  }
2342
2534
  catch (error) {
2343
- const networkError = {
2535
+ pending = Promise.reject(error);
2536
+ }
2537
+ // onRequest fires once the body preview is ready; response and error reports
2538
+ // are queued behind it so handlers always see the request first.
2539
+ const requestReported = (async () => {
2540
+ var _a, _b;
2541
+ if (bodyPreview)
2542
+ body = await bodyPreview;
2543
+ const request = {
2344
2544
  id,
2345
- message: (error === null || error === void 0 ? void 0 : error.message) || 'Network request failed',
2346
- stack: error === null || error === void 0 ? void 0 : error.stack,
2347
- timestamp: Date.now()
2545
+ method,
2546
+ url,
2547
+ headers,
2548
+ body: self.sanitizeBody(body),
2549
+ timestamp: Date.now(),
2550
+ type: 'fetch',
2348
2551
  };
2349
- (_d = (_c = self.handlers).onError) === null || _d === void 0 ? void 0 : _d.call(_c, networkError);
2350
- self.requestMap.delete(id);
2552
+ self.requestMap.set(id, request);
2553
+ (_b = (_a = self.handlers).onRequest) === null || _b === void 0 ? void 0 : _b.call(_a, request);
2554
+ })().catch(() => undefined);
2555
+ let response;
2556
+ try {
2557
+ response = await pending;
2558
+ }
2559
+ catch (error) {
2560
+ // The body will not be sent any more: stop reading its preview.
2561
+ stopPreview();
2562
+ void requestReported.then(() => {
2563
+ var _a, _b;
2564
+ const networkError = {
2565
+ id,
2566
+ message: (error === null || error === void 0 ? void 0 : error.message) || 'Network request failed',
2567
+ stack: error === null || error === void 0 ? void 0 : error.stack,
2568
+ timestamp: Date.now(),
2569
+ };
2570
+ try {
2571
+ (_b = (_a = self.handlers).onError) === null || _b === void 0 ? void 0 : _b.call(_a, networkError);
2572
+ }
2573
+ catch (_c) {
2574
+ // A failing handler must not replace the page's own error.
2575
+ }
2576
+ self.requestMap.delete(id);
2577
+ });
2351
2578
  throw error;
2352
2579
  }
2353
2580
  // Hand the response to the caller right away. The body preview is read from
2354
2581
  // a clone in the background (capped), so streaming responses (SSE, long
2355
2582
  // polling, large downloads) are never held back by the inspector.
2356
2583
  const duration = performance.now() - startTime;
2357
- void self.reportResponse(id, response, duration);
2584
+ void self.reportResponse(id, response, duration, requestReported);
2358
2585
  return response;
2359
2586
  };
2360
2587
  this.installed = instrumented;
2361
2588
  window.fetch = instrumented;
2362
2589
  }
2363
- async reportResponse(id, response, duration) {
2590
+ async reportResponse(id, response, duration, after) {
2364
2591
  var _a, _b;
2365
2592
  try {
2366
2593
  const responseHeaders = {};
@@ -2369,11 +2596,14 @@
2369
2596
  });
2370
2597
  let responseBody;
2371
2598
  try {
2372
- responseBody = response.bodyUsed ? '[Body already read]' : await this.extractResponseBody(response.clone());
2599
+ responseBody = response.bodyUsed
2600
+ ? '[Body already read]'
2601
+ : await this.extractResponseBody(response.clone());
2373
2602
  }
2374
2603
  catch (_c) {
2375
2604
  responseBody = '[Unable to read response]';
2376
2605
  }
2606
+ await after;
2377
2607
  (_b = (_a = this.handlers).onResponse) === null || _b === void 0 ? void 0 : _b.call(_a, {
2378
2608
  id,
2379
2609
  status: response.status,
@@ -2383,7 +2613,7 @@
2383
2613
  size: this.calculateSize(responseBody, responseHeaders),
2384
2614
  duration,
2385
2615
  timestamp: Date.now(),
2386
- fromCache: this.isFromCache(response, duration)
2616
+ fromCache: this.isFromCache(response, duration),
2387
2617
  });
2388
2618
  }
2389
2619
  catch (_d) {
@@ -2394,29 +2624,32 @@
2394
2624
  }
2395
2625
  }
2396
2626
  uninstall() {
2397
- if (this.installed && window.fetch === this.installed) {
2398
- window.fetch = this.originalFetch;
2399
- }
2627
+ if (this.installed)
2628
+ restorePatch(window, 'fetch', this.installed, this.originalFetch);
2400
2629
  this.installed = null;
2401
2630
  this.requestMap.clear();
2402
2631
  }
2403
- async extractBody(request) {
2632
+ /**
2633
+ * Previews a Request body. Everything up to the clone runs synchronously, so
2634
+ * call it before the real fetch takes the body. Only previewable bodies are
2635
+ * cloned (an unread clone would buffer the whole upload).
2636
+ */
2637
+ async extractBody(request, stop) {
2404
2638
  try {
2405
- const contentType = request.headers.get('content-type') || '';
2406
2639
  if (request.bodyUsed) {
2407
2640
  return '[Body already read]';
2408
2641
  }
2409
- const cloned = request.clone();
2410
- if (contentType.includes('application/json')) {
2411
- return await this.readPreview(cloned, true);
2412
- }
2413
- else if (contentType.includes('text/')) {
2414
- return await this.readPreview(cloned, false);
2642
+ if (!request.body) {
2643
+ return undefined;
2415
2644
  }
2416
- else if (contentType.includes('application/x-www-form-urlencoded')) {
2417
- return await this.readPreview(cloned, false);
2645
+ const contentType = request.headers.get('content-type') || '';
2646
+ const asJson = contentType.includes('application/json');
2647
+ if (asJson ||
2648
+ contentType.includes('text/') ||
2649
+ contentType.includes('application/x-www-form-urlencoded')) {
2650
+ return await this.readPreview(request.clone(), asJson, stop);
2418
2651
  }
2419
- else if (contentType.includes('multipart/form-data')) {
2652
+ if (contentType.includes('multipart/form-data')) {
2420
2653
  return '[FormData]';
2421
2654
  }
2422
2655
  return '[Binary data]';
@@ -2426,11 +2659,13 @@
2426
2659
  }
2427
2660
  }
2428
2661
  /** Reads at most MAX_BODY_PREVIEW bytes from a cloned body, then cancels the clone. */
2429
- async readCapped(body) {
2662
+ async readCapped(body, stop) {
2430
2663
  const stream = body.body;
2431
2664
  if (!stream || typeof stream.getReader !== 'function') {
2432
2665
  const text = await body.text();
2433
- return text.length > MAX_BODY_PREVIEW ? { text: text.slice(0, MAX_BODY_PREVIEW), truncated: true } : { text, truncated: false };
2666
+ return text.length > MAX_BODY_PREVIEW
2667
+ ? { text: text.slice(0, MAX_BODY_PREVIEW), truncated: true }
2668
+ : { text, truncated: false };
2434
2669
  }
2435
2670
  const reader = stream.getReader();
2436
2671
  const decoder = new TextDecoder();
@@ -2438,7 +2673,12 @@
2438
2673
  let received = 0;
2439
2674
  try {
2440
2675
  for (;;) {
2441
- const { done, value } = await reader.read();
2676
+ const next = await (stop
2677
+ ? Promise.race([reader.read(), stop.then(() => null)])
2678
+ : reader.read());
2679
+ if (!next)
2680
+ return { text: text + decoder.decode(), truncated: true };
2681
+ const { done, value } = next;
2442
2682
  if (done)
2443
2683
  return { text: text + decoder.decode(), truncated: false };
2444
2684
  received += value.byteLength;
@@ -2451,8 +2691,8 @@
2451
2691
  reader.cancel().catch(() => undefined);
2452
2692
  }
2453
2693
  }
2454
- async readPreview(body, asJson) {
2455
- const { text, truncated } = await this.readCapped(body);
2694
+ async readPreview(body, asJson, stop) {
2695
+ const { text, truncated } = await this.readCapped(body, stop);
2456
2696
  if (truncated)
2457
2697
  return `${text}... [truncated]`;
2458
2698
  if (asJson) {
@@ -2568,12 +2808,19 @@
2568
2808
  return;
2569
2809
  // eslint-disable-next-line @typescript-eslint/no-this-alias
2570
2810
  const self = this;
2571
- XMLHttpRequest.prototype.open = function (method, url, async = true, username, password) {
2811
+ XMLHttpRequest.prototype.open = function (...args) {
2812
+ var _a;
2813
+ // The arguments go through as given: an explicit `async: undefined` means a
2814
+ // synchronous request, and the native open() distinguishes 2 from 3+ arguments.
2815
+ const result = self.originalOpen.apply(this, args);
2816
+ const [method, url] = args;
2817
+ // open() on a request in flight cancels it without abort/loadend events.
2818
+ (_a = this._devinspectorCancel) === null || _a === void 0 ? void 0 : _a.call(this);
2572
2819
  this._devinspectorId = generateId();
2573
2820
  this._devinspectorMethod = method;
2574
2821
  this._devinspectorUrl = url.toString();
2575
2822
  this._devinspectorRequestHeaders = {};
2576
- return self.originalOpen.apply(this, [method, url, async, username, password]);
2823
+ return result;
2577
2824
  };
2578
2825
  XMLHttpRequest.prototype.setRequestHeader = function (name, value) {
2579
2826
  if (this._devinspectorRequestHeaders) {
@@ -2583,98 +2830,103 @@
2583
2830
  };
2584
2831
  XMLHttpRequest.prototype.send = function (body) {
2585
2832
  var _a, _b;
2586
- this._devinspectorStartTime = performance.now();
2833
+ // Uninstalled but still wrapped by someone else, or a second send() on a request
2834
+ // in flight (the native send() throws): pass straight through.
2835
+ if (!self.installed || this._devinspectorCancel)
2836
+ return self.originalSend.apply(this, [body]);
2837
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
2838
+ const xhr = this;
2839
+ const id = this._devinspectorId;
2840
+ const startTime = performance.now();
2841
+ this._devinspectorStartTime = startTime;
2587
2842
  this._devinspectorRequestBody = self.sanitizeBody(body);
2588
2843
  const request = {
2589
- id: this._devinspectorId,
2844
+ id,
2590
2845
  method: this._devinspectorMethod,
2591
2846
  url: this._devinspectorUrl,
2592
2847
  headers: this._devinspectorRequestHeaders || {},
2593
2848
  body: this._devinspectorRequestBody,
2594
2849
  timestamp: Date.now(),
2595
- type: 'xhr'
2850
+ type: 'xhr',
2596
2851
  };
2597
2852
  (_b = (_a = self.handlers).onRequest) === null || _b === void 0 ? void 0 : _b.call(_a, request);
2598
- // Track upload progress
2599
- if (this.upload && self.handlers.onProgress) {
2600
- this.upload.addEventListener('progress', (event) => {
2601
- if (event.lengthComputable) {
2602
- self.handlers.onProgress({
2603
- id: this._devinspectorId,
2604
- loaded: event.loaded,
2605
- total: event.total
2606
- });
2607
- }
2608
- });
2609
- }
2610
- // Track download progress
2853
+ // Listeners belong to this one request and are removed when it ends, so a
2854
+ // reused XHR reports every response once.
2855
+ const listeners = [];
2856
+ const listen = (target, type, handler) => {
2857
+ target.addEventListener(type, handler);
2858
+ listeners.push([target, type, handler]);
2859
+ };
2860
+ let ended = false;
2861
+ const detach = () => {
2862
+ ended = true;
2863
+ for (const [target, type, handler] of listeners)
2864
+ target.removeEventListener(type, handler);
2865
+ listeners.length = 0;
2866
+ if (xhr._devinspectorCancel === cancel)
2867
+ xhr._devinspectorCancel = undefined;
2868
+ };
2869
+ const fail = (message) => {
2870
+ var _a, _b;
2871
+ (_b = (_a = self.handlers).onError) === null || _b === void 0 ? void 0 : _b.call(_a, { id, message, timestamp: Date.now() });
2872
+ };
2873
+ const cancel = () => {
2874
+ detach();
2875
+ fail('Request aborted');
2876
+ };
2877
+ const onProgress = (event) => {
2878
+ var _a, _b;
2879
+ if (event.lengthComputable) {
2880
+ (_b = (_a = self.handlers).onProgress) === null || _b === void 0 ? void 0 : _b.call(_a, { id, loaded: event.loaded, total: event.total });
2881
+ }
2882
+ };
2611
2883
  if (self.handlers.onProgress) {
2612
- this.addEventListener('progress', (event) => {
2613
- if (event.lengthComputable) {
2614
- self.handlers.onProgress({
2615
- id: this._devinspectorId,
2616
- loaded: event.loaded,
2617
- total: event.total
2618
- });
2619
- }
2620
- });
2884
+ // Track upload and download progress
2885
+ if (this.upload)
2886
+ listen(this.upload, 'progress', onProgress);
2887
+ listen(this, 'progress', onProgress);
2621
2888
  }
2622
- // Handle load event
2623
- this.addEventListener('load', function () {
2889
+ listen(this, 'load', () => {
2624
2890
  var _a, _b;
2625
- const duration = performance.now() - this._devinspectorStartTime;
2626
- const responseHeaders = self.parseResponseHeaders(this.getAllResponseHeaders());
2627
- const responseBody = self.extractResponseBody(this);
2891
+ const duration = performance.now() - startTime;
2892
+ const responseHeaders = self.parseResponseHeaders(xhr.getAllResponseHeaders());
2893
+ const responseBody = self.extractResponseBody(xhr);
2628
2894
  const size = self.calculateSize(responseBody, responseHeaders);
2629
2895
  const response = {
2630
- id: this._devinspectorId,
2631
- status: this.status,
2632
- statusText: this.statusText,
2896
+ id,
2897
+ status: xhr.status,
2898
+ statusText: xhr.statusText,
2633
2899
  headers: responseHeaders,
2634
2900
  body: responseBody,
2635
2901
  size,
2636
2902
  duration,
2637
2903
  timestamp: Date.now(),
2638
- fromCache: duration < 5
2904
+ fromCache: duration < 5,
2639
2905
  };
2640
2906
  (_b = (_a = self.handlers).onResponse) === null || _b === void 0 ? void 0 : _b.call(_a, response);
2641
2907
  });
2642
- // Handle error event
2643
- this.addEventListener('error', function () {
2644
- var _a, _b;
2645
- const error = {
2646
- id: this._devinspectorId,
2647
- message: 'Network request failed',
2648
- timestamp: Date.now()
2649
- };
2650
- (_b = (_a = self.handlers).onError) === null || _b === void 0 ? void 0 : _b.call(_a, error);
2651
- });
2652
- // Handle timeout event
2653
- this.addEventListener('timeout', function () {
2654
- var _a, _b;
2655
- const error = {
2656
- id: this._devinspectorId,
2657
- message: `Request timeout after ${this.timeout}ms`,
2658
- timestamp: Date.now()
2659
- };
2660
- (_b = (_a = self.handlers).onError) === null || _b === void 0 ? void 0 : _b.call(_a, error);
2661
- });
2662
- // Handle abort event
2663
- this.addEventListener('abort', function () {
2664
- var _a, _b;
2665
- const error = {
2666
- id: this._devinspectorId,
2667
- message: 'Request aborted',
2668
- timestamp: Date.now()
2669
- };
2670
- (_b = (_a = self.handlers).onError) === null || _b === void 0 ? void 0 : _b.call(_a, error);
2671
- });
2672
- return self.originalSend.apply(this, [body]);
2908
+ listen(this, 'error', () => fail('Network request failed'));
2909
+ listen(this, 'timeout', () => fail(`Request timeout after ${xhr.timeout}ms`));
2910
+ listen(this, 'abort', () => fail('Request aborted'));
2911
+ listen(this, 'loadend', detach);
2912
+ this._devinspectorCancel = cancel;
2913
+ try {
2914
+ return self.originalSend.apply(this, [body]);
2915
+ }
2916
+ catch (error) {
2917
+ // No request was started (e.g. a synchronous network error), unless its
2918
+ // events were already dispatched and reported.
2919
+ if (!ended) {
2920
+ detach();
2921
+ fail(error instanceof Error ? error.message : String(error));
2922
+ }
2923
+ throw error;
2924
+ }
2673
2925
  };
2674
2926
  this.installed = {
2675
2927
  open: XMLHttpRequest.prototype.open,
2676
2928
  send: XMLHttpRequest.prototype.send,
2677
- setRequestHeader: XMLHttpRequest.prototype.setRequestHeader
2929
+ setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
2678
2930
  };
2679
2931
  }
2680
2932
  uninstall() {
@@ -2682,12 +2934,9 @@
2682
2934
  return;
2683
2935
  const proto = XMLHttpRequest.prototype;
2684
2936
  // Only restore methods that nobody has wrapped since we installed ours.
2685
- if (proto.open === this.installed.open)
2686
- proto.open = this.originalOpen;
2687
- if (proto.send === this.installed.send)
2688
- proto.send = this.originalSend;
2689
- if (proto.setRequestHeader === this.installed.setRequestHeader)
2690
- proto.setRequestHeader = this.originalSetRequestHeader;
2937
+ restorePatch(proto, 'open', this.installed.open, this.originalOpen);
2938
+ restorePatch(proto, 'send', this.installed.send, this.originalSend);
2939
+ restorePatch(proto, 'setRequestHeader', this.installed.setRequestHeader, this.originalSetRequestHeader);
2691
2940
  this.installed = null;
2692
2941
  }
2693
2942
  sanitizeBody(body) {
@@ -2724,7 +2973,7 @@
2724
2973
  if (!headersString)
2725
2974
  return headers;
2726
2975
  const lines = headersString.trim().split(/[\r\n]+/);
2727
- lines.forEach(line => {
2976
+ lines.forEach((line) => {
2728
2977
  const parts = line.split(': ');
2729
2978
  const key = parts.shift();
2730
2979
  if (key) {
@@ -2801,8 +3050,14 @@
2801
3050
  if (typeof OriginalWebSocket !== 'function' || this.installed)
2802
3051
  return;
2803
3052
  const MonitoredWebSocket = function (url, protocols) {
2804
- var _a, _b;
2805
- const ws = new OriginalWebSocket(url, protocols);
3053
+ var _a, _b, _c;
3054
+ // Construct with the caller's new.target so `class X extends WebSocket` keeps
3055
+ // X's prototype; argument handling stays with the native constructor.
3056
+ const args = protocols === undefined ? [url] : [url, protocols];
3057
+ const ws = Reflect.construct(OriginalWebSocket, args, (_a = new.target) !== null && _a !== void 0 ? _a : OriginalWebSocket);
3058
+ // Uninstalled but still wrapped by someone else: pass straight through.
3059
+ if (self.installed !== MonitoredWebSocket)
3060
+ return ws;
2806
3061
  const connectionId = generateId();
2807
3062
  ws._devinspectorId = connectionId;
2808
3063
  ws._devinspectorUrl = url.toString();
@@ -2813,10 +3068,10 @@
2813
3068
  protocols,
2814
3069
  timestamp: Date.now(),
2815
3070
  readyState: ws.readyState,
2816
- status: 'connecting'
3071
+ status: 'connecting',
2817
3072
  };
2818
3073
  self.connections.set(connectionId, connection);
2819
- (_b = (_a = self.handlers).onConnection) === null || _b === void 0 ? void 0 : _b.call(_a, connection);
3074
+ (_c = (_b = self.handlers).onConnection) === null || _c === void 0 ? void 0 : _c.call(_b, connection);
2820
3075
  // Monitor open event
2821
3076
  ws.addEventListener('open', function () {
2822
3077
  var _a, _b;
@@ -2826,7 +3081,7 @@
2826
3081
  conn.readyState = this.readyState;
2827
3082
  (_b = (_a = self.handlers).onStatusChange) === null || _b === void 0 ? void 0 : _b.call(_a, {
2828
3083
  connectionId,
2829
- status: 'open'
3084
+ status: 'open',
2830
3085
  });
2831
3086
  }
2832
3087
  });
@@ -2840,7 +3095,7 @@
2840
3095
  conn.readyState = this.readyState;
2841
3096
  (_b = (_a = self.handlers).onStatusChange) === null || _b === void 0 ? void 0 : _b.call(_a, {
2842
3097
  connectionId,
2843
- status: 'closed'
3098
+ status: 'closed',
2844
3099
  });
2845
3100
  }
2846
3101
  self.connections.delete(connectionId);
@@ -2853,7 +3108,7 @@
2853
3108
  id: generateId(),
2854
3109
  connectionId,
2855
3110
  message: 'WebSocket error occurred',
2856
- timestamp: Date.now()
3111
+ timestamp: Date.now(),
2857
3112
  };
2858
3113
  (_b = (_a = self.handlers).onError) === null || _b === void 0 ? void 0 : _b.call(_a, error);
2859
3114
  });
@@ -2866,7 +3121,7 @@
2866
3121
  type: 'received',
2867
3122
  data: self.parseMessageData(event.data),
2868
3123
  timestamp: Date.now(),
2869
- size: self.calculateMessageSize(event.data)
3124
+ size: self.calculateMessageSize(event.data),
2870
3125
  };
2871
3126
  (_b = (_a = self.handlers).onMessage) === null || _b === void 0 ? void 0 : _b.call(_a, message);
2872
3127
  });
@@ -2880,7 +3135,7 @@
2880
3135
  type: 'sent',
2881
3136
  data: self.parseMessageData(data),
2882
3137
  timestamp: Date.now(),
2883
- size: self.calculateMessageSize(data)
3138
+ size: self.calculateMessageSize(data),
2884
3139
  };
2885
3140
  (_b = (_a = self.handlers).onMessage) === null || _b === void 0 ? void 0 : _b.call(_a, message);
2886
3141
  return originalSend(data);
@@ -2895,7 +3150,7 @@
2895
3150
  conn.readyState = this.readyState;
2896
3151
  (_b = (_a = self.handlers).onStatusChange) === null || _b === void 0 ? void 0 : _b.call(_a, {
2897
3152
  connectionId,
2898
- status: 'closing'
3153
+ status: 'closing',
2899
3154
  });
2900
3155
  }
2901
3156
  return originalClose(code, reason);
@@ -2911,9 +3166,8 @@
2911
3166
  window.WebSocket = MonitoredWebSocket;
2912
3167
  }
2913
3168
  uninstall() {
2914
- if (this.installed && window.WebSocket === this.installed) {
2915
- window.WebSocket = this.originalWebSocket;
2916
- }
3169
+ if (this.installed)
3170
+ restorePatch(window, 'WebSocket', this.installed, this.originalWebSocket);
2917
3171
  this.installed = null;
2918
3172
  this.connections.clear();
2919
3173
  }
@@ -2974,19 +3228,19 @@
2974
3228
  this.fetchInterceptor = new FetchInterceptor({
2975
3229
  onRequest: this.handleRequest.bind(this, 'fetch'),
2976
3230
  onResponse: this.handleResponse.bind(this),
2977
- onError: this.handleError.bind(this)
3231
+ onError: this.handleError.bind(this),
2978
3232
  });
2979
3233
  this.xhrInterceptor = new XHRInterceptor({
2980
3234
  onRequest: this.handleRequest.bind(this, 'xhr'),
2981
3235
  onResponse: this.handleResponse.bind(this),
2982
3236
  onError: this.handleError.bind(this),
2983
- onProgress: this.handleProgress.bind(this)
3237
+ onProgress: this.handleProgress.bind(this),
2984
3238
  });
2985
3239
  this.websocketMonitor = new WebSocketMonitor({
2986
3240
  onConnection: this.handleWebSocketConnection.bind(this),
2987
3241
  onMessage: this.handleWebSocketMessage.bind(this),
2988
3242
  onStatusChange: this.handleWebSocketStatusChange.bind(this),
2989
- onError: this.handleWebSocketError.bind(this)
3243
+ onError: this.handleWebSocketError.bind(this),
2990
3244
  });
2991
3245
  }
2992
3246
  start() {
@@ -3012,14 +3266,14 @@
3012
3266
  id: request.id,
3013
3267
  type,
3014
3268
  request,
3015
- timestamp: request.timestamp
3269
+ timestamp: request.timestamp,
3016
3270
  };
3017
3271
  this.track(request.id, entry);
3018
3272
  const storage = this.inspector.getStorage('network');
3019
3273
  storage.push(entry);
3020
3274
  this.inspector.getEvents().emit('network:request', {
3021
3275
  ...request,
3022
- type
3276
+ type,
3023
3277
  });
3024
3278
  }
3025
3279
  handleResponse(response) {
@@ -3039,7 +3293,7 @@
3039
3293
  type: 'slow-network',
3040
3294
  message: `Slow network request: ${(_c = entry.request) === null || _c === void 0 ? void 0 : _c.url}`,
3041
3295
  duration: response.duration,
3042
- url: (_d = entry.request) === null || _d === void 0 ? void 0 : _d.url
3296
+ url: (_d = entry.request) === null || _d === void 0 ? void 0 : _d.url,
3043
3297
  });
3044
3298
  }
3045
3299
  }
@@ -3060,9 +3314,9 @@
3060
3314
  websocket: {
3061
3315
  connection,
3062
3316
  messages: [],
3063
- errors: []
3317
+ errors: [],
3064
3318
  },
3065
- timestamp: connection.timestamp
3319
+ timestamp: connection.timestamp,
3066
3320
  };
3067
3321
  this.track(connection.id, entry);
3068
3322
  const storage = this.inspector.getStorage('network');
@@ -3119,7 +3373,7 @@
3119
3373
  headers: {},
3120
3374
  body: self.sanitizeBeaconData(data),
3121
3375
  timestamp: Date.now(),
3122
- type: 'beacon'
3376
+ type: 'beacon',
3123
3377
  };
3124
3378
  self.handleRequest('beacon', request);
3125
3379
  const result = originalSendBeacon(url, data);
@@ -3132,7 +3386,7 @@
3132
3386
  headers: {},
3133
3387
  size: 0,
3134
3388
  duration: 0,
3135
- timestamp: Date.now()
3389
+ timestamp: Date.now(),
3136
3390
  };
3137
3391
  self.handleResponse(response);
3138
3392
  }, 0);
@@ -3158,9 +3412,7 @@
3158
3412
  if (data instanceof FormData) {
3159
3413
  const entries = {};
3160
3414
  data.forEach((value, key) => {
3161
- entries[key] = value instanceof File
3162
- ? `[File: ${value.name}]`
3163
- : value;
3415
+ entries[key] = value instanceof File ? `[File: ${value.name}]` : value;
3164
3416
  });
3165
3417
  return { type: 'FormData', entries };
3166
3418
  }
@@ -3207,14 +3459,31 @@
3207
3459
  }
3208
3460
  install() {
3209
3461
  const methods = [
3210
- 'log', 'info', 'warn', 'error', 'debug', 'trace', 'table',
3211
- 'group', 'groupCollapsed', 'groupEnd', 'clear',
3212
- 'count', 'countReset', 'time', 'timeEnd', 'timeLog',
3213
- 'assert', 'dir', 'dirxml', 'profile', 'profileEnd'
3462
+ 'log',
3463
+ 'info',
3464
+ 'warn',
3465
+ 'error',
3466
+ 'debug',
3467
+ 'trace',
3468
+ 'table',
3469
+ 'group',
3470
+ 'groupCollapsed',
3471
+ 'groupEnd',
3472
+ 'clear',
3473
+ 'count',
3474
+ 'countReset',
3475
+ 'time',
3476
+ 'timeEnd',
3477
+ 'timeLog',
3478
+ 'assert',
3479
+ 'dir',
3480
+ 'dirxml',
3481
+ 'profile',
3482
+ 'profileEnd',
3214
3483
  ];
3215
3484
  if (this.originalMethods.size > 0)
3216
3485
  return;
3217
- methods.forEach(method => {
3486
+ methods.forEach((method) => {
3218
3487
  if (typeof console[method] !== 'function')
3219
3488
  return;
3220
3489
  this.originalMethods.set(method, console[method]);
@@ -3224,9 +3493,7 @@
3224
3493
  uninstall() {
3225
3494
  this.originalMethods.forEach((original, method) => {
3226
3495
  // Leave methods alone that someone else has wrapped since; ours pass through once uninstalled.
3227
- if (console[method] === this.wrappers.get(method)) {
3228
- console[method] = original;
3229
- }
3496
+ restorePatch(console, method, this.wrappers.get(method), original);
3230
3497
  });
3231
3498
  this.originalMethods.clear();
3232
3499
  this.wrappers.clear();
@@ -3300,10 +3567,11 @@
3300
3567
  args: args,
3301
3568
  formattedArgs: this.formatArgs(args),
3302
3569
  timestamp: Date.now(),
3303
- groupLevel: this.groupLevel
3570
+ groupLevel: this.groupLevel,
3304
3571
  };
3305
3572
  // Capture stack trace if enabled
3306
- if (this.captureStackTraces && (method === 'error' || method === 'warn' || method === 'trace')) {
3573
+ if (this.captureStackTraces &&
3574
+ (method === 'error' || method === 'warn' || method === 'trace')) {
3307
3575
  // Drop the getStackTrace, capture and console wrapper frames so the first frame is the caller.
3308
3576
  const stack = getStackTrace().slice(3);
3309
3577
  entry.stack = stack;
@@ -3322,7 +3590,7 @@
3322
3590
  args: [`${key}: ${count}`],
3323
3591
  formattedArgs: [`${key}: ${count}`],
3324
3592
  timestamp: Date.now(),
3325
- groupLevel: this.groupLevel
3593
+ groupLevel: this.groupLevel,
3326
3594
  };
3327
3595
  (_b = (_a = this.handlers).onLog) === null || _b === void 0 ? void 0 : _b.call(_a, entry);
3328
3596
  }
@@ -3337,7 +3605,7 @@
3337
3605
  args: [`Timer '${key}' does not exist`],
3338
3606
  formattedArgs: [`Timer '${key}' does not exist`],
3339
3607
  timestamp: Date.now(),
3340
- groupLevel: this.groupLevel
3608
+ groupLevel: this.groupLevel,
3341
3609
  };
3342
3610
  (_b = (_a = this.handlers).onLog) === null || _b === void 0 ? void 0 : _b.call(_a, entry);
3343
3611
  return;
@@ -3352,12 +3620,12 @@
3352
3620
  args: [`${key}: ${duration.toFixed(3)}ms`],
3353
3621
  formattedArgs: [`${key}: ${duration.toFixed(3)}ms`],
3354
3622
  timestamp: Date.now(),
3355
- groupLevel: this.groupLevel
3623
+ groupLevel: this.groupLevel,
3356
3624
  };
3357
3625
  (_d = (_c = this.handlers).onLog) === null || _d === void 0 ? void 0 : _d.call(_c, entry);
3358
3626
  }
3359
3627
  formatArgs(args) {
3360
- return args.map(arg => this.formatValue(arg));
3628
+ return args.map((arg) => this.formatValue(arg));
3361
3629
  }
3362
3630
  formatValue(value) {
3363
3631
  if (value === null)
@@ -3373,33 +3641,33 @@
3373
3641
  type: 'error',
3374
3642
  name: value.name,
3375
3643
  message: value.message,
3376
- stack: value.stack
3644
+ stack: value.stack,
3377
3645
  };
3378
3646
  }
3379
3647
  if (value instanceof Date) {
3380
3648
  return {
3381
3649
  type: 'date',
3382
- value: value.toISOString()
3650
+ value: value.toISOString(),
3383
3651
  };
3384
3652
  }
3385
3653
  if (value instanceof RegExp) {
3386
3654
  return {
3387
3655
  type: 'regexp',
3388
- value: value.toString()
3656
+ value: value.toString(),
3389
3657
  };
3390
3658
  }
3391
3659
  if (typeof value === 'function') {
3392
3660
  return {
3393
3661
  type: 'function',
3394
3662
  name: value.name || '<anonymous>',
3395
- value: value.toString().substring(0, 100)
3663
+ value: value.toString().substring(0, 100),
3396
3664
  };
3397
3665
  }
3398
3666
  if (Array.isArray(value)) {
3399
3667
  return {
3400
3668
  type: 'array',
3401
3669
  length: value.length,
3402
- value: value.slice(0, 100).map(v => this.formatValue(v))
3670
+ value: value.slice(0, 100).map((v) => this.formatValue(v)),
3403
3671
  };
3404
3672
  }
3405
3673
  if (type === 'object') {
@@ -3408,13 +3676,13 @@
3408
3676
  const stringified = safeStringify(value, 2);
3409
3677
  return {
3410
3678
  type: 'object',
3411
- value: JSON.parse(stringified)
3679
+ value: JSON.parse(stringified),
3412
3680
  };
3413
3681
  }
3414
3682
  catch (error) {
3415
3683
  return {
3416
3684
  type: 'object',
3417
- value: '[Complex Object]'
3685
+ value: '[Complex Object]',
3418
3686
  };
3419
3687
  }
3420
3688
  }
@@ -3431,17 +3699,17 @@
3431
3699
  return {
3432
3700
  file: file.replace(/^.*\//, ''), // Get just filename
3433
3701
  line: parseInt(line, 10),
3434
- column: parseInt(column, 10)
3702
+ column: parseInt(column, 10),
3435
3703
  };
3436
3704
  }
3437
3705
  }
3438
3706
 
3439
3707
  class LogFormatter {
3440
3708
  formatArgs(args) {
3441
- return args.map(arg => this.formatValue(arg));
3709
+ return args.map((arg) => this.formatValue(arg));
3442
3710
  }
3443
3711
  formatArgsAsText(args) {
3444
- return args.map(arg => this.formatValueAsText(arg)).join(' ');
3712
+ return args.map((arg) => this.formatValueAsText(arg)).join(' ');
3445
3713
  }
3446
3714
  formatValue(value) {
3447
3715
  var _a;
@@ -3458,59 +3726,59 @@
3458
3726
  type: 'error',
3459
3727
  name: value.name,
3460
3728
  message: value.message,
3461
- stack: value.stack
3729
+ stack: value.stack,
3462
3730
  };
3463
3731
  }
3464
3732
  if (value instanceof Date) {
3465
3733
  return {
3466
3734
  type: 'date',
3467
- value: value.toISOString()
3735
+ value: value.toISOString(),
3468
3736
  };
3469
3737
  }
3470
3738
  if (value instanceof RegExp) {
3471
3739
  return {
3472
3740
  type: 'regexp',
3473
- value: value.toString()
3741
+ value: value.toString(),
3474
3742
  };
3475
3743
  }
3476
3744
  if (value instanceof Set) {
3477
3745
  return {
3478
3746
  type: 'set',
3479
3747
  size: value.size,
3480
- values: Array.from(value).slice(0, 100)
3748
+ values: Array.from(value).slice(0, 100),
3481
3749
  };
3482
3750
  }
3483
3751
  if (value instanceof Map) {
3484
3752
  return {
3485
3753
  type: 'map',
3486
3754
  size: value.size,
3487
- entries: Array.from(value.entries()).slice(0, 100)
3755
+ entries: Array.from(value.entries()).slice(0, 100),
3488
3756
  };
3489
3757
  }
3490
3758
  if (value instanceof WeakSet || value instanceof WeakMap) {
3491
3759
  return {
3492
3760
  type: value instanceof WeakSet ? 'weakset' : 'weakmap',
3493
- value: '[WeakCollection]'
3761
+ value: '[WeakCollection]',
3494
3762
  };
3495
3763
  }
3496
3764
  if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {
3497
3765
  return {
3498
3766
  type: 'arraybuffer',
3499
- byteLength: value.byteLength
3767
+ byteLength: value.byteLength,
3500
3768
  };
3501
3769
  }
3502
3770
  if (typeof value === 'function') {
3503
3771
  return {
3504
3772
  type: 'function',
3505
3773
  name: value.name || '<anonymous>',
3506
- value: value.toString().substring(0, 100)
3774
+ value: value.toString().substring(0, 100),
3507
3775
  };
3508
3776
  }
3509
3777
  if (Array.isArray(value)) {
3510
3778
  return {
3511
3779
  type: 'array',
3512
3780
  length: value.length,
3513
- value: value.slice(0, 100).map(v => this.formatValue(v))
3781
+ value: value.slice(0, 100).map((v) => this.formatValue(v)),
3514
3782
  };
3515
3783
  }
3516
3784
  if (type === 'object') {
@@ -3525,7 +3793,7 @@
3525
3793
  const formatted = {
3526
3794
  type: 'object',
3527
3795
  constructor: constructorName,
3528
- value: {}
3796
+ value: {},
3529
3797
  };
3530
3798
  for (const [key, val] of entries) {
3531
3799
  formatted.value[key] = this.formatValue(val);
@@ -3539,7 +3807,7 @@
3539
3807
  catch (error) {
3540
3808
  return {
3541
3809
  type: 'object',
3542
- value: '[Complex Object]'
3810
+ value: '[Complex Object]',
3543
3811
  };
3544
3812
  }
3545
3813
  }
@@ -3580,21 +3848,43 @@
3580
3848
  return JSON.stringify(value);
3581
3849
  }
3582
3850
  formatStackTrace(stack) {
3583
- return stack.map((frame, index) => {
3851
+ return stack
3852
+ .map((frame, index) => {
3584
3853
  // Remove leading "at " if present
3585
3854
  const cleanFrame = frame.replace(/^\s*at\s+/, '');
3586
3855
  // Add indentation
3587
3856
  return ' '.repeat(index) + cleanFrame;
3588
- }).join('\n');
3857
+ })
3858
+ .join('\n');
3589
3859
  }
3590
3860
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
3591
3861
  highlightSyntax(code, language = 'javascript') {
3592
3862
  // Simple syntax highlighting for console display
3593
3863
  // In a real implementation, you might use a proper syntax highlighter
3594
3864
  const keywords = [
3595
- 'const', 'let', 'var', 'function', 'class', 'if', 'else', 'for', 'while',
3596
- 'return', 'new', 'this', 'typeof', 'instanceof', 'try', 'catch', 'finally',
3597
- 'throw', 'async', 'await', 'import', 'export', 'default'
3865
+ 'const',
3866
+ 'let',
3867
+ 'var',
3868
+ 'function',
3869
+ 'class',
3870
+ 'if',
3871
+ 'else',
3872
+ 'for',
3873
+ 'while',
3874
+ 'return',
3875
+ 'new',
3876
+ 'this',
3877
+ 'typeof',
3878
+ 'instanceof',
3879
+ 'try',
3880
+ 'catch',
3881
+ 'finally',
3882
+ 'throw',
3883
+ 'async',
3884
+ 'await',
3885
+ 'import',
3886
+ 'export',
3887
+ 'default',
3598
3888
  ];
3599
3889
  let highlighted = code;
3600
3890
  // Highlight strings
@@ -3602,7 +3892,7 @@
3602
3892
  // Highlight numbers
3603
3893
  highlighted = highlighted.replace(/\b(\d+)\b/g, '<span class="number">$1</span>');
3604
3894
  // Highlight keywords
3605
- keywords.forEach(keyword => {
3895
+ keywords.forEach((keyword) => {
3606
3896
  const regex = new RegExp(`\\b${keyword}\\b`, 'g');
3607
3897
  highlighted = highlighted.replace(regex, `<span class="keyword">${keyword}</span>`);
3608
3898
  });
@@ -3622,7 +3912,7 @@
3622
3912
  this.formatter = new LogFormatter();
3623
3913
  this.interceptor = new ConsoleInterceptor({
3624
3914
  onLog: this.handleLog.bind(this),
3625
- onClear: this.handleClear.bind(this)
3915
+ onClear: this.handleClear.bind(this),
3626
3916
  }, inspector.getConfig().captureStackTraces);
3627
3917
  }
3628
3918
  start() {
@@ -3648,7 +3938,7 @@
3648
3938
  message: this.formatter.formatArgs(entry.args),
3649
3939
  stack: entry.stack,
3650
3940
  timestamp: entry.timestamp,
3651
- source: 'console'
3941
+ source: 'console',
3652
3942
  });
3653
3943
  }
3654
3944
  }
@@ -3675,7 +3965,7 @@
3675
3965
  args: [`> ${command}`],
3676
3966
  formattedArgs: [`> ${command}`],
3677
3967
  timestamp: Date.now(),
3678
- groupLevel: 0
3968
+ groupLevel: 0,
3679
3969
  };
3680
3970
  this.handleLog(commandEntry);
3681
3971
  // Execute the command
@@ -3693,7 +3983,7 @@
3693
3983
  args: [result],
3694
3984
  formattedArgs: this.formatter.formatArgs([result]),
3695
3985
  timestamp: Date.now(),
3696
- groupLevel: 0
3986
+ groupLevel: 0,
3697
3987
  };
3698
3988
  this.handleLog(resultEntry);
3699
3989
  }
@@ -3706,7 +3996,7 @@
3706
3996
  formattedArgs: this.formatter.formatArgs([error]),
3707
3997
  timestamp: Date.now(),
3708
3998
  groupLevel: 0,
3709
- stack: (_a = error.stack) === null || _a === void 0 ? void 0 : _a.split('\n')
3999
+ stack: (_a = error.stack) === null || _a === void 0 ? void 0 : _a.split('\n'),
3710
4000
  };
3711
4001
  this.handleLog(errorEntry);
3712
4002
  }
@@ -3728,7 +4018,7 @@
3728
4018
  filterLogs(filter) {
3729
4019
  const storage = this.inspector.getStorage('console');
3730
4020
  const logs = storage.getAll();
3731
- return logs.filter(log => {
4021
+ return logs.filter((log) => {
3732
4022
  var _a;
3733
4023
  // Filter by level
3734
4024
  if (filter.levels && filter.levels.length > 0) {
@@ -3759,13 +4049,15 @@
3759
4049
  return JSON.stringify(logs, null, 2);
3760
4050
  }
3761
4051
  // Text format
3762
- return logs.map(log => {
4052
+ return logs
4053
+ .map((log) => {
3763
4054
  const timestamp = new Date(log.timestamp).toISOString();
3764
4055
  const level = log.level.toUpperCase().padEnd(5);
3765
4056
  const args = this.formatter.formatArgsAsText(log.formattedArgs);
3766
4057
  const source = log.source ? ` [${log.source.file}:${log.source.line}]` : '';
3767
4058
  return `[${timestamp}] ${level} ${args}${source}`;
3768
- }).join('\n');
4059
+ })
4060
+ .join('\n');
3769
4061
  }
3770
4062
  }
3771
4063
 
@@ -3805,7 +4097,7 @@
3805
4097
  fps: Math.round(this.fps),
3806
4098
  timestamp: Date.now(),
3807
4099
  frameTime: avgFrameTime,
3808
- droppedFrames: this.droppedFrames
4100
+ droppedFrames: this.droppedFrames,
3809
4101
  });
3810
4102
  // Reset counters
3811
4103
  this.frameCount = 0;
@@ -3884,7 +4176,7 @@
3884
4176
  totalJSHeapSize,
3885
4177
  jsHeapSizeLimit,
3886
4178
  timestamp: Date.now(),
3887
- percentUsed
4179
+ percentUsed,
3888
4180
  };
3889
4181
  this.callback(data);
3890
4182
  }
@@ -3897,7 +4189,7 @@
3897
4189
  totalJSHeapSize,
3898
4190
  jsHeapSizeLimit,
3899
4191
  timestamp: Date.now(),
3900
- percentUsed: (usedJSHeapSize / jsHeapSizeLimit) * 100
4192
+ percentUsed: (usedJSHeapSize / jsHeapSizeLimit) * 100,
3901
4193
  };
3902
4194
  }
3903
4195
  isMemorySupported() {
@@ -4038,7 +4330,7 @@
4038
4330
  domProcessingTime: timing.domComplete - timing.domLoading,
4039
4331
  domContentLoadedTime: timing.domContentLoadedEventEnd - navigationStart,
4040
4332
  loadTime: timing.loadEventEnd - navigationStart,
4041
- totalTime: timing.loadEventEnd - navigationStart
4333
+ totalTime: timing.loadEventEnd - navigationStart,
4042
4334
  });
4043
4335
  this.reportMetrics();
4044
4336
  }
@@ -4117,14 +4409,15 @@
4117
4409
  duration: Math.round(entry.duration),
4118
4410
  startTime: Math.round(entry.startTime),
4119
4411
  timestamp: Date.now(),
4120
- attribution: longTaskEntry.attribution ?
4121
- longTaskEntry.attribution.map((attr) => ({
4412
+ attribution: longTaskEntry.attribution
4413
+ ? longTaskEntry.attribution.map((attr) => ({
4122
4414
  name: attr.name,
4123
4415
  containerType: attr.containerType,
4124
4416
  containerSrc: attr.containerSrc,
4125
4417
  containerId: attr.containerId,
4126
- containerName: attr.containerName
4127
- })) : []
4418
+ containerName: attr.containerName,
4419
+ }))
4420
+ : [],
4128
4421
  };
4129
4422
  this.callback(task);
4130
4423
  }
@@ -4141,10 +4434,12 @@
4141
4434
  duration: Math.round(deltaTime),
4142
4435
  startTime: Math.round(lastTime),
4143
4436
  timestamp: Date.now(),
4144
- attribution: [{
4437
+ attribution: [
4438
+ {
4145
4439
  name: 'unknown',
4146
- containerType: 'window'
4147
- }]
4440
+ containerType: 'window',
4441
+ },
4442
+ ],
4148
4443
  };
4149
4444
  this.callback(task);
4150
4445
  }
@@ -4201,7 +4496,7 @@
4201
4496
  type: 'low-fps',
4202
4497
  message: `Low FPS detected: ${data.fps}`,
4203
4498
  fps: data.fps,
4204
- droppedFrames: data.droppedFrames
4499
+ droppedFrames: data.droppedFrames,
4205
4500
  });
4206
4501
  }
4207
4502
  this.emitPerformanceData();
@@ -4217,7 +4512,7 @@
4217
4512
  type: 'high-memory',
4218
4513
  message: `High memory usage: ${data.percentUsed.toFixed(1)}%`,
4219
4514
  percentUsed: data.percentUsed,
4220
- usedBytes: data.usedJSHeapSize
4515
+ usedBytes: data.usedJSHeapSize,
4221
4516
  });
4222
4517
  }
4223
4518
  this.emitPerformanceData();
@@ -4232,21 +4527,21 @@
4232
4527
  (_b = (_a = this.inspector.getConfig()).onPerformanceIssue) === null || _b === void 0 ? void 0 : _b.call(_a, {
4233
4528
  type: 'poor-lcp',
4234
4529
  message: `Poor LCP: ${metrics.LCP}ms`,
4235
- value: metrics.LCP
4530
+ value: metrics.LCP,
4236
4531
  });
4237
4532
  }
4238
4533
  if (metrics.FID && metrics.FID > 100) {
4239
4534
  (_d = (_c = this.inspector.getConfig()).onPerformanceIssue) === null || _d === void 0 ? void 0 : _d.call(_c, {
4240
4535
  type: 'poor-fid',
4241
4536
  message: `Poor FID: ${metrics.FID}ms`,
4242
- value: metrics.FID
4537
+ value: metrics.FID,
4243
4538
  });
4244
4539
  }
4245
4540
  if (metrics.CLS && metrics.CLS > 0.1) {
4246
4541
  (_f = (_e = this.inspector.getConfig()).onPerformanceIssue) === null || _f === void 0 ? void 0 : _f.call(_e, {
4247
4542
  type: 'poor-cls',
4248
4543
  message: `Poor CLS: ${metrics.CLS}`,
4249
- value: metrics.CLS
4544
+ value: metrics.CLS,
4250
4545
  });
4251
4546
  }
4252
4547
  this.inspector.getEvents().emit('performance:metrics', metrics);
@@ -4268,7 +4563,7 @@
4268
4563
  type: 'long-task',
4269
4564
  message: `Long task detected: ${task.duration}ms`,
4270
4565
  duration: task.duration,
4271
- attribution: task.attribution
4566
+ attribution: task.attribution,
4272
4567
  });
4273
4568
  }
4274
4569
  }
@@ -4286,7 +4581,7 @@
4286
4581
  name: entry.name,
4287
4582
  duration: entry.duration,
4288
4583
  startTime: entry.startTime,
4289
- timestamp: Date.now()
4584
+ timestamp: Date.now(),
4290
4585
  });
4291
4586
  }
4292
4587
  });
@@ -4311,7 +4606,7 @@
4311
4606
  type: 'slow-resource',
4312
4607
  message: `Slow resource: ${resourceEntry.name}`,
4313
4608
  duration: resourceEntry.duration,
4314
- url: resourceEntry.name
4609
+ url: resourceEntry.name,
4315
4610
  });
4316
4611
  }
4317
4612
  }
@@ -4332,7 +4627,7 @@
4332
4627
  this.inspector.getEvents().emit('performance:mark', {
4333
4628
  name,
4334
4629
  duration,
4335
- timestamp: Date.now()
4630
+ timestamp: Date.now(),
4336
4631
  });
4337
4632
  }
4338
4633
  }
@@ -4342,7 +4637,7 @@
4342
4637
  memory: this.memoryMonitor.getCurrentMemory() || undefined,
4343
4638
  metrics: this.metricsCollector.getMetrics(),
4344
4639
  longTasks: this.inspector.getStorage('performance').get('longTasks') || [],
4345
- timestamp: Date.now()
4640
+ timestamp: Date.now(),
4346
4641
  };
4347
4642
  }
4348
4643
  }
@@ -4352,6 +4647,15 @@
4352
4647
  PerformanceMonitor: PerformanceMonitor
4353
4648
  });
4354
4649
 
4650
+ /**
4651
+ * `value instanceof globalThis[name]`, without a ReferenceError in runtimes that do
4652
+ * not define that event class (jsdom has no PromiseRejectionEvent, for example);
4653
+ * there the shape check done by the caller (`'reason' in event`) decides.
4654
+ */
4655
+ function isInstance(value, name) {
4656
+ const ctor = globalThis[name];
4657
+ return typeof ctor !== 'function' || value instanceof ctor;
4658
+ }
4355
4659
  class ErrorTracker {
4356
4660
  constructor(callback) {
4357
4661
  this.groups = new Map();
@@ -4368,7 +4672,7 @@
4368
4672
  /Network request failed/,
4369
4673
  /Failed to fetch/,
4370
4674
  /Load failed/,
4371
- /Script error/
4675
+ /Script error/,
4372
4676
  ];
4373
4677
  }
4374
4678
  addIgnorePattern(pattern) {
@@ -4402,28 +4706,30 @@
4402
4706
  let errorObject;
4403
4707
  if (error instanceof Error) {
4404
4708
  message = error.message || error.toString();
4405
- stack = error.stack ? error.stack.split('\n').map(line => line.trim()) : [];
4709
+ stack = error.stack ? error.stack.split('\n').map((line) => line.trim()) : [];
4406
4710
  errorObject = {
4407
4711
  name: error.name,
4408
4712
  message: error.message,
4409
- stack: error.stack
4713
+ stack: error.stack,
4410
4714
  };
4411
4715
  }
4412
- else if ('message' in error && error instanceof ErrorEvent) {
4716
+ else if ('message' in error && isInstance(error, 'ErrorEvent')) {
4413
4717
  message = error.message;
4414
4718
  source = error.filename;
4415
4719
  lineno = error.lineno;
4416
4720
  colno = error.colno;
4417
4721
  if (error.error) {
4418
- stack = error.error.stack ? error.error.stack.split('\n').map((line) => line.trim()) : [];
4722
+ stack = error.error.stack
4723
+ ? error.error.stack.split('\n').map((line) => line.trim())
4724
+ : [];
4419
4725
  errorObject = error.error;
4420
4726
  }
4421
4727
  }
4422
- else if ('reason' in error && error instanceof PromiseRejectionEvent) {
4728
+ else if ('reason' in error && isInstance(error, 'PromiseRejectionEvent')) {
4423
4729
  const reason = error.reason;
4424
4730
  if (reason instanceof Error) {
4425
4731
  message = reason.message || reason.toString();
4426
- stack = reason.stack ? reason.stack.split('\n').map(line => line.trim()) : [];
4732
+ stack = reason.stack ? reason.stack.split('\n').map((line) => line.trim()) : [];
4427
4733
  errorObject = reason;
4428
4734
  }
4429
4735
  else {
@@ -4433,8 +4739,8 @@
4433
4739
  }
4434
4740
  // Parse stack frames
4435
4741
  const stackFrames = stack
4436
- .map(frame => parseStackFrame(frame))
4437
- .filter(frame => frame !== null);
4742
+ .map((frame) => parseStackFrame(frame))
4743
+ .filter((frame) => frame !== null);
4438
4744
  const errorInfo = {
4439
4745
  id: generateId(),
4440
4746
  type,
@@ -4448,7 +4754,7 @@
4448
4754
  userAgent: navigator.userAgent,
4449
4755
  url: window.location.href,
4450
4756
  errorObject,
4451
- count: 1
4757
+ count: 1,
4452
4758
  };
4453
4759
  return errorInfo;
4454
4760
  }
@@ -4465,9 +4771,10 @@
4465
4771
  return true;
4466
4772
  }
4467
4773
  // Ignore errors from browser extensions
4468
- if (errorInfo.source && (errorInfo.source.includes('extension://') ||
4469
- errorInfo.source.includes('chrome-extension://') ||
4470
- errorInfo.source.includes('moz-extension://'))) {
4774
+ if (errorInfo.source &&
4775
+ (errorInfo.source.includes('extension://') ||
4776
+ errorInfo.source.includes('chrome-extension://') ||
4777
+ errorInfo.source.includes('moz-extension://'))) {
4471
4778
  return true;
4472
4779
  }
4473
4780
  return false;
@@ -4483,7 +4790,7 @@
4483
4790
  count: 0,
4484
4791
  firstSeen: errorInfo.timestamp,
4485
4792
  lastSeen: errorInfo.timestamp,
4486
- errors: []
4793
+ errors: [],
4487
4794
  };
4488
4795
  this.groups.set(fingerprint, group);
4489
4796
  }
@@ -4498,10 +4805,7 @@
4498
4805
  }
4499
4806
  generateFingerprint(errorInfo) {
4500
4807
  // Create a fingerprint based on error characteristics
4501
- const parts = [
4502
- errorInfo.type,
4503
- this.normalizeMessage(errorInfo.message)
4504
- ];
4808
+ const parts = [errorInfo.type, this.normalizeMessage(errorInfo.message)];
4505
4809
  // Add top stack frame if available
4506
4810
  if (errorInfo.stackFrames && errorInfo.stackFrames.length > 0) {
4507
4811
  const topFrame = errorInfo.stackFrames[0];
@@ -4519,7 +4823,7 @@
4519
4823
  }
4520
4824
  normalizeMessage(message) {
4521
4825
  // Remove dynamic parts from error messages for better grouping
4522
- return message
4826
+ return (message
4523
4827
  // Remove URLs
4524
4828
  .replace(/https?:\/\/[^\s]+/g, '<URL>')
4525
4829
  // Remove numbers
@@ -4531,11 +4835,10 @@
4531
4835
  .replace(/'[^']*'/g, "'<STRING>'")
4532
4836
  // Normalize whitespace
4533
4837
  .replace(/\s+/g, ' ')
4534
- .trim();
4838
+ .trim());
4535
4839
  }
4536
4840
  getGroups() {
4537
- return Array.from(this.groups.values())
4538
- .sort((a, b) => b.lastSeen - a.lastSeen);
4841
+ return Array.from(this.groups.values()).sort((a, b) => b.lastSeen - a.lastSeen);
4539
4842
  }
4540
4843
  getGroup(groupId) {
4541
4844
  for (const group of this.groups.values()) {
@@ -4565,7 +4868,7 @@
4565
4868
  totalErrors,
4566
4869
  totalGroups: this.groups.size,
4567
4870
  errorsByType,
4568
- recentErrors: recentErrors.slice(0, 10)
4871
+ recentErrors: recentErrors.slice(0, 10),
4569
4872
  };
4570
4873
  }
4571
4874
  }
@@ -4636,7 +4939,7 @@
4636
4939
  const response = await fetch(fileUrl, {
4637
4940
  method: 'GET',
4638
4941
  mode: 'cors',
4639
- credentials: 'omit'
4942
+ credentials: 'omit',
4640
4943
  });
4641
4944
  if (!response.ok)
4642
4945
  return null;
@@ -4675,7 +4978,7 @@
4675
4978
  const response = await fetch(sourceMapUrl, {
4676
4979
  method: 'GET',
4677
4980
  mode: 'cors',
4678
- credentials: 'omit'
4981
+ credentials: 'omit',
4679
4982
  });
4680
4983
  if (!response.ok)
4681
4984
  return null;
@@ -4685,7 +4988,7 @@
4685
4988
  // Cache it
4686
4989
  this.cache[fileUrl] = {
4687
4990
  sourceMapUrl,
4688
- sourceMap
4991
+ sourceMap,
4689
4992
  };
4690
4993
  return sourceMap;
4691
4994
  }
@@ -4706,7 +5009,7 @@
4706
5009
  source: sourceMap.sources[0] || 'unknown',
4707
5010
  line: line,
4708
5011
  column: column,
4709
- name: (_a = sourceMap.names) === null || _a === void 0 ? void 0 : _a[0]
5012
+ name: (_a = sourceMap.names) === null || _a === void 0 ? void 0 : _a[0],
4710
5013
  };
4711
5014
  }
4712
5015
  clearCache() {
@@ -4723,15 +5026,13 @@
4723
5026
  class ErrorMonitor {
4724
5027
  constructor(inspector) {
4725
5028
  this.isActive = false;
4726
- this.originalHandlers = {
4727
- error: null,
4728
- unhandledrejection: null
4729
- };
5029
+ /** Set while a window error/rejection event is being tracked (vs. trackError()). */
5030
+ this.trackingUncaught = false;
4730
5031
  this.handleErrorEvent = (event) => {
4731
- this.errorTracker.trackError(event, 'error');
5032
+ this.trackUncaught(() => this.errorTracker.trackError(event, 'error'));
4732
5033
  };
4733
5034
  this.handleRejectionEvent = (event) => {
4734
- this.errorTracker.trackError(event, 'unhandledRejection');
5035
+ this.trackUncaught(() => this.errorTracker.trackError(event, 'unhandledRejection'));
4735
5036
  };
4736
5037
  this.inspector = inspector;
4737
5038
  // eslint-disable-next-line @typescript-eslint/no-misused-promises -- 1.x behaviour: the tracker does not await the handler
@@ -4750,50 +5051,30 @@
4750
5051
  this.uninstallErrorHandlers();
4751
5052
  this.isActive = false;
4752
5053
  }
5054
+ // One subscription per event type: window.onerror / onunhandledrejection are left
5055
+ // to the page (setting them as well reported every error twice and returning true
5056
+ // from onerror hid the error from the browser console).
4753
5057
  installErrorHandlers() {
4754
- // Save original handlers
4755
- this.originalHandlers.error = window.onerror;
4756
- this.originalHandlers.unhandledrejection = window.onunhandledrejection;
4757
- // Install error handler
4758
- window.onerror = (message, source, lineno, colno, error) => {
4759
- const errorEvent = new ErrorEvent('error', {
4760
- // eslint-disable-next-line @typescript-eslint/no-base-to-string -- onerror passes a string or an Event
4761
- message: String(message),
4762
- filename: source,
4763
- lineno,
4764
- colno,
4765
- error
4766
- });
4767
- this.errorTracker.trackError(errorEvent, 'error');
4768
- // Call original handler if exists
4769
- if (this.originalHandlers.error) {
4770
- return this.originalHandlers.error(message, source, lineno, colno, error);
4771
- }
4772
- return true; // Prevent default browser error handling
4773
- };
4774
- // Install unhandled rejection handler
4775
- window.onunhandledrejection = (event) => {
4776
- this.errorTracker.trackError(event, 'unhandledRejection');
4777
- // Call original handler if exists
4778
- if (this.originalHandlers.unhandledrejection) {
4779
- return this.originalHandlers.unhandledrejection(event);
4780
- }
4781
- return true; // Prevent default browser error handling
4782
- };
4783
- // Also use addEventListener for better coverage
4784
5058
  window.addEventListener('error', this.handleErrorEvent);
4785
5059
  window.addEventListener('unhandledrejection', this.handleRejectionEvent);
4786
5060
  }
4787
5061
  uninstallErrorHandlers() {
4788
- // Restore original handlers
4789
- window.onerror = this.originalHandlers.error;
4790
- window.onunhandledrejection = this.originalHandlers.unhandledrejection;
4791
- // Remove event listeners
4792
5062
  window.removeEventListener('error', this.handleErrorEvent);
4793
5063
  window.removeEventListener('unhandledrejection', this.handleRejectionEvent);
4794
5064
  }
5065
+ trackUncaught(track) {
5066
+ this.trackingUncaught = true;
5067
+ try {
5068
+ track();
5069
+ }
5070
+ finally {
5071
+ this.trackingUncaught = false;
5072
+ }
5073
+ }
4795
5074
  async handleError(errorInfo) {
4796
5075
  var _a, _b;
5076
+ // Window errors and rejections are uncaught; errors passed to trackError() are caught.
5077
+ const uncaught = this.trackingUncaught;
4797
5078
  // Enhance stack trace with source maps if available
4798
5079
  if (errorInfo.stack && this.sourceMapSupport.isEnabled()) {
4799
5080
  try {
@@ -4807,13 +5088,9 @@
4807
5088
  const storage = this.inspector.getStorage('error');
4808
5089
  storage.push(errorInfo);
4809
5090
  // Emit events
4810
- this.inspector.getEvents().emit(errorInfo.type === 'unhandledRejection' ? 'error:uncaught' : 'error:caught', errorInfo);
5091
+ this.inspector.getEvents().emit(uncaught ? 'error:uncaught' : 'error:caught', errorInfo);
4811
5092
  // Call error callback
4812
5093
  (_b = (_a = this.inspector.getConfig()).onError) === null || _b === void 0 ? void 0 : _b.call(_a, new Error(errorInfo.message));
4813
- // Log to console in development
4814
- if (this.inspector.getConfig().enabled) {
4815
- console.error('[DevInspector] Error captured:', errorInfo);
4816
- }
4817
5094
  }
4818
5095
  // Public API
4819
5096
  trackError(error) {
@@ -4972,7 +5249,7 @@
4972
5249
  const rect = this.element.getBoundingClientRect();
4973
5250
  this.dragOffset = {
4974
5251
  x: e.clientX - rect.left,
4975
- y: e.clientY - rect.top
5252
+ y: e.clientY - rect.top,
4976
5253
  };
4977
5254
  this.element.style.cursor = 'grabbing';
4978
5255
  this.element.style.zIndex = '1000000';
@@ -5013,11 +5290,10 @@
5013
5290
  left: centerX,
5014
5291
  right: windowWidth - centerX,
5015
5292
  top: centerY,
5016
- bottom: windowHeight - centerY
5293
+ bottom: windowHeight - centerY,
5017
5294
  };
5018
5295
  // Find closest edge using type-safe approach
5019
- const closestEdge = Object.entries(distances)
5020
- .reduce((a, b) => a[1] < b[1] ? a : b)[0];
5296
+ const closestEdge = Object.entries(distances).reduce((a, b) => (a[1] < b[1] ? a : b))[0];
5021
5297
  // Animate to edge
5022
5298
  const margin = 20;
5023
5299
  switch (closestEdge) {
@@ -5091,7 +5367,7 @@
5091
5367
  document.removeEventListener('mousemove', this.boundMouseMove);
5092
5368
  document.removeEventListener('mouseup', this.boundMouseUp);
5093
5369
  // Unsubscribe from all inspector events
5094
- this.eventUnsubscribers.forEach(unsubscribe => unsubscribe());
5370
+ this.eventUnsubscribers.forEach((unsubscribe) => unsubscribe());
5095
5371
  this.eventUnsubscribers = [];
5096
5372
  if (this.element.parentNode) {
5097
5373
  this.element.parentNode.removeChild(this.element);
@@ -5152,7 +5428,7 @@
5152
5428
  setupEventListeners() {
5153
5429
  // Header controls
5154
5430
  const controls = this.headerElement.querySelectorAll('.devinspector-control');
5155
- controls.forEach(control => {
5431
+ controls.forEach((control) => {
5156
5432
  control.addEventListener('click', (e) => {
5157
5433
  e.stopPropagation();
5158
5434
  const className = control.className;
@@ -5195,7 +5471,7 @@
5195
5471
  const rect = this.element.getBoundingClientRect();
5196
5472
  this.dragOffset = {
5197
5473
  x: e.clientX - rect.left,
5198
- y: e.clientY - rect.top
5474
+ y: e.clientY - rect.top,
5199
5475
  };
5200
5476
  this.headerElement.style.cursor = 'grabbing';
5201
5477
  this.element.style.zIndex = '1000000';
@@ -5293,12 +5569,12 @@
5293
5569
  return;
5294
5570
  this.tabs.delete(tabId);
5295
5571
  // Remove tab element
5296
- const tab = Array.from(this.tabsElement.querySelectorAll('.devinspector-tab')).find(el => el.dataset.tabId === tabId);
5572
+ const tab = Array.from(this.tabsElement.querySelectorAll('.devinspector-tab')).find((el) => el.dataset.tabId === tabId);
5297
5573
  if (tab) {
5298
5574
  tab.remove();
5299
5575
  }
5300
5576
  // Remove panel element
5301
- const panel = Array.from(this.bodyElement.querySelectorAll('.devinspector-panel')).find(el => el.dataset.panelId === tabId);
5577
+ const panel = Array.from(this.bodyElement.querySelectorAll('.devinspector-panel')).find((el) => el.dataset.panelId === tabId);
5302
5578
  if (panel) {
5303
5579
  panel.remove();
5304
5580
  }
@@ -5318,12 +5594,12 @@
5318
5594
  return;
5319
5595
  this.activeTab = tabId;
5320
5596
  // Update tab states
5321
- this.tabsElement.querySelectorAll('.devinspector-tab').forEach(tab => {
5597
+ this.tabsElement.querySelectorAll('.devinspector-tab').forEach((tab) => {
5322
5598
  const htmlTab = tab;
5323
5599
  tab.classList.toggle('active', htmlTab.dataset.tabId === tabId);
5324
5600
  });
5325
5601
  // Update panel states
5326
- this.bodyElement.querySelectorAll('.devinspector-panel').forEach(panel => {
5602
+ this.bodyElement.querySelectorAll('.devinspector-panel').forEach((panel) => {
5327
5603
  const htmlPanel = panel;
5328
5604
  panel.classList.toggle('active', htmlPanel.dataset.panelId === tabId);
5329
5605
  });
@@ -5332,7 +5608,7 @@
5332
5608
  this.tabs.forEach((config, tabId) => {
5333
5609
  if (config.badge) {
5334
5610
  const count = config.badge();
5335
- const tab = Array.from(this.tabsElement.querySelectorAll('.devinspector-tab')).find(el => el.dataset.tabId === tabId);
5611
+ const tab = Array.from(this.tabsElement.querySelectorAll('.devinspector-tab')).find((el) => el.dataset.tabId === tabId);
5336
5612
  const badge = tab === null || tab === void 0 ? void 0 : tab.querySelector('.devinspector-tab-badge');
5337
5613
  if (badge) {
5338
5614
  badge.textContent = count.toString();
@@ -5375,31 +5651,33 @@
5375
5651
  }
5376
5652
 
5377
5653
  const createStyles = (theme = 'dark') => {
5378
- const colors = theme === 'dark' ? {
5379
- primary: '#1e1e1e',
5380
- secondary: '#2d2d30',
5381
- tertiary: '#3e3e42',
5382
- accent: '#007acc',
5383
- text: '#cccccc',
5384
- textSecondary: '#9d9d9d',
5385
- border: '#3e3e42',
5386
- success: '#4caf50',
5387
- warning: '#ff9800',
5388
- error: '#f44336',
5389
- info: '#2196f3'
5390
- } : {
5391
- primary: '#ffffff',
5392
- secondary: '#f5f5f5',
5393
- tertiary: '#e0e0e0',
5394
- accent: '#1976d2',
5395
- text: '#333333',
5396
- textSecondary: '#666666',
5397
- border: '#ddd',
5398
- success: '#4caf50',
5399
- warning: '#ff9800',
5400
- error: '#f44336',
5401
- info: '#2196f3'
5402
- };
5654
+ const colors = theme === 'dark'
5655
+ ? {
5656
+ primary: '#1e1e1e',
5657
+ secondary: '#2d2d30',
5658
+ tertiary: '#3e3e42',
5659
+ accent: '#007acc',
5660
+ text: '#cccccc',
5661
+ textSecondary: '#9d9d9d',
5662
+ border: '#3e3e42',
5663
+ success: '#4caf50',
5664
+ warning: '#ff9800',
5665
+ error: '#f44336',
5666
+ info: '#2196f3',
5667
+ }
5668
+ : {
5669
+ primary: '#ffffff',
5670
+ secondary: '#f5f5f5',
5671
+ tertiary: '#e0e0e0',
5672
+ accent: '#1976d2',
5673
+ text: '#333333',
5674
+ textSecondary: '#666666',
5675
+ border: '#ddd',
5676
+ success: '#4caf50',
5677
+ warning: '#ff9800',
5678
+ error: '#f44336',
5679
+ info: '#2196f3',
5680
+ };
5403
5681
  return `
5404
5682
  .devinspector {
5405
5683
  position: fixed;
@@ -5944,7 +6222,8 @@
5944
6222
  injectStyles() {
5945
6223
  this.styleElement = document.createElement('style');
5946
6224
  const theme = this.inspector.getConfig().theme;
5947
- const prefersDark = typeof window.matchMedia === 'function' && window.matchMedia('(prefers-color-scheme: dark)').matches;
6225
+ const prefersDark = typeof window.matchMedia === 'function' &&
6226
+ window.matchMedia('(prefers-color-scheme: dark)').matches;
5948
6227
  const resolvedTheme = theme === 'auto' ? (prefersDark ? 'dark' : 'light') : theme;
5949
6228
  this.styleElement.textContent = createStyles(resolvedTheme);
5950
6229
  document.head.appendChild(this.styleElement);
@@ -5955,27 +6234,27 @@
5955
6234
  id: 'network',
5956
6235
  label: 'Network',
5957
6236
  badge: () => this.inspector.getStorage('network').getSize(),
5958
- content: this.createNetworkPanel()
6237
+ content: this.createNetworkPanel(),
5959
6238
  };
5960
6239
  // Console tab
5961
6240
  const consoleTab = {
5962
6241
  id: 'console',
5963
6242
  label: 'Console',
5964
6243
  badge: () => this.inspector.getStorage('console').getSize(),
5965
- content: this.createConsolePanel()
6244
+ content: this.createConsolePanel(),
5966
6245
  };
5967
6246
  // Performance tab
5968
6247
  const performanceTab = {
5969
6248
  id: 'performance',
5970
6249
  label: 'Performance',
5971
- content: this.createPerformancePanel()
6250
+ content: this.createPerformancePanel(),
5972
6251
  };
5973
6252
  // Errors tab
5974
6253
  const errorsTab = {
5975
6254
  id: 'errors',
5976
6255
  label: 'Errors',
5977
6256
  badge: () => this.inspector.getStorage('error').getSize(),
5978
- content: this.createErrorsPanel()
6257
+ content: this.createErrorsPanel(),
5979
6258
  };
5980
6259
  this.mainPanel.addTab(networkTab);
5981
6260
  this.mainPanel.addTab(consoleTab);
@@ -6112,7 +6391,7 @@
6112
6391
  list.appendChild(entry);
6113
6392
  }
6114
6393
  updateNetworkEntry(panel, response) {
6115
- const entry = Array.from(panel.querySelectorAll('[data-request-id]')).find(el => el.dataset.requestId === String(response.id));
6394
+ const entry = Array.from(panel.querySelectorAll('[data-request-id]')).find((el) => el.dataset.requestId === String(response.id));
6116
6395
  if (!entry)
6117
6396
  return;
6118
6397
  const status = entry.querySelector('.devinspector-status');
@@ -6170,7 +6449,8 @@
6170
6449
  }
6171
6450
  }
6172
6451
  formatConsoleArgs(args) {
6173
- return args.map(arg => {
6452
+ return args
6453
+ .map((arg) => {
6174
6454
  if (typeof arg === 'string') {
6175
6455
  return arg;
6176
6456
  }
@@ -6180,7 +6460,8 @@
6180
6460
  else {
6181
6461
  return String(arg);
6182
6462
  }
6183
- }).join(' ');
6463
+ })
6464
+ .join(' ');
6184
6465
  }
6185
6466
  show() {
6186
6467
  this.mainPanel.show();