very-happy-dom 0.0.7 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +9 -3742
  2. package/package.json +1 -2
package/dist/index.js CHANGED
@@ -1,2750 +1,13 @@
1
1
  // @bun
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __moduleCache = /* @__PURE__ */ new WeakMap;
7
- var __toCommonJS = (from) => {
8
- var entry = __moduleCache.get(from), desc;
9
- if (entry)
10
- return entry;
11
- entry = __defProp({}, "__esModule", { value: true });
12
- if (from && typeof from === "object" || typeof from === "function")
13
- __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
14
- get: () => from[key],
15
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
- }));
17
- __moduleCache.set(from, entry);
18
- return entry;
19
- };
20
- var __export = (target, all) => {
21
- for (var name in all)
22
- __defProp(target, name, {
23
- get: all[name],
24
- enumerable: true,
25
- configurable: true,
26
- set: (newValue) => all[name] = () => newValue
27
- });
28
- };
29
-
30
- // src/window/DetachedWindowAPI.ts
31
- var exports_DetachedWindowAPI = {};
32
- __export(exports_DetachedWindowAPI, {
33
- DetachedWindowAPI: () => DetachedWindowAPI
34
- });
35
-
36
- class DetachedWindowAPI {
37
- _window;
38
- _pendingOperations = new Set;
39
- _aborted = false;
40
- constructor(window) {
41
- this._window = window;
42
- }
43
- get settings() {
44
- return this._window.settings;
45
- }
46
- async close() {
47
- await this.abort();
48
- this._window.document.documentElement.innerHTML = "";
49
- }
50
- async waitUntilComplete() {
51
- if (this._pendingOperations.size > 0) {
52
- await Promise.all(Array.from(this._pendingOperations));
53
- }
54
- const timerManager = this._window._getTimerManager?.();
55
- if (timerManager) {
56
- await timerManager.waitForTimers();
57
- }
58
- }
59
- async abort() {
60
- this._aborted = true;
61
- this._pendingOperations.clear();
62
- const timerManager = this._window._getTimerManager?.();
63
- if (timerManager) {
64
- timerManager.abort();
65
- }
66
- }
67
- setURL(url) {
68
- this._window.location = url;
69
- }
70
- setViewport(options) {
71
- if (options.width !== undefined) {
72
- this._window._width = options.width;
73
- }
74
- if (options.height !== undefined) {
75
- this._window._height = options.height;
76
- }
77
- }
78
- _trackOperation(operation) {
79
- this._pendingOperations.add(operation);
80
- operation.finally(() => {
81
- this._pendingOperations.delete(operation);
82
- });
83
- }
84
- _isAborted() {
85
- return this._aborted;
86
- }
87
- }
88
-
89
- // src/apis/BrowserAPIs.ts
90
- class Performance {
91
- _marks = new Map;
92
- _measures = new Map;
93
- _startTime = Date.now();
94
- now() {
95
- return Date.now() - this._startTime;
96
- }
97
- mark(name) {
98
- this._marks.set(name, this.now());
99
- }
100
- measure(name, startMark, endMark) {
101
- const end = endMark ? this._marks.get(endMark) : this.now();
102
- const start = startMark ? this._marks.get(startMark) : 0;
103
- if (end !== undefined && start !== undefined) {
104
- this._measures.set(name, {
105
- start,
106
- duration: end - start
107
- });
108
- }
109
- }
110
- clearMarks(name) {
111
- if (name) {
112
- this._marks.delete(name);
113
- } else {
114
- this._marks.clear();
115
- }
116
- }
117
- clearMeasures(name) {
118
- if (name) {
119
- this._measures.delete(name);
120
- } else {
121
- this._measures.clear();
122
- }
123
- }
124
- getEntriesByName(name) {
125
- const entries = [];
126
- if (this._marks.has(name)) {
127
- entries.push({ name, entryType: "mark", startTime: this._marks.get(name) });
128
- }
129
- if (this._measures.has(name)) {
130
- const measure = this._measures.get(name);
131
- entries.push({ name, entryType: "measure", startTime: measure.start, duration: measure.duration });
132
- }
133
- return entries;
134
- }
135
- }
136
-
137
- class Geolocation {
138
- getCurrentPosition(success, _error, _options) {
139
- setTimeout(() => {
140
- success({
141
- coords: {
142
- latitude: 37.7749,
143
- longitude: -122.4194,
144
- accuracy: 10,
145
- altitude: null,
146
- altitudeAccuracy: null,
147
- heading: null,
148
- speed: null
149
- },
150
- timestamp: Date.now()
151
- });
152
- }, 0);
153
- }
154
- watchPosition(success, _error, _options) {
155
- const id = setInterval(() => {
156
- success({
157
- coords: {
158
- latitude: 37.7749,
159
- longitude: -122.4194,
160
- accuracy: 10,
161
- altitude: null,
162
- altitudeAccuracy: null,
163
- heading: null,
164
- speed: null
165
- },
166
- timestamp: Date.now()
167
- });
168
- }, 1000);
169
- return id;
170
- }
171
- clearWatch(id) {
172
- clearInterval(id);
173
- }
174
- }
175
-
176
- class Notification {
177
- static permission = "default";
178
- title;
179
- body;
180
- icon;
181
- tag;
182
- onclick = null;
183
- onclose = null;
184
- onerror = null;
185
- onshow = null;
186
- constructor(title, options) {
187
- this.title = title;
188
- this.body = options?.body;
189
- this.icon = options?.icon;
190
- this.tag = options?.tag;
191
- setTimeout(() => {
192
- if (this.onshow) {
193
- this.onshow({});
194
- }
195
- }, 0);
196
- }
197
- static requestPermission() {
198
- return Promise.resolve("granted");
199
- }
200
- close() {
201
- if (this.onclose) {
202
- this.onclose({});
203
- }
204
- }
205
- }
206
-
207
- class EnhancedConsole {
208
- _groups = [];
209
- _timers = new Map;
210
- log(...args) {
211
- console.log(...this._prefix(), ...args);
212
- }
213
- warn(...args) {
214
- console.warn(...this._prefix(), ...args);
215
- }
216
- error(...args) {
217
- console.error(...this._prefix(), ...args);
218
- }
219
- info(...args) {
220
- console.info(...this._prefix(), ...args);
221
- }
222
- debug(...args) {
223
- console.debug(...this._prefix(), ...args);
224
- }
225
- table(data) {
226
- console.table(data);
227
- }
228
- group(label) {
229
- if (label) {
230
- this._groups.push(label);
231
- console.log(...this._prefix(), `\u25BC ${label}`);
232
- }
233
- }
234
- groupCollapsed(label) {
235
- this.group(label);
236
- }
237
- groupEnd() {
238
- this._groups.pop();
239
- }
240
- time(label) {
241
- this._timers.set(label, Date.now());
242
- }
243
- timeEnd(label) {
244
- const start = this._timers.get(label);
245
- if (start) {
246
- const duration = Date.now() - start;
247
- console.log(...this._prefix(), `${label}: ${duration}ms`);
248
- this._timers.delete(label);
249
- }
250
- }
251
- timeLog(label, ...args) {
252
- const start = this._timers.get(label);
253
- if (start) {
254
- const duration = Date.now() - start;
255
- console.log(...this._prefix(), `${label}: ${duration}ms`, ...args);
256
- }
257
- }
258
- clear() {
259
- console.clear();
260
- }
261
- count(label = "default") {
262
- console.log(...this._prefix(), label);
263
- }
264
- assert(condition, ...args) {
265
- if (!condition) {
266
- console.error(...this._prefix(), "Assertion failed:", ...args);
267
- }
268
- }
269
- trace(...args) {
270
- console.trace(...this._prefix(), ...args);
271
- }
272
- _prefix() {
273
- return this._groups.map(() => " ");
274
- }
275
- }
276
-
277
- class DataTransfer {
278
- _data = new Map;
279
- dropEffect = "none";
280
- effectAllowed = "uninitialized";
281
- files = [];
282
- items = [];
283
- types = [];
284
- setData(format, data) {
285
- this._data.set(format, data);
286
- if (!this.types.includes(format)) {
287
- this.types.push(format);
288
- }
289
- }
290
- getData(format) {
291
- return this._data.get(format) || "";
292
- }
293
- clearData(format) {
294
- if (format) {
295
- this._data.delete(format);
296
- const index = this.types.indexOf(format);
297
- if (index !== -1) {
298
- this.types.splice(index, 1);
299
- }
300
- } else {
301
- this._data.clear();
302
- this.types = [];
303
- }
304
- }
305
- setDragImage(_image, _x, _y) {}
306
- }
307
- // src/apis/Clipboard.ts
308
- class Clipboard {
309
- _text = "";
310
- async writeText(text) {
311
- this._text = text;
312
- }
313
- async readText() {
314
- return this._text;
315
- }
316
- async write(data) {
317
- for (const item of data) {
318
- for (const type of item.types) {
319
- const blob = await item.getType(type);
320
- if (type === "text/plain") {
321
- this._text = await blob.text();
322
- }
323
- }
324
- }
325
- }
326
- async read() {
327
- const blob = new Blob([this._text], { type: "text/plain" });
328
- const item = new ClipboardItem({
329
- "text/plain": blob
330
- });
331
- return [item];
332
- }
333
- }
334
-
335
- class Navigator {
336
- clipboard = new Clipboard;
337
- geolocation = new Geolocation;
338
- userAgent = "Mozilla/5.0 (X11; Linux x64) AppleWebKit/537.36 (KHTML, like Gecko) VeryHappyDOM/1.0.0";
339
- language = "en-US";
340
- languages = ["en-US", "en"];
341
- platform = "Linux x86_64";
342
- cookieEnabled = true;
343
- onLine = true;
344
- }
345
- // src/apis/FileAPI.ts
346
- class VeryHappyFile extends Blob {
347
- name;
348
- lastModified;
349
- constructor(bits, name, options) {
350
- super(bits, options);
351
- this.name = name;
352
- this.lastModified = options?.lastModified || Date.now();
353
- }
354
- }
355
-
356
- class VeryHappyFileReader {
357
- static EMPTY = 0;
358
- static LOADING = 1;
359
- static DONE = 2;
360
- readyState = VeryHappyFileReader.EMPTY;
361
- result = null;
362
- error = null;
363
- onload = null;
364
- onerror = null;
365
- onloadstart = null;
366
- onloadend = null;
367
- onprogress = null;
368
- onabort = null;
369
- _eventListeners = new Map;
370
- readAsText(blob, _encoding = "UTF-8") {
371
- this.readyState = VeryHappyFileReader.LOADING;
372
- this._trigger("loadstart");
373
- blob.text().then((text) => {
374
- this.result = text;
375
- this.readyState = VeryHappyFileReader.DONE;
376
- this._trigger("load");
377
- this._trigger("loadend");
378
- }).catch((error) => {
379
- this.error = error;
380
- this.readyState = VeryHappyFileReader.DONE;
381
- this._trigger("error");
382
- this._trigger("loadend");
383
- });
384
- }
385
- readAsDataURL(blob) {
386
- this.readyState = VeryHappyFileReader.LOADING;
387
- this._trigger("loadstart");
388
- blob.arrayBuffer().then((buffer) => {
389
- const base64 = Buffer.from(buffer).toString("base64");
390
- this.result = `data:${blob.type};base64,${base64}`;
391
- this.readyState = VeryHappyFileReader.DONE;
392
- this._trigger("load");
393
- this._trigger("loadend");
394
- }).catch((error) => {
395
- this.error = error;
396
- this.readyState = VeryHappyFileReader.DONE;
397
- this._trigger("error");
398
- this._trigger("loadend");
399
- });
400
- }
401
- readAsArrayBuffer(blob) {
402
- this.readyState = VeryHappyFileReader.LOADING;
403
- this._trigger("loadstart");
404
- blob.arrayBuffer().then((buffer) => {
405
- this.result = buffer;
406
- this.readyState = VeryHappyFileReader.DONE;
407
- this._trigger("load");
408
- this._trigger("loadend");
409
- }).catch((error) => {
410
- this.error = error;
411
- this.readyState = VeryHappyFileReader.DONE;
412
- this._trigger("error");
413
- this._trigger("loadend");
414
- });
415
- }
416
- readAsBinaryString(blob) {
417
- this.readyState = VeryHappyFileReader.LOADING;
418
- this._trigger("loadstart");
419
- blob.arrayBuffer().then((buffer) => {
420
- this.result = String.fromCharCode(...new Uint8Array(buffer));
421
- this.readyState = VeryHappyFileReader.DONE;
422
- this._trigger("load");
423
- this._trigger("loadend");
424
- }).catch((error) => {
425
- this.error = error;
426
- this.readyState = VeryHappyFileReader.DONE;
427
- this._trigger("error");
428
- this._trigger("loadend");
429
- });
430
- }
431
- abort() {
432
- this.readyState = VeryHappyFileReader.DONE;
433
- this._trigger("abort");
434
- this._trigger("loadend");
435
- }
436
- addEventListener(type, listener) {
437
- if (!this._eventListeners.has(type)) {
438
- this._eventListeners.set(type, new Set);
439
- }
440
- this._eventListeners.get(type).add(listener);
441
- }
442
- removeEventListener(type, listener) {
443
- const listeners = this._eventListeners.get(type);
444
- if (listeners) {
445
- listeners.delete(listener);
446
- }
447
- }
448
- _trigger(type) {
449
- const event = {
450
- type,
451
- lengthComputable: false,
452
- loaded: 0,
453
- total: 0
454
- };
455
- const listeners = this._eventListeners.get(type);
456
- if (listeners) {
457
- for (const listener of listeners) {
458
- listener(event);
459
- }
460
- }
461
- const handler = this[`on${type}`];
462
- if (handler) {
463
- handler.call(this, event);
464
- }
465
- }
466
- }
467
-
468
- class VeryHappyFileList {
469
- _files = [];
470
- constructor(files = []) {
471
- this._files = files;
472
- }
473
- get length() {
474
- return this._files.length;
475
- }
476
- item(index) {
477
- return this._files[index] || null;
478
- }
479
- [Symbol.iterator]() {
480
- return this._files[Symbol.iterator]();
481
- }
482
- }
483
- // src/browser/BrowserPage.ts
484
- import { Buffer as Buffer2 } from "buffer";
485
-
486
- // src/network/RequestInterceptor.ts
487
- class RequestInterceptor {
488
- _enabled = false;
489
- _handlers = new Set;
490
- _originalFetch;
491
- constructor() {
492
- this._originalFetch = globalThis.fetch;
493
- }
494
- enable() {
495
- if (this._enabled)
496
- return;
497
- this._enabled = true;
498
- const interceptor = this;
499
- const overriddenFetch = async function(input, init) {
500
- const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
501
- const method = init?.method || "GET";
502
- const headers = {};
503
- if (init?.headers) {
504
- if (init.headers instanceof Headers) {
505
- init.headers.forEach((value, key) => {
506
- headers[key] = value;
507
- });
508
- } else if (Array.isArray(init.headers)) {
509
- init.headers.forEach(([key, value]) => {
510
- headers[key] = value;
511
- });
512
- } else {
513
- Object.assign(headers, init.headers);
514
- }
515
- }
516
- let aborted = false;
517
- let responded = false;
518
- let mockResponse = null;
519
- let overrides = {};
520
- const interceptedRequest = {
521
- url,
522
- method,
523
- headers,
524
- postData: init?.body ? String(init.body) : null,
525
- resourceType: "fetch",
526
- continue(reqOverrides = {}) {
527
- overrides = reqOverrides;
528
- },
529
- abort(_errorCode = "failed") {
530
- aborted = true;
531
- },
532
- respond(response) {
533
- responded = true;
534
- mockResponse = new Response(response.body, {
535
- status: response.status,
536
- headers: response.headers
537
- });
538
- }
539
- };
540
- for (const handler of interceptor._handlers) {
541
- await handler(interceptedRequest);
542
- }
543
- if (aborted) {
544
- throw new Error("Request aborted");
545
- }
546
- if (responded && mockResponse) {
547
- return mockResponse;
548
- }
549
- const finalUrl = overrides.url || url;
550
- const finalMethod = overrides.method || method;
551
- const finalHeaders = overrides.headers || headers;
552
- const finalBody = overrides.postData !== undefined ? overrides.postData : init?.body;
553
- return interceptor._originalFetch(finalUrl, {
554
- ...init,
555
- method: finalMethod,
556
- headers: finalHeaders,
557
- body: finalBody
558
- });
559
- };
560
- Object.assign(overriddenFetch, { preconnect: () => {} });
561
- globalThis.fetch = overriddenFetch;
562
- }
563
- disable() {
564
- if (!this._enabled)
565
- return;
566
- this._enabled = false;
567
- globalThis.fetch = this._originalFetch;
568
- }
569
- addHandler(handler) {
570
- this._handlers.add(handler);
571
- }
572
- removeHandler(handler) {
573
- this._handlers.delete(handler);
574
- }
575
- clear() {
576
- this._handlers.clear();
577
- }
578
- }
579
-
580
- // src/events/VirtualEvent.ts
581
- class VirtualEvent {
582
- type;
583
- target = null;
584
- currentTarget = null;
585
- bubbles;
586
- cancelable;
587
- defaultPrevented = false;
588
- propagationStopped = false;
589
- immediatePropagationStopped = false;
590
- timeStamp;
591
- constructor(type, options = {}) {
592
- this.type = type;
593
- this.bubbles = options.bubbles ?? false;
594
- this.cancelable = options.cancelable ?? false;
595
- this.timeStamp = Date.now();
596
- }
597
- preventDefault() {
598
- if (this.cancelable) {
599
- this.defaultPrevented = true;
600
- }
601
- }
602
- stopPropagation() {
603
- this.propagationStopped = true;
604
- }
605
- stopImmediatePropagation() {
606
- this.immediatePropagationStopped = true;
607
- this.propagationStopped = true;
608
- }
609
- }
610
-
611
- // src/nodes/VirtualCommentNode.ts
612
- class VirtualCommentNode {
613
- nodeType = "comment";
614
- nodeName = "#comment";
615
- nodeValue;
616
- attributes = new Map;
617
- children = [];
618
- parentNode = null;
619
- constructor(text) {
620
- this.nodeValue = text;
621
- }
622
- get textContent() {
623
- return "";
624
- }
625
- set textContent(_value) {}
626
- }
627
-
628
- // src/selectors/engine.ts
629
- function querySelectorEngine(root, selector) {
630
- if (!selector || typeof selector !== "string") {
631
- return null;
632
- }
633
- if (!selector.trim()) {
634
- return null;
635
- }
636
- const results = querySelectorAllEngine(root, selector);
637
- return results.length > 0 ? results[0] : null;
638
- }
639
- function querySelectorAllEngine(root, selector) {
640
- if (!selector || typeof selector !== "string") {
641
- return [];
642
- }
643
- if (!selector.trim()) {
644
- return [];
645
- }
646
- if (selector.includes(",")) {
647
- const selectors = selector.split(",").map((s) => s.trim()).filter(Boolean);
648
- const allResults = [];
649
- const seen = new Set;
650
- for (const individualSelector of selectors) {
651
- const selectorResults = querySelectorAllEngine(root, individualSelector);
652
- for (const element of selectorResults) {
653
- if (!seen.has(element)) {
654
- seen.add(element);
655
- allResults.push(element);
656
- }
657
- }
658
- }
659
- return allResults;
660
- }
661
- const results = [];
662
- if (hasCombinators(selector)) {
663
- let traverse = function(node) {
664
- if (node.nodeType === "element" && matchesComplexSelector(node, selector, root)) {
665
- results.push(node);
666
- }
667
- for (const child of node.children) {
668
- traverse(child);
669
- }
670
- };
671
- for (const child of root.children) {
672
- traverse(child);
673
- }
674
- } else {
675
- let traverse = function(node) {
676
- if (node.nodeType === "element" && matchesSimpleSelector(node, selector)) {
677
- results.push(node);
678
- }
679
- for (const child of node.children) {
680
- traverse(child);
681
- }
682
- };
683
- for (const child of root.children) {
684
- traverse(child);
685
- }
686
- }
687
- return results;
688
- }
689
- function hasCombinators(selector) {
690
- const cleaned = selector.replace(/\[[^\]]*\]/g, "").replace(/:not\([^)]*\)/g, "").replace(/:nth-child\([^)]*\)/g, "");
691
- return /[>+~\s]/.test(cleaned);
692
- }
693
- function matchesComplexSelector(element, selector, root) {
694
- const parts = parseComplexSelector(selector);
695
- let currentElement = element;
696
- let skipCheck = false;
697
- for (let i = parts.length - 1;i >= 0; i--) {
698
- const part = parts[i];
699
- if (!skipCheck && !matchesSimpleSelector(currentElement, part.selector)) {
700
- return false;
701
- }
702
- skipCheck = false;
703
- if (i === 0) {
704
- return true;
705
- }
706
- const previousPart = parts[i - 1];
707
- switch (previousPart.combinator) {
708
- case ">": {
709
- currentElement = currentElement.parentNode;
710
- if (!currentElement || currentElement.nodeType !== "element") {
711
- return false;
712
- }
713
- break;
714
- }
715
- case "+": {
716
- currentElement = currentElement.previousElementSibling;
717
- if (!currentElement) {
718
- return false;
719
- }
720
- break;
721
- }
722
- case "~": {
723
- let found = false;
724
- let sibling = currentElement.previousElementSibling;
725
- while (sibling) {
726
- if (matchesSimpleSelector(sibling, previousPart.selector)) {
727
- currentElement = sibling;
728
- found = true;
729
- break;
730
- }
731
- sibling = sibling.previousElementSibling;
732
- }
733
- if (!found) {
734
- return false;
735
- }
736
- skipCheck = true;
737
- break;
738
- }
739
- case " ": {
740
- let found = false;
741
- let ancestor = currentElement.parentNode;
742
- while (ancestor && ancestor.nodeType !== "document") {
743
- if (ancestor === root) {
744
- if (root.nodeType === "element" && matchesSimpleSelector(root, previousPart.selector)) {
745
- currentElement = root;
746
- found = true;
747
- }
748
- break;
749
- }
750
- if (ancestor.nodeType === "element" && matchesSimpleSelector(ancestor, previousPart.selector)) {
751
- currentElement = ancestor;
752
- found = true;
753
- break;
754
- }
755
- ancestor = ancestor.parentNode;
756
- }
757
- if (!found) {
758
- return false;
759
- }
760
- skipCheck = true;
761
- break;
762
- }
763
- }
764
- }
765
- return true;
766
- }
767
- function parseComplexSelector(selector) {
768
- const parts = [];
769
- let currentSelector = "";
770
- let inBrackets = false;
771
- let inPseudo = false;
772
- let pseudoDepth = 0;
773
- function peekNextNonSpace(startIndex) {
774
- for (let j = startIndex;j < selector.length; j++) {
775
- if (selector[j] !== " ") {
776
- return selector[j];
777
- }
778
- }
779
- return null;
780
- }
781
- for (let i = 0;i < selector.length; i++) {
782
- const char = selector[i];
783
- const nextChar = selector[i + 1];
784
- if (char === "[") {
785
- inBrackets = true;
786
- currentSelector += char;
787
- } else if (char === "]") {
788
- inBrackets = false;
789
- currentSelector += char;
790
- } else if (char === "(" && currentSelector.endsWith(":not(")) {
791
- inPseudo = true;
792
- pseudoDepth = 1;
793
- currentSelector += char;
794
- } else if (char === "(" && /:\w+\($/.test(currentSelector)) {
795
- inPseudo = true;
796
- pseudoDepth = 1;
797
- currentSelector += char;
798
- } else if (inPseudo && char === "(") {
799
- pseudoDepth++;
800
- currentSelector += char;
801
- } else if (inPseudo && char === ")") {
802
- pseudoDepth--;
803
- if (pseudoDepth === 0) {
804
- inPseudo = false;
805
- }
806
- currentSelector += char;
807
- } else if (!inBrackets && !inPseudo && (char === ">" || char === "+" || char === "~")) {
808
- if (currentSelector.trim()) {
809
- parts.push({ selector: currentSelector.trim(), combinator: char });
810
- currentSelector = "";
811
- }
812
- while (selector[i + 1] === " ") {
813
- i++;
814
- }
815
- } else if (!inBrackets && !inPseudo && char === " ") {
816
- const nextNonSpace = peekNextNonSpace(i + 1);
817
- if (nextNonSpace && (nextNonSpace === ">" || nextNonSpace === "+" || nextNonSpace === "~")) {
818
- continue;
819
- } else if (currentSelector && nextChar && nextChar !== " ") {
820
- if (currentSelector.trim()) {
821
- parts.push({ selector: currentSelector.trim(), combinator: " " });
822
- currentSelector = "";
823
- }
824
- } else if (currentSelector) {
825
- currentSelector += char;
826
- }
827
- } else if (char !== " " || currentSelector) {
828
- currentSelector += char;
829
- }
830
- }
831
- if (currentSelector.trim()) {
832
- parts.push({ selector: currentSelector.trim(), combinator: null });
833
- }
834
- return parts;
835
- }
836
- function matchesSimpleSelector(element, selector) {
837
- if (selector === "*") {
838
- return true;
839
- }
840
- const selectorWithoutPseudo = selector.replace(/:([a-z-]+)\([^)]*\)/gi, ":$1");
841
- const selectorWithoutAttr = selectorWithoutPseudo.replace(/\[[^\]]+\]/g, "");
842
- const tagMatch = selectorWithoutAttr.match(/^([a-z0-9-]+)/i);
843
- const idMatch = selectorWithoutAttr.match(/#([\w-]+)/);
844
- const classMatches = selectorWithoutAttr.match(/\.([\w-]+)/g);
845
- const attrMatches = selectorWithoutPseudo.match(/\[([^\]]+)\]/g);
846
- const pseudoMatches = selector.match(/:([a-z-]+)(\([^)]*\))?/gi);
847
- if (tagMatch && tagMatch[1].toLowerCase() !== element.tagName.toLowerCase()) {
848
- return false;
849
- }
850
- if (idMatch && element.getAttribute("id") !== idMatch[1]) {
851
- return false;
852
- }
853
- if (classMatches) {
854
- const elementClasses = element.getAttribute("class")?.split(/\s+/).filter(Boolean) || [];
855
- for (const classMatch of classMatches) {
856
- const className = classMatch.slice(1);
857
- if (!elementClasses.includes(className)) {
858
- return false;
859
- }
860
- }
861
- }
862
- if (attrMatches) {
863
- for (const attrMatch of attrMatches) {
864
- const attrContent = attrMatch.slice(1, -1);
865
- if (!matchesAttributeSelector(element, attrContent)) {
866
- return false;
867
- }
868
- }
869
- }
870
- if (pseudoMatches) {
871
- for (const pseudoMatch of pseudoMatches) {
872
- if (!matchesPseudoClass(element, pseudoMatch)) {
873
- return false;
874
- }
875
- }
876
- }
877
- return true;
878
- }
879
- function matchesPseudoClass(element, pseudo) {
880
- const pseudoMatch = pseudo.match(/:([a-z-]+)(\(([^)]*)\))?/i);
881
- if (!pseudoMatch) {
882
- throw new Error(`Invalid pseudo-class selector: "${pseudo}"`);
883
- }
884
- const pseudoName = pseudoMatch[1];
885
- const pseudoArg = pseudoMatch[3];
886
- switch (pseudoName) {
887
- case "first-child": {
888
- const siblings = element.parentNode?.children.filter((child) => child.nodeType === "element") || [];
889
- return siblings[0] === element;
890
- }
891
- case "last-child": {
892
- const siblings = element.parentNode?.children.filter((child) => child.nodeType === "element") || [];
893
- return siblings[siblings.length - 1] === element;
894
- }
895
- case "nth-child": {
896
- if (!pseudoArg)
897
- return false;
898
- const siblings = element.parentNode?.children.filter((child) => child.nodeType === "element") || [];
899
- const index = siblings.indexOf(element);
900
- if (index === -1)
901
- return false;
902
- const position = index + 1;
903
- if (pseudoArg === "odd")
904
- return position % 2 === 1;
905
- if (pseudoArg === "even")
906
- return position % 2 === 0;
907
- const n = Number.parseInt(pseudoArg, 10);
908
- if (!Number.isNaN(n))
909
- return position === n;
910
- return false;
911
- }
912
- case "not": {
913
- if (!pseudoArg)
914
- return false;
915
- return !matchesSimpleSelector(element, pseudoArg);
916
- }
917
- case "disabled":
918
- return element.hasAttribute("disabled");
919
- case "enabled":
920
- return !element.hasAttribute("disabled");
921
- case "checked":
922
- return element.hasAttribute("checked");
923
- case "empty":
924
- return element.childNodes.length === 0 || element.childNodes.length === 1 && element.childNodes[0].nodeType === "text" && (element.childNodes[0].nodeValue?.trim() === "" || element.childNodes[0].nodeValue === null);
925
- case "first-of-type": {
926
- if (!element.parentNode)
927
- return false;
928
- const siblings = element.parentNode.children.filter((child) => child.nodeType === "element" && child.tagName === element.tagName);
929
- return siblings[0] === element;
930
- }
931
- case "last-of-type": {
932
- if (!element.parentNode)
933
- return false;
934
- const siblings = element.parentNode.children.filter((child) => child.nodeType === "element" && child.tagName === element.tagName);
935
- return siblings[siblings.length - 1] === element;
936
- }
937
- case "only-child": {
938
- if (!element.parentNode)
939
- return false;
940
- const siblings = element.parentNode.children.filter((child) => child.nodeType === "element");
941
- return siblings.length === 1 && siblings[0] === element;
942
- }
943
- case "only-of-type": {
944
- if (!element.parentNode)
945
- return false;
946
- const siblings = element.parentNode.children.filter((child) => child.nodeType === "element" && child.tagName === element.tagName);
947
- return siblings.length === 1 && siblings[0] === element;
948
- }
949
- case "nth-of-type": {
950
- if (!pseudoArg || !element.parentNode)
951
- return false;
952
- const siblings = element.parentNode.children.filter((child) => child.nodeType === "element" && child.tagName === element.tagName);
953
- const index = siblings.indexOf(element);
954
- if (index === -1)
955
- return false;
956
- const position = index + 1;
957
- if (pseudoArg === "odd")
958
- return position % 2 === 1;
959
- if (pseudoArg === "even")
960
- return position % 2 === 0;
961
- const anPlusBMatch = pseudoArg.match(/^(-?\d*)n([+-]\d+)?$/);
962
- if (anPlusBMatch) {
963
- const a = anPlusBMatch[1] === "" ? 1 : anPlusBMatch[1] === "-" ? -1 : Number.parseInt(anPlusBMatch[1], 10);
964
- const b = anPlusBMatch[2] ? Number.parseInt(anPlusBMatch[2], 10) : 0;
965
- if (a === 0)
966
- return position === b;
967
- const n2 = (position - b) / a;
968
- return n2 >= 0 && Number.isInteger(n2);
969
- }
970
- const n = Number.parseInt(pseudoArg, 10);
971
- if (!Number.isNaN(n))
972
- return position === n;
973
- return false;
974
- }
975
- case "nth-last-child": {
976
- if (!pseudoArg || !element.parentNode)
977
- return false;
978
- const siblings = element.parentNode.children.filter((child) => child.nodeType === "element");
979
- const index = siblings.indexOf(element);
980
- if (index === -1)
981
- return false;
982
- const position = siblings.length - index;
983
- if (pseudoArg === "odd")
984
- return position % 2 === 1;
985
- if (pseudoArg === "even")
986
- return position % 2 === 0;
987
- const n = Number.parseInt(pseudoArg, 10);
988
- if (!Number.isNaN(n))
989
- return position === n;
990
- return false;
991
- }
992
- case "nth-last-of-type": {
993
- if (!pseudoArg || !element.parentNode)
994
- return false;
995
- const siblings = element.parentNode.children.filter((child) => child.nodeType === "element" && child.tagName === element.tagName);
996
- const index = siblings.indexOf(element);
997
- if (index === -1)
998
- return false;
999
- const position = siblings.length - index;
1000
- if (pseudoArg === "odd")
1001
- return position % 2 === 1;
1002
- if (pseudoArg === "even")
1003
- return position % 2 === 0;
1004
- const n = Number.parseInt(pseudoArg, 10);
1005
- if (!Number.isNaN(n))
1006
- return position === n;
1007
- return false;
1008
- }
1009
- default:
1010
- throw new Error(`Unsupported pseudo-class: ":${pseudoName}". Supported pseudo-classes are: :first-child, :last-child, :first-of-type, :last-of-type, :only-child, :only-of-type, :nth-child(), :nth-last-child(), :nth-of-type(), :nth-last-of-type(), :not(), :disabled, :enabled, :checked, :empty`);
1011
- }
1012
- }
1013
- function matchesAttributeSelector(element, attrSelector) {
1014
- if (!attrSelector.includes("=")) {
1015
- return element.hasAttribute(attrSelector);
1016
- }
1017
- const exactMatch = attrSelector.match(/^([a-z0-9-]+)="([^"]*)"$/i);
1018
- if (exactMatch) {
1019
- return element.getAttribute(exactMatch[1]) === exactMatch[2];
1020
- }
1021
- const startsWithMatch = attrSelector.match(/^([a-z0-9-]+)\^="([^"]*)"$/i);
1022
- if (startsWithMatch) {
1023
- const value = element.getAttribute(startsWithMatch[1]);
1024
- return value !== null && value.startsWith(startsWithMatch[2]);
1025
- }
1026
- const endsWithMatch = attrSelector.match(/^([a-z0-9-]+)\$="([^"]*)"$/i);
1027
- if (endsWithMatch) {
1028
- const value = element.getAttribute(endsWithMatch[1]);
1029
- return value !== null && value.endsWith(endsWithMatch[2]);
1030
- }
1031
- const containsMatch = attrSelector.match(/^([a-z0-9-]+)\*="([^"]*)"$/i);
1032
- if (containsMatch) {
1033
- const value = element.getAttribute(containsMatch[1]);
1034
- return value !== null && value.includes(containsMatch[2]);
1035
- }
1036
- const wordMatch = attrSelector.match(/^([a-z0-9-]+)~="([^"]*)"$/i);
1037
- if (wordMatch) {
1038
- const value = element.getAttribute(wordMatch[1]);
1039
- if (value === null)
1040
- return false;
1041
- const words = value.split(/\s+/);
1042
- return words.includes(wordMatch[2]);
1043
- }
1044
- return false;
1045
- }
1046
-
1047
- // src/webcomponents/ShadowRoot.ts
1048
- class ShadowRoot {
1049
- mode;
1050
- delegatesFocus;
1051
- host;
1052
- innerHTML = "";
1053
- children = [];
1054
- constructor(host, init) {
1055
- this.host = host;
1056
- this.mode = init.mode;
1057
- this.delegatesFocus = init.delegatesFocus || false;
1058
- }
1059
- querySelector(selector) {
1060
- for (const child of this.children) {
1061
- if (child.nodeType === "element") {
1062
- const element = child;
1063
- if (element.matches?.(selector)) {
1064
- return element;
1065
- }
1066
- const result = element.querySelector(selector);
1067
- if (result)
1068
- return result;
1069
- }
1070
- }
1071
- return null;
1072
- }
1073
- querySelectorAll(selector) {
1074
- const results = [];
1075
- for (const child of this.children) {
1076
- if (child.nodeType === "element") {
1077
- const element = child;
1078
- if (element.matches?.(selector)) {
1079
- results.push(element);
1080
- }
1081
- results.push(...element.querySelectorAll(selector));
1082
- }
1083
- }
1084
- return results;
1085
- }
1086
- appendChild(child) {
1087
- this.children.push(child);
1088
- child.parentNode = this.host;
1089
- return child;
1090
- }
1091
- removeChild(child) {
1092
- const index = this.children.indexOf(child);
1093
- if (index !== -1) {
1094
- this.children.splice(index, 1);
1095
- child.parentNode = null;
1096
- }
1097
- return child;
1098
- }
1099
- getElementById(id) {
1100
- return this.querySelector(`#${id}`);
1101
- }
1102
- }
1103
-
1104
- // src/nodes/VirtualElement.ts
1105
- class VirtualElement {
1106
- nodeType = "element";
1107
- nodeName;
1108
- nodeValue = null;
1109
- tagName;
1110
- attributes = new Map;
1111
- childNodes = [];
1112
- parentNode = null;
1113
- shadowRoot = null;
1114
- eventListeners = new Map;
1115
- _customValidity = "";
1116
- _internalStyles = new Map;
1117
- get children() {
1118
- return this.childNodes.filter((node) => node.nodeType === "element");
1119
- }
1120
- constructor(tagName) {
1121
- this.tagName = tagName.toUpperCase();
1122
- this.nodeName = this.tagName;
1123
- }
1124
- getAttribute(name) {
1125
- return this.attributes.get(name.toLowerCase()) ?? null;
1126
- }
1127
- setAttribute(name, value) {
1128
- this.attributes.set(name.toLowerCase(), value);
1129
- }
1130
- removeAttribute(name) {
1131
- this.attributes.delete(name.toLowerCase());
1132
- }
1133
- hasAttribute(name) {
1134
- return this.attributes.has(name.toLowerCase());
1135
- }
1136
- appendChild(child) {
1137
- this.childNodes.push(child);
1138
- child.parentNode = this;
1139
- return child;
1140
- }
1141
- removeChild(child) {
1142
- const index = this.childNodes.indexOf(child);
1143
- if (index === -1) {
1144
- return child;
1145
- }
1146
- this.childNodes.splice(index, 1);
1147
- child.parentNode = null;
1148
- return child;
1149
- }
1150
- insertBefore(newNode, referenceNode) {
1151
- if (referenceNode === null) {
1152
- return this.appendChild(newNode);
1153
- }
1154
- const index = this.childNodes.indexOf(referenceNode);
1155
- if (index === -1) {
1156
- throw new Error("Reference node not found");
1157
- }
1158
- if (newNode.parentNode) {
1159
- const prevParent = newNode.parentNode;
1160
- const prevIndex = prevParent.childNodes.indexOf(newNode);
1161
- if (prevIndex !== -1) {
1162
- prevParent.childNodes.splice(prevIndex, 1);
1163
- }
1164
- }
1165
- this.childNodes.splice(index, 0, newNode);
1166
- newNode.parentNode = this;
1167
- return newNode;
1168
- }
1169
- replaceChild(newNode, oldNode) {
1170
- const index = this.childNodes.indexOf(oldNode);
1171
- if (index === -1) {
1172
- throw new Error("Old node not found");
1173
- }
1174
- if (newNode.parentNode) {
1175
- const prevParent = newNode.parentNode;
1176
- const prevIndex = prevParent.childNodes.indexOf(newNode);
1177
- if (prevIndex !== -1) {
1178
- prevParent.childNodes.splice(prevIndex, 1);
1179
- }
1180
- }
1181
- this.childNodes.splice(index, 1, newNode);
1182
- oldNode.parentNode = null;
1183
- newNode.parentNode = this;
1184
- return oldNode;
1185
- }
1186
- cloneNode(deep = false) {
1187
- const clone = new VirtualElement(this.tagName);
1188
- for (const [name, value] of this.attributes) {
1189
- clone.setAttribute(name, value);
1190
- }
1191
- if (deep) {
1192
- for (const child of this.childNodes) {
1193
- if (child.nodeType === "element") {
1194
- const childClone = child.cloneNode(true);
1195
- clone.appendChild(childClone);
1196
- } else {
1197
- const childClone = { ...child, parentNode: null };
1198
- clone.appendChild(childClone);
1199
- }
1200
- }
1201
- }
1202
- return clone;
1203
- }
1204
- closest(selector) {
1205
- let element = this;
1206
- while (element) {
1207
- if (matchesSimpleSelector(element, selector)) {
1208
- return element;
1209
- }
1210
- element = element.parentNode;
1211
- if (element?.nodeType !== "element") {
1212
- element = null;
1213
- }
1214
- }
1215
- return null;
1216
- }
1217
- get firstChild() {
1218
- return this.childNodes.length > 0 ? this.childNodes[0] : null;
1219
- }
1220
- get lastChild() {
1221
- return this.childNodes.length > 0 ? this.childNodes[this.childNodes.length - 1] : null;
1222
- }
1223
- get nextSibling() {
1224
- if (!this.parentNode)
1225
- return null;
1226
- const siblings = this.parentNode.childNodes;
1227
- const index = siblings.indexOf(this);
1228
- if (index === -1 || index >= siblings.length - 1)
1229
- return null;
1230
- return siblings[index + 1];
1231
- }
1232
- get previousSibling() {
1233
- if (!this.parentNode)
1234
- return null;
1235
- const siblings = this.parentNode.childNodes;
1236
- const index = siblings.indexOf(this);
1237
- if (index <= 0)
1238
- return null;
1239
- return siblings[index - 1];
1240
- }
1241
- get nextElementSibling() {
1242
- if (!this.parentNode)
1243
- return null;
1244
- const siblings = this.parentNode.children;
1245
- const index = siblings.indexOf(this);
1246
- if (index === -1)
1247
- return null;
1248
- for (let i = index + 1;i < siblings.length; i++) {
1249
- if (siblings[i].nodeType === "element") {
1250
- return siblings[i];
1251
- }
1252
- }
1253
- return null;
1254
- }
1255
- get previousElementSibling() {
1256
- if (!this.parentNode)
1257
- return null;
1258
- const siblings = this.parentNode.children;
1259
- const index = siblings.indexOf(this);
1260
- if (index === -1)
1261
- return null;
1262
- for (let i = index - 1;i >= 0; i--) {
1263
- if (siblings[i].nodeType === "element") {
1264
- return siblings[i];
1265
- }
1266
- }
1267
- return null;
1268
- }
1269
- get textContent() {
1270
- let text = "";
1271
- for (const child of this.childNodes) {
1272
- text += child.textContent;
1273
- }
1274
- return text;
1275
- }
1276
- set textContent(value) {
1277
- this.childNodes = [];
1278
- if (value) {
1279
- const textNode = {
1280
- nodeType: "text",
1281
- nodeName: "#text",
1282
- nodeValue: value,
1283
- attributes: new Map,
1284
- children: [],
1285
- parentNode: this,
1286
- textContent: value
1287
- };
1288
- this.childNodes.push(textNode);
1289
- }
1290
- }
1291
- get innerHTML() {
1292
- return this.childNodes.map((child) => this._serializeNode(child)).join("");
1293
- }
1294
- set innerHTML(html) {
1295
- this.childNodes = [];
1296
- if (html) {
1297
- const nodes = parseHTML(html);
1298
- if (this.tagName === "HTML" && nodes.length > 0) {
1299
- for (const node of nodes) {
1300
- if (node.nodeType === "element") {
1301
- const element = node;
1302
- if (element.tagName === "HTML") {
1303
- for (const child of element.children) {
1304
- this.appendChild(child);
1305
- }
1306
- continue;
1307
- }
1308
- }
1309
- this.appendChild(node);
1310
- }
1311
- } else {
1312
- for (const node of nodes) {
1313
- this.appendChild(node);
1314
- }
1315
- }
1316
- }
1317
- }
1318
- get outerHTML() {
1319
- return this._serializeNode(this);
1320
- }
1321
- get classList() {
1322
- const element = this;
1323
- return {
1324
- add(...tokens) {
1325
- const classes = element.getAttribute("class")?.split(/\s+/).filter(Boolean) || [];
1326
- for (const token of tokens) {
1327
- if (!classes.includes(token)) {
1328
- classes.push(token);
1329
- }
1330
- }
1331
- element.setAttribute("class", classes.join(" "));
1332
- },
1333
- remove(...tokens) {
1334
- const classes = element.getAttribute("class")?.split(/\s+/).filter(Boolean) || [];
1335
- const filtered = classes.filter((c) => !tokens.includes(c));
1336
- if (filtered.length > 0) {
1337
- element.setAttribute("class", filtered.join(" "));
1338
- } else {
1339
- element.removeAttribute("class");
1340
- }
1341
- },
1342
- toggle(token) {
1343
- const classes = element.getAttribute("class")?.split(/\s+/).filter(Boolean) || [];
1344
- const index = classes.indexOf(token);
1345
- if (index !== -1) {
1346
- classes.splice(index, 1);
1347
- if (classes.length > 0) {
1348
- element.setAttribute("class", classes.join(" "));
1349
- } else {
1350
- element.removeAttribute("class");
1351
- }
1352
- return false;
1353
- } else {
1354
- classes.push(token);
1355
- element.setAttribute("class", classes.join(" "));
1356
- return true;
1357
- }
1358
- },
1359
- contains(token) {
1360
- const classes = element.getAttribute("class")?.split(/\s+/).filter(Boolean) || [];
1361
- return classes.includes(token);
1362
- },
1363
- replace(oldToken, newToken) {
1364
- const classes = element.getAttribute("class")?.split(/\s+/).filter(Boolean) || [];
1365
- const index = classes.indexOf(oldToken);
1366
- if (index !== -1) {
1367
- classes[index] = newToken;
1368
- element.setAttribute("class", classes.join(" "));
1369
- return true;
1370
- }
1371
- return false;
1372
- }
1373
- };
1374
- }
1375
- _serializeNode(node) {
1376
- if (node.nodeType === "text") {
1377
- return node.nodeValue || "";
1378
- }
1379
- if (node.nodeType === "comment") {
1380
- return `<!--${node.nodeValue}-->`;
1381
- }
1382
- if (node.nodeType === "element") {
1383
- const element = node;
1384
- const tagName = element.tagName.toLowerCase();
1385
- let html = `<${tagName}`;
1386
- for (const [name, value] of element.attributes) {
1387
- html += ` ${name}="${value}"`;
1388
- }
1389
- const voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"];
1390
- if (voidElements.includes(tagName)) {
1391
- html += "/>";
1392
- return html;
1393
- }
1394
- html += ">";
1395
- for (const child of element.childNodes) {
1396
- html += this._serializeNode(child);
1397
- }
1398
- html += `</${tagName}>`;
1399
- return html;
1400
- }
1401
- return "";
1402
- }
1403
- get style() {
1404
- const element = this;
1405
- return new Proxy({
1406
- getPropertyValue(property) {
1407
- return element._internalStyles.get(property) || "";
1408
- },
1409
- setProperty(property, value) {
1410
- element._internalStyles.set(property, value);
1411
- element._updateStyleAttribute();
1412
- },
1413
- removeProperty(property) {
1414
- element._internalStyles.delete(property);
1415
- element._updateStyleAttribute();
1416
- }
1417
- }, {
1418
- get(target, prop) {
1419
- if (prop === "getPropertyValue" || prop === "setProperty" || prop === "removeProperty") {
1420
- return target[prop];
1421
- }
1422
- const kebabProp = prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
1423
- const value = element._internalStyles.get(kebabProp);
1424
- return value;
1425
- },
1426
- set(_target, prop, value) {
1427
- const kebabProp = prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
1428
- element._internalStyles.set(kebabProp, value);
1429
- element._updateStyleAttribute();
1430
- return true;
1431
- }
1432
- });
1433
- }
1434
- _updateStyleAttribute() {
1435
- const styleString = Array.from(this._internalStyles.entries()).map(([prop, value]) => `${prop}: ${value}`).join("; ");
1436
- if (styleString) {
1437
- this.setAttribute("style", styleString);
1438
- } else {
1439
- this.removeAttribute("style");
1440
- }
1441
- }
1442
- get dataset() {
1443
- const self = this;
1444
- return new Proxy({}, {
1445
- get(_target, prop) {
1446
- const kebabProp = prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
1447
- return self.getAttribute(`data-${kebabProp}`) || "";
1448
- },
1449
- set(_target, prop, value) {
1450
- const kebabProp = prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
1451
- self.setAttribute(`data-${kebabProp}`, value);
1452
- return true;
1453
- },
1454
- deleteProperty(_target, prop) {
1455
- const kebabProp = prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
1456
- self.removeAttribute(`data-${kebabProp}`);
1457
- return true;
1458
- },
1459
- has(_target, prop) {
1460
- const kebabProp = prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
1461
- return self.hasAttribute(`data-${kebabProp}`);
1462
- },
1463
- ownKeys(_target) {
1464
- const dataAttrs = [];
1465
- for (const [key] of self.attributes) {
1466
- if (key.startsWith("data-")) {
1467
- const camelKey = key.slice(5).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
1468
- dataAttrs.push(camelKey);
1469
- }
1470
- }
1471
- return dataAttrs;
1472
- },
1473
- getOwnPropertyDescriptor(_target, prop) {
1474
- const kebabProp = prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
1475
- if (self.hasAttribute(`data-${kebabProp}`)) {
1476
- return {
1477
- configurable: true,
1478
- enumerable: true,
1479
- writable: true,
1480
- value: self.getAttribute(`data-${kebabProp}`)
1481
- };
1482
- }
1483
- return;
1484
- }
1485
- });
1486
- }
1487
- get validity() {
1488
- const value = this.getAttribute("value") || "";
1489
- const type = this.getAttribute("type") || "text";
1490
- const required = this.hasAttribute("required");
1491
- const pattern = this.getAttribute("pattern");
1492
- const minlength = this.getAttribute("minlength");
1493
- const maxlength = this.getAttribute("maxlength");
1494
- const min = this.getAttribute("min");
1495
- const max = this.getAttribute("max");
1496
- const validity = {
1497
- valid: true,
1498
- valueMissing: false,
1499
- typeMismatch: false,
1500
- patternMismatch: false,
1501
- tooLong: false,
1502
- tooShort: false,
1503
- rangeUnderflow: false,
1504
- rangeOverflow: false,
1505
- stepMismatch: false,
1506
- badInput: false,
1507
- customError: false
1508
- };
1509
- if (required && !value) {
1510
- validity.valueMissing = true;
1511
- validity.valid = false;
1512
- }
1513
- if (pattern && value) {
1514
- const regex = new RegExp(pattern);
1515
- if (!regex.test(value)) {
1516
- validity.patternMismatch = true;
1517
- validity.valid = false;
1518
- }
1519
- }
1520
- if (minlength && value.length < Number.parseInt(minlength, 10)) {
1521
- validity.tooShort = true;
1522
- validity.valid = false;
1523
- }
1524
- if (maxlength && value.length > Number.parseInt(maxlength, 10)) {
1525
- validity.tooLong = true;
1526
- validity.valid = false;
1527
- }
1528
- if (type === "number" || type === "range") {
1529
- const numValue = Number.parseFloat(value);
1530
- if (!Number.isNaN(numValue)) {
1531
- if (min && numValue < Number.parseFloat(min)) {
1532
- validity.rangeUnderflow = true;
1533
- validity.valid = false;
1534
- }
1535
- if (max && numValue > Number.parseFloat(max)) {
1536
- validity.rangeOverflow = true;
1537
- validity.valid = false;
1538
- }
1539
- }
1540
- }
1541
- if (type === "email" && value) {
1542
- const emailRegex = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/;
1543
- if (!emailRegex.test(value)) {
1544
- validity.typeMismatch = true;
1545
- validity.valid = false;
1546
- }
1547
- }
1548
- if (type === "url" && value) {
1549
- try {
1550
- new URL(value);
1551
- } catch {
1552
- validity.typeMismatch = true;
1553
- validity.valid = false;
1554
- }
1555
- }
1556
- if (this._customValidity) {
1557
- validity.customError = true;
1558
- validity.valid = false;
1559
- }
1560
- return validity;
1561
- }
1562
- get validationMessage() {
1563
- if (this._customValidity) {
1564
- return this._customValidity;
1565
- }
1566
- const validity = this.validity;
1567
- if (validity.valueMissing) {
1568
- return "Please fill out this field.";
1569
- }
1570
- if (validity.typeMismatch) {
1571
- const type = this.getAttribute("type");
1572
- if (type === "email") {
1573
- return "Please enter an email address.";
1574
- }
1575
- if (type === "url") {
1576
- return "Please enter a URL.";
1577
- }
1578
- return "Please match the requested format.";
1579
- }
1580
- if (validity.patternMismatch) {
1581
- return "Please match the requested format.";
1582
- }
1583
- if (validity.tooShort) {
1584
- const minlength = this.getAttribute("minlength");
1585
- return `Please lengthen this text to ${minlength} characters or more.`;
1586
- }
1587
- if (validity.tooLong) {
1588
- const maxlength = this.getAttribute("maxlength");
1589
- return `Please shorten this text to ${maxlength} characters or less.`;
1590
- }
1591
- if (validity.rangeUnderflow) {
1592
- const min = this.getAttribute("min");
1593
- return `Value must be greater than or equal to ${min}.`;
1594
- }
1595
- if (validity.rangeOverflow) {
1596
- const max = this.getAttribute("max");
1597
- return `Value must be less than or equal to ${max}.`;
1598
- }
1599
- return "";
1600
- }
1601
- setCustomValidity(message) {
1602
- this._customValidity = message;
1603
- }
1604
- checkValidity() {
1605
- return this.validity.valid;
1606
- }
1607
- reportValidity() {
1608
- const isValid = this.checkValidity();
1609
- if (!isValid) {
1610
- const event = new VirtualEvent("invalid", { bubbles: false, cancelable: true });
1611
- this.dispatchEvent(event);
1612
- }
1613
- return isValid;
1614
- }
1615
- querySelector(selector) {
1616
- return querySelectorEngine(this, selector);
1617
- }
1618
- querySelectorAll(selector) {
1619
- return querySelectorAllEngine(this, selector);
1620
- }
1621
- matches(selector) {
1622
- if (hasCombinators(selector)) {
1623
- let root = this;
1624
- while (root.parentNode && root.parentNode.nodeType !== "document") {
1625
- root = root.parentNode;
1626
- }
1627
- if (root.parentNode && root.parentNode.nodeType === "document") {
1628
- root = root.parentNode;
1629
- }
1630
- return matchesComplexSelector(this, selector, root);
1631
- } else {
1632
- return matchesSimpleSelector(this, selector);
1633
- }
1634
- }
1635
- addEventListener(type, listener, options = {}) {
1636
- const opts = typeof options === "boolean" ? { capture: options } : { capture: options.capture ?? false, once: options.once, passive: options.passive };
1637
- if (!this.eventListeners.has(type)) {
1638
- this.eventListeners.set(type, []);
1639
- }
1640
- const listeners = this.eventListeners.get(type);
1641
- const isDuplicate = listeners.some((l) => l.listener === listener && l.options.capture === opts.capture);
1642
- if (!isDuplicate) {
1643
- listeners.push({
1644
- listener,
1645
- options: opts
1646
- });
1647
- }
1648
- }
1649
- removeEventListener(type, listener, options = {}) {
1650
- const opts = typeof options === "boolean" ? { capture: options } : { capture: options.capture ?? false };
1651
- const listeners = this.eventListeners.get(type);
1652
- if (!listeners)
1653
- return;
1654
- const index = listeners.findIndex((l) => l.listener === listener && l.options.capture === opts.capture);
1655
- if (index !== -1) {
1656
- listeners.splice(index, 1);
1657
- }
1658
- }
1659
- dispatchEvent(event) {
1660
- try {
1661
- event.target = this;
1662
- event.currentTarget = this;
1663
- } catch {}
1664
- const path = [];
1665
- let current = this;
1666
- while (current && current.nodeType === "element") {
1667
- path.unshift(current);
1668
- current = current.parentNode;
1669
- }
1670
- const isPropagationStopped = () => event.propagationStopped || event._propagationStopped || false;
1671
- for (let i = 0;i < path.length - 1 && !isPropagationStopped(); i++) {
1672
- const element = path[i];
1673
- try {
1674
- event.currentTarget = element;
1675
- } catch {}
1676
- this._invokeEventListeners(element, event, true);
1677
- }
1678
- if (!isPropagationStopped()) {
1679
- try {
1680
- event.currentTarget = this;
1681
- } catch {}
1682
- this._invokeEventListeners(this, event, false);
1683
- this._invokeEventListeners(this, event, true);
1684
- }
1685
- const bubbles = event.bubbles ?? true;
1686
- if (bubbles && !isPropagationStopped()) {
1687
- for (let i = path.length - 2;i >= 0 && !isPropagationStopped(); i--) {
1688
- const element = path[i];
1689
- try {
1690
- event.currentTarget = element;
1691
- } catch {}
1692
- this._invokeEventListeners(element, event, false);
1693
- }
1694
- }
1695
- return !(event.defaultPrevented ?? false);
1696
- }
1697
- _invokeEventListeners(element, event, capture) {
1698
- const listeners = element.eventListeners.get(event.type);
1699
- if (!listeners)
1700
- return;
1701
- const listenersCopy = [...listeners];
1702
- for (const { listener, options } of listenersCopy) {
1703
- if (options.capture !== capture)
1704
- continue;
1705
- if (event.immediatePropagationStopped)
1706
- break;
1707
- try {
1708
- listener.call(element, event);
1709
- } catch (error) {
1710
- console.error("Error in event listener:", error);
1711
- }
1712
- if (options.once) {
1713
- element.removeEventListener(event.type, listener, options);
1714
- }
1715
- }
1716
- }
1717
- click() {
1718
- const event = new VirtualEvent("click", { bubbles: true, cancelable: true });
1719
- this.dispatchEvent(event);
1720
- }
1721
- isVisible() {
1722
- const display = this.style.getPropertyValue("display");
1723
- if (display === "none")
1724
- return false;
1725
- const visibility = this.style.getPropertyValue("visibility");
1726
- if (visibility === "hidden")
1727
- return false;
1728
- const opacity = this.style.getPropertyValue("opacity");
1729
- if (opacity === "0")
1730
- return false;
1731
- return true;
1732
- }
1733
- attachShadow(init) {
1734
- if (this.shadowRoot) {
1735
- throw new Error("Shadow root already exists");
1736
- }
1737
- this.shadowRoot = new ShadowRoot(this, init);
1738
- return this.shadowRoot;
1739
- }
1740
- }
1741
-
1742
- // src/nodes/VirtualTextNode.ts
1743
- class VirtualTextNode {
1744
- nodeType = "text";
1745
- nodeName = "#text";
1746
- nodeValue;
1747
- attributes = new Map;
1748
- children = [];
1749
- parentNode = null;
1750
- constructor(text) {
1751
- this.nodeValue = text;
1752
- }
1753
- get textContent() {
1754
- return this.nodeValue || "";
1755
- }
1756
- set textContent(value) {
1757
- this.nodeValue = value;
1758
- }
1759
- }
1760
-
1761
- // src/parsers/html-parser.ts
1762
- function parseHTML(html) {
1763
- let pos = 0;
1764
- function peek() {
1765
- return html[pos] || "";
1766
- }
1767
- function consume() {
1768
- return html[pos++] || "";
1769
- }
1770
- function consumeWhitespace() {
1771
- while (/\s/.test(peek())) {
1772
- consume();
1773
- }
1774
- }
1775
- function parseTag() {
1776
- if (peek() !== "<")
1777
- return null;
1778
- consume();
1779
- if (html.slice(pos, pos + 3) === "!--") {
1780
- pos += 3;
1781
- const commentEnd = html.indexOf("-->", pos);
1782
- if (commentEnd === -1) {
1783
- throw new Error("Unclosed comment");
1784
- }
1785
- const commentText = html.slice(pos, commentEnd);
1786
- pos = commentEnd + 3;
1787
- return new VirtualCommentNode(commentText);
1788
- }
1789
- if (html.slice(pos, pos + 8).toUpperCase() === "!DOCTYPE") {
1790
- const doctypeEnd = html.indexOf(">", pos);
1791
- if (doctypeEnd === -1) {
1792
- throw new Error("Unclosed DOCTYPE");
1793
- }
1794
- pos = doctypeEnd + 1;
1795
- return null;
1796
- }
1797
- if (peek() === "/") {
1798
- consume();
1799
- const tagNameEnd = html.indexOf(">", pos);
1800
- if (tagNameEnd === -1) {
1801
- throw new Error("Unclosed tag");
1802
- }
1803
- pos = tagNameEnd + 1;
1804
- return null;
1805
- }
1806
- let tagName = "";
1807
- while (peek() && /[a-z0-9-]/i.test(peek())) {
1808
- tagName += consume();
1809
- }
1810
- if (!tagName) {
1811
- throw new Error("Invalid tag name");
1812
- }
1813
- const element = new VirtualElement(tagName);
1814
- while (peek() && peek() !== ">" && peek() !== "/") {
1815
- consumeWhitespace();
1816
- if (peek() === ">" || peek() === "/")
1817
- break;
1818
- let attrName = "";
1819
- while (peek() && /[\w\-:]/.test(peek())) {
1820
- attrName += consume();
1821
- }
1822
- if (!attrName)
1823
- break;
1824
- consumeWhitespace();
1825
- let attrValue = "";
1826
- let hasValue = false;
1827
- if (peek() === "=") {
1828
- hasValue = true;
1829
- consume();
1830
- consumeWhitespace();
1831
- if (peek() === '"' || peek() === "'") {
1832
- const quote = consume();
1833
- while (peek() && peek() !== quote) {
1834
- attrValue += consume();
1835
- }
1836
- if (peek() === quote) {
1837
- consume();
1838
- }
1839
- } else {
1840
- while (peek() && !/[\s>]/.test(peek())) {
1841
- attrValue += consume();
1842
- }
1843
- }
1844
- }
1845
- element.setAttribute(attrName, hasValue ? attrValue : attrName);
1846
- }
1847
- const isSelfClosing = peek() === "/";
1848
- if (isSelfClosing) {
1849
- consume();
1850
- }
1851
- if (peek() === ">") {
1852
- consume();
1853
- }
1854
- const voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"];
1855
- if (isSelfClosing || voidElements.includes(tagName.toLowerCase())) {
1856
- return element;
1857
- }
1858
- const children = parseNodes(tagName);
1859
- for (const child of children) {
1860
- element.appendChild(child);
1861
- }
1862
- return element;
1863
- }
1864
- function parseText() {
1865
- let text = "";
1866
- while (peek() && peek() !== "<") {
1867
- text += consume();
1868
- }
1869
- if (!text)
1870
- return null;
1871
- return new VirtualTextNode(text);
1872
- }
1873
- function parseNodes(closingTag) {
1874
- const children = [];
1875
- while (pos < html.length) {
1876
- if (closingTag && html.slice(pos, pos + 2 + closingTag.length + 1) === `</${closingTag}>`) {
1877
- pos += 2 + closingTag.length + 1;
1878
- break;
1879
- }
1880
- if (peek() === "<") {
1881
- const node = parseTag();
1882
- if (node === null) {
1883
- continue;
1884
- }
1885
- children.push(node);
1886
- } else {
1887
- const textNode = parseText();
1888
- if (textNode) {
1889
- children.push(textNode);
1890
- }
1891
- }
1892
- }
1893
- return children;
1894
- }
1895
- const rootNodes = parseNodes();
1896
- return rootNodes;
1897
- }
1898
-
1899
- // src/xpath/XPathResult.ts
1900
- var XPathResultType;
1901
- ((XPathResultType2) => {
1902
- XPathResultType2[XPathResultType2["ANY_TYPE"] = 0] = "ANY_TYPE";
1903
- XPathResultType2[XPathResultType2["NUMBER_TYPE"] = 1] = "NUMBER_TYPE";
1904
- XPathResultType2[XPathResultType2["STRING_TYPE"] = 2] = "STRING_TYPE";
1905
- XPathResultType2[XPathResultType2["BOOLEAN_TYPE"] = 3] = "BOOLEAN_TYPE";
1906
- XPathResultType2[XPathResultType2["UNORDERED_NODE_ITERATOR_TYPE"] = 4] = "UNORDERED_NODE_ITERATOR_TYPE";
1907
- XPathResultType2[XPathResultType2["ORDERED_NODE_ITERATOR_TYPE"] = 5] = "ORDERED_NODE_ITERATOR_TYPE";
1908
- XPathResultType2[XPathResultType2["UNORDERED_NODE_SNAPSHOT_TYPE"] = 6] = "UNORDERED_NODE_SNAPSHOT_TYPE";
1909
- XPathResultType2[XPathResultType2["ORDERED_NODE_SNAPSHOT_TYPE"] = 7] = "ORDERED_NODE_SNAPSHOT_TYPE";
1910
- XPathResultType2[XPathResultType2["ANY_UNORDERED_NODE_TYPE"] = 8] = "ANY_UNORDERED_NODE_TYPE";
1911
- XPathResultType2[XPathResultType2["FIRST_ORDERED_NODE_TYPE"] = 9] = "FIRST_ORDERED_NODE_TYPE";
1912
- })(XPathResultType ||= {});
1913
-
1914
- class XPathResult {
1915
- resultType;
1916
- numberValue;
1917
- stringValue;
1918
- booleanValue;
1919
- singleNodeValue;
1920
- snapshotLength;
1921
- _nodes = [];
1922
- _iteratorIndex = 0;
1923
- constructor(resultType, nodes = [], numberValue = 0, stringValue = "", booleanValue = false) {
1924
- this.resultType = resultType;
1925
- this._nodes = nodes;
1926
- this.numberValue = numberValue;
1927
- this.stringValue = stringValue;
1928
- this.booleanValue = booleanValue;
1929
- this.singleNodeValue = nodes.length > 0 ? nodes[0] : null;
1930
- this.snapshotLength = nodes.length;
1931
- }
1932
- iterateNext() {
1933
- if (this._iteratorIndex < this._nodes.length) {
1934
- return this._nodes[this._iteratorIndex++];
1935
- }
1936
- return null;
1937
- }
1938
- snapshotItem(index) {
1939
- return this._nodes[index] || null;
1940
- }
1941
- }
1942
-
1943
- // src/xpath/XPathEvaluator.ts
1944
- class XPathEvaluator {
1945
- evaluate(expression, contextNode, _resolver = null, type = 0 /* ANY_TYPE */, _result = null) {
1946
- const nodes = this._evaluateExpression(expression, contextNode);
1947
- let actualType = type;
1948
- if (type === 0 /* ANY_TYPE */) {
1949
- actualType = 7 /* ORDERED_NODE_SNAPSHOT_TYPE */;
1950
- }
1951
- return new XPathResult(actualType, nodes);
1952
- }
1953
- _evaluateExpression(expression, contextNode) {
1954
- const trimmed = expression.trim();
1955
- if (trimmed === ".") {
1956
- return [contextNode];
1957
- }
1958
- if (trimmed === "..") {
1959
- return contextNode.parentNode ? [contextNode.parentNode] : [];
1960
- }
1961
- if (trimmed.startsWith("//")) {
1962
- const rest = trimmed.substring(2);
1963
- return this._findDescendants(contextNode, rest);
1964
- }
1965
- if (trimmed.startsWith("/")) {
1966
- const rest = trimmed.substring(1);
1967
- return this._findChildren(contextNode, rest);
1968
- }
1969
- if (trimmed.startsWith("@")) {
1970
- const attrName = trimmed.substring(1);
1971
- if (contextNode.nodeType === "element") {
1972
- const value = contextNode.getAttribute(attrName);
1973
- if (value !== null) {
1974
- return [{ nodeType: "text", nodeValue: value, nodeName: "#text" }];
1975
- }
1976
- }
1977
- return [];
1978
- }
1979
- return this._findDescendants(contextNode, trimmed);
1980
- }
1981
- _findChildren(node, expression) {
1982
- const results = [];
1983
- const parts = expression.split("/").filter((p) => p.trim());
1984
- if (parts.length === 0)
1985
- return results;
1986
- const [first, ...rest] = parts;
1987
- for (const child of node.children || []) {
1988
- if (this._matchesExpression(child, first)) {
1989
- if (rest.length === 0) {
1990
- results.push(child);
1991
- } else {
1992
- results.push(...this._findChildren(child, rest.join("/")));
1993
- }
1994
- }
1995
- }
1996
- return results;
1997
- }
1998
- _findDescendants(node, expression) {
1999
- const results = [];
2000
- const parts = expression.split("/").filter((p) => p.trim());
2001
- if (parts.length === 0)
2002
- return results;
2003
- const [first, ...rest] = parts;
2004
- const traverse = (current) => {
2005
- if (this._matchesExpression(current, first)) {
2006
- if (rest.length === 0) {
2007
- results.push(current);
2008
- } else {
2009
- results.push(...this._findChildren(current, rest.join("/")));
2010
- }
2011
- }
2012
- for (const child of current.children || []) {
2013
- traverse(child);
2014
- }
2015
- };
2016
- traverse(node);
2017
- return results;
2018
- }
2019
- _matchesExpression(node, expression) {
2020
- if (expression === "*") {
2021
- return node.nodeType === "element";
2022
- }
2023
- if (expression === "text()") {
2024
- return node.nodeType === "text";
2025
- }
2026
- if (expression === "node()") {
2027
- return true;
2028
- }
2029
- const predicateMatch = expression.match(/^(\w+)\[(.+)\]$/);
2030
- if (predicateMatch) {
2031
- const [, tagName, predicate] = predicateMatch;
2032
- if (node.nodeType !== "element")
2033
- return false;
2034
- const element = node;
2035
- if (tagName !== "*" && element.tagName !== tagName.toUpperCase()) {
2036
- return false;
2037
- }
2038
- return this._evaluatePredicate(element, predicate);
2039
- }
2040
- if (node.nodeType === "element") {
2041
- const element = node;
2042
- return element.tagName === expression.toUpperCase();
2043
- }
2044
- return false;
2045
- }
2046
- _evaluatePredicate(element, predicate) {
2047
- const attrMatch = predicate.match(/^@(\w+)=['"](.+)['"]$/);
2048
- if (attrMatch) {
2049
- const [, attrName, attrValue] = attrMatch;
2050
- return element.getAttribute(attrName) === attrValue;
2051
- }
2052
- if (predicate.startsWith("@")) {
2053
- const attrName = predicate.substring(1);
2054
- return element.getAttribute(attrName) !== null;
2055
- }
2056
- const indexMatch = predicate.match(/^(\d+)$/);
2057
- if (indexMatch) {
2058
- const index = Number.parseInt(indexMatch[1]);
2059
- const parent = element.parentNode;
2060
- if (parent) {
2061
- const siblings = parent.children.filter((c) => c.nodeType === "element");
2062
- return siblings.indexOf(element) === index - 1;
2063
- }
2064
- }
2065
- return false;
2066
- }
2067
- _parseTagName(expression) {
2068
- const match = expression.match(/^(\w+)/);
2069
- return match ? match[1] : expression;
2070
- }
2071
- }
2072
-
2073
- // src/nodes/VirtualDocument.ts
2074
- class VirtualDocument {
2075
- nodeType = "document";
2076
- nodeName = "#document";
2077
- nodeValue = null;
2078
- attributes = new Map;
2079
- children = [];
2080
- parentNode = null;
2081
- documentElement = null;
2082
- head = null;
2083
- body = null;
2084
- location;
2085
- history;
2086
- title = "";
2087
- _historyStack = [];
2088
- _historyIndex = -1;
2089
- _eventListeners = new Map;
2090
- _xpathEvaluator = new XPathEvaluator;
2091
- _cookies = {};
2092
- constructor() {
2093
- this.documentElement = new VirtualElement("html");
2094
- this.head = new VirtualElement("head");
2095
- this.body = new VirtualElement("body");
2096
- this.documentElement.appendChild(this.head);
2097
- this.documentElement.appendChild(this.body);
2098
- this.appendChild(this.documentElement);
2099
- this.location = {
2100
- href: "",
2101
- protocol: "",
2102
- host: "",
2103
- hostname: "",
2104
- port: "",
2105
- pathname: "",
2106
- search: "",
2107
- hash: "",
2108
- origin: "",
2109
- assign: (url) => {
2110
- this._updateLocation(url);
2111
- },
2112
- replace: (url) => {
2113
- this._updateLocation(url);
2114
- },
2115
- reload: () => {}
2116
- };
2117
- const doc = this;
2118
- this.history = {
2119
- get length() {
2120
- return doc._historyStack.length;
2121
- },
2122
- get state() {
2123
- return doc._historyStack[doc._historyIndex]?.state || null;
2124
- },
2125
- pushState(state, title, url) {
2126
- doc._historyStack = doc._historyStack.slice(0, doc._historyIndex + 1);
2127
- doc._historyStack.push({
2128
- state,
2129
- title,
2130
- url: url || doc.location.href
2131
- });
2132
- doc._historyIndex++;
2133
- if (url) {
2134
- doc._updateLocation(url);
2135
- }
2136
- },
2137
- replaceState(state, title, url) {
2138
- if (doc._historyIndex >= 0) {
2139
- doc._historyStack[doc._historyIndex] = {
2140
- state,
2141
- title,
2142
- url: url || doc.location.href
2143
- };
2144
- if (url) {
2145
- doc._updateLocation(url);
2146
- }
2147
- }
2148
- },
2149
- back() {
2150
- if (doc._historyIndex > 0) {
2151
- doc._historyIndex--;
2152
- const entry = doc._historyStack[doc._historyIndex];
2153
- if (entry.url) {
2154
- doc._updateLocation(entry.url);
2155
- }
2156
- }
2157
- },
2158
- forward() {
2159
- if (doc._historyIndex < doc._historyStack.length - 1) {
2160
- doc._historyIndex++;
2161
- const entry = doc._historyStack[doc._historyIndex];
2162
- if (entry.url) {
2163
- doc._updateLocation(entry.url);
2164
- }
2165
- }
2166
- },
2167
- go(delta) {
2168
- const newIndex = doc._historyIndex + delta;
2169
- if (newIndex >= 0 && newIndex < doc._historyStack.length) {
2170
- doc._historyIndex = newIndex;
2171
- const entry = doc._historyStack[doc._historyIndex];
2172
- if (entry.url) {
2173
- doc._updateLocation(entry.url);
2174
- }
2175
- }
2176
- }
2177
- };
2178
- }
2179
- _updateLocation(url) {
2180
- try {
2181
- const parsed = new URL(url, this.location.href);
2182
- this.location.href = parsed.href;
2183
- this.location.protocol = parsed.protocol;
2184
- this.location.host = parsed.host;
2185
- this.location.hostname = parsed.hostname;
2186
- this.location.port = parsed.port;
2187
- this.location.pathname = parsed.pathname;
2188
- this.location.search = parsed.search;
2189
- this.location.hash = parsed.hash;
2190
- this.location.origin = parsed.origin;
2191
- } catch {}
2192
- }
2193
- get textContent() {
2194
- return this.documentElement?.textContent || "";
2195
- }
2196
- set textContent(value) {
2197
- if (this.documentElement) {
2198
- this.documentElement.textContent = value;
2199
- }
2200
- }
2201
- appendChild(child) {
2202
- this.children.push(child);
2203
- child.parentNode = this;
2204
- return child;
2205
- }
2206
- createElement(tagName) {
2207
- return new VirtualElement(tagName);
2208
- }
2209
- createTextNode(text) {
2210
- return new VirtualTextNode(text);
2211
- }
2212
- createComment(text) {
2213
- return new VirtualCommentNode(text);
2214
- }
2215
- createDocumentFragment() {
2216
- const fragment = new VirtualElement("document-fragment");
2217
- fragment._isFragment = true;
2218
- return fragment;
2219
- }
2220
- querySelector(selector) {
2221
- return this.documentElement?.querySelector(selector) || null;
2222
- }
2223
- querySelectorAll(selector) {
2224
- return this.documentElement?.querySelectorAll(selector) || [];
2225
- }
2226
- getElementById(id) {
2227
- return this.querySelector(`#${id}`);
2228
- }
2229
- getElementsByTagName(tagName) {
2230
- return this.querySelectorAll(tagName);
2231
- }
2232
- getElementsByClassName(className) {
2233
- return this.querySelectorAll(`.${className}`);
2234
- }
2235
- parseHTML(html) {
2236
- const nodes = parseHTML(html);
2237
- if (this.body) {
2238
- this.body.childNodes = [];
2239
- for (const node of nodes) {
2240
- this.body.appendChild(node);
2241
- }
2242
- }
2243
- }
2244
- write(html) {
2245
- const nodes = parseHTML(html);
2246
- for (const node of nodes) {
2247
- if (node.nodeType === "element") {
2248
- const element = node;
2249
- if (element.tagName === "HTML") {
2250
- this.documentElement = element;
2251
- element.parentNode = this;
2252
- for (const child of element.children) {
2253
- if (child.nodeType === "element") {
2254
- const childEl = child;
2255
- if (childEl.tagName === "HEAD") {
2256
- this.head = childEl;
2257
- } else if (childEl.tagName === "BODY") {
2258
- this.body = childEl;
2259
- }
2260
- }
2261
- }
2262
- return;
2263
- }
2264
- }
2265
- }
2266
- if (this.body) {
2267
- for (const node of nodes) {
2268
- this.body.appendChild(node);
2269
- }
2270
- }
2271
- }
2272
- getComputedStyle(element) {
2273
- const defaultDisplay = {
2274
- DIV: "block",
2275
- P: "block",
2276
- H1: "block",
2277
- H2: "block",
2278
- H3: "block",
2279
- H4: "block",
2280
- H5: "block",
2281
- H6: "block",
2282
- UL: "block",
2283
- OL: "block",
2284
- LI: "list-item",
2285
- TABLE: "table",
2286
- TR: "table-row",
2287
- TD: "table-cell",
2288
- TH: "table-cell",
2289
- SPAN: "inline",
2290
- A: "inline",
2291
- EM: "inline",
2292
- STRONG: "inline",
2293
- SCRIPT: "none",
2294
- STYLE: "none",
2295
- HEAD: "none"
2296
- };
2297
- const self = element;
2298
- return new Proxy({
2299
- getPropertyValue(property) {
2300
- const value = self.style.getPropertyValue(property);
2301
- if (value)
2302
- return value;
2303
- if (property === "display" && !value) {
2304
- return defaultDisplay[self.tagName] || "block";
2305
- }
2306
- return value || "";
2307
- }
2308
- }, {
2309
- get(target, prop) {
2310
- if (prop === "getPropertyValue") {
2311
- return target.getPropertyValue;
2312
- }
2313
- const kebabProp = prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
2314
- const value = self.style.getPropertyValue(kebabProp);
2315
- if (value)
2316
- return value;
2317
- if (kebabProp === "display" && !value) {
2318
- return defaultDisplay[self.tagName] || "block";
2319
- }
2320
- return value || "";
2321
- }
2322
- });
2323
- }
2324
- addEventListener(type, listener) {
2325
- if (!this._eventListeners.has(type)) {
2326
- this._eventListeners.set(type, []);
2327
- }
2328
- this._eventListeners.get(type).push(listener);
2329
- }
2330
- removeEventListener(type, listener) {
2331
- const listeners = this._eventListeners.get(type);
2332
- if (listeners) {
2333
- const index = listeners.indexOf(listener);
2334
- if (index !== -1) {
2335
- listeners.splice(index, 1);
2336
- }
2337
- }
2338
- }
2339
- dispatchEvent(event) {
2340
- const listeners = this._eventListeners.get(event.type);
2341
- if (listeners) {
2342
- for (const listener of listeners) {
2343
- listener(event);
2344
- }
2345
- }
2346
- return true;
2347
- }
2348
- evaluate(expression, contextNode = this, resolver = null, type = 0 /* ANY_TYPE */, result = null) {
2349
- const actualContext = contextNode === this ? this.documentElement || this : contextNode;
2350
- return this._xpathEvaluator.evaluate(expression, actualContext, resolver, type, result);
2351
- }
2352
- createExpression(expression, resolver = null) {
2353
- return {
2354
- evaluate: (contextNode, type = 0 /* ANY_TYPE */) => {
2355
- const actualContext = contextNode === this ? this.documentElement || this : contextNode;
2356
- return this._xpathEvaluator.evaluate(expression, actualContext, resolver, type, null);
2357
- }
2358
- };
2359
- }
2360
- get cookie() {
2361
- return Object.entries(this._cookies).map(([key, value]) => `${key}=${value}`).join("; ");
2362
- }
2363
- set cookie(value) {
2364
- const parts = value.split(";").map((p) => p.trim());
2365
- const [nameValue] = parts;
2366
- if (nameValue) {
2367
- const [name, val] = nameValue.split("=").map((s) => s.trim());
2368
- if (name) {
2369
- this._cookies[name] = val || "";
2370
- }
2371
- }
2372
- }
2373
- }
2374
- function createDocument() {
2375
- return new VirtualDocument;
2376
- }
2377
-
2378
- // src/browser/BrowserFrame.ts
2379
- class BrowserFrame {
2380
- window;
2381
- document;
2382
- _page;
2383
- _parentFrame = null;
2384
- _childFrames = [];
2385
- _url;
2386
- _content = "";
2387
- constructor(page, parentFrame = null) {
2388
- this._page = page;
2389
- this._parentFrame = parentFrame;
2390
- this._url = "about:blank";
2391
- this.document = new VirtualDocument;
2392
- this.window = {
2393
- document: this.document,
2394
- location: {
2395
- href: this._url,
2396
- toString: () => this._url
2397
- },
2398
- Event: VirtualEvent
2399
- };
2400
- }
2401
- get childFrames() {
2402
- return this._childFrames;
2403
- }
2404
- get parentFrame() {
2405
- return this._parentFrame;
2406
- }
2407
- get page() {
2408
- return this._page;
2409
- }
2410
- get content() {
2411
- return this.document.documentElement?.outerHTML || "";
2412
- }
2413
- set content(html) {
2414
- this._content = html;
2415
- this.document.documentElement.innerHTML = html;
2416
- }
2417
- get url() {
2418
- return this._url;
2419
- }
2420
- set url(url) {
2421
- this._url = url;
2422
- this.window.location = { href: url, toString: () => url };
2423
- }
2424
- async waitUntilComplete() {}
2425
- async waitForNavigation() {}
2426
- async abort() {}
2427
- evaluate(code) {
2428
- if (typeof code === "function") {
2429
- const _window = this.window;
2430
- const document = this.document;
2431
- const wrappedFn = new Function("window", "document", `return (${code.toString()})()`).bind(null, _window, document);
2432
- return wrappedFn();
2433
- } else {
2434
- return eval(code);
2435
- }
2436
- }
2437
- async goto(url) {
2438
- this.url = url;
2439
- return null;
2440
- }
2441
- async goBack() {
2442
- return null;
2443
- }
2444
- async goForward() {
2445
- return null;
2446
- }
2447
- async goSteps(_steps) {
2448
- return null;
2449
- }
2450
- async reload() {
2451
- return null;
2452
- }
2453
- }
2454
-
2455
- // src/browser/BrowserPage.ts
2456
- class BrowserPage {
2457
- mainFrame;
2458
- console;
2459
- virtualConsolePrinter = null;
2460
- _context;
2461
- _viewport;
2462
- _frames = [];
2463
- _eventListeners = new Map;
2464
- _requestInterceptor = new RequestInterceptor;
2465
- constructor(context) {
2466
- this._context = context;
2467
- this._viewport = { width: 1024, height: 768 };
2468
- this.console = globalThis.console;
2469
- this.mainFrame = new BrowserFrame(this);
2470
- this._frames.push(this.mainFrame);
2471
- }
2472
- get context() {
2473
- return this._context;
2474
- }
2475
- get viewport() {
2476
- return this._viewport;
2477
- }
2478
- get frames() {
2479
- return this._frames;
2480
- }
2481
- get content() {
2482
- return this.mainFrame.content;
2483
- }
2484
- set content(html) {
2485
- this.mainFrame.content = html;
2486
- }
2487
- get url() {
2488
- return this.mainFrame.url;
2489
- }
2490
- set url(url) {
2491
- this.mainFrame.url = url;
2492
- }
2493
- async close() {
2494
- await this.abort();
2495
- this._context._removePage(this);
2496
- }
2497
- async waitUntilComplete() {
2498
- await Promise.all(this._frames.map((frame) => frame.waitUntilComplete()));
2499
- }
2500
- async waitForNavigation() {
2501
- await this.mainFrame.waitForNavigation();
2502
- }
2503
- async abort() {
2504
- await Promise.all(this._frames.map((frame) => frame.abort()));
2505
- }
2506
- evaluate(code2) {
2507
- return this.mainFrame.evaluate(code2);
2508
- }
2509
- setViewport(viewport) {
2510
- this._viewport = { ...viewport };
2511
- }
2512
- async goto(url) {
2513
- return await this.mainFrame.goto(url);
2514
- }
2515
- async goBack() {
2516
- return await this.mainFrame.goBack();
2517
- }
2518
- async goForward() {
2519
- return await this.mainFrame.goForward();
2520
- }
2521
- async goSteps(steps) {
2522
- return await this.mainFrame.goSteps(steps);
2523
- }
2524
- async reload() {
2525
- return await this.mainFrame.reload();
2526
- }
2527
- async waitForSelector(selector, options = {}) {
2528
- const { timeout = 30000, visible = false } = options;
2529
- const startTime = Date.now();
2530
- while (Date.now() - startTime < timeout) {
2531
- const element = this.mainFrame.document.querySelector(selector);
2532
- if (element) {
2533
- if (!visible || element.isVisible?.()) {
2534
- return element;
2535
- }
2536
- }
2537
- await new Promise((resolve) => setTimeout(resolve, 50));
2538
- }
2539
- return null;
2540
- }
2541
- async waitForFunction(fn, options = {}) {
2542
- const { timeout = 30000, polling = 100 } = options;
2543
- const startTime = Date.now();
2544
- const pollInterval = polling === "raf" ? 16 : polling;
2545
- while (Date.now() - startTime < timeout) {
2546
- const result = this.evaluate(fn);
2547
- if (result) {
2548
- return result;
2549
- }
2550
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
2551
- }
2552
- throw new Error(`waitForFunction timed out after ${timeout}ms`);
2553
- }
2554
- async waitForTimeout(ms) {
2555
- await new Promise((resolve) => setTimeout(resolve, ms));
2556
- }
2557
- async click(selector, options = {}) {
2558
- const element = this.mainFrame.document.querySelector(selector);
2559
- if (!element) {
2560
- throw new Error(`Element not found: ${selector}`);
2561
- }
2562
- if (options.delay) {
2563
- await this.waitForTimeout(options.delay);
2564
- }
2565
- element.click?.();
2566
- }
2567
- async type(selector, text, options = {}) {
2568
- const element = this.mainFrame.document.querySelector(selector);
2569
- if (!element) {
2570
- throw new Error(`Element not found: ${selector}`);
2571
- }
2572
- const delay = options.delay || 0;
2573
- if (element.tagName === "INPUT" || element.tagName === "TEXTAREA") {
2574
- let currentValue = element.getAttribute?.("value") || "";
2575
- for (const char of text) {
2576
- currentValue += char;
2577
- element.setAttribute?.("value", currentValue);
2578
- if (delay > 0) {
2579
- await this.waitForTimeout(delay);
2580
- }
2581
- }
2582
- } else {
2583
- element.textContent = (element.textContent || "") + text;
2584
- }
2585
- }
2586
- async focus(selector) {
2587
- const element = this.mainFrame.document.querySelector(selector);
2588
- if (!element) {
2589
- throw new Error(`Element not found: ${selector}`);
2590
- }
2591
- const event = new this.mainFrame.window.Event("focus", { bubbles: true });
2592
- element.dispatchEvent?.(event);
2593
- }
2594
- async hover(selector) {
2595
- const element = this.mainFrame.document.querySelector(selector);
2596
- if (!element) {
2597
- throw new Error(`Element not found: ${selector}`);
2598
- }
2599
- const event = new this.mainFrame.window.Event("mouseenter", { bubbles: true });
2600
- element.dispatchEvent?.(event);
2601
- }
2602
- get keyboard() {
2603
- return {
2604
- press: async (key, options = {}) => {
2605
- const { delay = 0 } = options;
2606
- const keydownEvent = new this.mainFrame.window.Event("keydown", { bubbles: true });
2607
- keydownEvent.key = key;
2608
- this.mainFrame.document.dispatchEvent?.(keydownEvent);
2609
- if (delay > 0) {
2610
- await this.waitForTimeout(delay);
2611
- }
2612
- const keyupEvent = new this.mainFrame.window.Event("keyup", { bubbles: true });
2613
- keyupEvent.key = key;
2614
- this.mainFrame.document.dispatchEvent?.(keyupEvent);
2615
- },
2616
- type: async (text, options = {}) => {
2617
- for (const char of text) {
2618
- await this.keyboard.press(char, options);
2619
- }
2620
- }
2621
- };
2622
- }
2623
- get mouse() {
2624
- return {
2625
- click: async (x, y, options = {}) => {
2626
- const { delay = 0 } = options;
2627
- const clickEvent = new this.mainFrame.window.Event("click", { bubbles: true });
2628
- clickEvent.clientX = x;
2629
- clickEvent.clientY = y;
2630
- this.mainFrame.document.dispatchEvent?.(clickEvent);
2631
- if (delay > 0) {
2632
- await this.waitForTimeout(delay);
2633
- }
2634
- },
2635
- move: async (x, y) => {
2636
- const moveEvent = new this.mainFrame.window.Event("mousemove", { bubbles: true });
2637
- moveEvent.clientX = x;
2638
- moveEvent.clientY = y;
2639
- this.mainFrame.document.dispatchEvent?.(moveEvent);
2640
- }
2641
- };
2642
- }
2643
- on(event, handler) {
2644
- if (!this._eventListeners.has(event)) {
2645
- this._eventListeners.set(event, new Set);
2646
- }
2647
- this._eventListeners.get(event).add(handler);
2648
- }
2649
- off(event, handler) {
2650
- const handlers = this._eventListeners.get(event);
2651
- if (handlers) {
2652
- handlers.delete(handler);
2653
- }
2654
- }
2655
- emit(event, data) {
2656
- const handlers = this._eventListeners.get(event);
2657
- if (handlers) {
2658
- for (const handler of handlers) {
2659
- handler(data);
2660
- }
2661
- }
2662
- if (event === "console" && this.virtualConsolePrinter) {
2663
- this.virtualConsolePrinter(data.type, ...data.args);
2664
- }
2665
- }
2666
- _emitConsole(type, ...args) {
2667
- this.emit("console", { type, args });
2668
- }
2669
- _emitRequest(request) {
2670
- this.emit("request", request);
2671
- }
2672
- _emitResponse(response) {
2673
- this.emit("response", response);
2674
- }
2675
- _emitError(error) {
2676
- this.emit("error", error);
2677
- }
2678
- async dragAndDrop(source, target, options = {}) {
2679
- const sourceElement = this.mainFrame.document.querySelector(source);
2680
- const targetElement = this.mainFrame.document.querySelector(target);
2681
- if (!sourceElement || !targetElement) {
2682
- throw new Error("Source or target element not found");
2683
- }
2684
- const dragStartEvent = new this.mainFrame.window.Event("dragstart", { bubbles: true });
2685
- sourceElement.dispatchEvent?.(dragStartEvent);
2686
- if (options.delay) {
2687
- await this.waitForTimeout(options.delay);
2688
- }
2689
- const dropEvent = new this.mainFrame.window.Event("drop", { bubbles: true });
2690
- targetElement.dispatchEvent?.(dropEvent);
2691
- const dragEndEvent = new this.mainFrame.window.Event("dragend", { bubbles: true });
2692
- sourceElement.dispatchEvent?.(dragEndEvent);
2693
- }
2694
- async setRequestInterception(enabled) {
2695
- if (enabled) {
2696
- this._requestInterceptor.enable();
2697
- const handler = (request) => {
2698
- this._emitRequest(request);
2699
- };
2700
- this._requestInterceptor.addHandler(handler);
2701
- } else {
2702
- this._requestInterceptor.disable();
2703
- this._requestInterceptor.clear();
2704
- }
2705
- }
2706
- async screenshot(options = {}) {
2707
- const {
2708
- type: _type = "png",
2709
- quality: _quality = 100,
2710
- fullPage: _fullPage = false,
2711
- encoding = "binary"
2712
- } = options;
2713
- const html = this.content;
2714
- const svg = this._generateSVG(html);
2715
- if (encoding === "base64") {
2716
- return Buffer2.from(svg).toString("base64");
2717
- }
2718
- return Buffer2.from(svg);
2719
- }
2720
- async pdf(options = {}) {
2721
- const {
2722
- scale: _scale = 1,
2723
- displayHeaderFooter: _displayHeaderFooter = false,
2724
- printBackground: _printBackground = false,
2725
- landscape: _landscape = false,
2726
- format: _format = "A4"
2727
- } = options;
2728
- const html = this.content;
2729
- const pdf = this._generatePDF(html);
2730
- return Buffer2.from(pdf);
2731
- }
2732
- _generateSVG(html) {
2733
- const width = this._viewport.width;
2734
- const height = this._viewport.height;
2735
- return `<?xml version="1.0" encoding="UTF-8"?>
2736
- <svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">
2
+ var{defineProperty:t,getOwnPropertyNames:A_,getOwnPropertyDescriptor:L_}=Object,W_=Object.prototype.hasOwnProperty;var Z_=new WeakMap,T_=(_)=>{var G=Z_.get(_),$;if(G)return G;if(G=t({},"__esModule",{value:!0}),_&&typeof _==="object"||typeof _==="function")A_(_).map((K)=>!W_.call(G,K)&&t(G,K,{get:()=>_[K],enumerable:!($=L_(_,K))||$.enumerable}));return Z_.set(_,G),G};var F_=(_,G)=>{for(var $ in G)t(_,$,{get:G[$],enumerable:!0,configurable:!0,set:(K)=>G[$]=()=>K})};var B_={};F_(B_,{DetachedWindowAPI:()=>Y_});class Y_{_window;_pendingOperations=new Set;_aborted=!1;constructor(_){this._window=_}get settings(){return this._window.settings}async close(){await this.abort(),this._window.document.documentElement.innerHTML=""}async waitUntilComplete(){if(this._pendingOperations.size>0)await Promise.all(Array.from(this._pendingOperations));let _=this._window._getTimerManager?.();if(_)await _.waitForTimers()}async abort(){this._aborted=!0,this._pendingOperations.clear();let _=this._window._getTimerManager?.();if(_)_.abort()}setURL(_){this._window.location=_}setViewport(_){if(_.width!==void 0)this._window._width=_.width;if(_.height!==void 0)this._window._height=_.height}_trackOperation(_){this._pendingOperations.add(_),_.finally(()=>{this._pendingOperations.delete(_)})}_isAborted(){return this._aborted}}class H{_marks=new Map;_measures=new Map;_startTime=Date.now();now(){return Date.now()-this._startTime}mark(_){this._marks.set(_,this.now())}measure(_,G,$){let K=$?this._marks.get($):this.now(),J=G?this._marks.get(G):0;if(K!==void 0&&J!==void 0)this._measures.set(_,{start:J,duration:K-J})}clearMarks(_){if(_)this._marks.delete(_);else this._marks.clear()}clearMeasures(_){if(_)this._measures.delete(_);else this._measures.clear()}getEntriesByName(_){let G=[];if(this._marks.has(_))G.push({name:_,entryType:"mark",startTime:this._marks.get(_)});if(this._measures.has(_)){let $=this._measures.get(_);G.push({name:_,entryType:"measure",startTime:$.start,duration:$.duration})}return G}}class M{getCurrentPosition(_,G,$){setTimeout(()=>{_({coords:{latitude:37.7749,longitude:-122.4194,accuracy:10,altitude:null,altitudeAccuracy:null,heading:null,speed:null},timestamp:Date.now()})},0)}watchPosition(_,G,$){return setInterval(()=>{_({coords:{latitude:37.7749,longitude:-122.4194,accuracy:10,altitude:null,altitudeAccuracy:null,heading:null,speed:null},timestamp:Date.now()})},1000)}clearWatch(_){clearInterval(_)}}class V{static permission="default";title;body;icon;tag;onclick=null;onclose=null;onerror=null;onshow=null;constructor(_,G){this.title=_,this.body=G?.body,this.icon=G?.icon,this.tag=G?.tag,setTimeout(()=>{if(this.onshow)this.onshow({})},0)}static requestPermission(){return Promise.resolve("granted")}close(){if(this.onclose)this.onclose({})}}class z_{_groups=[];_timers=new Map;log(..._){console.log(...this._prefix(),..._)}warn(..._){console.warn(...this._prefix(),..._)}error(..._){console.error(...this._prefix(),..._)}info(..._){console.info(...this._prefix(),..._)}debug(..._){console.debug(...this._prefix(),..._)}table(_){console.table(_)}group(_){if(_)this._groups.push(_),console.log(...this._prefix(),`\u25BC ${_}`)}groupCollapsed(_){this.group(_)}groupEnd(){this._groups.pop()}time(_){this._timers.set(_,Date.now())}timeEnd(_){let G=this._timers.get(_);if(G){let $=Date.now()-G;console.log(...this._prefix(),`${_}: ${$}ms`),this._timers.delete(_)}}timeLog(_,...G){let $=this._timers.get(_);if($){let K=Date.now()-$;console.log(...this._prefix(),`${_}: ${K}ms`,...G)}}clear(){console.clear()}count(_="default"){console.log(...this._prefix(),_)}assert(_,...G){if(!_)console.error(...this._prefix(),"Assertion failed:",...G)}trace(..._){console.trace(...this._prefix(),..._)}_prefix(){return this._groups.map(()=>" ")}}class N{_data=new Map;dropEffect="none";effectAllowed="uninitialized";files=[];items=[];types=[];setData(_,G){if(this._data.set(_,G),!this.types.includes(_))this.types.push(_)}getData(_){return this._data.get(_)||""}clearData(_){if(_){this._data.delete(_);let G=this.types.indexOf(_);if(G!==-1)this.types.splice(G,1)}else this._data.clear(),this.types=[]}setDragImage(_,G,$){}}class e{_text="";async writeText(_){this._text=_}async readText(){return this._text}async write(_){for(let G of _)for(let $ of G.types){let K=await G.getType($);if($==="text/plain")this._text=await K.text()}}async read(){let _=new Blob([this._text],{type:"text/plain"});return[new ClipboardItem({"text/plain":_})]}}class S{clipboard=new e;geolocation=new M;userAgent="Mozilla/5.0 (X11; Linux x64) AppleWebKit/537.36 (KHTML, like Gecko) VeryHappyDOM/1.0.0";language="en-US";languages=["en-US","en"];platform="Linux x86_64";cookieEnabled=!0;onLine=!0}class g extends Blob{name;lastModified;constructor(_,G,$){super(_,$);this.name=G,this.lastModified=$?.lastModified||Date.now()}}class D{static EMPTY=0;static LOADING=1;static DONE=2;readyState=D.EMPTY;result=null;error=null;onload=null;onerror=null;onloadstart=null;onloadend=null;onprogress=null;onabort=null;_eventListeners=new Map;readAsText(_,G="UTF-8"){this.readyState=D.LOADING,this._trigger("loadstart"),_.text().then(($)=>{this.result=$,this.readyState=D.DONE,this._trigger("load"),this._trigger("loadend")}).catch(($)=>{this.error=$,this.readyState=D.DONE,this._trigger("error"),this._trigger("loadend")})}readAsDataURL(_){this.readyState=D.LOADING,this._trigger("loadstart"),_.arrayBuffer().then((G)=>{let $=Buffer.from(G).toString("base64");this.result=`data:${_.type};base64,${$}`,this.readyState=D.DONE,this._trigger("load"),this._trigger("loadend")}).catch((G)=>{this.error=G,this.readyState=D.DONE,this._trigger("error"),this._trigger("loadend")})}readAsArrayBuffer(_){this.readyState=D.LOADING,this._trigger("loadstart"),_.arrayBuffer().then((G)=>{this.result=G,this.readyState=D.DONE,this._trigger("load"),this._trigger("loadend")}).catch((G)=>{this.error=G,this.readyState=D.DONE,this._trigger("error"),this._trigger("loadend")})}readAsBinaryString(_){this.readyState=D.LOADING,this._trigger("loadstart"),_.arrayBuffer().then((G)=>{this.result=String.fromCharCode(...new Uint8Array(G)),this.readyState=D.DONE,this._trigger("load"),this._trigger("loadend")}).catch((G)=>{this.error=G,this.readyState=D.DONE,this._trigger("error"),this._trigger("loadend")})}abort(){this.readyState=D.DONE,this._trigger("abort"),this._trigger("loadend")}addEventListener(_,G){if(!this._eventListeners.has(_))this._eventListeners.set(_,new Set);this._eventListeners.get(_).add(G)}removeEventListener(_,G){let $=this._eventListeners.get(_);if($)$.delete(G)}_trigger(_){let G={type:_,lengthComputable:!1,loaded:0,total:0},$=this._eventListeners.get(_);if($)for(let J of $)J(G);let K=this[`on${_}`];if(K)K.call(this,G)}}class R{_files=[];constructor(_=[]){this._files=_}get length(){return this._files.length}item(_){return this._files[_]||null}[Symbol.iterator](){return this._files[Symbol.iterator]()}}import{Buffer as J_}from"buffer";class x{_enabled=!1;_handlers=new Set;_originalFetch;constructor(){this._originalFetch=globalThis.fetch}enable(){if(this._enabled)return;this._enabled=!0;let _=this,G=async function($,K){let J=typeof $==="string"?$:$ instanceof URL?$.href:$.url,Q=K?.method||"GET",Y={};if(K?.headers)if(K.headers instanceof Headers)K.headers.forEach((B,q)=>{Y[q]=B});else if(Array.isArray(K.headers))K.headers.forEach(([B,q])=>{Y[B]=q});else Object.assign(Y,K.headers);let Z=!1,z=!1,U=null,O={},f={url:J,method:Q,headers:Y,postData:K?.body?String(K.body):null,resourceType:"fetch",continue(B={}){O=B},abort(B="failed"){Z=!0},respond(B){z=!0,U=new Response(B.body,{status:B.status,headers:B.headers})}};for(let B of _._handlers)await B(f);if(Z)throw Error("Request aborted");if(z&&U)return U;let b=O.url||J,l=O.method||Q,j=O.headers||Y,T=O.postData!==void 0?O.postData:K?.body;return _._originalFetch(b,{...K,method:l,headers:j,body:T})};Object.assign(G,{preconnect:()=>{}}),globalThis.fetch=G}disable(){if(!this._enabled)return;this._enabled=!1,globalThis.fetch=this._originalFetch}addHandler(_){this._handlers.add(_)}removeHandler(_){this._handlers.delete(_)}clear(){this._handlers.clear()}}class W{type;target=null;currentTarget=null;bubbles;cancelable;defaultPrevented=!1;propagationStopped=!1;immediatePropagationStopped=!1;timeStamp;constructor(_,G={}){this.type=_,this.bubbles=G.bubbles??!1,this.cancelable=G.cancelable??!1,this.timeStamp=Date.now()}preventDefault(){if(this.cancelable)this.defaultPrevented=!0}stopPropagation(){this.propagationStopped=!0}stopImmediatePropagation(){this.immediatePropagationStopped=!0,this.propagationStopped=!0}}class C{nodeType="comment";nodeName="#comment";nodeValue;attributes=new Map;children=[];parentNode=null;constructor(_){this.nodeValue=_}get textContent(){return""}set textContent(_){}}function __(_,G){if(!G||typeof G!=="string")return null;if(!G.trim())return null;let $=X(_,G);return $.length>0?$[0]:null}function X(_,G){if(!G||typeof G!=="string")return[];if(!G.trim())return[];if(G.includes(",")){let K=G.split(",").map((Y)=>Y.trim()).filter(Boolean),J=[],Q=new Set;for(let Y of K){let Z=X(_,Y);for(let z of Z)if(!Q.has(z))Q.add(z),J.push(z)}return J}let $=[];if(G_(G)){let K=function(J){if(J.nodeType==="element"&&$_(J,G,_))$.push(J);for(let Q of J.children)K(Q)};for(let J of _.children)K(J)}else{let K=function(J){if(J.nodeType==="element"&&L(J,G))$.push(J);for(let Q of J.children)K(Q)};for(let J of _.children)K(J)}return $}function G_(_){let G=_.replace(/\[[^\]]*\]/g,"").replace(/:not\([^)]*\)/g,"").replace(/:nth-child\([^)]*\)/g,"");return/[>+~\s]/.test(G)}function $_(_,G,$){let K=q_(G),J=_,Q=!1;for(let Y=K.length-1;Y>=0;Y--){let Z=K[Y];if(!Q&&!L(J,Z.selector))return!1;if(Q=!1,Y===0)return!0;let z=K[Y-1];switch(z.combinator){case">":{if(J=J.parentNode,!J||J.nodeType!=="element")return!1;break}case"+":{if(J=J.previousElementSibling,!J)return!1;break}case"~":{let U=!1,O=J.previousElementSibling;while(O){if(L(O,z.selector)){J=O,U=!0;break}O=O.previousElementSibling}if(!U)return!1;Q=!0;break}case" ":{let U=!1,O=J.parentNode;while(O&&O.nodeType!=="document"){if(O===$){if($.nodeType==="element"&&L($,z.selector))J=$,U=!0;break}if(O.nodeType==="element"&&L(O,z.selector)){J=O,U=!0;break}O=O.parentNode}if(!U)return!1;Q=!0;break}}}return!0}function q_(_){let G=[],$="",K=!1,J=!1,Q=0;function Y(Z){for(let z=Z;z<_.length;z++)if(_[z]!==" ")return _[z];return null}for(let Z=0;Z<_.length;Z++){let z=_[Z],U=_[Z+1];if(z==="[")K=!0,$+=z;else if(z==="]")K=!1,$+=z;else if(z==="("&&$.endsWith(":not("))J=!0,Q=1,$+=z;else if(z==="("&&/:\w+\($/.test($))J=!0,Q=1,$+=z;else if(J&&z==="(")Q++,$+=z;else if(J&&z===")"){if(Q--,Q===0)J=!1;$+=z}else if(!K&&!J&&(z===">"||z==="+"||z==="~")){if($.trim())G.push({selector:$.trim(),combinator:z}),$="";while(_[Z+1]===" ")Z++}else if(!K&&!J&&z===" "){let O=Y(Z+1);if(O&&(O===">"||O==="+"||O==="~"))continue;else if($&&U&&U!==" "){if($.trim())G.push({selector:$.trim(),combinator:" "}),$=""}else if($)$+=z}else if(z!==" "||$)$+=z}if($.trim())G.push({selector:$.trim(),combinator:null});return G}function L(_,G){if(G==="*")return!0;let $=G.replace(/:([a-z-]+)\([^)]*\)/gi,":$1"),K=$.replace(/\[[^\]]+\]/g,""),J=K.match(/^([a-z0-9-]+)/i),Q=K.match(/#([\w-]+)/),Y=K.match(/\.([\w-]+)/g),Z=$.match(/\[([^\]]+)\]/g),z=G.match(/:([a-z-]+)(\([^)]*\))?/gi);if(J&&J[1].toLowerCase()!==_.tagName.toLowerCase())return!1;if(Q&&_.getAttribute("id")!==Q[1])return!1;if(Y){let U=_.getAttribute("class")?.split(/\s+/).filter(Boolean)||[];for(let O of Y){let f=O.slice(1);if(!U.includes(f))return!1}}if(Z)for(let U of Z){let O=U.slice(1,-1);if(!U_(_,O))return!1}if(z){for(let U of z)if(!O_(_,U))return!1}return!0}function O_(_,G){let $=G.match(/:([a-z-]+)(\(([^)]*)\))?/i);if(!$)throw Error(`Invalid pseudo-class selector: "${G}"`);let K=$[1],J=$[3];switch(K){case"first-child":return(_.parentNode?.children.filter((Y)=>Y.nodeType==="element")||[])[0]===_;case"last-child":{let Q=_.parentNode?.children.filter((Y)=>Y.nodeType==="element")||[];return Q[Q.length-1]===_}case"nth-child":{if(!J)return!1;let Y=(_.parentNode?.children.filter((U)=>U.nodeType==="element")||[]).indexOf(_);if(Y===-1)return!1;let Z=Y+1;if(J==="odd")return Z%2===1;if(J==="even")return Z%2===0;let z=Number.parseInt(J,10);if(!Number.isNaN(z))return Z===z;return!1}case"not":{if(!J)return!1;return!L(_,J)}case"disabled":return _.hasAttribute("disabled");case"enabled":return!_.hasAttribute("disabled");case"checked":return _.hasAttribute("checked");case"empty":return _.childNodes.length===0||_.childNodes.length===1&&_.childNodes[0].nodeType==="text"&&(_.childNodes[0].nodeValue?.trim()===""||_.childNodes[0].nodeValue===null);case"first-of-type":{if(!_.parentNode)return!1;return _.parentNode.children.filter((Y)=>Y.nodeType==="element"&&Y.tagName===_.tagName)[0]===_}case"last-of-type":{if(!_.parentNode)return!1;let Q=_.parentNode.children.filter((Y)=>Y.nodeType==="element"&&Y.tagName===_.tagName);return Q[Q.length-1]===_}case"only-child":{if(!_.parentNode)return!1;let Q=_.parentNode.children.filter((Y)=>Y.nodeType==="element");return Q.length===1&&Q[0]===_}case"only-of-type":{if(!_.parentNode)return!1;let Q=_.parentNode.children.filter((Y)=>Y.nodeType==="element"&&Y.tagName===_.tagName);return Q.length===1&&Q[0]===_}case"nth-of-type":{if(!J||!_.parentNode)return!1;let Y=_.parentNode.children.filter((O)=>O.nodeType==="element"&&O.tagName===_.tagName).indexOf(_);if(Y===-1)return!1;let Z=Y+1;if(J==="odd")return Z%2===1;if(J==="even")return Z%2===0;let z=J.match(/^(-?\d*)n([+-]\d+)?$/);if(z){let O=z[1]===""?1:z[1]==="-"?-1:Number.parseInt(z[1],10),f=z[2]?Number.parseInt(z[2],10):0;if(O===0)return Z===f;let b=(Z-f)/O;return b>=0&&Number.isInteger(b)}let U=Number.parseInt(J,10);if(!Number.isNaN(U))return Z===U;return!1}case"nth-last-child":{if(!J||!_.parentNode)return!1;let Q=_.parentNode.children.filter((U)=>U.nodeType==="element"),Y=Q.indexOf(_);if(Y===-1)return!1;let Z=Q.length-Y;if(J==="odd")return Z%2===1;if(J==="even")return Z%2===0;let z=Number.parseInt(J,10);if(!Number.isNaN(z))return Z===z;return!1}case"nth-last-of-type":{if(!J||!_.parentNode)return!1;let Q=_.parentNode.children.filter((U)=>U.nodeType==="element"&&U.tagName===_.tagName),Y=Q.indexOf(_);if(Y===-1)return!1;let Z=Q.length-Y;if(J==="odd")return Z%2===1;if(J==="even")return Z%2===0;let z=Number.parseInt(J,10);if(!Number.isNaN(z))return Z===z;return!1}default:throw Error(`Unsupported pseudo-class: ":${K}". Supported pseudo-classes are: :first-child, :last-child, :first-of-type, :last-of-type, :only-child, :only-of-type, :nth-child(), :nth-last-child(), :nth-of-type(), :nth-last-of-type(), :not(), :disabled, :enabled, :checked, :empty`)}}function U_(_,G){if(!G.includes("="))return _.hasAttribute(G);let $=G.match(/^([a-z0-9-]+)="([^"]*)"$/i);if($)return _.getAttribute($[1])===$[2];let K=G.match(/^([a-z0-9-]+)\^="([^"]*)"$/i);if(K){let Z=_.getAttribute(K[1]);return Z!==null&&Z.startsWith(K[2])}let J=G.match(/^([a-z0-9-]+)\$="([^"]*)"$/i);if(J){let Z=_.getAttribute(J[1]);return Z!==null&&Z.endsWith(J[2])}let Q=G.match(/^([a-z0-9-]+)\*="([^"]*)"$/i);if(Q){let Z=_.getAttribute(Q[1]);return Z!==null&&Z.includes(Q[2])}let Y=G.match(/^([a-z0-9-]+)~="([^"]*)"$/i);if(Y){let Z=_.getAttribute(Y[1]);if(Z===null)return!1;return Z.split(/\s+/).includes(Y[2])}return!1}class k{mode;delegatesFocus;host;innerHTML="";children=[];constructor(_,G){this.host=_,this.mode=G.mode,this.delegatesFocus=G.delegatesFocus||!1}querySelector(_){for(let G of this.children)if(G.nodeType==="element"){let $=G;if($.matches?.(_))return $;let K=$.querySelector(_);if(K)return K}return null}querySelectorAll(_){let G=[];for(let $ of this.children)if($.nodeType==="element"){let K=$;if(K.matches?.(_))G.push(K);G.push(...K.querySelectorAll(_))}return G}appendChild(_){return this.children.push(_),_.parentNode=this.host,_}removeChild(_){let G=this.children.indexOf(_);if(G!==-1)this.children.splice(G,1),_.parentNode=null;return _}getElementById(_){return this.querySelector(`#${_}`)}}class A{nodeType="element";nodeName;nodeValue=null;tagName;attributes=new Map;childNodes=[];parentNode=null;shadowRoot=null;eventListeners=new Map;_customValidity="";_internalStyles=new Map;get children(){return this.childNodes.filter((_)=>_.nodeType==="element")}constructor(_){this.tagName=_.toUpperCase(),this.nodeName=this.tagName}getAttribute(_){return this.attributes.get(_.toLowerCase())??null}setAttribute(_,G){this.attributes.set(_.toLowerCase(),G)}removeAttribute(_){this.attributes.delete(_.toLowerCase())}hasAttribute(_){return this.attributes.has(_.toLowerCase())}appendChild(_){return this.childNodes.push(_),_.parentNode=this,_}removeChild(_){let G=this.childNodes.indexOf(_);if(G===-1)return _;return this.childNodes.splice(G,1),_.parentNode=null,_}insertBefore(_,G){if(G===null)return this.appendChild(_);let $=this.childNodes.indexOf(G);if($===-1)throw Error("Reference node not found");if(_.parentNode){let K=_.parentNode,J=K.childNodes.indexOf(_);if(J!==-1)K.childNodes.splice(J,1)}return this.childNodes.splice($,0,_),_.parentNode=this,_}replaceChild(_,G){let $=this.childNodes.indexOf(G);if($===-1)throw Error("Old node not found");if(_.parentNode){let K=_.parentNode,J=K.childNodes.indexOf(_);if(J!==-1)K.childNodes.splice(J,1)}return this.childNodes.splice($,1,_),G.parentNode=null,_.parentNode=this,G}cloneNode(_=!1){let G=new A(this.tagName);for(let[$,K]of this.attributes)G.setAttribute($,K);if(_)for(let $ of this.childNodes)if($.nodeType==="element"){let K=$.cloneNode(!0);G.appendChild(K)}else{let K={...$,parentNode:null};G.appendChild(K)}return G}closest(_){let G=this;while(G){if(L(G,_))return G;if(G=G.parentNode,G?.nodeType!=="element")G=null}return null}get firstChild(){return this.childNodes.length>0?this.childNodes[0]:null}get lastChild(){return this.childNodes.length>0?this.childNodes[this.childNodes.length-1]:null}get nextSibling(){if(!this.parentNode)return null;let _=this.parentNode.childNodes,G=_.indexOf(this);if(G===-1||G>=_.length-1)return null;return _[G+1]}get previousSibling(){if(!this.parentNode)return null;let _=this.parentNode.childNodes,G=_.indexOf(this);if(G<=0)return null;return _[G-1]}get nextElementSibling(){if(!this.parentNode)return null;let _=this.parentNode.children,G=_.indexOf(this);if(G===-1)return null;for(let $=G+1;$<_.length;$++)if(_[$].nodeType==="element")return _[$];return null}get previousElementSibling(){if(!this.parentNode)return null;let _=this.parentNode.children,G=_.indexOf(this);if(G===-1)return null;for(let $=G-1;$>=0;$--)if(_[$].nodeType==="element")return _[$];return null}get textContent(){let _="";for(let G of this.childNodes)_+=G.textContent;return _}set textContent(_){if(this.childNodes=[],_){let G={nodeType:"text",nodeName:"#text",nodeValue:_,attributes:new Map,children:[],parentNode:this,textContent:_};this.childNodes.push(G)}}get innerHTML(){return this.childNodes.map((_)=>this._serializeNode(_)).join("")}set innerHTML(_){if(this.childNodes=[],_){let G=w(_);if(this.tagName==="HTML"&&G.length>0)for(let $ of G){if($.nodeType==="element"){let K=$;if(K.tagName==="HTML"){for(let J of K.children)this.appendChild(J);continue}}this.appendChild($)}else for(let $ of G)this.appendChild($)}}get outerHTML(){return this._serializeNode(this)}get classList(){let _=this;return{add(...G){let $=_.getAttribute("class")?.split(/\s+/).filter(Boolean)||[];for(let K of G)if(!$.includes(K))$.push(K);_.setAttribute("class",$.join(" "))},remove(...G){let K=(_.getAttribute("class")?.split(/\s+/).filter(Boolean)||[]).filter((J)=>!G.includes(J));if(K.length>0)_.setAttribute("class",K.join(" "));else _.removeAttribute("class")},toggle(G){let $=_.getAttribute("class")?.split(/\s+/).filter(Boolean)||[],K=$.indexOf(G);if(K!==-1){if($.splice(K,1),$.length>0)_.setAttribute("class",$.join(" "));else _.removeAttribute("class");return!1}else return $.push(G),_.setAttribute("class",$.join(" ")),!0},contains(G){return(_.getAttribute("class")?.split(/\s+/).filter(Boolean)||[]).includes(G)},replace(G,$){let K=_.getAttribute("class")?.split(/\s+/).filter(Boolean)||[],J=K.indexOf(G);if(J!==-1)return K[J]=$,_.setAttribute("class",K.join(" ")),!0;return!1}}}_serializeNode(_){if(_.nodeType==="text")return _.nodeValue||"";if(_.nodeType==="comment")return`<!--${_.nodeValue}-->`;if(_.nodeType==="element"){let G=_,$=G.tagName.toLowerCase(),K=`<${$}`;for(let[Q,Y]of G.attributes)K+=` ${Q}="${Y}"`;if(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"].includes($))return K+="/>",K;K+=">";for(let Q of G.childNodes)K+=this._serializeNode(Q);return K+=`</${$}>`,K}return""}get style(){let _=this;return new Proxy({getPropertyValue(G){return _._internalStyles.get(G)||""},setProperty(G,$){_._internalStyles.set(G,$),_._updateStyleAttribute()},removeProperty(G){_._internalStyles.delete(G),_._updateStyleAttribute()}},{get(G,$){if($==="getPropertyValue"||$==="setProperty"||$==="removeProperty")return G[$];let K=$.replace(/[A-Z]/g,(Q)=>`-${Q.toLowerCase()}`);return _._internalStyles.get(K)},set(G,$,K){let J=$.replace(/[A-Z]/g,(Q)=>`-${Q.toLowerCase()}`);return _._internalStyles.set(J,K),_._updateStyleAttribute(),!0}})}_updateStyleAttribute(){let _=Array.from(this._internalStyles.entries()).map(([G,$])=>`${G}: ${$}`).join("; ");if(_)this.setAttribute("style",_);else this.removeAttribute("style")}get dataset(){let _=this;return new Proxy({},{get(G,$){let K=$.replace(/[A-Z]/g,(J)=>`-${J.toLowerCase()}`);return _.getAttribute(`data-${K}`)||""},set(G,$,K){let J=$.replace(/[A-Z]/g,(Q)=>`-${Q.toLowerCase()}`);return _.setAttribute(`data-${J}`,K),!0},deleteProperty(G,$){let K=$.replace(/[A-Z]/g,(J)=>`-${J.toLowerCase()}`);return _.removeAttribute(`data-${K}`),!0},has(G,$){let K=$.replace(/[A-Z]/g,(J)=>`-${J.toLowerCase()}`);return _.hasAttribute(`data-${K}`)},ownKeys(G){let $=[];for(let[K]of _.attributes)if(K.startsWith("data-")){let J=K.slice(5).replace(/-([a-z])/g,(Q,Y)=>Y.toUpperCase());$.push(J)}return $},getOwnPropertyDescriptor(G,$){let K=$.replace(/[A-Z]/g,(J)=>`-${J.toLowerCase()}`);if(_.hasAttribute(`data-${K}`))return{configurable:!0,enumerable:!0,writable:!0,value:_.getAttribute(`data-${K}`)};return}})}get validity(){let _=this.getAttribute("value")||"",G=this.getAttribute("type")||"text",$=this.hasAttribute("required"),K=this.getAttribute("pattern"),J=this.getAttribute("minlength"),Q=this.getAttribute("maxlength"),Y=this.getAttribute("min"),Z=this.getAttribute("max"),z={valid:!0,valueMissing:!1,typeMismatch:!1,patternMismatch:!1,tooLong:!1,tooShort:!1,rangeUnderflow:!1,rangeOverflow:!1,stepMismatch:!1,badInput:!1,customError:!1};if($&&!_)z.valueMissing=!0,z.valid=!1;if(K&&_){if(!new RegExp(K).test(_))z.patternMismatch=!0,z.valid=!1}if(J&&_.length<Number.parseInt(J,10))z.tooShort=!0,z.valid=!1;if(Q&&_.length>Number.parseInt(Q,10))z.tooLong=!0,z.valid=!1;if(G==="number"||G==="range"){let U=Number.parseFloat(_);if(!Number.isNaN(U)){if(Y&&U<Number.parseFloat(Y))z.rangeUnderflow=!0,z.valid=!1;if(Z&&U>Number.parseFloat(Z))z.rangeOverflow=!0,z.valid=!1}}if(G==="email"&&_){if(!/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(_))z.typeMismatch=!0,z.valid=!1}if(G==="url"&&_)try{new URL(_)}catch{z.typeMismatch=!0,z.valid=!1}if(this._customValidity)z.customError=!0,z.valid=!1;return z}get validationMessage(){if(this._customValidity)return this._customValidity;let _=this.validity;if(_.valueMissing)return"Please fill out this field.";if(_.typeMismatch){let G=this.getAttribute("type");if(G==="email")return"Please enter an email address.";if(G==="url")return"Please enter a URL.";return"Please match the requested format."}if(_.patternMismatch)return"Please match the requested format.";if(_.tooShort)return`Please lengthen this text to ${this.getAttribute("minlength")} characters or more.`;if(_.tooLong)return`Please shorten this text to ${this.getAttribute("maxlength")} characters or less.`;if(_.rangeUnderflow)return`Value must be greater than or equal to ${this.getAttribute("min")}.`;if(_.rangeOverflow)return`Value must be less than or equal to ${this.getAttribute("max")}.`;return""}setCustomValidity(_){this._customValidity=_}checkValidity(){return this.validity.valid}reportValidity(){let _=this.checkValidity();if(!_){let G=new W("invalid",{bubbles:!1,cancelable:!0});this.dispatchEvent(G)}return _}querySelector(_){return __(this,_)}querySelectorAll(_){return X(this,_)}matches(_){if(G_(_)){let G=this;while(G.parentNode&&G.parentNode.nodeType!=="document")G=G.parentNode;if(G.parentNode&&G.parentNode.nodeType==="document")G=G.parentNode;return $_(this,_,G)}else return L(this,_)}addEventListener(_,G,$={}){let K=typeof $==="boolean"?{capture:$}:{capture:$.capture??!1,once:$.once,passive:$.passive};if(!this.eventListeners.has(_))this.eventListeners.set(_,[]);let J=this.eventListeners.get(_);if(!J.some((Y)=>Y.listener===G&&Y.options.capture===K.capture))J.push({listener:G,options:K})}removeEventListener(_,G,$={}){let K=typeof $==="boolean"?{capture:$}:{capture:$.capture??!1},J=this.eventListeners.get(_);if(!J)return;let Q=J.findIndex((Y)=>Y.listener===G&&Y.options.capture===K.capture);if(Q!==-1)J.splice(Q,1)}dispatchEvent(_){try{_.target=this,_.currentTarget=this}catch{}let G=[],$=this;while($&&$.nodeType==="element")G.unshift($),$=$.parentNode;let K=()=>_.propagationStopped||_._propagationStopped||!1;for(let Q=0;Q<G.length-1&&!K();Q++){let Y=G[Q];try{_.currentTarget=Y}catch{}this._invokeEventListeners(Y,_,!0)}if(!K()){try{_.currentTarget=this}catch{}this._invokeEventListeners(this,_,!1),this._invokeEventListeners(this,_,!0)}if((_.bubbles??!0)&&!K())for(let Q=G.length-2;Q>=0&&!K();Q--){let Y=G[Q];try{_.currentTarget=Y}catch{}this._invokeEventListeners(Y,_,!1)}return!(_.defaultPrevented??!1)}_invokeEventListeners(_,G,$){let K=_.eventListeners.get(G.type);if(!K)return;let J=[...K];for(let{listener:Q,options:Y}of J){if(Y.capture!==$)continue;if(G.immediatePropagationStopped)break;try{Q.call(_,G)}catch(Z){console.error("Error in event listener:",Z)}if(Y.once)_.removeEventListener(G.type,Q,Y)}}click(){let _=new W("click",{bubbles:!0,cancelable:!0});this.dispatchEvent(_)}isVisible(){if(this.style.getPropertyValue("display")==="none")return!1;if(this.style.getPropertyValue("visibility")==="hidden")return!1;if(this.style.getPropertyValue("opacity")==="0")return!1;return!0}attachShadow(_){if(this.shadowRoot)throw Error("Shadow root already exists");return this.shadowRoot=new k(this,_),this.shadowRoot}}class P{nodeType="text";nodeName="#text";nodeValue;attributes=new Map;children=[];parentNode=null;constructor(_){this.nodeValue=_}get textContent(){return this.nodeValue||""}set textContent(_){this.nodeValue=_}}function w(_){let G=0;function $(){return _[G]||""}function K(){return _[G++]||""}function J(){while(/\s/.test($()))K()}function Q(){if($()!=="<")return null;if(K(),_.slice(G,G+3)==="!--"){G+=3;let j=_.indexOf("-->",G);if(j===-1)throw Error("Unclosed comment");let T=_.slice(G,j);return G=j+3,new C(T)}if(_.slice(G,G+8).toUpperCase()==="!DOCTYPE"){let j=_.indexOf(">",G);if(j===-1)throw Error("Unclosed DOCTYPE");return G=j+1,null}if($()==="/"){K();let j=_.indexOf(">",G);if(j===-1)throw Error("Unclosed tag");return G=j+1,null}let U="";while($()&&/[a-z0-9-]/i.test($()))U+=K();if(!U)throw Error("Invalid tag name");let O=new A(U);while($()&&$()!==">"&&$()!=="/"){if(J(),$()===">"||$()==="/")break;let j="";while($()&&/[\w\-:]/.test($()))j+=K();if(!j)break;J();let T="",B=!1;if($()==="=")if(B=!0,K(),J(),$()==='"'||$()==="'"){let q=K();while($()&&$()!==q)T+=K();if($()===q)K()}else while($()&&!/[\s>]/.test($()))T+=K();O.setAttribute(j,B?T:j)}let f=$()==="/";if(f)K();if($()===">")K();if(f||["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"].includes(U.toLowerCase()))return O;let l=Z(U);for(let j of l)O.appendChild(j);return O}function Y(){let U="";while($()&&$()!=="<")U+=K();if(!U)return null;return new P(U)}function Z(U){let O=[];while(G<_.length){if(U&&_.slice(G,G+2+U.length+1)===`</${U}>`){G+=2+U.length+1;break}if($()==="<"){let f=Q();if(f===null)continue;O.push(f)}else{let f=Y();if(f)O.push(f)}}return O}return Z()}var K_;((O)=>{O[O.ANY_TYPE=0]="ANY_TYPE";O[O.NUMBER_TYPE=1]="NUMBER_TYPE";O[O.STRING_TYPE=2]="STRING_TYPE";O[O.BOOLEAN_TYPE=3]="BOOLEAN_TYPE";O[O.UNORDERED_NODE_ITERATOR_TYPE=4]="UNORDERED_NODE_ITERATOR_TYPE";O[O.ORDERED_NODE_ITERATOR_TYPE=5]="ORDERED_NODE_ITERATOR_TYPE";O[O.UNORDERED_NODE_SNAPSHOT_TYPE=6]="UNORDERED_NODE_SNAPSHOT_TYPE";O[O.ORDERED_NODE_SNAPSHOT_TYPE=7]="ORDERED_NODE_SNAPSHOT_TYPE";O[O.ANY_UNORDERED_NODE_TYPE=8]="ANY_UNORDERED_NODE_TYPE";O[O.FIRST_ORDERED_NODE_TYPE=9]="FIRST_ORDERED_NODE_TYPE"})(K_||={});class v{resultType;numberValue;stringValue;booleanValue;singleNodeValue;snapshotLength;_nodes=[];_iteratorIndex=0;constructor(_,G=[],$=0,K="",J=!1){this.resultType=_,this._nodes=G,this.numberValue=$,this.stringValue=K,this.booleanValue=J,this.singleNodeValue=G.length>0?G[0]:null,this.snapshotLength=G.length}iterateNext(){if(this._iteratorIndex<this._nodes.length)return this._nodes[this._iteratorIndex++];return null}snapshotItem(_){return this._nodes[_]||null}}class y{evaluate(_,G,$=null,K=0,J=null){let Q=this._evaluateExpression(_,G),Y=K;if(K===0)Y=7;return new v(Y,Q)}_evaluateExpression(_,G){let $=_.trim();if($===".")return[G];if($==="..")return G.parentNode?[G.parentNode]:[];if($.startsWith("//")){let K=$.substring(2);return this._findDescendants(G,K)}if($.startsWith("/")){let K=$.substring(1);return this._findChildren(G,K)}if($.startsWith("@")){let K=$.substring(1);if(G.nodeType==="element"){let J=G.getAttribute(K);if(J!==null)return[{nodeType:"text",nodeValue:J,nodeName:"#text"}]}return[]}return this._findDescendants(G,$)}_findChildren(_,G){let $=[],K=G.split("/").filter((Y)=>Y.trim());if(K.length===0)return $;let[J,...Q]=K;for(let Y of _.children||[])if(this._matchesExpression(Y,J))if(Q.length===0)$.push(Y);else $.push(...this._findChildren(Y,Q.join("/")));return $}_findDescendants(_,G){let $=[],K=G.split("/").filter((Z)=>Z.trim());if(K.length===0)return $;let[J,...Q]=K,Y=(Z)=>{if(this._matchesExpression(Z,J))if(Q.length===0)$.push(Z);else $.push(...this._findChildren(Z,Q.join("/")));for(let z of Z.children||[])Y(z)};return Y(_),$}_matchesExpression(_,G){if(G==="*")return _.nodeType==="element";if(G==="text()")return _.nodeType==="text";if(G==="node()")return!0;let $=G.match(/^(\w+)\[(.+)\]$/);if($){let[,K,J]=$;if(_.nodeType!=="element")return!1;let Q=_;if(K!=="*"&&Q.tagName!==K.toUpperCase())return!1;return this._evaluatePredicate(Q,J)}if(_.nodeType==="element")return _.tagName===G.toUpperCase();return!1}_evaluatePredicate(_,G){let $=G.match(/^@(\w+)=['"](.+)['"]$/);if($){let[,J,Q]=$;return _.getAttribute(J)===Q}if(G.startsWith("@")){let J=G.substring(1);return _.getAttribute(J)!==null}let K=G.match(/^(\d+)$/);if(K){let J=Number.parseInt(K[1]),Q=_.parentNode;if(Q)return Q.children.filter((Z)=>Z.nodeType==="element").indexOf(_)===J-1}return!1}_parseTagName(_){let G=_.match(/^(\w+)/);return G?G[1]:_}}class F{nodeType="document";nodeName="#document";nodeValue=null;attributes=new Map;children=[];parentNode=null;documentElement=null;head=null;body=null;location;history;title="";_historyStack=[];_historyIndex=-1;_eventListeners=new Map;_xpathEvaluator=new y;_cookies={};constructor(){this.documentElement=new A("html"),this.head=new A("head"),this.body=new A("body"),this.documentElement.appendChild(this.head),this.documentElement.appendChild(this.body),this.appendChild(this.documentElement),this.location={href:"",protocol:"",host:"",hostname:"",port:"",pathname:"",search:"",hash:"",origin:"",assign:(G)=>{this._updateLocation(G)},replace:(G)=>{this._updateLocation(G)},reload:()=>{}};let _=this;this.history={get length(){return _._historyStack.length},get state(){return _._historyStack[_._historyIndex]?.state||null},pushState(G,$,K){if(_._historyStack=_._historyStack.slice(0,_._historyIndex+1),_._historyStack.push({state:G,title:$,url:K||_.location.href}),_._historyIndex++,K)_._updateLocation(K)},replaceState(G,$,K){if(_._historyIndex>=0){if(_._historyStack[_._historyIndex]={state:G,title:$,url:K||_.location.href},K)_._updateLocation(K)}},back(){if(_._historyIndex>0){_._historyIndex--;let G=_._historyStack[_._historyIndex];if(G.url)_._updateLocation(G.url)}},forward(){if(_._historyIndex<_._historyStack.length-1){_._historyIndex++;let G=_._historyStack[_._historyIndex];if(G.url)_._updateLocation(G.url)}},go(G){let $=_._historyIndex+G;if($>=0&&$<_._historyStack.length){_._historyIndex=$;let K=_._historyStack[_._historyIndex];if(K.url)_._updateLocation(K.url)}}}}_updateLocation(_){try{let G=new URL(_,this.location.href);this.location.href=G.href,this.location.protocol=G.protocol,this.location.host=G.host,this.location.hostname=G.hostname,this.location.port=G.port,this.location.pathname=G.pathname,this.location.search=G.search,this.location.hash=G.hash,this.location.origin=G.origin}catch{}}get textContent(){return this.documentElement?.textContent||""}set textContent(_){if(this.documentElement)this.documentElement.textContent=_}appendChild(_){return this.children.push(_),_.parentNode=this,_}createElement(_){return new A(_)}createTextNode(_){return new P(_)}createComment(_){return new C(_)}createDocumentFragment(){let _=new A("document-fragment");return _._isFragment=!0,_}querySelector(_){return this.documentElement?.querySelector(_)||null}querySelectorAll(_){return this.documentElement?.querySelectorAll(_)||[]}getElementById(_){return this.querySelector(`#${_}`)}getElementsByTagName(_){return this.querySelectorAll(_)}getElementsByClassName(_){return this.querySelectorAll(`.${_}`)}parseHTML(_){let G=w(_);if(this.body){this.body.childNodes=[];for(let $ of G)this.body.appendChild($)}}write(_){let G=w(_);for(let $ of G)if($.nodeType==="element"){let K=$;if(K.tagName==="HTML"){this.documentElement=K,K.parentNode=this;for(let J of K.children)if(J.nodeType==="element"){let Q=J;if(Q.tagName==="HEAD")this.head=Q;else if(Q.tagName==="BODY")this.body=Q}return}}if(this.body)for(let $ of G)this.body.appendChild($)}getComputedStyle(_){let G={DIV:"block",P:"block",H1:"block",H2:"block",H3:"block",H4:"block",H5:"block",H6:"block",UL:"block",OL:"block",LI:"list-item",TABLE:"table",TR:"table-row",TD:"table-cell",TH:"table-cell",SPAN:"inline",A:"inline",EM:"inline",STRONG:"inline",SCRIPT:"none",STYLE:"none",HEAD:"none"},$=_;return new Proxy({getPropertyValue(K){let J=$.style.getPropertyValue(K);if(J)return J;if(K==="display"&&!J)return G[$.tagName]||"block";return J||""}},{get(K,J){if(J==="getPropertyValue")return K.getPropertyValue;let Q=J.replace(/[A-Z]/g,(Z)=>`-${Z.toLowerCase()}`),Y=$.style.getPropertyValue(Q);if(Y)return Y;if(Q==="display"&&!Y)return G[$.tagName]||"block";return Y||""}})}addEventListener(_,G){if(!this._eventListeners.has(_))this._eventListeners.set(_,[]);this._eventListeners.get(_).push(G)}removeEventListener(_,G){let $=this._eventListeners.get(_);if($){let K=$.indexOf(G);if(K!==-1)$.splice(K,1)}}dispatchEvent(_){let G=this._eventListeners.get(_.type);if(G)for(let $ of G)$(_);return!0}evaluate(_,G=this,$=null,K=0,J=null){let Q=G===this?this.documentElement||this:G;return this._xpathEvaluator.evaluate(_,Q,$,K,J)}createExpression(_,G=null){return{evaluate:($,K=0)=>{let J=$===this?this.documentElement||this:$;return this._xpathEvaluator.evaluate(_,J,G,K,null)}}}get cookie(){return Object.entries(this._cookies).map(([_,G])=>`${_}=${G}`).join("; ")}set cookie(_){let G=_.split(";").map((K)=>K.trim()),[$]=G;if($){let[K,J]=$.split("=").map((Q)=>Q.trim());if(K)this._cookies[K]=J||""}}}function C_(){return new F}class BrowserFrame{window;document;_page;_parentFrame=null;_childFrames=[];_url;_content="";constructor(_,G=null){this._page=_,this._parentFrame=G,this._url="about:blank",this.document=new F,this.window={document:this.document,location:{href:this._url,toString:()=>this._url},Event:W}}get childFrames(){return this._childFrames}get parentFrame(){return this._parentFrame}get page(){return this._page}get content(){return this.document.documentElement?.outerHTML||""}set content(_){this._content=_,this.document.documentElement.innerHTML=_}get url(){return this._url}set url(_){this._url=_,this.window.location={href:_,toString:()=>_}}async waitUntilComplete(){}async waitForNavigation(){}async abort(){}evaluate(code){if(typeof code==="function"){let _=this.window,G=this.document;return Function("window","document",`return (${code.toString()})()`).bind(null,_,G)()}else return eval(code)}async goto(_){return this.url=_,null}async goBack(){return null}async goForward(){return null}async goSteps(_){return null}async reload(){return null}}class h{mainFrame;console;virtualConsolePrinter=null;_context;_viewport;_frames=[];_eventListeners=new Map;_requestInterceptor=new x;constructor(_){this._context=_,this._viewport={width:1024,height:768},this.console=globalThis.console,this.mainFrame=new BrowserFrame(this),this._frames.push(this.mainFrame)}get context(){return this._context}get viewport(){return this._viewport}get frames(){return this._frames}get content(){return this.mainFrame.content}set content(_){this.mainFrame.content=_}get url(){return this.mainFrame.url}set url(_){this.mainFrame.url=_}async close(){await this.abort(),this._context._removePage(this)}async waitUntilComplete(){await Promise.all(this._frames.map((_)=>_.waitUntilComplete()))}async waitForNavigation(){await this.mainFrame.waitForNavigation()}async abort(){await Promise.all(this._frames.map((_)=>_.abort()))}evaluate(_){return this.mainFrame.evaluate(_)}setViewport(_){this._viewport={..._}}async goto(_){return await this.mainFrame.goto(_)}async goBack(){return await this.mainFrame.goBack()}async goForward(){return await this.mainFrame.goForward()}async goSteps(_){return await this.mainFrame.goSteps(_)}async reload(){return await this.mainFrame.reload()}async waitForSelector(_,G={}){let{timeout:$=30000,visible:K=!1}=G,J=Date.now();while(Date.now()-J<$){let Q=this.mainFrame.document.querySelector(_);if(Q){if(!K||Q.isVisible?.())return Q}await new Promise((Y)=>setTimeout(Y,50))}return null}async waitForFunction(_,G={}){let{timeout:$=30000,polling:K=100}=G,J=Date.now(),Q=K==="raf"?16:K;while(Date.now()-J<$){let Y=this.evaluate(_);if(Y)return Y;await new Promise((Z)=>setTimeout(Z,Q))}throw Error(`waitForFunction timed out after ${$}ms`)}async waitForTimeout(_){await new Promise((G)=>setTimeout(G,_))}async click(_,G={}){let $=this.mainFrame.document.querySelector(_);if(!$)throw Error(`Element not found: ${_}`);if(G.delay)await this.waitForTimeout(G.delay);$.click?.()}async type(_,G,$={}){let K=this.mainFrame.document.querySelector(_);if(!K)throw Error(`Element not found: ${_}`);let J=$.delay||0;if(K.tagName==="INPUT"||K.tagName==="TEXTAREA"){let Q=K.getAttribute?.("value")||"";for(let Y of G)if(Q+=Y,K.setAttribute?.("value",Q),J>0)await this.waitForTimeout(J)}else K.textContent=(K.textContent||"")+G}async focus(_){let G=this.mainFrame.document.querySelector(_);if(!G)throw Error(`Element not found: ${_}`);let $=new this.mainFrame.window.Event("focus",{bubbles:!0});G.dispatchEvent?.($)}async hover(_){let G=this.mainFrame.document.querySelector(_);if(!G)throw Error(`Element not found: ${_}`);let $=new this.mainFrame.window.Event("mouseenter",{bubbles:!0});G.dispatchEvent?.($)}get keyboard(){return{press:async(_,G={})=>{let{delay:$=0}=G,K=new this.mainFrame.window.Event("keydown",{bubbles:!0});if(K.key=_,this.mainFrame.document.dispatchEvent?.(K),$>0)await this.waitForTimeout($);let J=new this.mainFrame.window.Event("keyup",{bubbles:!0});J.key=_,this.mainFrame.document.dispatchEvent?.(J)},type:async(_,G={})=>{for(let $ of _)await this.keyboard.press($,G)}}}get mouse(){return{click:async(_,G,$={})=>{let{delay:K=0}=$,J=new this.mainFrame.window.Event("click",{bubbles:!0});if(J.clientX=_,J.clientY=G,this.mainFrame.document.dispatchEvent?.(J),K>0)await this.waitForTimeout(K)},move:async(_,G)=>{let $=new this.mainFrame.window.Event("mousemove",{bubbles:!0});$.clientX=_,$.clientY=G,this.mainFrame.document.dispatchEvent?.($)}}}on(_,G){if(!this._eventListeners.has(_))this._eventListeners.set(_,new Set);this._eventListeners.get(_).add(G)}off(_,G){let $=this._eventListeners.get(_);if($)$.delete(G)}emit(_,G){let $=this._eventListeners.get(_);if($)for(let K of $)K(G);if(_==="console"&&this.virtualConsolePrinter)this.virtualConsolePrinter(G.type,...G.args)}_emitConsole(_,...G){this.emit("console",{type:_,args:G})}_emitRequest(_){this.emit("request",_)}_emitResponse(_){this.emit("response",_)}_emitError(_){this.emit("error",_)}async dragAndDrop(_,G,$={}){let K=this.mainFrame.document.querySelector(_),J=this.mainFrame.document.querySelector(G);if(!K||!J)throw Error("Source or target element not found");let Q=new this.mainFrame.window.Event("dragstart",{bubbles:!0});if(K.dispatchEvent?.(Q),$.delay)await this.waitForTimeout($.delay);let Y=new this.mainFrame.window.Event("drop",{bubbles:!0});J.dispatchEvent?.(Y);let Z=new this.mainFrame.window.Event("dragend",{bubbles:!0});K.dispatchEvent?.(Z)}async setRequestInterception(_){if(_){this._requestInterceptor.enable();let G=($)=>{this._emitRequest($)};this._requestInterceptor.addHandler(G)}else this._requestInterceptor.disable(),this._requestInterceptor.clear()}async screenshot(_={}){let{type:G="png",quality:$=100,fullPage:K=!1,encoding:J="binary"}=_,Q=this.content,Y=this._generateSVG(Q);if(J==="base64")return J_.from(Y).toString("base64");return J_.from(Y)}async pdf(_={}){let{scale:G=1,displayHeaderFooter:$=!1,printBackground:K=!1,landscape:J=!1,format:Q="A4"}=_,Y=this.content,Z=this._generatePDF(Y);return J_.from(Z)}_generateSVG(_){let G=this._viewport.width,$=this._viewport.height;return`<?xml version="1.0" encoding="UTF-8"?>
3
+ <svg xmlns="http://www.w3.org/2000/svg" width="${G}" height="${$}">
2737
4
  <rect width="100%" height="100%" fill="white"/>
2738
5
  <foreignObject width="100%" height="100%">
2739
6
  <div xmlns="http://www.w3.org/1999/xhtml">
2740
- <pre style="font-family: monospace; font-size: 12px; padding: 10px;">${this._escapeXML(html.substring(0, 500))}</pre>
7
+ <pre style="font-family: monospace; font-size: 12px; padding: 10px;">${this._escapeXML(_.substring(0,500))}</pre>
2741
8
  </div>
2742
9
  </foreignObject>
2743
- </svg>`;
2744
- }
2745
- _generatePDF(html) {
2746
- const _title = this.mainFrame.document.title || "Document";
2747
- return `%PDF-1.4
10
+ </svg>`}_generatePDF(_){let G=this.mainFrame.document.title||"Document";return`%PDF-1.4
2748
11
  % VeryHappyDOM Generated PDF
2749
12
  1 0 obj
2750
13
  <<
@@ -2771,10 +34,10 @@ endobj
2771
34
 
2772
35
  4 0 obj
2773
36
  <<
2774
- /Length ${html.length}
37
+ /Length ${_.length}
2775
38
  >>
2776
39
  stream
2777
- ${html}
40
+ ${_}
2778
41
  endstream
2779
42
  endobj
2780
43
 
@@ -2791,1002 +54,6 @@ trailer
2791
54
  /Root 1 0 R
2792
55
  >>
2793
56
  startxref
2794
- ${284 + html.length}
2795
- %%EOF`;
2796
- }
2797
- _escapeXML(text) {
2798
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
2799
- }
2800
- }
2801
-
2802
- // src/browser/CookieContainer.ts
2803
- var CookieSameSiteEnum;
2804
- ((CookieSameSiteEnum2) => {
2805
- CookieSameSiteEnum2["none"] = "None";
2806
- CookieSameSiteEnum2["lax"] = "Lax";
2807
- CookieSameSiteEnum2["strict"] = "Strict";
2808
- })(CookieSameSiteEnum ||= {});
2809
-
2810
- class CookieContainer {
2811
- _cookies = [];
2812
- addCookies(cookies) {
2813
- for (const cookie of cookies) {
2814
- this._cookies = this._cookies.filter((c) => !(c.key === cookie.key && (c.domain || new URL(c.originURL).hostname) === (cookie.domain || new URL(cookie.originURL).hostname) && (c.path || "/") === (cookie.path || "/")));
2815
- this._cookies.push({
2816
- ...cookie,
2817
- value: cookie.value || "",
2818
- domain: cookie.domain || new URL(cookie.originURL).hostname,
2819
- path: cookie.path || "/",
2820
- expires: cookie.expires,
2821
- httpOnly: cookie.httpOnly || false,
2822
- secure: cookie.secure || false,
2823
- sameSite: cookie.sameSite || "Lax" /* lax */
2824
- });
2825
- }
2826
- }
2827
- getCookies(url, includeHttpOnly = false) {
2828
- const parsedURL = new URL(url);
2829
- const hostname = parsedURL.hostname;
2830
- const pathname = parsedURL.pathname;
2831
- const isSecure = parsedURL.protocol === "https:";
2832
- const now = new Date;
2833
- return this._cookies.filter((cookie) => {
2834
- if (cookie.expires && cookie.expires < now) {
2835
- return false;
2836
- }
2837
- if (cookie.httpOnly && !includeHttpOnly) {
2838
- return false;
2839
- }
2840
- if (cookie.secure && !isSecure) {
2841
- return false;
2842
- }
2843
- const cookieDomain = cookie.domain || new URL(cookie.originURL).hostname;
2844
- if (!hostname.endsWith(cookieDomain) && hostname !== cookieDomain) {
2845
- return false;
2846
- }
2847
- const cookiePath = cookie.path || "/";
2848
- if (!pathname.startsWith(cookiePath)) {
2849
- return false;
2850
- }
2851
- return true;
2852
- });
2853
- }
2854
- clearCookies() {
2855
- this._cookies = [];
2856
- }
2857
- }
2858
-
2859
- // src/browser/BrowserContext.ts
2860
- class BrowserContext {
2861
- cookieContainer;
2862
- responseCache = new Map;
2863
- preflightResponseCache = new Map;
2864
- _browser;
2865
- _pages = [];
2866
- constructor(browser) {
2867
- this._browser = browser;
2868
- this.cookieContainer = new CookieContainer;
2869
- }
2870
- get pages() {
2871
- return this._pages;
2872
- }
2873
- get browser() {
2874
- return this._browser;
2875
- }
2876
- async close() {
2877
- await Promise.all(this._pages.map((page) => page.close()));
2878
- this._pages = [];
2879
- this.cookieContainer.clearCookies();
2880
- this.responseCache.clear();
2881
- this.preflightResponseCache.clear();
2882
- }
2883
- async waitUntilComplete() {
2884
- await Promise.all(this._pages.map((page) => page.waitUntilComplete()));
2885
- }
2886
- async abort() {
2887
- await Promise.all(this._pages.map((page) => page.abort()));
2888
- }
2889
- newPage() {
2890
- const page = new BrowserPage(this);
2891
- this._pages.push(page);
2892
- return page;
2893
- }
2894
- _removePage(page) {
2895
- const index = this._pages.indexOf(page);
2896
- if (index !== -1) {
2897
- this._pages.splice(index, 1);
2898
- }
2899
- }
2900
- }
2901
-
2902
- // src/browser/Browser.ts
2903
- class Browser {
2904
- console;
2905
- defaultContext;
2906
- _contexts = [];
2907
- _settings;
2908
- constructor(options = {}) {
2909
- const { settings = {}, console: consoleInstance } = options;
2910
- this.console = consoleInstance || globalThis.console;
2911
- this._settings = {
2912
- navigator: {
2913
- userAgent: settings.navigator?.userAgent || "Mozilla/5.0 (X11; Linux x64) AppleWebKit/537.36 (KHTML, like Gecko) VeryHappyDOM/1.0.0"
2914
- },
2915
- device: {
2916
- prefersColorScheme: settings.device?.prefersColorScheme || "light"
2917
- }
2918
- };
2919
- this.defaultContext = new BrowserContext(this);
2920
- this._contexts.push(this.defaultContext);
2921
- }
2922
- get contexts() {
2923
- return this._contexts;
2924
- }
2925
- get settings() {
2926
- return this._settings;
2927
- }
2928
- async close() {
2929
- await Promise.all(this._contexts.map((context) => context.close()));
2930
- this._contexts = [];
2931
- }
2932
- async waitUntilComplete() {
2933
- await Promise.all(this._contexts.map((context) => context.waitUntilComplete()));
2934
- }
2935
- async abort() {
2936
- await Promise.all(this._contexts.map((context) => context.abort()));
2937
- }
2938
- newIncognitoContext() {
2939
- const context = new BrowserContext(this);
2940
- this._contexts.push(context);
2941
- return context;
2942
- }
2943
- newPage() {
2944
- return this.defaultContext.newPage();
2945
- }
2946
- }
2947
- // src/events/CustomEvent.ts
2948
- class CustomEvent extends VirtualEvent {
2949
- detail;
2950
- constructor(type, eventInitDict = {}) {
2951
- super(type, eventInitDict);
2952
- this.detail = eventInitDict.detail;
2953
- }
2954
- }
2955
- // src/http/XMLHttpRequest.ts
2956
- class XMLHttpRequest {
2957
- static UNSENT = 0;
2958
- static OPENED = 1;
2959
- static HEADERS_RECEIVED = 2;
2960
- static LOADING = 3;
2961
- static DONE = 4;
2962
- readyState = XMLHttpRequest.UNSENT;
2963
- response = null;
2964
- responseText = "";
2965
- responseType = "";
2966
- responseURL = "";
2967
- responseXML = null;
2968
- status = 0;
2969
- statusText = "";
2970
- timeout = 0;
2971
- upload = new XMLHttpRequestUpload;
2972
- withCredentials = false;
2973
- onreadystatechange = null;
2974
- onload = null;
2975
- onerror = null;
2976
- onabort = null;
2977
- onloadstart = null;
2978
- onloadend = null;
2979
- onprogress = null;
2980
- ontimeout = null;
2981
- _method = "";
2982
- _url = "";
2983
- _requestHeaders = new Map;
2984
- _responseHeaders = new Map;
2985
- _aborted = false;
2986
- _eventListeners = new Map;
2987
- constructor() {}
2988
- open(method, url, _async = true, _username, _password) {
2989
- this._method = method.toUpperCase();
2990
- this._url = url;
2991
- this.readyState = XMLHttpRequest.OPENED;
2992
- this._triggerEvent("readystatechange");
2993
- }
2994
- send(body) {
2995
- if (this.readyState !== XMLHttpRequest.OPENED) {
2996
- throw new Error("InvalidStateError: Object state must be OPENED");
2997
- }
2998
- this._triggerEvent("loadstart", true);
2999
- const headers = {};
3000
- for (const [key, value] of this._requestHeaders) {
3001
- headers[key] = value;
3002
- }
3003
- const fetchOptions = {
3004
- method: this._method,
3005
- headers,
3006
- body,
3007
- credentials: this.withCredentials ? "include" : "same-origin"
3008
- };
3009
- const controller = new AbortController;
3010
- let timeoutId = null;
3011
- if (this.timeout > 0) {
3012
- timeoutId = setTimeout(() => {
3013
- controller.abort();
3014
- this._triggerEvent("timeout", true);
3015
- }, this.timeout);
3016
- }
3017
- fetch(this._url, { ...fetchOptions, signal: controller.signal }).then(async (response) => {
3018
- if (timeoutId)
3019
- clearTimeout(timeoutId);
3020
- if (this._aborted)
3021
- return;
3022
- this.status = response.status;
3023
- this.statusText = response.statusText;
3024
- this.responseURL = response.url;
3025
- response.headers.forEach((value, key) => {
3026
- this._responseHeaders.set(key.toLowerCase(), value);
3027
- });
3028
- this.readyState = XMLHttpRequest.HEADERS_RECEIVED;
3029
- this._triggerEvent("readystatechange");
3030
- this.readyState = XMLHttpRequest.LOADING;
3031
- this._triggerEvent("readystatechange");
3032
- if (this.responseType === "" || this.responseType === "text") {
3033
- this.responseText = await response.text();
3034
- this.response = this.responseText;
3035
- } else if (this.responseType === "json") {
3036
- this.response = await response.json();
3037
- this.responseText = JSON.stringify(this.response);
3038
- } else if (this.responseType === "arraybuffer") {
3039
- this.response = await response.arrayBuffer();
3040
- } else if (this.responseType === "blob") {
3041
- this.response = await response.blob();
3042
- }
3043
- this.readyState = XMLHttpRequest.DONE;
3044
- this._triggerEvent("readystatechange");
3045
- this._triggerEvent("load", true);
3046
- this._triggerEvent("loadend", true);
3047
- }).catch(() => {
3048
- if (timeoutId)
3049
- clearTimeout(timeoutId);
3050
- if (this._aborted) {
3051
- this._triggerEvent("abort", true);
3052
- this._triggerEvent("loadend", true);
3053
- return;
3054
- }
3055
- this.readyState = XMLHttpRequest.DONE;
3056
- this._triggerEvent("readystatechange");
3057
- this._triggerEvent("error", true);
3058
- this._triggerEvent("loadend", true);
3059
- });
3060
- }
3061
- abort() {
3062
- this._aborted = true;
3063
- if (this.readyState !== XMLHttpRequest.UNSENT && this.readyState !== XMLHttpRequest.DONE) {
3064
- this.readyState = XMLHttpRequest.UNSENT;
3065
- this._triggerEvent("abort", true);
3066
- this._triggerEvent("loadend", true);
3067
- }
3068
- }
3069
- setRequestHeader(name, value) {
3070
- if (this.readyState !== XMLHttpRequest.OPENED) {
3071
- throw new Error("InvalidStateError: Object state must be OPENED");
3072
- }
3073
- this._requestHeaders.set(name.toLowerCase(), value);
3074
- }
3075
- getResponseHeader(name) {
3076
- return this._responseHeaders.get(name.toLowerCase()) || null;
3077
- }
3078
- getAllResponseHeaders() {
3079
- const headers = [];
3080
- for (const [key, value] of this._responseHeaders) {
3081
- headers.push(`${key}: ${value}`);
3082
- }
3083
- return headers.join(`\r
3084
- `);
3085
- }
3086
- overrideMimeType(_mime) {}
3087
- addEventListener(type, listener) {
3088
- if (!this._eventListeners.has(type)) {
3089
- this._eventListeners.set(type, new Set);
3090
- }
3091
- this._eventListeners.get(type).add(listener);
3092
- }
3093
- removeEventListener(type, listener) {
3094
- const listeners = this._eventListeners.get(type);
3095
- if (listeners) {
3096
- listeners.delete(listener);
3097
- }
3098
- }
3099
- dispatchEvent(event) {
3100
- const listeners = this._eventListeners.get(event.type);
3101
- if (listeners) {
3102
- for (const listener of listeners) {
3103
- listener(event);
3104
- }
3105
- }
3106
- const handler = this[`on${event.type}`];
3107
- if (handler) {
3108
- handler.call(this, event);
3109
- }
3110
- return true;
3111
- }
3112
- _triggerEvent(type, isProgressEvent = false) {
3113
- const event = isProgressEvent ? { type, lengthComputable: false, loaded: 0, total: 0 } : { type };
3114
- this.dispatchEvent(event);
3115
- }
3116
- }
3117
-
3118
- class XMLHttpRequestUpload {
3119
- onprogress = null;
3120
- onload = null;
3121
- onerror = null;
3122
- addEventListener(_type, _listener) {}
3123
- removeEventListener(_type, _listener) {}
3124
- dispatchEvent(_event) {
3125
- return true;
3126
- }
3127
- }
3128
- // src/network/WebSocket.ts
3129
- class VeryHappyWebSocket {
3130
- static CONNECTING = 0 /* CONNECTING */;
3131
- static OPEN = 1 /* OPEN */;
3132
- static CLOSING = 2 /* CLOSING */;
3133
- static CLOSED = 3 /* CLOSED */;
3134
- readyState = 0 /* CONNECTING */;
3135
- url;
3136
- protocol = "";
3137
- extensions = "";
3138
- binaryType = "blob";
3139
- bufferedAmount = 0;
3140
- onopen = null;
3141
- onmessage = null;
3142
- onerror = null;
3143
- onclose = null;
3144
- _ws = null;
3145
- _eventListeners = new Map;
3146
- constructor(url, protocols) {
3147
- this.url = url;
3148
- try {
3149
- this._ws = new WebSocket(url, protocols);
3150
- this._ws.addEventListener("open", (_event) => {
3151
- this.readyState = 1 /* OPEN */;
3152
- this.dispatchEvent({ type: "open" });
3153
- });
3154
- this._ws.addEventListener("message", (event) => {
3155
- const messageEvent = {
3156
- type: "message",
3157
- data: event.data,
3158
- origin: this.url,
3159
- lastEventId: "",
3160
- source: null,
3161
- ports: []
3162
- };
3163
- this.dispatchEvent(messageEvent);
3164
- });
3165
- this._ws.addEventListener("error", (_event) => {
3166
- this.dispatchEvent({ type: "error" });
3167
- });
3168
- this._ws.addEventListener("close", (event) => {
3169
- this.readyState = 3 /* CLOSED */;
3170
- const closeEvent = {
3171
- type: "close",
3172
- code: event.code || 1000,
3173
- reason: event.reason || "",
3174
- wasClean: event.wasClean !== false
3175
- };
3176
- this.dispatchEvent(closeEvent);
3177
- });
3178
- } catch {
3179
- this.readyState = 3 /* CLOSED */;
3180
- setTimeout(() => {
3181
- this.dispatchEvent({ type: "error" });
3182
- }, 0);
3183
- }
3184
- }
3185
- send(data) {
3186
- if (this.readyState !== 1 /* OPEN */) {
3187
- throw new Error(`WebSocket is not open: readyState ${this.readyState}`);
3188
- }
3189
- if (this._ws) {
3190
- if (data instanceof Blob) {
3191
- data.arrayBuffer().then((buffer) => {
3192
- this._ws?.send(buffer);
3193
- });
3194
- } else {
3195
- this._ws.send(data);
3196
- }
3197
- }
3198
- }
3199
- close(code2, reason) {
3200
- if (this.readyState === 2 /* CLOSING */ || this.readyState === 3 /* CLOSED */) {
3201
- return;
3202
- }
3203
- this.readyState = 2 /* CLOSING */;
3204
- if (this._ws) {
3205
- this._ws.close(code2, reason);
3206
- }
3207
- }
3208
- addEventListener(type, listener) {
3209
- if (!this._eventListeners.has(type)) {
3210
- this._eventListeners.set(type, new Set);
3211
- }
3212
- this._eventListeners.get(type).add(listener);
3213
- }
3214
- removeEventListener(type, listener) {
3215
- const listeners = this._eventListeners.get(type);
3216
- if (listeners) {
3217
- listeners.delete(listener);
3218
- }
3219
- }
3220
- dispatchEvent(event) {
3221
- const listeners = this._eventListeners.get(event.type);
3222
- if (listeners) {
3223
- for (const listener of listeners) {
3224
- listener(event);
3225
- }
3226
- }
3227
- const handler = this[`on${event.type}`];
3228
- if (handler) {
3229
- handler.call(this, event);
3230
- }
3231
- return true;
3232
- }
3233
- }
3234
- // src/observers/IntersectionObserver.ts
3235
- class IntersectionObserver {
3236
- root;
3237
- rootMargin;
3238
- thresholds;
3239
- _callback;
3240
- _observedElements = new Set;
3241
- constructor(callback, options = {}) {
3242
- this._callback = callback;
3243
- this.root = options.root || null;
3244
- this.rootMargin = options.rootMargin || "0px";
3245
- if (options.threshold === undefined) {
3246
- this.thresholds = [0];
3247
- } else if (Array.isArray(options.threshold)) {
3248
- this.thresholds = options.threshold;
3249
- } else {
3250
- this.thresholds = [options.threshold];
3251
- }
3252
- }
3253
- observe(target) {
3254
- if (this._observedElements.has(target))
3255
- return;
3256
- this._observedElements.add(target);
3257
- setTimeout(() => {
3258
- if (this._observedElements.has(target)) {
3259
- const entry = this._createEntry(target, true);
3260
- this._callback([entry], this);
3261
- }
3262
- }, 0);
3263
- }
3264
- unobserve(target) {
3265
- this._observedElements.delete(target);
3266
- }
3267
- disconnect() {
3268
- this._observedElements.clear();
3269
- }
3270
- takeRecords() {
3271
- return [];
3272
- }
3273
- _createEntry(target, isIntersecting) {
3274
- const rect = this._getBoundingClientRect(target);
3275
- return {
3276
- boundingClientRect: rect,
3277
- intersectionRatio: isIntersecting ? 1 : 0,
3278
- intersectionRect: isIntersecting ? rect : this._createEmptyRect(),
3279
- isIntersecting,
3280
- rootBounds: this.root ? this._getBoundingClientRect(this.root) : null,
3281
- target,
3282
- time: Date.now()
3283
- };
3284
- }
3285
- _getBoundingClientRect(_element) {
3286
- return {
3287
- x: 0,
3288
- y: 0,
3289
- width: 100,
3290
- height: 100,
3291
- top: 0,
3292
- right: 100,
3293
- bottom: 100,
3294
- left: 0
3295
- };
3296
- }
3297
- _createEmptyRect() {
3298
- return {
3299
- x: 0,
3300
- y: 0,
3301
- width: 0,
3302
- height: 0,
3303
- top: 0,
3304
- right: 0,
3305
- bottom: 0,
3306
- left: 0
3307
- };
3308
- }
3309
- }
3310
- // src/observers/MutationObserver.ts
3311
- class MutationObserver {
3312
- _callback;
3313
- _records = [];
3314
- _observing = false;
3315
- constructor(callback) {
3316
- this._callback = callback;
3317
- }
3318
- observe(_target, _options = {}) {
3319
- this._observing = true;
3320
- }
3321
- disconnect() {
3322
- this._observing = false;
3323
- this._records = [];
3324
- }
3325
- takeRecords() {
3326
- const records = this._records;
3327
- this._records = [];
3328
- return records;
3329
- }
3330
- _addRecord(record) {
3331
- if (!this._observing)
3332
- return;
3333
- this._records.push(record);
3334
- setTimeout(() => {
3335
- if (this._records.length > 0) {
3336
- const records = this.takeRecords();
3337
- this._callback(records, this);
3338
- }
3339
- }, 0);
3340
- }
3341
- }
3342
- // src/observers/ResizeObserver.ts
3343
- class ResizeObserver {
3344
- _callback;
3345
- _observedElements = new Set;
3346
- constructor(callback) {
3347
- this._callback = callback;
3348
- }
3349
- observe(target, _options) {
3350
- if (this._observedElements.has(target))
3351
- return;
3352
- this._observedElements.add(target);
3353
- setTimeout(() => {
3354
- if (this._observedElements.has(target)) {
3355
- const entry = this._createEntry(target);
3356
- this._callback([entry], this);
3357
- }
3358
- }, 0);
3359
- }
3360
- unobserve(target) {
3361
- this._observedElements.delete(target);
3362
- }
3363
- disconnect() {
3364
- this._observedElements.clear();
3365
- }
3366
- _createEntry(target) {
3367
- const rect = this._getContentRect(target);
3368
- const size = {
3369
- inlineSize: rect.width,
3370
- blockSize: rect.height
3371
- };
3372
- return {
3373
- target,
3374
- contentRect: rect,
3375
- borderBoxSize: [size],
3376
- contentBoxSize: [size],
3377
- devicePixelContentBoxSize: [size]
3378
- };
3379
- }
3380
- _getContentRect(_element) {
3381
- return {
3382
- x: 0,
3383
- y: 0,
3384
- width: 100,
3385
- height: 100,
3386
- top: 0,
3387
- right: 100,
3388
- bottom: 100,
3389
- left: 0
3390
- };
3391
- }
3392
- }
3393
- // src/storage/Storage.ts
3394
- class Storage {
3395
- _data = new Map;
3396
- get length() {
3397
- return this._data.size;
3398
- }
3399
- key(index) {
3400
- const keys = Array.from(this._data.keys());
3401
- return keys[index] ?? null;
3402
- }
3403
- getItem(key) {
3404
- return this._data.get(key) ?? null;
3405
- }
3406
- setItem(key, value) {
3407
- this._data.set(key, String(value));
3408
- }
3409
- removeItem(key) {
3410
- this._data.delete(key);
3411
- }
3412
- clear() {
3413
- this._data.clear();
3414
- }
3415
- }
3416
- function createStorage() {
3417
- const storage = new Storage;
3418
- return new Proxy(storage, {
3419
- get(target, prop) {
3420
- if (prop in target || typeof prop === "symbol") {
3421
- return target[prop];
3422
- }
3423
- return target.getItem(prop);
3424
- },
3425
- set(target, prop, value) {
3426
- if (prop in target) {
3427
- target[prop] = value;
3428
- return true;
3429
- }
3430
- target.setItem(prop, value);
3431
- return true;
3432
- },
3433
- deleteProperty(target, prop) {
3434
- target.removeItem(prop);
3435
- return true;
3436
- },
3437
- has(target, prop) {
3438
- return prop in target || target.getItem(prop) !== null;
3439
- }
3440
- });
3441
- }
3442
- // src/timers/TimerManager.ts
3443
- class TimerManager {
3444
- _timeouts = new Map;
3445
- _intervals = new Map;
3446
- _animationFrames = new Map;
3447
- _nextId = 1;
3448
- _aborted = false;
3449
- setTimeout(callback, delay = 0, ...args) {
3450
- if (this._aborted)
3451
- return -1;
3452
- const id = this._nextId++;
3453
- const timeout = globalThis.setTimeout(() => {
3454
- this._timeouts.delete(id);
3455
- if (!this._aborted) {
3456
- callback(...args);
3457
- }
3458
- }, delay);
3459
- this._timeouts.set(id, timeout);
3460
- return id;
3461
- }
3462
- clearTimeout(id) {
3463
- const timeout = this._timeouts.get(id);
3464
- if (timeout) {
3465
- globalThis.clearTimeout(timeout);
3466
- this._timeouts.delete(id);
3467
- }
3468
- }
3469
- setInterval(callback, delay = 0, ...args) {
3470
- if (this._aborted)
3471
- return -1;
3472
- const id = this._nextId++;
3473
- const interval = globalThis.setInterval(() => {
3474
- if (!this._aborted) {
3475
- callback(...args);
3476
- }
3477
- }, delay);
3478
- this._intervals.set(id, interval);
3479
- return id;
3480
- }
3481
- clearInterval(id) {
3482
- const interval = this._intervals.get(id);
3483
- if (interval) {
3484
- globalThis.clearInterval(interval);
3485
- this._intervals.delete(id);
3486
- }
3487
- }
3488
- requestAnimationFrame(callback) {
3489
- if (this._aborted)
3490
- return -1;
3491
- const id = this._nextId++;
3492
- const timeout = globalThis.setTimeout(() => {
3493
- this._animationFrames.delete(id);
3494
- if (!this._aborted) {
3495
- callback(Date.now());
3496
- }
3497
- }, 16);
3498
- this._animationFrames.set(id, timeout);
3499
- return id;
3500
- }
3501
- cancelAnimationFrame(id) {
3502
- const timeout = this._animationFrames.get(id);
3503
- if (timeout) {
3504
- globalThis.clearTimeout(timeout);
3505
- this._animationFrames.delete(id);
3506
- }
3507
- }
3508
- hasPendingTimers() {
3509
- return this._timeouts.size > 0 || this._animationFrames.size > 0;
3510
- }
3511
- async waitForTimers() {
3512
- while (this._timeouts.size > 0 || this._animationFrames.size > 0) {
3513
- await new Promise((resolve) => globalThis.setTimeout(resolve, 10));
3514
- }
3515
- }
3516
- clearAll() {
3517
- for (const timeout of this._timeouts.values()) {
3518
- globalThis.clearTimeout(timeout);
3519
- }
3520
- this._timeouts.clear();
3521
- for (const interval of this._intervals.values()) {
3522
- globalThis.clearInterval(interval);
3523
- }
3524
- this._intervals.clear();
3525
- for (const timeout of this._animationFrames.values()) {
3526
- globalThis.clearTimeout(timeout);
3527
- }
3528
- this._animationFrames.clear();
3529
- }
3530
- abort() {
3531
- this._aborted = true;
3532
- this.clearAll();
3533
- }
3534
- }
3535
- // src/webcomponents/CustomElementRegistry.ts
3536
- class CustomElementRegistry {
3537
- _definitions = new Map;
3538
- _whenDefinedPromises = new Map;
3539
- define(name, constructor, _options) {
3540
- if (!/^[a-z][\\.0-9_a-z]*-[\\.0-9_a-z]*$/.test(name)) {
3541
- throw new Error(`Failed to execute 'define' on 'CustomElementRegistry': "${name}" is not a valid custom element name`);
3542
- }
3543
- if (this._definitions.has(name)) {
3544
- throw new Error(`Failed to execute 'define' on 'CustomElementRegistry': the name "${name}" has already been used`);
3545
- }
3546
- this._definitions.set(name, constructor);
3547
- const promises = this._whenDefinedPromises.get(name);
3548
- if (promises) {
3549
- promises.forEach((p) => p.resolve());
3550
- this._whenDefinedPromises.delete(name);
3551
- }
3552
- }
3553
- get(name) {
3554
- return this._definitions.get(name);
3555
- }
3556
- whenDefined(name) {
3557
- if (this._definitions.has(name)) {
3558
- return Promise.resolve(this._definitions.get(name));
3559
- }
3560
- return new Promise((resolve, reject) => {
3561
- if (!this._whenDefinedPromises.has(name)) {
3562
- this._whenDefinedPromises.set(name, []);
3563
- }
3564
- this._whenDefinedPromises.get(name).push({
3565
- resolve: () => resolve(this._definitions.get(name)),
3566
- reject
3567
- });
3568
- });
3569
- }
3570
- upgrade(_root) {}
3571
- }
3572
-
3573
- class HTMLElement extends VirtualElement {
3574
- static get observedAttributes() {
3575
- return [];
3576
- }
3577
- }
3578
- // src/window/Window.ts
3579
- class Window {
3580
- document;
3581
- happyDOM;
3582
- console;
3583
- navigator;
3584
- customElements = new CustomElementRegistry;
3585
- HTMLElement = HTMLElement;
3586
- localStorage;
3587
- sessionStorage;
3588
- fetch = globalThis.fetch.bind(globalThis);
3589
- Request = globalThis.Request;
3590
- Response = globalThis.Response;
3591
- Headers = globalThis.Headers;
3592
- FormData = globalThis.FormData;
3593
- URL = globalThis.URL;
3594
- URLSearchParams = globalThis.URLSearchParams;
3595
- CustomEvent = CustomEvent;
3596
- MutationObserver = MutationObserver;
3597
- IntersectionObserver = IntersectionObserver;
3598
- ResizeObserver = ResizeObserver;
3599
- XMLHttpRequest = XMLHttpRequest;
3600
- WebSocket = VeryHappyWebSocket;
3601
- File = VeryHappyFile;
3602
- FileReader = VeryHappyFileReader;
3603
- FileList = VeryHappyFileList;
3604
- performance = new Performance;
3605
- Notification = Notification;
3606
- DataTransfer = DataTransfer;
3607
- _location;
3608
- _settings;
3609
- _width;
3610
- _height;
3611
- _timerManager;
3612
- constructor(options = {}) {
3613
- const {
3614
- url = "about:blank",
3615
- width = 1024,
3616
- height = 768,
3617
- console: consoleInstance,
3618
- settings = {}
3619
- } = options;
3620
- this._width = width;
3621
- this._height = height;
3622
- this._settings = {
3623
- navigator: {
3624
- userAgent: settings.navigator?.userAgent || "Mozilla/5.0 (X11; Linux x64) AppleWebKit/537.36 (KHTML, like Gecko) VeryHappyDOM/1.0.0"
3625
- },
3626
- device: {
3627
- prefersColorScheme: settings.device?.prefersColorScheme || "light"
3628
- }
3629
- };
3630
- this.console = consoleInstance || globalThis.console;
3631
- this.navigator = new Navigator;
3632
- this.localStorage = createStorage();
3633
- this.sessionStorage = createStorage();
3634
- this._timerManager = new TimerManager;
3635
- this.document = new VirtualDocument;
3636
- this._location = this._createLocation(url);
3637
- const { DetachedWindowAPI: DetachedWindowAPI2 } = __toCommonJS(exports_DetachedWindowAPI);
3638
- this.happyDOM = new DetachedWindowAPI2(this);
3639
- }
3640
- get location() {
3641
- return this._location;
3642
- }
3643
- set location(url) {
3644
- const urlString = typeof url === "string" ? url : url.href;
3645
- this._location = this._createLocation(urlString);
3646
- }
3647
- get innerWidth() {
3648
- return this._width;
3649
- }
3650
- get innerHeight() {
3651
- return this._height;
3652
- }
3653
- get outerWidth() {
3654
- return this._width;
3655
- }
3656
- get outerHeight() {
3657
- return this._height;
3658
- }
3659
- _createLocation(url) {
3660
- try {
3661
- const parsed = new URL(url);
3662
- return {
3663
- href: parsed.href,
3664
- origin: parsed.origin,
3665
- protocol: parsed.protocol,
3666
- host: parsed.host,
3667
- hostname: parsed.hostname,
3668
- port: parsed.port,
3669
- pathname: parsed.pathname,
3670
- search: parsed.search,
3671
- hash: parsed.hash,
3672
- assign: (url2) => {
3673
- this.location = url2;
3674
- },
3675
- replace: (url2) => {
3676
- this.location = url2;
3677
- },
3678
- reload: () => {},
3679
- toString: () => parsed.href
3680
- };
3681
- } catch {
3682
- return {
3683
- href: url,
3684
- origin: "",
3685
- protocol: "",
3686
- host: "",
3687
- hostname: "",
3688
- port: "",
3689
- pathname: "",
3690
- search: "",
3691
- hash: "",
3692
- assign: (url2) => {
3693
- this.location = url2;
3694
- },
3695
- replace: (url2) => {
3696
- this.location = url2;
3697
- },
3698
- reload: () => {},
3699
- toString: () => url
3700
- };
3701
- }
3702
- }
3703
- get settings() {
3704
- return this._settings;
3705
- }
3706
- setTimeout(callback, delay, ...args) {
3707
- return this._timerManager.setTimeout(callback, delay, ...args);
3708
- }
3709
- clearTimeout(id) {
3710
- this._timerManager.clearTimeout(id);
3711
- }
3712
- setInterval(callback, delay, ...args) {
3713
- return this._timerManager.setInterval(callback, delay, ...args);
3714
- }
3715
- clearInterval(id) {
3716
- this._timerManager.clearInterval(id);
3717
- }
3718
- requestAnimationFrame(callback) {
3719
- return this._timerManager.requestAnimationFrame(callback);
3720
- }
3721
- cancelAnimationFrame(id) {
3722
- this._timerManager.cancelAnimationFrame(id);
3723
- }
3724
- _getTimerManager() {
3725
- return this._timerManager;
3726
- }
3727
- }
3728
-
3729
- // src/window/GlobalWindow.ts
3730
- class GlobalWindow extends Window {
3731
- constructor(options = {}) {
3732
- super(options);
3733
- }
3734
- setGlobal(key, value) {
3735
- globalThis[key] = value;
3736
- }
3737
- getGlobal(key) {
3738
- return globalThis[key];
3739
- }
3740
- async close() {
3741
- await this.happyDOM.close();
3742
- }
3743
- }
3744
- export {
3745
- querySelectorEngine,
3746
- querySelectorAllEngine,
3747
- parseHTML,
3748
- matchesSimpleSelector,
3749
- matchesPseudoClass,
3750
- matchesAttributeSelector,
3751
- createStorage,
3752
- createDocument,
3753
- XPathResultType,
3754
- XPathResult,
3755
- XPathEvaluator,
3756
- XMLHttpRequest,
3757
- Window,
3758
- VeryHappyWebSocket as WebSocket,
3759
- VirtualTextNode,
3760
- VirtualEvent,
3761
- VirtualElement,
3762
- VirtualDocument,
3763
- VirtualCommentNode,
3764
- TimerManager,
3765
- Storage,
3766
- ShadowRoot,
3767
- ResizeObserver,
3768
- RequestInterceptor,
3769
- Performance,
3770
- Notification,
3771
- Navigator,
3772
- MutationObserver,
3773
- IntersectionObserver,
3774
- HTMLElement,
3775
- GlobalWindow,
3776
- Geolocation,
3777
- VeryHappyFileReader as FileReader,
3778
- VeryHappyFileList as FileList,
3779
- VeryHappyFile as File,
3780
- EnhancedConsole,
3781
- DetachedWindowAPI,
3782
- DataTransfer,
3783
- CustomEvent,
3784
- CustomElementRegistry,
3785
- CookieSameSiteEnum,
3786
- CookieContainer,
3787
- Clipboard,
3788
- BrowserPage,
3789
- BrowserFrame,
3790
- BrowserContext,
3791
- Browser
3792
- };
57
+ ${284+_.length}
58
+ %%EOF`}_escapeXML(_){return _.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}}var j_;((K)=>{K.none="None";K.lax="Lax";K.strict="Strict"})(j_||={});class u{_cookies=[];addCookies(_){for(let G of _)this._cookies=this._cookies.filter(($)=>!($.key===G.key&&($.domain||new URL($.originURL).hostname)===(G.domain||new URL(G.originURL).hostname)&&($.path||"/")===(G.path||"/"))),this._cookies.push({...G,value:G.value||"",domain:G.domain||new URL(G.originURL).hostname,path:G.path||"/",expires:G.expires,httpOnly:G.httpOnly||!1,secure:G.secure||!1,sameSite:G.sameSite||"Lax"})}getCookies(_,G=!1){let $=new URL(_),K=$.hostname,J=$.pathname,Q=$.protocol==="https:",Y=new Date;return this._cookies.filter((Z)=>{if(Z.expires&&Z.expires<Y)return!1;if(Z.httpOnly&&!G)return!1;if(Z.secure&&!Q)return!1;let z=Z.domain||new URL(Z.originURL).hostname;if(!K.endsWith(z)&&K!==z)return!1;let U=Z.path||"/";if(!J.startsWith(U))return!1;return!0})}clearCookies(){this._cookies=[]}}class E{cookieContainer;responseCache=new Map;preflightResponseCache=new Map;_browser;_pages=[];constructor(_){this._browser=_,this.cookieContainer=new u}get pages(){return this._pages}get browser(){return this._browser}async close(){await Promise.all(this._pages.map((_)=>_.close())),this._pages=[],this.cookieContainer.clearCookies(),this.responseCache.clear(),this.preflightResponseCache.clear()}async waitUntilComplete(){await Promise.all(this._pages.map((_)=>_.waitUntilComplete()))}async abort(){await Promise.all(this._pages.map((_)=>_.abort()))}newPage(){let _=new h(this);return this._pages.push(_),_}_removePage(_){let G=this._pages.indexOf(_);if(G!==-1)this._pages.splice(G,1)}}class D_{console;defaultContext;_contexts=[];_settings;constructor(_={}){let{settings:G={},console:$}=_;this.console=$||globalThis.console,this._settings={navigator:{userAgent:G.navigator?.userAgent||"Mozilla/5.0 (X11; Linux x64) AppleWebKit/537.36 (KHTML, like Gecko) VeryHappyDOM/1.0.0"},device:{prefersColorScheme:G.device?.prefersColorScheme||"light"}},this.defaultContext=new E(this),this._contexts.push(this.defaultContext)}get contexts(){return this._contexts}get settings(){return this._settings}async close(){await Promise.all(this._contexts.map((_)=>_.close())),this._contexts=[]}async waitUntilComplete(){await Promise.all(this._contexts.map((_)=>_.waitUntilComplete()))}async abort(){await Promise.all(this._contexts.map((_)=>_.abort()))}newIncognitoContext(){let _=new E(this);return this._contexts.push(_),_}newPage(){return this.defaultContext.newPage()}}class m extends W{detail;constructor(_,G={}){super(_,G);this.detail=G.detail}}class I{static UNSENT=0;static OPENED=1;static HEADERS_RECEIVED=2;static LOADING=3;static DONE=4;readyState=I.UNSENT;response=null;responseText="";responseType="";responseURL="";responseXML=null;status=0;statusText="";timeout=0;upload=new f_;withCredentials=!1;onreadystatechange=null;onload=null;onerror=null;onabort=null;onloadstart=null;onloadend=null;onprogress=null;ontimeout=null;_method="";_url="";_requestHeaders=new Map;_responseHeaders=new Map;_aborted=!1;_eventListeners=new Map;constructor(){}open(_,G,$=!0,K,J){this._method=_.toUpperCase(),this._url=G,this.readyState=I.OPENED,this._triggerEvent("readystatechange")}send(_){if(this.readyState!==I.OPENED)throw Error("InvalidStateError: Object state must be OPENED");this._triggerEvent("loadstart",!0);let G={};for(let[Q,Y]of this._requestHeaders)G[Q]=Y;let $={method:this._method,headers:G,body:_,credentials:this.withCredentials?"include":"same-origin"},K=new AbortController,J=null;if(this.timeout>0)J=setTimeout(()=>{K.abort(),this._triggerEvent("timeout",!0)},this.timeout);fetch(this._url,{...$,signal:K.signal}).then(async(Q)=>{if(J)clearTimeout(J);if(this._aborted)return;if(this.status=Q.status,this.statusText=Q.statusText,this.responseURL=Q.url,Q.headers.forEach((Y,Z)=>{this._responseHeaders.set(Z.toLowerCase(),Y)}),this.readyState=I.HEADERS_RECEIVED,this._triggerEvent("readystatechange"),this.readyState=I.LOADING,this._triggerEvent("readystatechange"),this.responseType===""||this.responseType==="text")this.responseText=await Q.text(),this.response=this.responseText;else if(this.responseType==="json")this.response=await Q.json(),this.responseText=JSON.stringify(this.response);else if(this.responseType==="arraybuffer")this.response=await Q.arrayBuffer();else if(this.responseType==="blob")this.response=await Q.blob();this.readyState=I.DONE,this._triggerEvent("readystatechange"),this._triggerEvent("load",!0),this._triggerEvent("loadend",!0)}).catch(()=>{if(J)clearTimeout(J);if(this._aborted){this._triggerEvent("abort",!0),this._triggerEvent("loadend",!0);return}this.readyState=I.DONE,this._triggerEvent("readystatechange"),this._triggerEvent("error",!0),this._triggerEvent("loadend",!0)})}abort(){if(this._aborted=!0,this.readyState!==I.UNSENT&&this.readyState!==I.DONE)this.readyState=I.UNSENT,this._triggerEvent("abort",!0),this._triggerEvent("loadend",!0)}setRequestHeader(_,G){if(this.readyState!==I.OPENED)throw Error("InvalidStateError: Object state must be OPENED");this._requestHeaders.set(_.toLowerCase(),G)}getResponseHeader(_){return this._responseHeaders.get(_.toLowerCase())||null}getAllResponseHeaders(){let _=[];for(let[G,$]of this._responseHeaders)_.push(`${G}: ${$}`);return _.join(`\r
59
+ `)}overrideMimeType(_){}addEventListener(_,G){if(!this._eventListeners.has(_))this._eventListeners.set(_,new Set);this._eventListeners.get(_).add(G)}removeEventListener(_,G){let $=this._eventListeners.get(_);if($)$.delete(G)}dispatchEvent(_){let G=this._eventListeners.get(_.type);if(G)for(let K of G)K(_);let $=this[`on${_.type}`];if($)$.call(this,_);return!0}_triggerEvent(_,G=!1){let $=G?{type:_,lengthComputable:!1,loaded:0,total:0}:{type:_};this.dispatchEvent($)}}class f_{onprogress=null;onload=null;onerror=null;addEventListener(_,G){}removeEventListener(_,G){}dispatchEvent(_){return!0}}class i{static CONNECTING=0;static OPEN=1;static CLOSING=2;static CLOSED=3;readyState=0;url;protocol="";extensions="";binaryType="blob";bufferedAmount=0;onopen=null;onmessage=null;onerror=null;onclose=null;_ws=null;_eventListeners=new Map;constructor(_,G){this.url=_;try{this._ws=new WebSocket(_,G),this._ws.addEventListener("open",($)=>{this.readyState=1,this.dispatchEvent({type:"open"})}),this._ws.addEventListener("message",($)=>{let K={type:"message",data:$.data,origin:this.url,lastEventId:"",source:null,ports:[]};this.dispatchEvent(K)}),this._ws.addEventListener("error",($)=>{this.dispatchEvent({type:"error"})}),this._ws.addEventListener("close",($)=>{this.readyState=3;let K={type:"close",code:$.code||1000,reason:$.reason||"",wasClean:$.wasClean!==!1};this.dispatchEvent(K)})}catch{this.readyState=3,setTimeout(()=>{this.dispatchEvent({type:"error"})},0)}}send(_){if(this.readyState!==1)throw Error(`WebSocket is not open: readyState ${this.readyState}`);if(this._ws)if(_ instanceof Blob)_.arrayBuffer().then((G)=>{this._ws?.send(G)});else this._ws.send(_)}close(_,G){if(this.readyState===2||this.readyState===3)return;if(this.readyState=2,this._ws)this._ws.close(_,G)}addEventListener(_,G){if(!this._eventListeners.has(_))this._eventListeners.set(_,new Set);this._eventListeners.get(_).add(G)}removeEventListener(_,G){let $=this._eventListeners.get(_);if($)$.delete(G)}dispatchEvent(_){let G=this._eventListeners.get(_.type);if(G)for(let K of G)K(_);let $=this[`on${_.type}`];if($)$.call(this,_);return!0}}class d{root;rootMargin;thresholds;_callback;_observedElements=new Set;constructor(_,G={}){if(this._callback=_,this.root=G.root||null,this.rootMargin=G.rootMargin||"0px",G.threshold===void 0)this.thresholds=[0];else if(Array.isArray(G.threshold))this.thresholds=G.threshold;else this.thresholds=[G.threshold]}observe(_){if(this._observedElements.has(_))return;this._observedElements.add(_),setTimeout(()=>{if(this._observedElements.has(_)){let G=this._createEntry(_,!0);this._callback([G],this)}},0)}unobserve(_){this._observedElements.delete(_)}disconnect(){this._observedElements.clear()}takeRecords(){return[]}_createEntry(_,G){let $=this._getBoundingClientRect(_);return{boundingClientRect:$,intersectionRatio:G?1:0,intersectionRect:G?$:this._createEmptyRect(),isIntersecting:G,rootBounds:this.root?this._getBoundingClientRect(this.root):null,target:_,time:Date.now()}}_getBoundingClientRect(_){return{x:0,y:0,width:100,height:100,top:0,right:100,bottom:100,left:0}}_createEmptyRect(){return{x:0,y:0,width:0,height:0,top:0,right:0,bottom:0,left:0}}}class c{_callback;_records=[];_observing=!1;constructor(_){this._callback=_}observe(_,G={}){this._observing=!0}disconnect(){this._observing=!1,this._records=[]}takeRecords(){let _=this._records;return this._records=[],_}_addRecord(_){if(!this._observing)return;this._records.push(_),setTimeout(()=>{if(this._records.length>0){let G=this.takeRecords();this._callback(G,this)}},0)}}class p{_callback;_observedElements=new Set;constructor(_){this._callback=_}observe(_,G){if(this._observedElements.has(_))return;this._observedElements.add(_),setTimeout(()=>{if(this._observedElements.has(_)){let $=this._createEntry(_);this._callback([$],this)}},0)}unobserve(_){this._observedElements.delete(_)}disconnect(){this._observedElements.clear()}_createEntry(_){let G=this._getContentRect(_),$={inlineSize:G.width,blockSize:G.height};return{target:_,contentRect:G,borderBoxSize:[$],contentBoxSize:[$],devicePixelContentBoxSize:[$]}}_getContentRect(_){return{x:0,y:0,width:100,height:100,top:0,right:100,bottom:100,left:0}}}class Q_{_data=new Map;get length(){return this._data.size}key(_){return Array.from(this._data.keys())[_]??null}getItem(_){return this._data.get(_)??null}setItem(_,G){this._data.set(_,String(G))}removeItem(_){this._data.delete(_)}clear(){this._data.clear()}}function s(){let _=new Q_;return new Proxy(_,{get(G,$){if($ in G||typeof $==="symbol")return G[$];return G.getItem($)},set(G,$,K){if($ in G)return G[$]=K,!0;return G.setItem($,K),!0},deleteProperty(G,$){return G.removeItem($),!0},has(G,$){return $ in G||G.getItem($)!==null}})}class a{_timeouts=new Map;_intervals=new Map;_animationFrames=new Map;_nextId=1;_aborted=!1;setTimeout(_,G=0,...$){if(this._aborted)return-1;let K=this._nextId++,J=globalThis.setTimeout(()=>{if(this._timeouts.delete(K),!this._aborted)_(...$)},G);return this._timeouts.set(K,J),K}clearTimeout(_){let G=this._timeouts.get(_);if(G)globalThis.clearTimeout(G),this._timeouts.delete(_)}setInterval(_,G=0,...$){if(this._aborted)return-1;let K=this._nextId++,J=globalThis.setInterval(()=>{if(!this._aborted)_(...$)},G);return this._intervals.set(K,J),K}clearInterval(_){let G=this._intervals.get(_);if(G)globalThis.clearInterval(G),this._intervals.delete(_)}requestAnimationFrame(_){if(this._aborted)return-1;let G=this._nextId++,$=globalThis.setTimeout(()=>{if(this._animationFrames.delete(G),!this._aborted)_(Date.now())},16);return this._animationFrames.set(G,$),G}cancelAnimationFrame(_){let G=this._animationFrames.get(_);if(G)globalThis.clearTimeout(G),this._animationFrames.delete(_)}hasPendingTimers(){return this._timeouts.size>0||this._animationFrames.size>0}async waitForTimers(){while(this._timeouts.size>0||this._animationFrames.size>0)await new Promise((_)=>globalThis.setTimeout(_,10))}clearAll(){for(let _ of this._timeouts.values())globalThis.clearTimeout(_);this._timeouts.clear();for(let _ of this._intervals.values())globalThis.clearInterval(_);this._intervals.clear();for(let _ of this._animationFrames.values())globalThis.clearTimeout(_);this._animationFrames.clear()}abort(){this._aborted=!0,this.clearAll()}}class o{_definitions=new Map;_whenDefinedPromises=new Map;define(_,G,$){if(!/^[a-z][\\.0-9_a-z]*-[\\.0-9_a-z]*$/.test(_))throw Error(`Failed to execute 'define' on 'CustomElementRegistry': "${_}" is not a valid custom element name`);if(this._definitions.has(_))throw Error(`Failed to execute 'define' on 'CustomElementRegistry': the name "${_}" has already been used`);this._definitions.set(_,G);let K=this._whenDefinedPromises.get(_);if(K)K.forEach((J)=>J.resolve()),this._whenDefinedPromises.delete(_)}get(_){return this._definitions.get(_)}whenDefined(_){if(this._definitions.has(_))return Promise.resolve(this._definitions.get(_));return new Promise((G,$)=>{if(!this._whenDefinedPromises.has(_))this._whenDefinedPromises.set(_,[]);this._whenDefinedPromises.get(_).push({resolve:()=>G(this._definitions.get(_)),reject:$})})}upgrade(_){}}class n extends A{static get observedAttributes(){return[]}}class r{document;happyDOM;console;navigator;customElements=new o;HTMLElement=n;localStorage;sessionStorage;fetch=globalThis.fetch.bind(globalThis);Request=globalThis.Request;Response=globalThis.Response;Headers=globalThis.Headers;FormData=globalThis.FormData;URL=globalThis.URL;URLSearchParams=globalThis.URLSearchParams;CustomEvent=m;MutationObserver=c;IntersectionObserver=d;ResizeObserver=p;XMLHttpRequest=I;WebSocket=i;File=g;FileReader=D;FileList=R;performance=new H;Notification=V;DataTransfer=N;_location;_settings;_width;_height;_timerManager;constructor(_={}){let{url:G="about:blank",width:$=1024,height:K=768,console:J,settings:Q={}}=_;this._width=$,this._height=K,this._settings={navigator:{userAgent:Q.navigator?.userAgent||"Mozilla/5.0 (X11; Linux x64) AppleWebKit/537.36 (KHTML, like Gecko) VeryHappyDOM/1.0.0"},device:{prefersColorScheme:Q.device?.prefersColorScheme||"light"}},this.console=J||globalThis.console,this.navigator=new S,this.localStorage=s(),this.sessionStorage=s(),this._timerManager=new a,this.document=new F,this._location=this._createLocation(G);let{DetachedWindowAPI:Y}=T_(B_);this.happyDOM=new Y(this)}get location(){return this._location}set location(_){let G=typeof _==="string"?_:_.href;this._location=this._createLocation(G)}get innerWidth(){return this._width}get innerHeight(){return this._height}get outerWidth(){return this._width}get outerHeight(){return this._height}_createLocation(_){try{let G=new URL(_);return{href:G.href,origin:G.origin,protocol:G.protocol,host:G.host,hostname:G.hostname,port:G.port,pathname:G.pathname,search:G.search,hash:G.hash,assign:($)=>{this.location=$},replace:($)=>{this.location=$},reload:()=>{},toString:()=>G.href}}catch{return{href:_,origin:"",protocol:"",host:"",hostname:"",port:"",pathname:"",search:"",hash:"",assign:(G)=>{this.location=G},replace:(G)=>{this.location=G},reload:()=>{},toString:()=>_}}}get settings(){return this._settings}setTimeout(_,G,...$){return this._timerManager.setTimeout(_,G,...$)}clearTimeout(_){this._timerManager.clearTimeout(_)}setInterval(_,G,...$){return this._timerManager.setInterval(_,G,...$)}clearInterval(_){this._timerManager.clearInterval(_)}requestAnimationFrame(_){return this._timerManager.requestAnimationFrame(_)}cancelAnimationFrame(_){this._timerManager.cancelAnimationFrame(_)}_getTimerManager(){return this._timerManager}}class I_ extends r{constructor(_={}){super(_)}setGlobal(_,G){globalThis[_]=G}getGlobal(_){return globalThis[_]}async close(){await this.happyDOM.close()}}export{__ as querySelectorEngine,X as querySelectorAllEngine,w as parseHTML,L as matchesSimpleSelector,O_ as matchesPseudoClass,U_ as matchesAttributeSelector,s as createStorage,C_ as createDocument,K_ as XPathResultType,v as XPathResult,y as XPathEvaluator,I as XMLHttpRequest,r as Window,i as WebSocket,P as VirtualTextNode,W as VirtualEvent,A as VirtualElement,F as VirtualDocument,C as VirtualCommentNode,a as TimerManager,Q_ as Storage,k as ShadowRoot,p as ResizeObserver,x as RequestInterceptor,H as Performance,V as Notification,S as Navigator,c as MutationObserver,d as IntersectionObserver,n as HTMLElement,I_ as GlobalWindow,M as Geolocation,D as FileReader,R as FileList,g as File,z_ as EnhancedConsole,Y_ as DetachedWindowAPI,N as DataTransfer,m as CustomEvent,o as CustomElementRegistry,j_ as CookieSameSiteEnum,u as CookieContainer,e as Clipboard,h as BrowserPage,BrowserFrame,E as BrowserContext,D_ as Browser};