@luckylillia-dev/plugin-aiimgdetector 0.0.0-stage → 1.0.5

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 (99) hide show
  1. package/README.md +2 -2
  2. package/assets/demo.png +0 -0
  3. package/assets/icon.svg +15 -0
  4. package/assets/synthid-login-check.jpg +0 -0
  5. package/docs/details.md +45 -0
  6. package/docs/publishing.md +66 -0
  7. package/docs/synthid.md +80 -0
  8. package/lib/image.js +90 -0
  9. package/lib/index.js +207 -0
  10. package/lib/provenance.js +21 -0
  11. package/lib/synthid-auth.js +100 -0
  12. package/lib/synthid-browser.js +451 -0
  13. package/lib/synthid-http-runtime/chromium-css-property-catalog.mjs +7 -0
  14. package/lib/synthid-http-runtime/complete-protocol.mjs +88 -0
  15. package/lib/synthid-http-runtime/entry.d.mts +41 -0
  16. package/lib/synthid-http-runtime/entry.mjs +6 -0
  17. package/lib/synthid-http-runtime/event-listener-diagnostics.mjs +141 -0
  18. package/lib/synthid-http-runtime/independent-request-reference.mjs +49 -0
  19. package/lib/synthid-http-runtime/jsdom-event-clock-compat.mjs +76 -0
  20. package/lib/synthid-http-runtime/lifecycle-client.mjs +165 -0
  21. package/lib/synthid-http-runtime/lifecycle-web-session.mjs +114 -0
  22. package/lib/synthid-http-runtime/lifecycle-worker.mjs +363 -0
  23. package/lib/synthid-http-runtime/node-platform-failure-diagnostics.mjs +108 -0
  24. package/lib/synthid-http-runtime/realm-activation-diagnostic.js +31 -0
  25. package/lib/synthid-http-runtime/realm-focus-diagnostic.js +9 -0
  26. package/lib/synthid-http-runtime/realm-init.js +34 -0
  27. package/lib/synthid-http-runtime/realm-pointer-diagnostic.js +49 -0
  28. package/lib/synthid-http-runtime/runtime-anchor-href-translate.mjs +242 -0
  29. package/lib/synthid-http-runtime/runtime-child-web-compat.mjs +103 -0
  30. package/lib/synthid-http-runtime/runtime-chrome-csi.mjs +216 -0
  31. package/lib/synthid-http-runtime/runtime-clock-precision-control.mjs +51 -0
  32. package/lib/synthid-http-runtime/runtime-css-properties-compat.mjs +165 -0
  33. package/lib/synthid-http-runtime/runtime-detached-frame-compat.mjs +214 -0
  34. package/lib/synthid-http-runtime/runtime-javascript-bindings.mjs +69 -0
  35. package/lib/synthid-http-runtime/runtime-navigator-compat.mjs +99 -0
  36. package/lib/synthid-http-runtime/runtime-permissions-binding.mjs +64 -0
  37. package/lib/synthid-http-runtime/runtime-permissions-control.mjs +143 -0
  38. package/lib/synthid-http-runtime/runtime-web-compat.mjs +639 -0
  39. package/lib/synthid-http-runtime/runtime-webidl-callable-control.mjs +151 -0
  40. package/lib/synthid-http-runtime/runtime-webidl-realm-compat.mjs +132 -0
  41. package/lib/synthid-http-runtime/runtime-window-state-compat.mjs +128 -0
  42. package/lib/synthid-http-runtime/scripting-parser.mjs +13 -0
  43. package/lib/synthid-http-runtime/web-session.mjs +64 -0
  44. package/lib/synthid-http-runtime/webidl-brand-errors-preload.mjs +49 -0
  45. package/lib/synthid-http-runtime/webidl-callable-source-catalog.mjs +4491 -0
  46. package/lib/synthid-http-runtime/webidl-realm-catalog.mjs +124 -0
  47. package/lib/synthid-http.js +314 -0
  48. package/lib/synthid-manual.js +365 -0
  49. package/lib/synthid-page.js +101 -0
  50. package/lib/synthid-result.js +189 -0
  51. package/lib/synthid.js +540 -0
  52. package/lib/vision.js +41 -0
  53. package/package.json +84 -4
  54. package/src/image.ts +74 -0
  55. package/src/index.ts +203 -0
  56. package/src/provenance.ts +40 -0
  57. package/src/synthid-auth.ts +83 -0
  58. package/src/synthid-browser.ts +426 -0
  59. package/src/synthid-http-runtime/chromium-css-property-catalog.mjs +7 -0
  60. package/src/synthid-http-runtime/complete-protocol.mjs +88 -0
  61. package/src/synthid-http-runtime/entry.d.mts +41 -0
  62. package/src/synthid-http-runtime/entry.mjs +6 -0
  63. package/src/synthid-http-runtime/event-listener-diagnostics.mjs +141 -0
  64. package/src/synthid-http-runtime/independent-request-reference.mjs +49 -0
  65. package/src/synthid-http-runtime/jsdom-event-clock-compat.mjs +76 -0
  66. package/src/synthid-http-runtime/lifecycle-client.mjs +165 -0
  67. package/src/synthid-http-runtime/lifecycle-web-session.mjs +114 -0
  68. package/src/synthid-http-runtime/lifecycle-worker.mjs +363 -0
  69. package/src/synthid-http-runtime/node-platform-failure-diagnostics.mjs +108 -0
  70. package/src/synthid-http-runtime/realm-activation-diagnostic.js +31 -0
  71. package/src/synthid-http-runtime/realm-focus-diagnostic.js +9 -0
  72. package/src/synthid-http-runtime/realm-init.js +34 -0
  73. package/src/synthid-http-runtime/realm-pointer-diagnostic.js +49 -0
  74. package/src/synthid-http-runtime/runtime-anchor-href-translate.mjs +242 -0
  75. package/src/synthid-http-runtime/runtime-child-web-compat.mjs +103 -0
  76. package/src/synthid-http-runtime/runtime-chrome-csi.mjs +216 -0
  77. package/src/synthid-http-runtime/runtime-clock-precision-control.mjs +51 -0
  78. package/src/synthid-http-runtime/runtime-css-properties-compat.mjs +165 -0
  79. package/src/synthid-http-runtime/runtime-detached-frame-compat.mjs +214 -0
  80. package/src/synthid-http-runtime/runtime-javascript-bindings.mjs +69 -0
  81. package/src/synthid-http-runtime/runtime-navigator-compat.mjs +99 -0
  82. package/src/synthid-http-runtime/runtime-permissions-binding.mjs +64 -0
  83. package/src/synthid-http-runtime/runtime-permissions-control.mjs +143 -0
  84. package/src/synthid-http-runtime/runtime-web-compat.mjs +639 -0
  85. package/src/synthid-http-runtime/runtime-webidl-callable-control.mjs +151 -0
  86. package/src/synthid-http-runtime/runtime-webidl-realm-compat.mjs +132 -0
  87. package/src/synthid-http-runtime/runtime-window-state-compat.mjs +128 -0
  88. package/src/synthid-http-runtime/scripting-parser.mjs +13 -0
  89. package/src/synthid-http-runtime/web-session.mjs +64 -0
  90. package/src/synthid-http-runtime/webidl-brand-errors-preload.mjs +49 -0
  91. package/src/synthid-http-runtime/webidl-callable-source-catalog.mjs +4491 -0
  92. package/src/synthid-http-runtime/webidl-realm-catalog.mjs +124 -0
  93. package/src/synthid-http.ts +290 -0
  94. package/src/synthid-manual.ts +388 -0
  95. package/src/synthid-page.ts +103 -0
  96. package/src/synthid-result.ts +177 -0
  97. package/src/synthid.ts +514 -0
  98. package/src/vision.ts +57 -0
  99. package/webui/index.js +279 -0
@@ -0,0 +1,639 @@
1
+ // Narrow, functional missing-Web-API compatibility for an isolated JSDOM realm.
2
+ // This is not a browser sandbox and does not forge native function source.
3
+ import generatedUtils from 'jsdom/lib/jsdom/living/generated/utils.js';
4
+ import PerformanceModule from 'jsdom/lib/jsdom/living/hr-time/Performance-impl.js';
5
+ import jsdomPackage from 'jsdom/package.json' with { type: 'json' };
6
+ import {quantizeCompletedClock100us} from './runtime-clock-precision-control.mjs';
7
+ const MAX_ENTRIES = 512;
8
+ const TIMING_FIELDS = ['workerStart', 'redirectStart', 'redirectEnd', 'fetchStart',
9
+ 'domainLookupStart', 'domainLookupEnd', 'connectStart', 'secureConnectionStart',
10
+ 'connectEnd', 'requestStart', 'responseStart', 'responseEnd', 'transferSize',
11
+ 'encodedBodySize', 'decodedBodySize'];
12
+ const STRING_FIELDS = ['initiatorType', 'nextHopProtocol', 'deliveryType'];
13
+ const dataValue = (object, key) => {
14
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
15
+ if (descriptor && !Object.hasOwn(descriptor, 'value')) throw TypeError('WEB_COMPAT_DATA_OPTIONS_REQUIRED');
16
+ return descriptor?.value;
17
+ };
18
+ const finiteNonnegative = value => typeof value === 'number' && Number.isFinite(value) && value >= 0;
19
+ // Authored-interface brands are shared across isolated realms. These weak
20
+ // registries and their bridges are never installed on a Window or navigator.
21
+ const activationByWindow = new WeakMap(), activationByNavigator = new WeakMap(), activationByInstance = new WeakMap();
22
+ const activationReadFields = ['navigator', 'hasBeenActive', 'isActive', 'invalidReceiver', 'foreignGetter',
23
+ 'stickyTrue', 'stickyFalse', 'activeTrue', 'activeFalse'];
24
+ const activationReadKinds = ['top', 'connectedChild', 'detachedChild'];
25
+ const emptyActivationReads = () => Object.fromEntries(activationReadKinds.map(kind => [kind, Object.fromEntries(activationReadFields.map(field => [field, 0]))]));
26
+ const copyActivationReads = record => Object.fromEntries(activationReadKinds.map(kind => [kind, { ...record.reads[kind] }]));
27
+ function activationRealmKind(record) {
28
+ // Use JSDOM implementation nodes, never a page getter, to classify the
29
+ // receiver's frame at the time of the actual API read (including detach).
30
+ record.frame ??= Object.getOwnPropertyDescriptor(record.window, '_frameElement')?.value;
31
+ if (!record.frame) return 'top';
32
+ let frame = record.frame;
33
+ const visited = new Set();
34
+ while (frame) {
35
+ if (visited.has(frame) || visited.size >= 256 || !frame.isConnected) return 'detachedChild';
36
+ visited.add(frame);
37
+ frame = Object.getOwnPropertyDescriptor(frame._ownerDocument?._defaultView ?? {}, '_frameElement')?.value;
38
+ }
39
+ return 'connectedChild';
40
+ }
41
+ function countActivationRead(record, field) {
42
+ const row = record.reads[activationRealmKind(record)];
43
+ row[field] = Math.min(1000000, row[field] + 1);
44
+ }
45
+ function makeActivationBridge(window) {
46
+ let ownRecord;
47
+ return Object.freeze({
48
+ register(navigator, instance, clock) {
49
+ if (ownRecord || activationByWindow.has(window) || typeof clock !== 'function') throw Error('ACTIVATION_REGISTRATION_FAILED');
50
+ ownRecord = { window, navigator, instance, clock, sticky: false, startedAt: 0, transientMs: 0,
51
+ reads: emptyActivationReads(), controller: undefined, frame: undefined };
52
+ activationByWindow.set(window, ownRecord); activationByNavigator.set(navigator, ownRecord); activationByInstance.set(instance, ownRecord);
53
+ },
54
+ read(kind, receiver) {
55
+ const record = kind === 'navigator' ? activationByNavigator.get(receiver) : activationByInstance.get(receiver);
56
+ if (!record) { if (ownRecord) countActivationRead(ownRecord, 'invalidReceiver'); return undefined; }
57
+ countActivationRead(record, kind);
58
+ if (record !== ownRecord) countActivationRead(record, 'foreignGetter');
59
+ if (kind === 'navigator') return record.instance;
60
+ const value = kind === 'hasBeenActive' ? record.sticky
61
+ : record.sticky && record.transientMs > 0 && record.clock() - record.startedAt < record.transientMs;
62
+ countActivationRead(record, kind === 'hasBeenActive' ? value ? 'stickyTrue' : 'stickyFalse' : value ? 'activeTrue' : 'activeFalse');
63
+ return value;
64
+ },
65
+ snapshot() { return ownRecord ? copyActivationReads(ownRecord) : undefined; },
66
+ dispose() {
67
+ if (!ownRecord) return;
68
+ activationByWindow.delete(window); activationByNavigator.delete(ownRecord.navigator); activationByInstance.delete(ownRecord.instance);
69
+ // Keep the counter record for the trusted controller's final snapshot.
70
+ },
71
+ });
72
+ }
73
+
74
+ /** Explicit diagnostic state, not a trusted user event. It changes the receiver
75
+ * instance's private state without replacing getters or altering their brands. */
76
+ export function createRuntimeUserActivationDiagnostic(window, transientMs = 0) {
77
+ if (![0, 5000].includes(transientMs)) throw TypeError('INVALID_ACTIVATION_CONTROL');
78
+ const record = activationByWindow.get(window);
79
+ if (!record) throw TypeError('ACTIVATION_STATE_UNAVAILABLE');
80
+ const previous = { sticky: record.sticky, startedAt: record.startedAt, transientMs: record.transientMs, controller: record.controller };
81
+ const identity = {}; let disposed = false;
82
+ const snapshot = () => ({ diagnosticOnly: true, sticky: record.sticky,
83
+ transient: record.sticky && record.transientMs > 0 && record.clock() - record.startedAt < record.transientMs,
84
+ transientMs: record.transientMs, disposed });
85
+ const activate = () => {
86
+ if (disposed) throw Error('ACTIVATION_CONTROL_DISPOSED');
87
+ record.controller = identity; record.startedAt = record.clock(); record.sticky = true; record.transientMs = transientMs;
88
+ return snapshot();
89
+ };
90
+ activate();
91
+ return { activate, snapshot, dispose() {
92
+ if (disposed) return; disposed = true;
93
+ if (record.controller === identity) Object.assign(record, previous);
94
+ } };
95
+ }
96
+
97
+ // Shared by the child hook so only this small, copied numerical sample crosses
98
+ // into a child. Incomplete samples do not become invented network information.
99
+ export function normalizeRuntimeNetworkSample(input) {
100
+ if (input === undefined || input === null) return undefined;
101
+ if (typeof input !== 'object' || Array.isArray(input)) throw TypeError('WEB_COMPAT_INVALID_NETWORK_SAMPLE');
102
+ const result = {};
103
+ const fields = ['requestStart', 'responseStart', 'responseEnd', 'encodedBodySize'];
104
+ for (const key of fields) {
105
+ const value = dataValue(input, key);
106
+ if (value === undefined) continue;
107
+ if (!finiteNonnegative(value) || value > Number.MAX_SAFE_INTEGER) throw TypeError('WEB_COMPAT_INVALID_NETWORK_SAMPLE');
108
+ result[key] = value;
109
+ }
110
+ if (fields.some(key => !Object.hasOwn(result, key))) return undefined;
111
+ if (!Number.isSafeInteger(result.encodedBodySize) || result.responseStart < result.requestStart
112
+ || result.responseEnd < result.responseStart) throw TypeError('WEB_COMPAT_INVALID_NETWORK_SAMPLE');
113
+ if (result.encodedBodySize === 0 || result.responseEnd === result.requestStart) return undefined;
114
+ return result;
115
+ }
116
+
117
+ /** options.physicalMemoryBytes: actual host RAM, read by the trusted parent.
118
+ * options.performanceEntries: actual completed HTTP timings; startTime and all
119
+ * timing fields must use this window's performance.timeOrigin, in milliseconds.
120
+ * Omit records when that clock correspondence is not known. No entries are
121
+ * invented. Install once, before page code; call dispose before window.close. */
122
+ export function installRuntimeWebCompat(window, options = {}) {
123
+ if (!window || window.Function === Function || typeof window.eval !== 'function'
124
+ || !options || typeof options !== 'object') throw TypeError('WEB_COMPAT_ISOLATED_REALM_REQUIRED');
125
+ const physicalMemoryBytes = dataValue(options, 'physicalMemoryBytes');
126
+ if (physicalMemoryBytes !== undefined && (!Number.isSafeInteger(physicalMemoryBytes) || physicalMemoryBytes <= 0)) {
127
+ throw TypeError('WEB_COMPAT_INVALID_MEMORY');
128
+ }
129
+ const deviceMemoryMaxGiB = dataValue(options, 'deviceMemoryMaxGiB') ?? 8;
130
+ if (![8, 32].includes(deviceMemoryMaxGiB)) throw TypeError('WEB_COMPAT_INVALID_MEMORY_CEILING');
131
+ const platform = dataValue(options, 'platform');
132
+ if (platform !== undefined && !['Win32', 'MacIntel', 'Linux x86_64', 'Linux aarch64'].includes(platform)) throw TypeError('WEB_COMPAT_INVALID_PLATFORM');
133
+ const virtualScreen = dataValue(options, 'virtualScreen') ?? false;
134
+ if (typeof virtualScreen !== 'boolean') throw TypeError('WEB_COMPAT_INVALID_SCREEN');
135
+ const suppliedVirtualMouse = dataValue(options, 'virtualMouse');
136
+ const virtualMouse = suppliedVirtualMouse === undefined ? false : suppliedVirtualMouse;
137
+ if (typeof virtualMouse !== 'boolean') throw TypeError('WEB_COMPAT_INVALID_MOUSE');
138
+ const networkSample = normalizeRuntimeNetworkSample(dataValue(options, 'networkSample'));
139
+ const suppliedClockPrecision=dataValue(options,'clockPrecision100us');
140
+ const clockPrecision100us=suppliedClockPrecision===undefined?false:suppliedClockPrecision;
141
+ if(typeof clockPrecision100us!=='boolean')throw TypeError('WEB_COMPAT_INVALID_CLOCK_PRECISION');
142
+ const suppliedUserActivation = dataValue(options, 'userActivationWebIdlCompatibility');
143
+ const userActivationWebIdlCompatibility = suppliedUserActivation === undefined ? false : suppliedUserActivation;
144
+ if (typeof userActivationWebIdlCompatibility !== 'boolean') throw TypeError('WEB_COMPAT_INVALID_USER_ACTIVATION');
145
+ const performanceTimeOriginEpochMs = dataValue(options, 'performanceTimeOriginEpochMs');
146
+ if (performanceTimeOriginEpochMs !== undefined && (!finiteNonnegative(performanceTimeOriginEpochMs)
147
+ || performanceTimeOriginEpochMs === 0 || performanceTimeOriginEpochMs > window.performance.timeOrigin)) throw TypeError('WEB_COMPAT_INVALID_TIME_ORIGIN');
148
+ const supplied = dataValue(options, 'performanceEntries') ?? [];
149
+ if (!Array.isArray(supplied) || supplied.length > MAX_ENTRIES) throw TypeError('WEB_COMPAT_INVALID_ENTRIES');
150
+ const entries = Array.from({ length: supplied.length }, (_, index) => {
151
+ const input = dataValue(supplied, String(index));
152
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw TypeError('WEB_COMPAT_INVALID_ENTRY');
153
+ const entry = {};
154
+ for (const key of ['name', 'entryType', 'startTime', 'duration', ...TIMING_FIELDS, ...STRING_FIELDS]) {
155
+ const value = dataValue(input, key);
156
+ if (value !== undefined) entry[key] = value;
157
+ }
158
+ if (typeof entry.name !== 'string' || entry.name.length > 8192
159
+ || !['resource', 'navigation'].includes(entry.entryType)
160
+ || !finiteNonnegative(entry.startTime) || !finiteNonnegative(entry.duration)) throw TypeError('WEB_COMPAT_INVALID_ENTRY');
161
+ if (TIMING_FIELDS.some(key => key in entry && !finiteNonnegative(entry[key]))
162
+ || STRING_FIELDS.some(key => key in entry && (typeof entry[key] !== 'string' || entry[key].length > 256))) {
163
+ throw TypeError('WEB_COMPAT_INVALID_ENTRY');
164
+ }
165
+ return entry;
166
+ });
167
+ // Keep the ORIGINAL JSDOM monotonic clock and its private event-clock users
168
+ // aligned to the actual HTTP-session origin. No host callable enters the realm.
169
+ let performanceImpl, oldOrigin, oldNowAtOrigin, clockOffsetMs = 0;
170
+ if (performanceTimeOriginEpochMs !== undefined) {
171
+ performanceImpl = generatedUtils.implForWrapper(window.performance);
172
+ if (jsdomPackage.version !== '26.1.0' || !PerformanceModule.implementation.prototype.isPrototypeOf(performanceImpl)
173
+ || !Number.isFinite(performanceImpl._nowAtTimeOrigin) || !Number.isFinite(performanceImpl.timeOrigin)) {
174
+ throw TypeError('WEB_COMPAT_UNSUPPORTED_CLOCK');
175
+ }
176
+ oldOrigin = performanceImpl.timeOrigin;
177
+ oldNowAtOrigin = performanceImpl._nowAtTimeOrigin;
178
+ clockOffsetMs = oldOrigin - performanceTimeOriginEpochMs;
179
+ performanceImpl.timeOrigin = performanceTimeOriginEpochMs;
180
+ performanceImpl._nowAtTimeOrigin = oldNowAtOrigin - clockOffsetMs;
181
+ }
182
+ const restoreClock = () => {
183
+ if (!performanceImpl) return;
184
+ performanceImpl.timeOrigin = oldOrigin;
185
+ performanceImpl._nowAtTimeOrigin = oldNowAtOrigin;
186
+ performanceImpl = undefined;
187
+ };
188
+ // Options and installed methods are realm-owned; Event/DOMException keep the
189
+ // existing JSDOM wrappers.
190
+ const payload = JSON.stringify({ physicalMemoryBytes, deviceMemoryMaxGiB, platform, virtualScreen, virtualMouse,
191
+ entries, clockOffsetMs, networkSample, clockPrecision100us, userActivationWebIdlCompatibility,
192
+ rebaseClock: performanceTimeOriginEpochMs !== undefined });
193
+ const activationBridge = userActivationWebIdlCompatibility ? makeActivationBridge(window) : undefined;
194
+ try {
195
+ let controller;
196
+ if (activationBridge) {
197
+ controller=Reflect.apply(window.eval('('+installInRealm.toString()+')'),undefined,[window.eval('('+payload+')'),
198
+ clockPrecision100us ? window.eval('('+quantizeCompletedClock100us.toString()+')') : undefined,activationBridge]);
199
+ }else controller = window.eval('(' + installInRealm.toString() + ')(' + payload + ',' + (clockPrecision100us?'('+quantizeCompletedClock100us.toString()+')':'undefined') + ')');
200
+ // This controller remains in the trusted parent, never on the window.
201
+ return { installed: controller.installed, snapshot() { return { ...controller.snapshot(),
202
+ ...(activationBridge ? { userActivationReads: activationBridge.snapshot() } : {}) }; },
203
+ dispose() { try { controller.dispose(); } finally { activationBridge?.dispose(); restoreClock(); } } };
204
+ } catch (error) { activationBridge?.dispose(); restoreClock(); throw error; }
205
+ }
206
+
207
+ function installInRealm(options,quantizeClock,activationBridge) {
208
+ 'use strict';
209
+ const win = globalThis;
210
+ const saved = [];
211
+ const installed = [];
212
+ const now = win.performance.now.bind(win.performance);
213
+ const schedule = win.setTimeout.bind(win);
214
+ const unschedule = win.clearTimeout.bind(win);
215
+ let disposed = false;
216
+ function install(object, key, descriptor, label = key, replace = false) {
217
+ if (!replace && key in object) return false;
218
+ const previous = Object.getOwnPropertyDescriptor(object, key);
219
+ const next = { configurable: true, enumerable: true, ...descriptor };
220
+ Object.defineProperty(object, key, next);
221
+ saved.push({ object, key, previous, next });
222
+ installed.push(label);
223
+ return true;
224
+ }
225
+ const activeLists = new Set();
226
+ const listState = new WeakMap();
227
+ // Diagnostic-only query labels. Unknown strings stay inside the runtime and
228
+ // are never retained. Reads reuse the already constructed list's state.
229
+ const mediaQueryLabels = new Set(['screen', 'all', 'not all',
230
+ '(pointer: fine)', '(pointer: coarse)', '(pointer: none)',
231
+ '(any-pointer: fine)', '(any-pointer: coarse)', '(any-pointer: none)',
232
+ '(hover: hover)', '(hover: none)', '(any-hover: hover)', '(any-hover: none)',
233
+ '(prefers-color-scheme: light)', '(prefers-color-scheme: dark)', '(prefers-color-scheme: no-preference)',
234
+ '(prefers-reduced-motion: reduce)', '(prefers-reduced-motion: no-preference)',
235
+ '(forced-colors: active)', '(forced-colors: none)',
236
+ '(display-mode: browser)', '(display-mode: fullscreen)', '(display-mode: standalone)', '(display-mode: minimal-ui)',
237
+ '(resolution: 1dppx)', '(resolution: 1.5dppx)', '(resolution: 2dppx)',
238
+ ]);
239
+ const mediaQueries = { diagnosticOnly: true, fixedPublicQueriesOnly: true,
240
+ declaredVirtualMouse: options.virtualMouse,
241
+ targetPropertyReadsIntroduced: 0, extraQueryConversions: 0,
242
+ maximumRecords: 32, calls: 0, unknown: 0, limitReached: false, records: [] };
243
+ function recordMediaQuery(media, matches) {
244
+ mediaQueries.calls = Math.min(1000000, mediaQueries.calls + 1);
245
+ const label = media.trim().toLowerCase().replace(/\s+/g, ' ')
246
+ .replace(/\(\s*/g, '(').replace(/\s*\)/g, ')').replace(/\s*:\s*/g, ': ');
247
+ if (!mediaQueryLabels.has(label)) {
248
+ mediaQueries.unknown = Math.min(1000000, mediaQueries.unknown + 1); return;
249
+ }
250
+ if (mediaQueries.records.length >= mediaQueries.maximumRecords) { mediaQueries.limitReached = true; return; }
251
+ mediaQueries.records.push({ query: label, matches });
252
+ }
253
+ const number = '(?:\\d+(?:\\.\\d*)?|\\.\\d+)';
254
+ const dimensionPattern = new RegExp('^(' + number + ')(px|em|rem|in|cm|mm|q|pt|pc)?$');
255
+ function dimension(text, resolution = false) {
256
+ if (resolution) {
257
+ const match = new RegExp('^(' + number + ')(dppx|dpi|dpcm|x)$').exec(text);
258
+ if (!match) return undefined;
259
+ return Number(match[1]) * ({ dppx: 1, x: 1, dpi: 1 / 96, dpcm: 2.54 / 96 }[match[2]]);
260
+ }
261
+ const match = dimensionPattern.exec(text);
262
+ if (!match || (!match[2] && Number(match[1]) !== 0)) return undefined;
263
+ // Media-query em/rem refer to the UA initial font size (16 CSS px), not
264
+ // document styles. This grammar implements CSS absolute/initial lengths.
265
+ return Number(match[1]) * ({ px: 1, em: 16, rem: 16, in: 96, cm: 96 / 2.54,
266
+ mm: 96 / 25.4, q: 96 / 101.6, pt: 96 / 72, pc: 16 }[match[2] || 'px']);
267
+ }
268
+ function feature(text) {
269
+ const split = /^([a-z-]+)(?:\s*:\s*(.+))?$/.exec(text.trim());
270
+ if (!split) return false;
271
+ let name = split[1];
272
+ const argument = split[2]?.trim();
273
+ const prefix = /^(min|max)-/.exec(name)?.[1];
274
+ if (prefix) name = name.slice(4);
275
+ // A declared desktop virtual mouse is one fine pointing device that can
276
+ // hover. These are discrete CSS features: min/max forms are unsupported.
277
+ // Without this option the previous unsupported-feature behavior remains.
278
+ if (['pointer', 'any-pointer', 'hover', 'any-hover'].includes(name)) {
279
+ if (!options.virtualMouse || prefix) return false;
280
+ if (argument === undefined) return true;
281
+ return name === 'pointer' || name === 'any-pointer' ? argument === 'fine' : argument === 'hover';
282
+ }
283
+ const width = Number(win.innerWidth), height = Number(win.innerHeight);
284
+ let actual, expected;
285
+ if (name === 'orientation') {
286
+ return !prefix && (argument === 'portrait' ? height >= width : argument === 'landscape' && width > height);
287
+ }
288
+ if (['width', 'height', 'device-width', 'device-height'].includes(name)) {
289
+ actual = name === 'width' ? width : name === 'height' ? height
290
+ : Number(win.screen?.[name === 'device-width' ? 'width' : 'height']);
291
+ if (name.startsWith('device-') && !(actual > 0)) return false;
292
+ expected = argument === undefined ? undefined : dimension(argument);
293
+ } else if (name === 'aspect-ratio') {
294
+ actual = height > 0 ? width / height : undefined;
295
+ const ratio = argument === undefined ? null : /^(\d+(?:\.\d+)?)\s*\/\s*(\d+(?:\.\d+)?)$/.exec(argument);
296
+ expected = ratio && Number(ratio[2]) > 0 ? Number(ratio[1]) / Number(ratio[2]) : undefined;
297
+ } else if (name === 'resolution') {
298
+ actual = Number(win.devicePixelRatio);
299
+ expected = argument === undefined ? undefined : dimension(argument, true);
300
+ } else return false;
301
+ if (!Number.isFinite(actual)) return false;
302
+ if (argument === undefined) return !prefix && actual > 0;
303
+ if (!Number.isFinite(expected)) return false;
304
+ return prefix === 'min' ? actual >= expected : prefix === 'max' ? actual <= expected : Math.abs(actual - expected) <= 1e-9;
305
+ }
306
+ function evaluate(query) {
307
+ if (!query.trim()) return true;
308
+ const alternatives = query.toLowerCase().split(',');
309
+ if (alternatives.length > 64) return false;
310
+ return alternatives.some(raw => {
311
+ let text = raw.trim();
312
+ let negate = false;
313
+ const modifier = /^(not|only)\s+/.exec(text);
314
+ if (modifier) { negate = modifier[1] === 'not'; text = text.slice(modifier[0].length); }
315
+ let result = true;
316
+ const media = /^([a-z-]+)(?:\s+|$)/.exec(text);
317
+ if (media) {
318
+ result = media[1] === 'all' || media[1] === 'screen';
319
+ text = text.slice(media[0].length).trim();
320
+ if (text) {
321
+ if (!/^and\s+/.test(text)) return false;
322
+ text = text.replace(/^and\s+/, '');
323
+ }
324
+ } else if (modifier) return false; // MQ3 modifiers require a media type.
325
+ let count = 0;
326
+ while (text) {
327
+ const part = /^\(([^()]*)\)/.exec(text);
328
+ if (!part || ++count > 64) return false;
329
+ result = feature(part[1]) && result;
330
+ text = text.slice(part[0].length).trim();
331
+ if (text) {
332
+ if (!/^and\s+/.test(text)) return false;
333
+ text = text.replace(/^and\s+/, '');
334
+ if (!text) return false;
335
+ }
336
+ }
337
+ if (!media && !count) return false;
338
+ return negate ? !result : result;
339
+ });
340
+ }
341
+ const mqlKey = {};
342
+ class MediaQueryList {
343
+ constructor(key, media) {
344
+ if (key !== mqlKey) throw new TypeError('Illegal constructor');
345
+ const result = Reflect.construct(EventTarget, [], new.target);
346
+ listState.set(result, { media, matches: evaluate(media), onchange: null, handler: null });
347
+ return result;
348
+ }
349
+ get media() { return listState.get(this).media; }
350
+ get matches() { return evaluate(listState.get(this).media); }
351
+ get onchange() { return listState.get(this).onchange; }
352
+ set onchange(value) {
353
+ const state = listState.get(this);
354
+ state.onchange = typeof value === 'function' ? value : null;
355
+ if (!state.handler) {
356
+ state.handler = event => { if (state.onchange) Reflect.apply(state.onchange, this, [event]); };
357
+ this.addEventListener('change', state.handler);
358
+ }
359
+ }
360
+ addListener(listener) { this.addEventListener('change', listener); }
361
+ removeListener(listener) { this.removeEventListener('change', listener); }
362
+ }
363
+ Object.setPrototypeOf(MediaQueryList.prototype, EventTarget.prototype);
364
+ function onResize() {
365
+ for (const list of activeLists) {
366
+ const state = listState.get(list);
367
+ const matches = evaluate(state.media);
368
+ if (matches === state.matches) continue;
369
+ state.matches = matches;
370
+ const event = new Event('change');
371
+ Object.defineProperties(event, { matches: { value: matches, enumerable: true }, media: { value: state.media, enumerable: true } });
372
+ list.dispatchEvent(event);
373
+ }
374
+ }
375
+ const mediaInstalled = install(win, 'matchMedia', { writable: true, value: function matchMedia(query) {
376
+ if (arguments.length === 0) throw new TypeError('matchMedia requires one argument');
377
+ if (disposed) throw new DOMException('Runtime disposed', 'InvalidStateError');
378
+ const media = String(query);
379
+ if (media.length > 4096 || activeLists.size >= 1024) throw new DOMException('Media query limit', 'QuotaExceededError');
380
+ const list = new MediaQueryList(mqlKey, media);
381
+ activeLists.add(list);
382
+ recordMediaQuery(media, listState.get(list).matches);
383
+ return list;
384
+ } });
385
+ if (mediaInstalled) {
386
+ install(win, 'MediaQueryList', { writable: true, value: MediaQueryList });
387
+ win.addEventListener('resize', onResize);
388
+ }
389
+
390
+ const pending = new Map();
391
+ let nextHandle = 0;
392
+ const deadlineState = new WeakMap();
393
+ const deadlineKey = {};
394
+ class IdleDeadline {
395
+ constructor(key, didTimeout, end) {
396
+ if (key !== deadlineKey) throw new TypeError('Illegal constructor');
397
+ deadlineState.set(this, { didTimeout, end });
398
+ }
399
+ get didTimeout() { return deadlineState.get(this).didTimeout; }
400
+ timeRemaining() {
401
+ const state = deadlineState.get(this);
402
+ return state.didTimeout ? 0 : Math.max(0, Math.min(50, state.end - now()));
403
+ }
404
+ }
405
+ // A Node task boundary approximates an available idle turn; it is not a
406
+ // renderer idle scheduler. Deadlines use the actual monotonic realm clock.
407
+ const idleInstalled = !('requestIdleCallback' in win) && !('cancelIdleCallback' in win);
408
+ if (idleInstalled) {
409
+ install(win, 'requestIdleCallback', { writable: true, value: function requestIdleCallback(callback, idleOptions = {}) {
410
+ if (typeof callback !== 'function') throw new TypeError('Idle callback must be callable');
411
+ if (disposed) throw new DOMException('Runtime disposed', 'InvalidStateError');
412
+ if (pending.size >= 1024) throw new DOMException('Idle callback limit', 'QuotaExceededError');
413
+ const timeoutValue = idleOptions?.timeout;
414
+ let timeout;
415
+ if (timeoutValue !== undefined) {
416
+ timeout = Number(timeoutValue);
417
+ if (!Number.isFinite(timeout) || timeout < 0 || timeout > 4294967295) throw new TypeError('Invalid idle timeout');
418
+ timeout = Math.floor(timeout);
419
+ }
420
+ const requestedAt = now();
421
+ do { nextHandle = nextHandle % 4294967295 + 1; } while (pending.has(nextHandle));
422
+ const handle = nextHandle;
423
+ const timer = schedule(() => {
424
+ if (!pending.delete(handle) || disposed) return;
425
+ const startedAt = now();
426
+ const didTimeout = timeout !== undefined && startedAt - requestedAt >= timeout;
427
+ Reflect.apply(callback, win, [new IdleDeadline(deadlineKey, didTimeout, startedAt + 50)]);
428
+ }, 1);
429
+ pending.set(handle, timer);
430
+ return handle;
431
+ } });
432
+ install(win, 'cancelIdleCallback', { writable: true, value: function cancelIdleCallback(handle) {
433
+ const id = Number(handle) >>> 0;
434
+ if (pending.has(id)) { unschedule(pending.get(id)); pending.delete(id); }
435
+ } });
436
+ install(win, 'IdleDeadline', { writable: true, value: IdleDeadline });
437
+ }
438
+
439
+ const animationFrames = new Set();
440
+ let cancelFrame;
441
+ if ((options.rebaseClock || options.clockPrecision100us) && typeof win.requestAnimationFrame === 'function' && typeof win.cancelAnimationFrame === 'function') {
442
+ const requestFrame = win.requestAnimationFrame.bind(win);
443
+ cancelFrame = win.cancelAnimationFrame.bind(win);
444
+ install(win, 'requestAnimationFrame', { writable: true, value: function requestAnimationFrame(callback) {
445
+ if (typeof callback !== 'function') throw new TypeError('Animation callback must be callable');
446
+ if (disposed) throw new DOMException('Runtime disposed', 'InvalidStateError');
447
+ if (animationFrames.size >= 1024) throw new DOMException('Animation callback limit', 'QuotaExceededError');
448
+ const handle = requestFrame(stamp => {
449
+ animationFrames.delete(handle);
450
+ if (!disposed) {
451
+ const completed=stamp+options.clockOffsetMs;
452
+ Reflect.apply(callback, win, [options.clockPrecision100us?quantizeClock(completed):completed]);
453
+ }
454
+ });
455
+ animationFrames.add(handle);
456
+ return handle;
457
+ } }, 'requestAnimationFrame.clock', true);
458
+ install(win, 'cancelAnimationFrame', { writable: true, value: function cancelAnimationFrame(handle) {
459
+ const id = Number(handle) >>> 0;
460
+ animationFrames.delete(id);
461
+ cancelFrame(id);
462
+ } }, 'cancelAnimationFrame.clock', true);
463
+ }
464
+
465
+ const entryState = new WeakMap();
466
+ const entryKey = {};
467
+ class PerformanceEntry {
468
+ constructor(key, record) {
469
+ if (key !== entryKey) throw new TypeError('Illegal constructor');
470
+ const data = Object.freeze({ ...record });
471
+ entryState.set(this, data);
472
+ for (const name of Object.keys(data)) if (!['name', 'entryType', 'startTime', 'duration'].includes(name)) {
473
+ Object.defineProperty(this, name, { get: () => data[name], enumerable: true });
474
+ }
475
+ }
476
+ get name() { return entryState.get(this).name; }
477
+ get entryType() { return entryState.get(this).entryType; }
478
+ get startTime() { return entryState.get(this).startTime; }
479
+ get duration() { return entryState.get(this).duration; }
480
+ toJSON() { return { ...entryState.get(this) }; }
481
+ }
482
+ const entries = options.entries.map(entry => new PerformanceEntry(entryKey, entry)).sort((a, b) => a.startTime - b.startTime);
483
+ const performancePrototype = Object.getPrototypeOf(win.performance);
484
+ const checkPerformance = receiver => { if (receiver !== win.performance) throw new TypeError('Illegal invocation'); };
485
+ install(performancePrototype, 'getEntries', { writable: true, value: function getEntries() {
486
+ checkPerformance(this); return entries.slice();
487
+ } }, 'performance.getEntries');
488
+ install(performancePrototype, 'getEntriesByType', { writable: true, value: function getEntriesByType(type) {
489
+ checkPerformance(this);
490
+ if (arguments.length === 0) throw new TypeError('getEntriesByType requires one argument');
491
+ const requested = String(type);
492
+ return entries.filter(entry => entry.entryType === requested);
493
+ } }, 'performance.getEntriesByType');
494
+ install(performancePrototype, 'getEntriesByName', { writable: true, value: function getEntriesByName(name, type) {
495
+ checkPerformance(this);
496
+ if (arguments.length === 0) throw new TypeError('getEntriesByName requires one argument');
497
+ const requested = String(name), requestedType = type === undefined ? undefined : String(type);
498
+ return entries.filter(entry => entry.name === requested && (requestedType === undefined || entry.entryType === requestedType));
499
+ } }, 'performance.getEntriesByName');
500
+ install(win, 'PerformanceEntry', { writable: true, value: PerformanceEntry });
501
+ const navigatorPrototype = Object.getPrototypeOf(win.navigator);
502
+ const checkNavigator = receiver => { if (receiver !== win.navigator) throw new TypeError('Illegal invocation'); };
503
+ // This Node runtime is not controlled by WebDriver. Do not change an existing
504
+ // implementation or hide the ordinary JavaScript getter's source.
505
+ install(navigatorPrototype, 'webdriver', { get: function webdriver() { checkNavigator(this); return false; } }, 'navigator.webdriver');
506
+ install(navigatorPrototype, 'maxTouchPoints', { get: function maxTouchPoints() { checkNavigator(this); return 0; } }, 'navigator.maxTouchPoints');
507
+ const activationKey = {};
508
+ const activations = new WeakSet();
509
+ const LegacyUserActivation = class UserActivation {
510
+ constructor(key) { if (key !== activationKey) throw new TypeError('Illegal constructor'); activations.add(this); }
511
+ get isActive() { if (!activations.has(this)) throw new TypeError('Illegal invocation'); return false; }
512
+ get hasBeenActive() { if (!activations.has(this)) throw new TypeError('Illegal invocation'); return false; }
513
+ };
514
+ let UserActivation = LegacyUserActivation;
515
+ let activation;
516
+ if (options.userActivationWebIdlCompatibility) {
517
+ // Authored implementation with the retained public WebIDL descriptor shape.
518
+ // The class stays outside JSDOM's generated-constructor registry; neither
519
+ // native callable identity nor native function source is asserted here.
520
+ UserActivation = class UserActivation {
521
+ constructor() { throw new TypeError('Illegal constructor'); }
522
+ };
523
+ delete UserActivation.prototype.constructor;
524
+ const readActivation = (kind, receiver) => {
525
+ let value;
526
+ try { value = activationBridge.read(kind, receiver); }
527
+ catch { throw new TypeError('Illegal invocation'); }
528
+ if (typeof value !== 'boolean') throw new TypeError('Illegal invocation');
529
+ return value;
530
+ };
531
+ const getters = {
532
+ get hasBeenActive() { return readActivation('hasBeenActive', this); },
533
+ get isActive() { return readActivation('isActive', this); },
534
+ };
535
+ Object.defineProperties(UserActivation.prototype, {
536
+ hasBeenActive: Object.getOwnPropertyDescriptor(getters, 'hasBeenActive'),
537
+ isActive: Object.getOwnPropertyDescriptor(getters, 'isActive'),
538
+ constructor: { configurable: true, writable: true, value: UserActivation },
539
+ [Symbol.toStringTag]: { configurable: true, value: 'UserActivation' },
540
+ });
541
+ activation = Object.create(UserActivation.prototype);
542
+ } else activation = new UserActivation(activationKey);
543
+ const activationDescriptor = options.userActivationWebIdlCompatibility
544
+ ? Object.getOwnPropertyDescriptor({ get userActivation() {
545
+ let value;
546
+ try { value = activationBridge.read('navigator', this); } catch { throw new TypeError('Illegal invocation'); }
547
+ if (value === undefined) throw new TypeError('Illegal invocation');
548
+ return value;
549
+ } }, 'userActivation')
550
+ : { get: function userActivation() { checkNavigator(this); return activation; } };
551
+ if (install(navigatorPrototype, 'userActivation', activationDescriptor, 'navigator.userActivation')) {
552
+ install(win, 'UserActivation', { writable: true, value: UserActivation,
553
+ ...(options.userActivationWebIdlCompatibility ? { enumerable: false } : {}) });
554
+ if (options.userActivationWebIdlCompatibility) activationBridge.register(win.navigator, activation, now);
555
+ }
556
+ if (options.networkSample) {
557
+ const sample = options.networkSample;
558
+ // App-measured HTTP path estimates: headers include server/proxy delay, and
559
+ // throughput deliberately includes the entire request, including latency.
560
+ // This is NOT Chromium's native network-quality estimator or a replay.
561
+ const rtt = Math.round((sample.responseStart - sample.requestStart) / 25) * 25;
562
+ const downlink = Math.floor(Math.min(10, sample.encodedBodySize * 8
563
+ / (sample.responseEnd - sample.requestStart) / 1000) * 40) / 40;
564
+ const effectiveType = rtt >= 2000 || downlink <= 0.05 ? 'slow-2g'
565
+ : rtt >= 1400 || downlink <= 0.07 ? '2g'
566
+ : rtt >= 270 || downlink <= 0.7 ? '3g' : '4g';
567
+ const infoKey = {};
568
+ const infoState = new WeakMap();
569
+ class NetworkInformation {
570
+ constructor(key) {
571
+ if (key !== infoKey) throw new TypeError('Illegal constructor');
572
+ const result = Reflect.construct(EventTarget, [], new.target);
573
+ infoState.set(result, { onchange: null, handler: null });
574
+ return result;
575
+ }
576
+ get rtt() { if (!infoState.has(this)) throw new TypeError('Illegal invocation'); return rtt; }
577
+ get downlink() { if (!infoState.has(this)) throw new TypeError('Illegal invocation'); return downlink; }
578
+ get effectiveType() { if (!infoState.has(this)) throw new TypeError('Illegal invocation'); return effectiveType; }
579
+ get saveData() { if (!infoState.has(this)) throw new TypeError('Illegal invocation'); return false; }
580
+ get onchange() { return infoState.get(this).onchange; }
581
+ set onchange(value) {
582
+ const state = infoState.get(this);
583
+ state.onchange = typeof value === 'function' ? value : null;
584
+ if (!state.handler) {
585
+ state.handler = event => { if (state.onchange) Reflect.apply(state.onchange, this, [event]); };
586
+ this.addEventListener('change', state.handler);
587
+ }
588
+ }
589
+ }
590
+ Object.setPrototypeOf(NetworkInformation.prototype, EventTarget.prototype);
591
+ const information = new NetworkInformation(infoKey);
592
+ if (install(navigatorPrototype, 'connection', { get: function connection() { checkNavigator(this); return information; } }, 'navigator.connection')) {
593
+ install(win, 'NetworkInformation', { writable: true, value: NetworkInformation });
594
+ }
595
+ }
596
+ if (options.platform !== undefined) {
597
+ install(navigatorPrototype, 'platform', { get: function platform() { checkNavigator(this); return options.platform; } }, 'navigator.platform', true);
598
+ }
599
+ if (options.virtualScreen) {
600
+ const screen = win.screen;
601
+ const screenPrototype = Object.getPrototypeOf(screen);
602
+ for (const key of ['width', 'height', 'availWidth', 'availHeight']) {
603
+ install(screenPrototype, key, { get: function screenDimension() {
604
+ if (this !== screen) throw new TypeError('Illegal invocation');
605
+ return Number(win[key.endsWith('Width') || key === 'width' ? 'innerWidth' : 'innerHeight']);
606
+ } }, 'screen.' + key, true);
607
+ }
608
+ }
609
+ if (options.physicalMemoryBytes !== undefined) {
610
+ // Device Memory approximation: nearest power of two MiB, ties downward;
611
+ // expose GiB clamped to [0.25, 8]. https://www.w3.org/TR/device-memory/
612
+ const physicalMiB = Math.floor(options.physicalMemoryBytes / 1048576);
613
+ const lower = 2 ** Math.floor(Math.log2(Math.max(1, physicalMiB)));
614
+ const upper = lower * 2;
615
+ const nearest = physicalMiB - lower <= upper - physicalMiB ? lower : upper;
616
+ const memory = Math.min(options.deviceMemoryMaxGiB, Math.max(0.25, nearest / 1024));
617
+ install(navigatorPrototype, 'deviceMemory', { get: function deviceMemory() { checkNavigator(this); return memory; } }, 'navigator.deviceMemory');
618
+ }
619
+ return Object.freeze({
620
+ installed: Object.freeze(installed.slice()),
621
+ snapshot() { return { mediaQueries: { ...mediaQueries, records: mediaQueries.records.map(row => ({ ...row })) } }; },
622
+ dispose() {
623
+ if (disposed) return;
624
+ disposed = true;
625
+ for (const timer of pending.values()) unschedule(timer);
626
+ pending.clear();
627
+ if (cancelFrame) for (const handle of animationFrames) cancelFrame(handle);
628
+ animationFrames.clear();
629
+ if (mediaInstalled) win.removeEventListener('resize', onResize);
630
+ activeLists.clear();
631
+ for (const { object, key, previous, next } of saved.reverse()) {
632
+ const current = Object.getOwnPropertyDescriptor(object, key);
633
+ if (!current || current.value !== next.value || current.get !== next.get || current.set !== next.set) continue;
634
+ if (previous) Object.defineProperty(object, key, previous);
635
+ else delete object[key];
636
+ }
637
+ },
638
+ });
639
+ }