appscms-tools-theme 3.2.0 → 3.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1876 +1,2699 @@
1
1
  /* Partytown 0.7.5 - MIT builder.io */
2
- (self => {
3
- const WinIdKey = Symbol();
4
- const InstanceIdKey = Symbol();
5
- const InstanceDataKey = Symbol();
6
- const NamespaceKey = Symbol();
7
- const ApplyPathKey = Symbol();
8
- const InstanceStateKey = Symbol();
9
- const HookContinue = Symbol();
10
- const HookPrevent = Symbol();
11
- const webWorkerInstances = new Map;
12
- const webWorkerRefsByRefId = {};
13
- const webWorkerRefIdsByRef = new WeakMap;
14
- const postMessages = [];
15
- const webWorkerCtx = {};
16
- const webWorkerlocalStorage = new Map;
17
- const webWorkerSessionStorage = new Map;
18
- const environments = {};
19
- const cachedDimensions = new Map;
20
- const cachedStructure = new Map;
21
- const commaSplit = str => str.split(",");
22
- const partytownLibUrl = url => {
23
- url = webWorkerCtx.$libPath$ + url;
24
- if (new URL(url).origin != location.origin) {
25
- throw "Invalid " + url;
26
- }
27
- return url;
28
- };
29
- const getterDimensionPropNames = commaSplit("clientWidth,clientHeight,clientTop,clientLeft,innerWidth,innerHeight,offsetWidth,offsetHeight,offsetTop,offsetLeft,outerWidth,outerHeight,pageXOffset,pageYOffset,scrollWidth,scrollHeight,scrollTop,scrollLeft");
30
- const elementStructurePropNames = commaSplit("childElementCount,children,firstElementChild,lastElementChild,nextElementSibling,previousElementSibling");
31
- const structureChangingMethodNames = commaSplit("insertBefore,remove,removeChild,replaceChild");
32
- const dimensionChangingSetterNames = commaSplit("className,width,height,hidden,innerHTML,innerText,textContent");
33
- const dimensionChangingMethodNames = commaSplit("setAttribute,setAttributeNS,setProperty");
34
- const eventTargetMethods = commaSplit("addEventListener,dispatchEvent,removeEventListener");
35
- const nonBlockingMethods = eventTargetMethods.concat(dimensionChangingMethodNames, commaSplit("add,observe,remove,unobserve"));
36
- const IS_TAG_REG = /^[A-Z_]([A-Z0-9-]*[A-Z0-9])?$/;
37
- const noop = () => {};
38
- const len = obj => obj.length;
39
- const getConstructorName = obj => {
40
- var _a, _b, _c;
41
- try {
42
- const constructorName = null === (_a = null == obj ? void 0 : obj.constructor) || void 0 === _a ? void 0 : _a.name;
43
- if (constructorName) {
44
- return constructorName;
45
- }
46
- } catch (e) {}
47
- try {
48
- const zoneJsConstructorName = null === (_c = null === (_b = null == obj ? void 0 : obj.__zone_symbol__originalInstance) || void 0 === _b ? void 0 : _b.constructor) || void 0 === _c ? void 0 : _c.name;
49
- if (zoneJsConstructorName) {
50
- return zoneJsConstructorName;
51
- }
52
- } catch (e) {}
53
- return "";
54
- };
55
- const EMPTY_ARRAY = [];
56
- const randomId = () => Math.round(Math.random() * Number.MAX_SAFE_INTEGER).toString(36);
57
- const SCRIPT_TYPE = "text/partytown";
58
- const defineProperty = (obj, memberName, descriptor) => Object.defineProperty(obj, memberName, {
59
- ...descriptor,
60
- configurable: true
2
+ ((self) => {
3
+ const WinIdKey = Symbol();
4
+ const InstanceIdKey = Symbol();
5
+ const InstanceDataKey = Symbol();
6
+ const NamespaceKey = Symbol();
7
+ const ApplyPathKey = Symbol();
8
+ const InstanceStateKey = Symbol();
9
+ const HookContinue = Symbol();
10
+ const HookPrevent = Symbol();
11
+ const webWorkerInstances = new Map();
12
+ const webWorkerRefsByRefId = {};
13
+ const webWorkerRefIdsByRef = new WeakMap();
14
+ const postMessages = [];
15
+ const webWorkerCtx = {};
16
+ const webWorkerlocalStorage = new Map();
17
+ const webWorkerSessionStorage = new Map();
18
+ const environments = {};
19
+ const cachedDimensions = new Map();
20
+ const cachedStructure = new Map();
21
+ const commaSplit = (str) => str.split(",");
22
+ const partytownLibUrl = (url) => {
23
+ url = webWorkerCtx.$libPath$ + url;
24
+ if (new URL(url).origin != location.origin) {
25
+ throw "Invalid " + url;
26
+ }
27
+ return url;
28
+ };
29
+ const getterDimensionPropNames = commaSplit(
30
+ "clientWidth,clientHeight,clientTop,clientLeft,innerWidth,innerHeight,offsetWidth,offsetHeight,offsetTop,offsetLeft,outerWidth,outerHeight,pageXOffset,pageYOffset,scrollWidth,scrollHeight,scrollTop,scrollLeft"
31
+ );
32
+ const elementStructurePropNames = commaSplit(
33
+ "childElementCount,children,firstElementChild,lastElementChild,nextElementSibling,previousElementSibling"
34
+ );
35
+ const structureChangingMethodNames = commaSplit(
36
+ "insertBefore,remove,removeChild,replaceChild"
37
+ );
38
+ const dimensionChangingSetterNames = commaSplit(
39
+ "className,width,height,hidden,innerHTML,innerText,textContent"
40
+ );
41
+ const dimensionChangingMethodNames = commaSplit(
42
+ "setAttribute,setAttributeNS,setProperty"
43
+ );
44
+ const eventTargetMethods = commaSplit(
45
+ "addEventListener,dispatchEvent,removeEventListener"
46
+ );
47
+ const nonBlockingMethods = eventTargetMethods.concat(
48
+ dimensionChangingMethodNames,
49
+ commaSplit("add,observe,remove,unobserve")
50
+ );
51
+ const IS_TAG_REG = /^[A-Z_]([A-Z0-9-]*[A-Z0-9])?$/;
52
+ const noop = () => {};
53
+ const len = (obj) => obj.length;
54
+ const getConstructorName = (obj) => {
55
+ var _a, _b, _c;
56
+ try {
57
+ const constructorName =
58
+ null === (_a = null == obj ? void 0 : obj.constructor) || void 0 === _a
59
+ ? void 0
60
+ : _a.name;
61
+ if (constructorName) {
62
+ return constructorName;
63
+ }
64
+ } catch (e) {}
65
+ try {
66
+ const zoneJsConstructorName =
67
+ null ===
68
+ (_c =
69
+ null ===
70
+ (_b =
71
+ null == obj ? void 0 : obj.__zone_symbol__originalInstance) ||
72
+ void 0 === _b
73
+ ? void 0
74
+ : _b.constructor) || void 0 === _c
75
+ ? void 0
76
+ : _c.name;
77
+ if (zoneJsConstructorName) {
78
+ return zoneJsConstructorName;
79
+ }
80
+ } catch (e) {}
81
+ return "";
82
+ };
83
+ const EMPTY_ARRAY = [];
84
+ const randomId = () =>
85
+ Math.round(Math.random() * Number.MAX_SAFE_INTEGER).toString(36);
86
+ const SCRIPT_TYPE = "text/partytown";
87
+ const defineProperty = (obj, memberName, descriptor) =>
88
+ Object.defineProperty(obj, memberName, {
89
+ ...descriptor,
90
+ configurable: true,
61
91
  });
62
- const defineConstructorName = (Cstr, value) => defineProperty(Cstr, "name", {
63
- value: value
92
+ const defineConstructorName = (Cstr, value) =>
93
+ defineProperty(Cstr, "name", {
94
+ value: value,
64
95
  });
65
- const definePrototypeProperty = (Cstr, memberName, descriptor) => defineProperty(Cstr.prototype, memberName, descriptor);
66
- const definePrototypePropertyDescriptor = (Cstr, propertyDescriptorMap) => Object.defineProperties(Cstr.prototype, propertyDescriptorMap);
67
- const definePrototypeValue = (Cstr, memberName, value) => definePrototypeProperty(Cstr, memberName, {
68
- value: value,
69
- writable: true
96
+ const definePrototypeProperty = (Cstr, memberName, descriptor) =>
97
+ defineProperty(Cstr.prototype, memberName, descriptor);
98
+ const definePrototypePropertyDescriptor = (Cstr, propertyDescriptorMap) =>
99
+ Object.defineProperties(Cstr.prototype, propertyDescriptorMap);
100
+ const definePrototypeValue = (Cstr, memberName, value) =>
101
+ definePrototypeProperty(Cstr, memberName, {
102
+ value: value,
103
+ writable: true,
70
104
  });
71
- const hasInstanceStateValue = (instance, stateKey) => stateKey in instance[InstanceStateKey];
72
- const getInstanceStateValue = (instance, stateKey) => instance[InstanceStateKey][stateKey];
73
- const setInstanceStateValue = (instance, stateKey, stateValue) => instance[InstanceStateKey][stateKey] = stateValue;
74
- const setWorkerRef = (ref, refId) => {
75
- if (!(refId = webWorkerRefIdsByRef.get(ref))) {
76
- webWorkerRefIdsByRef.set(ref, refId = randomId());
77
- webWorkerRefsByRefId[refId] = ref;
78
- }
79
- return refId;
80
- };
81
- const getOrCreateNodeInstance = (winId, instanceId, nodeName, namespace, instance) => {
82
- instance = webWorkerInstances.get(instanceId);
83
- if (!instance && nodeName && environments[winId]) {
84
- instance = environments[winId].$createNode$(nodeName, instanceId, namespace);
85
- webWorkerInstances.set(instanceId, instance);
86
- }
87
- return instance;
88
- };
89
- const definePrototypeNodeType = (Cstr, nodeType) => definePrototypeValue(Cstr, "nodeType", nodeType);
90
- const cachedTreeProps = (Cstr, treeProps) => treeProps.map((propName => definePrototypeProperty(Cstr, propName, {
105
+ const hasInstanceStateValue = (instance, stateKey) =>
106
+ stateKey in instance[InstanceStateKey];
107
+ const getInstanceStateValue = (instance, stateKey) =>
108
+ instance[InstanceStateKey][stateKey];
109
+ const setInstanceStateValue = (instance, stateKey, stateValue) =>
110
+ (instance[InstanceStateKey][stateKey] = stateValue);
111
+ const setWorkerRef = (ref, refId) => {
112
+ if (!(refId = webWorkerRefIdsByRef.get(ref))) {
113
+ webWorkerRefIdsByRef.set(ref, (refId = randomId()));
114
+ webWorkerRefsByRefId[refId] = ref;
115
+ }
116
+ return refId;
117
+ };
118
+ const getOrCreateNodeInstance = (
119
+ winId,
120
+ instanceId,
121
+ nodeName,
122
+ namespace,
123
+ instance
124
+ ) => {
125
+ instance = webWorkerInstances.get(instanceId);
126
+ if (!instance && nodeName && environments[winId]) {
127
+ instance = environments[winId].$createNode$(
128
+ nodeName,
129
+ instanceId,
130
+ namespace
131
+ );
132
+ webWorkerInstances.set(instanceId, instance);
133
+ }
134
+ return instance;
135
+ };
136
+ const definePrototypeNodeType = (Cstr, nodeType) =>
137
+ definePrototypeValue(Cstr, "nodeType", nodeType);
138
+ const cachedTreeProps = (Cstr, treeProps) =>
139
+ treeProps.map((propName) =>
140
+ definePrototypeProperty(Cstr, propName, {
91
141
  get() {
92
- let cacheKey = getInstanceCacheKey(this, propName);
93
- let result = cachedStructure.get(cacheKey);
94
- if (!result) {
95
- result = getter(this, [ propName ]);
96
- cachedStructure.set(cacheKey, result);
97
- }
98
- return result;
99
- }
100
- })));
101
- const getInstanceCacheKey = (instance, memberName, args) => [ instance[WinIdKey], instance[InstanceIdKey], memberName, ...(args || EMPTY_ARRAY).map((arg => String(arg && arg[WinIdKey] ? arg[InstanceIdKey] : arg))) ].join(".");
102
- const cachedProps = (Cstr, propNames) => commaSplit(propNames).map((propName => definePrototypeProperty(Cstr, propName, {
142
+ let cacheKey = getInstanceCacheKey(this, propName);
143
+ let result = cachedStructure.get(cacheKey);
144
+ if (!result) {
145
+ result = getter(this, [propName]);
146
+ cachedStructure.set(cacheKey, result);
147
+ }
148
+ return result;
149
+ },
150
+ })
151
+ );
152
+ const getInstanceCacheKey = (instance, memberName, args) =>
153
+ [
154
+ instance[WinIdKey],
155
+ instance[InstanceIdKey],
156
+ memberName,
157
+ ...(args || EMPTY_ARRAY).map((arg) =>
158
+ String(arg && arg[WinIdKey] ? arg[InstanceIdKey] : arg)
159
+ ),
160
+ ].join(".");
161
+ const cachedProps = (Cstr, propNames) =>
162
+ commaSplit(propNames).map((propName) =>
163
+ definePrototypeProperty(Cstr, propName, {
103
164
  get() {
104
- hasInstanceStateValue(this, propName) || setInstanceStateValue(this, propName, getter(this, [ propName ]));
105
- return getInstanceStateValue(this, propName);
165
+ hasInstanceStateValue(this, propName) ||
166
+ setInstanceStateValue(this, propName, getter(this, [propName]));
167
+ return getInstanceStateValue(this, propName);
106
168
  },
107
169
  set(val) {
108
- getInstanceStateValue(this, propName) !== val && setter(this, [ propName ], val);
109
- setInstanceStateValue(this, propName, val);
110
- }
111
- })));
112
- const cachedDimensionProps = Cstr => getterDimensionPropNames.map((propName => definePrototypeProperty(Cstr, propName, {
170
+ getInstanceStateValue(this, propName) !== val &&
171
+ setter(this, [propName], val);
172
+ setInstanceStateValue(this, propName, val);
173
+ },
174
+ })
175
+ );
176
+ const cachedDimensionProps = (Cstr) =>
177
+ getterDimensionPropNames.map((propName) =>
178
+ definePrototypeProperty(Cstr, propName, {
113
179
  get() {
114
- const dimension = cachedDimensions.get(getInstanceCacheKey(this, propName));
115
- if ("number" == typeof dimension) {
116
- return dimension;
117
- }
118
- const groupedDimensions = getter(this, [ propName ], getterDimensionPropNames);
119
- if (groupedDimensions && "object" == typeof groupedDimensions) {
120
- Object.entries(groupedDimensions).map((([dimensionPropName, value]) => cachedDimensions.set(getInstanceCacheKey(this, dimensionPropName), value)));
121
- return groupedDimensions[propName];
122
- }
123
- return groupedDimensions;
124
- }
125
- })));
126
- const cachedDimensionMethods = (Cstr, dimensionMethodNames) => dimensionMethodNames.map((methodName => {
127
- Cstr.prototype[methodName] = function(...args) {
128
- let cacheKey = getInstanceCacheKey(this, methodName, args);
129
- let dimensions = cachedDimensions.get(cacheKey);
130
- if (!dimensions) {
131
- dimensions = callMethod(this, [ methodName ], args);
132
- cachedDimensions.set(cacheKey, dimensions);
133
- }
134
- return dimensions;
135
- };
136
- }));
137
- const serializeForMain = ($winId$, $instanceId$, value, added, type) => void 0 !== value && (type = typeof value) ? "string" === type || "boolean" === type || "number" === type || null == value ? [ 0, value ] : "function" === type ? [ 4, {
138
- $winId$: $winId$,
139
- $instanceId$: $instanceId$,
140
- $refId$: setWorkerRef(value)
141
- } ] : (added = added || new Set) && Array.isArray(value) ? added.has(value) ? [ 1, [] ] : added.add(value) && [ 1, value.map((v => serializeForMain($winId$, $instanceId$, v, added))) ] : "object" === type ? value[InstanceIdKey] ? [ 3, [ value[WinIdKey], value[InstanceIdKey] ] ] : value instanceof Event ? [ 5, serializeObjectForMain($winId$, $instanceId$, value, false, added) ] : supportsTrustedHTML && value instanceof TrustedHTML ? [ 0, value.toString() ] : value instanceof ArrayBuffer ? [ 8, value ] : ArrayBuffer.isView(value) ? [ 9, value.buffer, getConstructorName(value) ] : [ 2, serializeObjectForMain($winId$, $instanceId$, value, true, added) ] : void 0 : value;
142
- const supportsTrustedHTML = "undefined" != typeof TrustedHTML;
143
- const serializeObjectForMain = (winId, instanceId, obj, includeFunctions, added, serializedObj, propName, propValue) => {
144
- serializedObj = {};
145
- if (!added.has(obj)) {
146
- added.add(obj);
147
- for (propName in obj) {
148
- propValue = obj[propName];
149
- (includeFunctions || "function" != typeof propValue) && (serializedObj[propName] = serializeForMain(winId, instanceId, propValue, added));
150
- }
151
- }
152
- return serializedObj;
153
- };
154
- const serializeInstanceForMain = (instance, value) => instance ? serializeForMain(instance[WinIdKey], instance[InstanceIdKey], value) : [ 0, value ];
155
- const deserializeFromMain = (winId, instanceId, applyPath, serializedValueTransfer, serializedType, serializedValue, obj, key) => {
156
- if (serializedValueTransfer) {
157
- serializedType = serializedValueTransfer[0];
158
- serializedValue = serializedValueTransfer[1];
159
- if (0 === serializedType || 11 === serializedType || 12 === serializedType) {
160
- return serializedValue;
161
- }
162
- if (4 === serializedType) {
163
- return deserializeRefFromMain(applyPath, serializedValue);
164
- }
165
- if (6 === serializedType) {
166
- return winId && applyPath.length > 0 ? (...args) => callMethod(environments[winId].$window$, applyPath, args, 1) : noop;
167
- }
168
- if (3 === serializedType) {
169
- return getOrCreateSerializedInstance(serializedValue);
170
- }
171
- if (7 === serializedType) {
172
- return new NodeList(serializedValue.map(getOrCreateSerializedInstance));
173
- }
174
- if (10 === serializedType) {
175
- return new Attr(serializedValue);
176
- }
177
- if (1 === serializedType) {
178
- return serializedValue.map((v => deserializeFromMain(winId, instanceId, applyPath, v)));
179
- }
180
- if (14 === serializedType) {
181
- return new CustomError(serializedValue);
182
- }
183
- obj = {};
184
- for (key in serializedValue) {
185
- obj[key] = deserializeFromMain(winId, instanceId, [ ...applyPath, key ], serializedValue[key]);
186
- }
187
- if (13 === serializedType) {
188
- return new environments[winId].$window$.CSSStyleDeclaration(winId, instanceId, applyPath, obj);
189
- }
190
- if (5 === serializedType) {
191
- if ("message" === obj.type && obj.origin) {
192
- let postMessageKey = JSON.stringify(obj.data);
193
- let postMessageData = postMessages.find((pm => pm.$data$ === postMessageKey));
194
- let env;
195
- if (postMessageData) {
196
- env = environments[postMessageData.$winId$];
197
- if (env) {
198
- obj.source = env.$window$;
199
- obj.origin = env.$location$.origin;
200
- }
201
- }
202
- }
203
- return new Proxy(new Event(obj.type, obj), {
204
- get: (target, propName) => propName in obj ? obj[propName] : "function" == typeof target[String(propName)] ? noop : target[String(propName)]
205
- });
206
- }
207
- if (2 === serializedType) {
208
- return obj;
209
- }
210
- }
211
- };
212
- const getOrCreateSerializedInstance = ([winId, instanceId, nodeName]) => instanceId === winId && environments[winId] ? environments[winId].$window$ : getOrCreateNodeInstance(winId, instanceId, nodeName);
213
- const deserializeRefFromMain = (applyPath, {$winId$: $winId$, $instanceId$: $instanceId$, $nodeName$: $nodeName$, $refId$: $refId$}) => {
214
- webWorkerRefsByRefId[$refId$] || webWorkerRefIdsByRef.set(webWorkerRefsByRefId[$refId$] = function(...args) {
215
- const instance = getOrCreateNodeInstance($winId$, $instanceId$, $nodeName$);
216
- return callMethod(instance, applyPath, args);
217
- }, $refId$);
218
- return webWorkerRefsByRefId[$refId$];
219
- };
220
- class CustomError extends Error {
221
- constructor(errorObject) {
222
- super(errorObject.message);
223
- this.name = errorObject.name;
224
- this.message = errorObject.message;
225
- this.stack = errorObject.stack;
180
+ const dimension = cachedDimensions.get(
181
+ getInstanceCacheKey(this, propName)
182
+ );
183
+ if ("number" == typeof dimension) {
184
+ return dimension;
185
+ }
186
+ const groupedDimensions = getter(
187
+ this,
188
+ [propName],
189
+ getterDimensionPropNames
190
+ );
191
+ if (groupedDimensions && "object" == typeof groupedDimensions) {
192
+ Object.entries(groupedDimensions).map(
193
+ ([dimensionPropName, value]) =>
194
+ cachedDimensions.set(
195
+ getInstanceCacheKey(this, dimensionPropName),
196
+ value
197
+ )
198
+ );
199
+ return groupedDimensions[propName];
200
+ }
201
+ return groupedDimensions;
202
+ },
203
+ })
204
+ );
205
+ const cachedDimensionMethods = (Cstr, dimensionMethodNames) =>
206
+ dimensionMethodNames.map((methodName) => {
207
+ Cstr.prototype[methodName] = function (...args) {
208
+ let cacheKey = getInstanceCacheKey(this, methodName, args);
209
+ let dimensions = cachedDimensions.get(cacheKey);
210
+ if (!dimensions) {
211
+ dimensions = callMethod(this, [methodName], args);
212
+ cachedDimensions.set(cacheKey, dimensions);
226
213
  }
214
+ return dimensions;
215
+ };
216
+ });
217
+ const serializeForMain = ($winId$, $instanceId$, value, added, type) =>
218
+ void 0 !== value && (type = typeof value)
219
+ ? "string" === type ||
220
+ "boolean" === type ||
221
+ "number" === type ||
222
+ null == value
223
+ ? [0, value]
224
+ : "function" === type
225
+ ? [
226
+ 4,
227
+ {
228
+ $winId$: $winId$,
229
+ $instanceId$: $instanceId$,
230
+ $refId$: setWorkerRef(value),
231
+ },
232
+ ]
233
+ : (added = added || new Set()) && Array.isArray(value)
234
+ ? added.has(value)
235
+ ? [1, []]
236
+ : added.add(value) && [
237
+ 1,
238
+ value.map((v) =>
239
+ serializeForMain($winId$, $instanceId$, v, added)
240
+ ),
241
+ ]
242
+ : "object" === type
243
+ ? value[InstanceIdKey]
244
+ ? [3, [value[WinIdKey], value[InstanceIdKey]]]
245
+ : value instanceof Event
246
+ ? [
247
+ 5,
248
+ serializeObjectForMain(
249
+ $winId$,
250
+ $instanceId$,
251
+ value,
252
+ false,
253
+ added
254
+ ),
255
+ ]
256
+ : supportsTrustedHTML && value instanceof TrustedHTML
257
+ ? [0, value.toString()]
258
+ : value instanceof ArrayBuffer
259
+ ? [8, value]
260
+ : ArrayBuffer.isView(value)
261
+ ? [9, value.buffer, getConstructorName(value)]
262
+ : [
263
+ 2,
264
+ serializeObjectForMain($winId$, $instanceId$, value, true, added),
265
+ ]
266
+ : void 0
267
+ : value;
268
+ const supportsTrustedHTML = "undefined" != typeof TrustedHTML;
269
+ const serializeObjectForMain = (
270
+ winId,
271
+ instanceId,
272
+ obj,
273
+ includeFunctions,
274
+ added,
275
+ serializedObj,
276
+ propName,
277
+ propValue
278
+ ) => {
279
+ serializedObj = {};
280
+ if (!added.has(obj)) {
281
+ added.add(obj);
282
+ for (propName in obj) {
283
+ propValue = obj[propName];
284
+ (includeFunctions || "function" != typeof propValue) &&
285
+ (serializedObj[propName] = serializeForMain(
286
+ winId,
287
+ instanceId,
288
+ propValue,
289
+ added
290
+ ));
291
+ }
227
292
  }
228
- class NodeList {
229
- constructor(nodes) {
230
- (this._ = nodes).map(((node, index) => this[index] = node));
231
- }
232
- entries() {
233
- return this._.entries();
234
- }
235
- forEach(cb, thisArg) {
236
- this._.map(cb, thisArg);
237
- }
238
- item(index) {
239
- return this[index];
240
- }
241
- keys() {
242
- return this._.keys();
243
- }
244
- get length() {
245
- return len(this._);
246
- }
247
- values() {
248
- return this._.values();
249
- }
250
- [Symbol.iterator]() {
251
- return this._[Symbol.iterator]();
293
+ return serializedObj;
294
+ };
295
+ const serializeInstanceForMain = (instance, value) =>
296
+ instance
297
+ ? serializeForMain(instance[WinIdKey], instance[InstanceIdKey], value)
298
+ : [0, value];
299
+ const deserializeFromMain = (
300
+ winId,
301
+ instanceId,
302
+ applyPath,
303
+ serializedValueTransfer,
304
+ serializedType,
305
+ serializedValue,
306
+ obj,
307
+ key
308
+ ) => {
309
+ if (serializedValueTransfer) {
310
+ serializedType = serializedValueTransfer[0];
311
+ serializedValue = serializedValueTransfer[1];
312
+ if (
313
+ 0 === serializedType ||
314
+ 11 === serializedType ||
315
+ 12 === serializedType
316
+ ) {
317
+ return serializedValue;
318
+ }
319
+ if (4 === serializedType) {
320
+ return deserializeRefFromMain(applyPath, serializedValue);
321
+ }
322
+ if (6 === serializedType) {
323
+ return winId && applyPath.length > 0
324
+ ? (...args) =>
325
+ callMethod(environments[winId].$window$, applyPath, args, 1)
326
+ : noop;
327
+ }
328
+ if (3 === serializedType) {
329
+ return getOrCreateSerializedInstance(serializedValue);
330
+ }
331
+ if (7 === serializedType) {
332
+ return new NodeList(serializedValue.map(getOrCreateSerializedInstance));
333
+ }
334
+ if (10 === serializedType) {
335
+ return new Attr(serializedValue);
336
+ }
337
+ if (1 === serializedType) {
338
+ return serializedValue.map((v) =>
339
+ deserializeFromMain(winId, instanceId, applyPath, v)
340
+ );
341
+ }
342
+ if (14 === serializedType) {
343
+ return new CustomError(serializedValue);
344
+ }
345
+ obj = {};
346
+ for (key in serializedValue) {
347
+ obj[key] = deserializeFromMain(
348
+ winId,
349
+ instanceId,
350
+ [...applyPath, key],
351
+ serializedValue[key]
352
+ );
353
+ }
354
+ if (13 === serializedType) {
355
+ return new environments[winId].$window$.CSSStyleDeclaration(
356
+ winId,
357
+ instanceId,
358
+ applyPath,
359
+ obj
360
+ );
361
+ }
362
+ if (5 === serializedType) {
363
+ if ("message" === obj.type && obj.origin) {
364
+ let postMessageKey = JSON.stringify(obj.data);
365
+ let postMessageData = postMessages.find(
366
+ (pm) => pm.$data$ === postMessageKey
367
+ );
368
+ let env;
369
+ if (postMessageData) {
370
+ env = environments[postMessageData.$winId$];
371
+ if (env) {
372
+ obj.source = env.$window$;
373
+ obj.origin = env.$location$.origin;
374
+ }
375
+ }
252
376
  }
377
+ return new Proxy(new Event(obj.type, obj), {
378
+ get: (target, propName) =>
379
+ propName in obj
380
+ ? obj[propName]
381
+ : "function" == typeof target[String(propName)]
382
+ ? noop
383
+ : target[String(propName)],
384
+ });
385
+ }
386
+ if (2 === serializedType) {
387
+ return obj;
388
+ }
389
+ }
390
+ };
391
+ const getOrCreateSerializedInstance = ([winId, instanceId, nodeName]) =>
392
+ instanceId === winId && environments[winId]
393
+ ? environments[winId].$window$
394
+ : getOrCreateNodeInstance(winId, instanceId, nodeName);
395
+ const deserializeRefFromMain = (
396
+ applyPath,
397
+ {
398
+ $winId$: $winId$,
399
+ $instanceId$: $instanceId$,
400
+ $nodeName$: $nodeName$,
401
+ $refId$: $refId$,
402
+ }
403
+ ) => {
404
+ webWorkerRefsByRefId[$refId$] ||
405
+ webWorkerRefIdsByRef.set(
406
+ (webWorkerRefsByRefId[$refId$] = function (...args) {
407
+ const instance = getOrCreateNodeInstance(
408
+ $winId$,
409
+ $instanceId$,
410
+ $nodeName$
411
+ );
412
+ return callMethod(instance, applyPath, args);
413
+ }),
414
+ $refId$
415
+ );
416
+ return webWorkerRefsByRefId[$refId$];
417
+ };
418
+ class CustomError extends Error {
419
+ constructor(errorObject) {
420
+ super(errorObject.message);
421
+ this.name = errorObject.name;
422
+ this.message = errorObject.message;
423
+ this.stack = errorObject.stack;
424
+ }
425
+ }
426
+ class NodeList {
427
+ constructor(nodes) {
428
+ (this._ = nodes).map((node, index) => (this[index] = node));
429
+ }
430
+ entries() {
431
+ return this._.entries();
432
+ }
433
+ forEach(cb, thisArg) {
434
+ this._.map(cb, thisArg);
435
+ }
436
+ item(index) {
437
+ return this[index];
438
+ }
439
+ keys() {
440
+ return this._.keys();
441
+ }
442
+ get length() {
443
+ return len(this._);
444
+ }
445
+ values() {
446
+ return this._.values();
447
+ }
448
+ [Symbol.iterator]() {
449
+ return this._[Symbol.iterator]();
253
450
  }
254
- const Attr = class {
255
- constructor(serializedAttr) {
256
- this.name = serializedAttr[0];
257
- this.value = serializedAttr[1];
451
+ }
452
+ const Attr = class {
453
+ constructor(serializedAttr) {
454
+ this.name = serializedAttr[0];
455
+ this.value = serializedAttr[1];
456
+ }
457
+ get nodeName() {
458
+ return this.name;
459
+ }
460
+ get nodeType() {
461
+ return 2;
462
+ }
463
+ };
464
+ const warnCrossOrgin = (apiType, apiName, env) =>
465
+ console.warn(
466
+ `Partytown unable to ${apiType} cross-origin ${apiName}: ` +
467
+ env.$location$
468
+ );
469
+ const logWorker = (msg, winId) => {
470
+ try {
471
+ const config = webWorkerCtx.$config$;
472
+ if (config.logStackTraces) {
473
+ const frames = new Error().stack.split("\n");
474
+ const i = frames.findIndex((f) => f.includes("logWorker"));
475
+ msg += "\n" + frames.slice(i + 1).join("\n");
476
+ }
477
+ let prefix;
478
+ let color;
479
+ if (winId) {
480
+ prefix = `Worker (${normalizedWinId(winId)}) 🎉`;
481
+ color = winColor(winId);
482
+ } else {
483
+ prefix = self.name;
484
+ color = "#9844bf";
485
+ }
486
+ if (webWorkerCtx.lastLog !== msg) {
487
+ webWorkerCtx.lastLog = msg;
488
+ console.debug.apply(console, [
489
+ `%c${prefix}`,
490
+ `background: ${color}; color: white; padding: 2px 3px; border-radius: 2px; font-size: 0.8em;`,
491
+ msg,
492
+ ]);
493
+ }
494
+ } catch (e) {}
495
+ };
496
+ const winIds = [];
497
+ const normalizedWinId = (winId) => {
498
+ winIds.includes(winId) || winIds.push(winId);
499
+ return winIds.indexOf(winId) + 1;
500
+ };
501
+ const winColor = (winId) => {
502
+ const colors = ["#00309e", "#ea3655", "#eea727"];
503
+ const index = normalizedWinId(winId) - 1;
504
+ return colors[index] || colors[colors.length - 1];
505
+ };
506
+ const getTargetProp = (target, applyPath) => {
507
+ let n = "";
508
+ if (target) {
509
+ const cstrName = getConstructorName(target);
510
+ if ("Window" === cstrName) {
511
+ n = "";
512
+ } else if ("string" == typeof target[InstanceDataKey]) {
513
+ let nodeName = target[InstanceDataKey];
514
+ n =
515
+ "#text" === nodeName
516
+ ? "textNode."
517
+ : "#comment" === nodeName
518
+ ? "commentNode."
519
+ : "#document" === nodeName
520
+ ? "document."
521
+ : "html" === nodeName
522
+ ? "doctype."
523
+ : nodeName.toLowerCase() + ".";
524
+ } else {
525
+ n =
526
+ "nodeType" in target && 2 === target.nodeType
527
+ ? "attributes."
528
+ : "CanvasRenderingContext2D" === cstrName
529
+ ? "context2D."
530
+ : "CanvasRenderingContextWebGL" === cstrName
531
+ ? "contextWebGL."
532
+ : "CSSStyleDeclaration" === cstrName
533
+ ? "style."
534
+ : "MutationObserver" === cstrName
535
+ ? "mutationObserver."
536
+ : "NamedNodeMap" === cstrName
537
+ ? "namedNodeMap."
538
+ : "ResizeObserver" === cstrName
539
+ ? "resizeObserver."
540
+ : cstrName.substring(0, 1).toLowerCase() +
541
+ cstrName.substring(1) +
542
+ ".";
543
+ }
544
+ target[ApplyPathKey] &&
545
+ target[ApplyPathKey].length &&
546
+ (n += [...target[ApplyPathKey]].join(".") + ".");
547
+ }
548
+ if (applyPath.length > 1) {
549
+ const first = applyPath.slice(0, applyPath.length - 1);
550
+ const last = applyPath[applyPath.length - 1];
551
+ if (!isNaN(last)) {
552
+ return n + `${first.join(".")}[${last}]`;
553
+ }
554
+ }
555
+ return n + applyPath.join(".");
556
+ };
557
+ const getLogValue = (applyPath, v) => {
558
+ const type = typeof v;
559
+ if (void 0 === v) {
560
+ return "undefined";
561
+ }
562
+ if ("boolean" === type || "number" === type || null == v) {
563
+ return JSON.stringify(v);
564
+ }
565
+ if ("string" === type) {
566
+ return applyPath.includes("cookie")
567
+ ? JSON.stringify(v.slice(0, 10) + "...")
568
+ : JSON.stringify(v.length > 50 ? v.slice(0, 40) + "..." : v);
569
+ }
570
+ if (Array.isArray(v)) {
571
+ return `[${v.map(getLogValue).join(", ")}]`;
572
+ }
573
+ if ("object" === type) {
574
+ const instanceId = v[InstanceIdKey];
575
+ const cstrName = getConstructorName(v);
576
+ if ("string" == typeof instanceId) {
577
+ if ("Window" === cstrName) {
578
+ return "window";
258
579
  }
259
- get nodeName() {
260
- return this.name;
580
+ if ("string" == typeof v[InstanceDataKey]) {
581
+ if (1 === v.nodeType) {
582
+ return `<${v[InstanceDataKey].toLowerCase()}>`;
583
+ }
584
+ if (10 === v.nodeType) {
585
+ return `<!DOCTYPE ${v[InstanceDataKey]}>`;
586
+ }
587
+ if (v.nodeType <= 11) {
588
+ return v[InstanceDataKey];
589
+ }
261
590
  }
262
- get nodeType() {
263
- return 2;
591
+ return "¯\\_()_/¯ instance obj";
592
+ }
593
+ return v[Symbol.iterator]
594
+ ? `[${Array.from(v)
595
+ .map((i) => getLogValue(applyPath, i))
596
+ .join(", ")}]`
597
+ : "value" in v
598
+ ? "string" == typeof v.value
599
+ ? `"${v.value}"`
600
+ : objToString(v.value)
601
+ : objToString(v);
602
+ }
603
+ return ((v) => "object" == typeof v && v && v.then)(v)
604
+ ? "Promise"
605
+ : "function" === type
606
+ ? `ƒ() ${v.name || ""}`.trim()
607
+ : `¯\\_(ツ)_/¯ ${String(v)}`.trim();
608
+ };
609
+ const objToString = (obj) => {
610
+ const s = [];
611
+ for (let key in obj) {
612
+ const value = obj[key];
613
+ const type = typeof value;
614
+ "string" === type
615
+ ? s.push(`${key}: "${value}"`)
616
+ : "function" === type
617
+ ? s.push(`${key}: ƒ`)
618
+ : Array.isArray(type)
619
+ ? s.push(`${key}: [..]`)
620
+ : "object" === type && value
621
+ ? s.push(`${key}: {..}`)
622
+ : s.push(`${key}: ${String(value)}`);
623
+ }
624
+ let str = s.join(", ");
625
+ str.length > 200 && (str = str.substring(0, 200) + "..");
626
+ return `{ ${str} }`;
627
+ };
628
+ const logDimensionCacheClearStyle = (target, propName) => {
629
+ (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logSetters) &&
630
+ logWorker(
631
+ `Dimension cache cleared from style.${propName} setter`,
632
+ target[WinIdKey]
633
+ );
634
+ };
635
+ const logDimensionCacheClearMethod = (target, methodName) => {
636
+ (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logCalls) &&
637
+ logWorker(
638
+ `Dimension cache cleared from method call ${methodName}()`,
639
+ target[WinIdKey]
640
+ );
641
+ };
642
+ const taskQueue = [];
643
+ const queue = (
644
+ instance,
645
+ $applyPath$,
646
+ callType,
647
+ $assignInstanceId$,
648
+ $groupedGetters$,
649
+ buffer
650
+ ) => {
651
+ if (instance[ApplyPathKey]) {
652
+ taskQueue.push({
653
+ $winId$: instance[WinIdKey],
654
+ $instanceId$: instance[InstanceIdKey],
655
+ $applyPath$: [...instance[ApplyPathKey], ...$applyPath$],
656
+ $assignInstanceId$: $assignInstanceId$,
657
+ $groupedGetters$: $groupedGetters$,
658
+ });
659
+ taskQueue[len(taskQueue) - 1].$debug$ = ((
660
+ target,
661
+ applyPath,
662
+ callType
663
+ ) => {
664
+ let m = getTargetProp(target, applyPath);
665
+ 1 === callType
666
+ ? (m += " (blocking)")
667
+ : 2 === callType
668
+ ? (m += " (non-blocking)")
669
+ : 3 === callType && (m += " (non-blocking, no-side-effect)");
670
+ return m.trim();
671
+ })(instance, $applyPath$, callType);
672
+ buffer &&
673
+ 3 !== callType &&
674
+ console.error("buffer must be sent NonBlockingNoSideEffect");
675
+ if (3 === callType) {
676
+ webWorkerCtx.$postMessage$(
677
+ [
678
+ 12,
679
+ {
680
+ $msgId$: randomId(),
681
+ $tasks$: [...taskQueue],
682
+ },
683
+ ],
684
+ buffer
685
+ ? [buffer instanceof ArrayBuffer ? buffer : buffer.buffer]
686
+ : void 0
687
+ );
688
+ taskQueue.length = 0;
689
+ } else if (1 === callType) {
690
+ return sendToMain(true);
691
+ }
692
+ webWorkerCtx.$asyncMsgTimer$ = setTimeout(sendToMain, 20);
693
+ }
694
+ };
695
+ const sendToMain = (isBlocking) => {
696
+ clearTimeout(webWorkerCtx.$asyncMsgTimer$);
697
+ if (len(taskQueue)) {
698
+ webWorkerCtx.$config$.logMainAccess &&
699
+ logWorker(`Main access, tasks sent: ${taskQueue.length}`);
700
+ const endTask = taskQueue[len(taskQueue) - 1];
701
+ const accessReq = {
702
+ $msgId$: randomId(),
703
+ $tasks$: [...taskQueue],
704
+ };
705
+ taskQueue.length = 0;
706
+ if (isBlocking) {
707
+ const accessRsp = ((webWorkerCtx, accessReq) => {
708
+ const sharedDataBuffer = webWorkerCtx.$sharedDataBuffer$;
709
+ const sharedData = new Int32Array(sharedDataBuffer);
710
+ Atomics.store(sharedData, 0, 0);
711
+ webWorkerCtx.$postMessage$([11, accessReq]);
712
+ Atomics.wait(sharedData, 0, 0);
713
+ let dataLength = Atomics.load(sharedData, 0);
714
+ let accessRespStr = "";
715
+ let i = 0;
716
+ for (; i < dataLength; i++) {
717
+ accessRespStr += String.fromCharCode(sharedData[i + 1]);
718
+ }
719
+ return JSON.parse(accessRespStr);
720
+ })(webWorkerCtx, accessReq);
721
+ const isPromise = accessRsp.$isPromise$;
722
+ const rtnValue = deserializeFromMain(
723
+ endTask.$winId$,
724
+ endTask.$instanceId$,
725
+ endTask.$applyPath$,
726
+ accessRsp.$rtnValue$
727
+ );
728
+ if (accessRsp.$error$) {
729
+ if (isPromise) {
730
+ return Promise.reject(accessRsp.$error$);
731
+ }
732
+ throw new Error(accessRsp.$error$);
264
733
  }
265
- };
266
- const warnCrossOrgin = (apiType, apiName, env) => console.warn(`Partytown unable to ${apiType} cross-origin ${apiName}: ` + env.$location$);
267
- const logWorker = (msg, winId) => {
734
+ return isPromise ? Promise.resolve(rtnValue) : rtnValue;
735
+ }
736
+ webWorkerCtx.$postMessage$([12, accessReq]);
737
+ }
738
+ };
739
+ const getter = (instance, applyPath, groupedGetters, rtnValue) => {
740
+ if (webWorkerCtx.$config$.get) {
741
+ rtnValue = webWorkerCtx.$config$.get(
742
+ createHookOptions(instance, applyPath)
743
+ );
744
+ if (rtnValue !== HookContinue) {
745
+ return rtnValue;
746
+ }
747
+ }
748
+ rtnValue = queue(instance, applyPath, 1, void 0, groupedGetters);
749
+ ((
750
+ target,
751
+ applyPath,
752
+ rtnValue,
753
+ restrictedToWorker = false,
754
+ groupedGetters = false
755
+ ) => {
756
+ if (webWorkerCtx.$config$.logGetters) {
268
757
  try {
269
- const config = webWorkerCtx.$config$;
270
- if (config.logStackTraces) {
271
- const frames = (new Error).stack.split("\n");
272
- const i = frames.findIndex((f => f.includes("logWorker")));
273
- msg += "\n" + frames.slice(i + 1).join("\n");
274
- }
275
- let prefix;
276
- let color;
277
- if (winId) {
278
- prefix = `Worker (${normalizedWinId(winId)}) 🎉`;
279
- color = winColor(winId);
280
- } else {
281
- prefix = self.name;
282
- color = "#9844bf";
283
- }
284
- if (webWorkerCtx.lastLog !== msg) {
285
- webWorkerCtx.lastLog = msg;
286
- console.debug.apply(console, [ `%c${prefix}`, `background: ${color}; color: white; padding: 2px 3px; border-radius: 2px; font-size: 0.8em;`, msg ]);
287
- }
758
+ const msg = `Get ${getTargetProp(
759
+ target,
760
+ applyPath
761
+ )}, returned: ${getLogValue(applyPath, rtnValue)}${
762
+ restrictedToWorker ? " (restricted to worker)" : ""
763
+ }${groupedGetters ? " (grouped getter)" : ""}`;
764
+ msg.includes("Symbol(") || logWorker(msg, target[WinIdKey]);
288
765
  } catch (e) {}
766
+ }
767
+ })(instance, applyPath, rtnValue, false, !!groupedGetters);
768
+ return rtnValue;
769
+ };
770
+ const setter = (instance, applyPath, value, hookSetterValue) => {
771
+ if (webWorkerCtx.$config$.set) {
772
+ hookSetterValue = webWorkerCtx.$config$.set({
773
+ value: value,
774
+ prevent: HookPrevent,
775
+ ...createHookOptions(instance, applyPath),
776
+ });
777
+ if (hookSetterValue === HookPrevent) {
778
+ return;
779
+ }
780
+ hookSetterValue !== HookContinue && (value = hookSetterValue);
781
+ }
782
+ if (dimensionChangingSetterNames.some((s) => applyPath.includes(s))) {
783
+ cachedDimensions.clear();
784
+ ((target, propName) => {
785
+ (webWorkerCtx.$config$.logGetters ||
786
+ webWorkerCtx.$config$.logSetters) &&
787
+ logWorker(
788
+ `Dimension cache cleared from setter "${propName}"`,
789
+ target[WinIdKey]
790
+ );
791
+ })(instance, applyPath[applyPath.length - 1]);
792
+ }
793
+ applyPath = [...applyPath, serializeInstanceForMain(instance, value), 0];
794
+ ((target, applyPath, value, restrictedToWorker = false) => {
795
+ if (webWorkerCtx.$config$.logSetters) {
796
+ try {
797
+ applyPath = applyPath.slice(0, applyPath.length - 2);
798
+ logWorker(
799
+ `Set ${getTargetProp(target, applyPath)}, value: ${getLogValue(
800
+ applyPath,
801
+ value
802
+ )}${restrictedToWorker ? " (restricted to worker)" : ""}`,
803
+ target[WinIdKey]
804
+ );
805
+ } catch (e) {}
806
+ }
807
+ })(instance, applyPath, value);
808
+ queue(instance, applyPath, 2);
809
+ };
810
+ const callMethod = (
811
+ instance,
812
+ applyPath,
813
+ args,
814
+ callType,
815
+ assignInstanceId,
816
+ buffer,
817
+ rtnValue,
818
+ methodName
819
+ ) => {
820
+ if (webWorkerCtx.$config$.apply) {
821
+ rtnValue = webWorkerCtx.$config$.apply({
822
+ args: args,
823
+ ...createHookOptions(instance, applyPath),
824
+ });
825
+ if (rtnValue !== HookContinue) {
826
+ return rtnValue;
827
+ }
828
+ }
829
+ methodName = applyPath[len(applyPath) - 1];
830
+ applyPath = [...applyPath, serializeInstanceForMain(instance, args)];
831
+ callType = callType || (nonBlockingMethods.includes(methodName) ? 2 : 1);
832
+ if (
833
+ "setAttribute" === methodName &&
834
+ hasInstanceStateValue(instance, args[0])
835
+ ) {
836
+ setInstanceStateValue(instance, args[0], args[1]);
837
+ } else if (structureChangingMethodNames.includes(methodName)) {
838
+ cachedDimensions.clear();
839
+ cachedStructure.clear();
840
+ ((target, methodName) => {
841
+ (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logCalls) &&
842
+ logWorker(
843
+ `Dimension and DOM structure cache cleared from method call ${methodName}()`,
844
+ target[WinIdKey]
845
+ );
846
+ })(instance, methodName);
847
+ } else if (dimensionChangingMethodNames.includes(methodName)) {
848
+ callType = 2;
849
+ cachedDimensions.clear();
850
+ logDimensionCacheClearMethod(instance, methodName);
851
+ }
852
+ rtnValue = queue(
853
+ instance,
854
+ applyPath,
855
+ callType,
856
+ assignInstanceId,
857
+ void 0,
858
+ buffer
859
+ );
860
+ ((target, applyPath, args, rtnValue) => {
861
+ if (webWorkerCtx.$config$.logCalls) {
862
+ try {
863
+ applyPath = applyPath.slice(0, applyPath.length - 1);
864
+ logWorker(
865
+ `Call ${getTargetProp(target, applyPath)}(${args
866
+ .map((v) => getLogValue(applyPath, v))
867
+ .join(", ")}), returned: ${getLogValue(applyPath, rtnValue)}`,
868
+ target[WinIdKey]
869
+ );
870
+ } catch (e) {}
871
+ }
872
+ })(instance, applyPath, args, rtnValue);
873
+ return rtnValue;
874
+ };
875
+ const constructGlobal = (instance, cstrName, args) => {
876
+ ((target, cstrName, args) => {
877
+ if (webWorkerCtx.$config$.logCalls) {
878
+ try {
879
+ logWorker(
880
+ `Construct new ${cstrName}(${args
881
+ .map((v) => getLogValue([], v))
882
+ .join(", ")})`,
883
+ target[WinIdKey]
884
+ );
885
+ } catch (e) {}
886
+ }
887
+ })(instance, cstrName, args);
888
+ queue(instance, [1, cstrName, serializeInstanceForMain(instance, args)], 1);
889
+ };
890
+ const createHookOptions = (instance, applyPath) => ({
891
+ name: applyPath.join("."),
892
+ continue: HookContinue,
893
+ nodeName: instance[InstanceDataKey],
894
+ constructor: getConstructorName(instance),
895
+ instance: instance,
896
+ window: environments[instance[WinIdKey]].$window$,
897
+ });
898
+ const addStorageApi = (win, storageName, storages, isSameOrigin, env) => {
899
+ let getItems = (items) => {
900
+ items = storages.get(win.origin);
901
+ items || storages.set(win.origin, (items = []));
902
+ return items;
289
903
  };
290
- const winIds = [];
291
- const normalizedWinId = winId => {
292
- winIds.includes(winId) || winIds.push(winId);
293
- return winIds.indexOf(winId) + 1;
294
- };
295
- const winColor = winId => {
296
- const colors = [ "#00309e", "#ea3655", "#eea727" ];
297
- const index = normalizedWinId(winId) - 1;
298
- return colors[index] || colors[colors.length - 1];
904
+ let getIndexByKey = (key) =>
905
+ getItems().findIndex((i) => i[STORAGE_KEY] === key);
906
+ let index;
907
+ let item;
908
+ let storage = {
909
+ getItem(key) {
910
+ index = getIndexByKey(key);
911
+ return index > -1 ? getItems()[index][STORAGE_VALUE] : null;
912
+ },
913
+ setItem(key, value) {
914
+ index = getIndexByKey(key);
915
+ index > -1
916
+ ? (getItems()[index][STORAGE_VALUE] = value)
917
+ : getItems().push([key, value]);
918
+ isSameOrigin
919
+ ? callMethod(win, [storageName, "setItem"], [key, value], 2)
920
+ : warnCrossOrgin("set", storageName, env);
921
+ },
922
+ removeItem(key) {
923
+ index = getIndexByKey(key);
924
+ index > -1 && getItems().splice(index, 1);
925
+ isSameOrigin
926
+ ? callMethod(win, [storageName, "removeItem"], [key], 2)
927
+ : warnCrossOrgin("remove", storageName, env);
928
+ },
929
+ key(index) {
930
+ item = getItems()[index];
931
+ return item ? item[STORAGE_KEY] : null;
932
+ },
933
+ clear() {
934
+ getItems().length = 0;
935
+ isSameOrigin
936
+ ? callMethod(win, [storageName, "clear"], EMPTY_ARRAY, 2)
937
+ : warnCrossOrgin("clear", storageName, env);
938
+ },
939
+ get length() {
940
+ return getItems().length;
941
+ },
299
942
  };
300
- const getTargetProp = (target, applyPath) => {
301
- let n = "";
302
- if (target) {
303
- const cstrName = getConstructorName(target);
304
- if ("Window" === cstrName) {
305
- n = "";
306
- } else if ("string" == typeof target[InstanceDataKey]) {
307
- let nodeName = target[InstanceDataKey];
308
- n = "#text" === nodeName ? "textNode." : "#comment" === nodeName ? "commentNode." : "#document" === nodeName ? "document." : "html" === nodeName ? "doctype." : nodeName.toLowerCase() + ".";
309
- } else {
310
- n = "nodeType" in target && 2 === target.nodeType ? "attributes." : "CanvasRenderingContext2D" === cstrName ? "context2D." : "CanvasRenderingContextWebGL" === cstrName ? "contextWebGL." : "CSSStyleDeclaration" === cstrName ? "style." : "MutationObserver" === cstrName ? "mutationObserver." : "NamedNodeMap" === cstrName ? "namedNodeMap." : "ResizeObserver" === cstrName ? "resizeObserver." : cstrName.substring(0, 1).toLowerCase() + cstrName.substring(1) + ".";
311
- }
312
- target[ApplyPathKey] && target[ApplyPathKey].length && (n += [ ...target[ApplyPathKey] ].join(".") + ".");
313
- }
314
- if (applyPath.length > 1) {
315
- const first = applyPath.slice(0, applyPath.length - 1);
316
- const last = applyPath[applyPath.length - 1];
317
- if (!isNaN(last)) {
318
- return n + `${first.join(".")}[${last}]`;
319
- }
943
+ win[storageName] = new Proxy(storage, {
944
+ get: (target, key) =>
945
+ Reflect.has(target, key)
946
+ ? Reflect.get(target, key)
947
+ : target.getItem(key),
948
+ set(target, key, value) {
949
+ target.setItem(key, value);
950
+ return true;
951
+ },
952
+ has: (target, key) =>
953
+ !!Reflect.has(target, key) ||
954
+ ("string" == typeof key && null !== target.getItem(key)),
955
+ deleteProperty(target, key) {
956
+ target.removeItem(key);
957
+ return true;
958
+ },
959
+ });
960
+ };
961
+ const STORAGE_KEY = 0;
962
+ const STORAGE_VALUE = 1;
963
+ const createCSSStyleDeclarationCstr = (win, WorkerBase, cstrName) => {
964
+ win[cstrName] = defineConstructorName(
965
+ class extends WorkerBase {
966
+ constructor(winId, instanceId, applyPath, styles) {
967
+ super(winId, instanceId, applyPath, styles || {});
968
+ return new Proxy(this, {
969
+ get(target, propName) {
970
+ if (target[propName]) {
971
+ return target[propName];
972
+ }
973
+ target[propName] ||
974
+ "string" != typeof propName ||
975
+ target[InstanceDataKey][propName] ||
976
+ (target[InstanceDataKey][propName] = getter(target, [
977
+ propName,
978
+ ]));
979
+ return target[InstanceDataKey][propName];
980
+ },
981
+ set(target, propName, propValue) {
982
+ target[InstanceDataKey][propName] = propValue;
983
+ setter(target, [propName], propValue);
984
+ logDimensionCacheClearStyle(target, propName);
985
+ cachedDimensions.clear();
986
+ return true;
987
+ },
988
+ });
320
989
  }
321
- return n + applyPath.join(".");
322
- };
323
- const getLogValue = (applyPath, v) => {
324
- const type = typeof v;
325
- if (void 0 === v) {
326
- return "undefined";
990
+ setProperty(...args) {
991
+ this[InstanceDataKey][args[0]] = args[1];
992
+ callMethod(this, ["setProperty"], args, 2);
993
+ logDimensionCacheClearStyle(this, args[0]);
994
+ cachedDimensions.clear();
327
995
  }
328
- if ("boolean" === type || "number" === type || null == v) {
329
- return JSON.stringify(v);
996
+ getPropertyValue(propName) {
997
+ return this[propName];
330
998
  }
331
- if ("string" === type) {
332
- return applyPath.includes("cookie") ? JSON.stringify(v.slice(0, 10) + "...") : JSON.stringify(v.length > 50 ? v.slice(0, 40) + "..." : v);
999
+ removeProperty(propName) {
1000
+ let value = this[InstanceDataKey][propName];
1001
+ callMethod(this, ["removeProperty"], [propName], 2);
1002
+ logDimensionCacheClearStyle(this, propName);
1003
+ cachedDimensions.clear();
1004
+ this[InstanceDataKey][propName] = void 0;
1005
+ return value;
333
1006
  }
334
- if (Array.isArray(v)) {
335
- return `[${v.map(getLogValue).join(", ")}]`;
1007
+ },
1008
+ cstrName
1009
+ );
1010
+ };
1011
+ const createCSSStyleSheetConstructor = (win, cssStyleSheetCstrName) => {
1012
+ win[cssStyleSheetCstrName] = defineConstructorName(
1013
+ class {
1014
+ constructor(ownerNode) {
1015
+ this.ownerNode = ownerNode;
336
1016
  }
337
- if ("object" === type) {
338
- const instanceId = v[InstanceIdKey];
339
- const cstrName = getConstructorName(v);
340
- if ("string" == typeof instanceId) {
341
- if ("Window" === cstrName) {
342
- return "window";
343
- }
344
- if ("string" == typeof v[InstanceDataKey]) {
345
- if (1 === v.nodeType) {
346
- return `<${v[InstanceDataKey].toLowerCase()}>`;
347
- }
348
- if (10 === v.nodeType) {
349
- return `<!DOCTYPE ${v[InstanceDataKey]}>`;
350
- }
351
- if (v.nodeType <= 11) {
352
- return v[InstanceDataKey];
353
- }
354
- }
355
- return "¯\\_(ツ)_/¯ instance obj";
356
- }
357
- return v[Symbol.iterator] ? `[${Array.from(v).map((i => getLogValue(applyPath, i))).join(", ")}]` : "value" in v ? "string" == typeof v.value ? `"${v.value}"` : objToString(v.value) : objToString(v);
1017
+ get cssRules() {
1018
+ const ownerNode = this.ownerNode;
1019
+ return new Proxy(
1020
+ {},
1021
+ {
1022
+ get(target, propKey) {
1023
+ const propName = String(propKey);
1024
+ return "item" === propName
1025
+ ? (index) => getCssRule(ownerNode, index)
1026
+ : "length" === propName
1027
+ ? getCssRules(ownerNode).length
1028
+ : isNaN(propName)
1029
+ ? target[propKey]
1030
+ : getCssRule(ownerNode, propName);
1031
+ },
1032
+ }
1033
+ );
358
1034
  }
359
- return (v => "object" == typeof v && v && v.then)(v) ? "Promise" : "function" === type ? `ƒ() ${v.name || ""}`.trim() : `¯\\_(ツ)_/¯ ${String(v)}`.trim();
360
- };
361
- const objToString = obj => {
362
- const s = [];
363
- for (let key in obj) {
364
- const value = obj[key];
365
- const type = typeof value;
366
- "string" === type ? s.push(`${key}: "${value}"`) : "function" === type ? s.push(`${key}: ƒ`) : Array.isArray(type) ? s.push(`${key}: [..]`) : "object" === type && value ? s.push(`${key}: {..}`) : s.push(`${key}: ${String(value)}`);
1035
+ insertRule(ruleText, index) {
1036
+ const cssRules = getCssRules(this.ownerNode);
1037
+ index = void 0 === index ? 0 : index;
1038
+ if (index >= 0 && index <= cssRules.length) {
1039
+ callMethod(
1040
+ this.ownerNode,
1041
+ ["sheet", "insertRule"],
1042
+ [ruleText, index],
1043
+ 2
1044
+ );
1045
+ cssRules.splice(index, 0, 0);
1046
+ }
1047
+ logDimensionCacheClearMethod(this.ownerNode, "insertRule");
1048
+ cachedDimensions.clear();
1049
+ return index;
367
1050
  }
368
- let str = s.join(", ");
369
- str.length > 200 && (str = str.substring(0, 200) + "..");
370
- return `{ ${str} }`;
371
- };
372
- const logDimensionCacheClearStyle = (target, propName) => {
373
- (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logSetters) && logWorker(`Dimension cache cleared from style.${propName} setter`, target[WinIdKey]);
374
- };
375
- const logDimensionCacheClearMethod = (target, methodName) => {
376
- (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logCalls) && logWorker(`Dimension cache cleared from method call ${methodName}()`, target[WinIdKey]);
377
- };
378
- const taskQueue = [];
379
- const queue = (instance, $applyPath$, callType, $assignInstanceId$, $groupedGetters$, buffer) => {
380
- if (instance[ApplyPathKey]) {
381
- taskQueue.push({
382
- $winId$: instance[WinIdKey],
383
- $instanceId$: instance[InstanceIdKey],
384
- $applyPath$: [ ...instance[ApplyPathKey], ...$applyPath$ ],
385
- $assignInstanceId$: $assignInstanceId$,
386
- $groupedGetters$: $groupedGetters$
387
- });
388
- taskQueue[len(taskQueue) - 1].$debug$ = ((target, applyPath, callType) => {
389
- let m = getTargetProp(target, applyPath);
390
- 1 === callType ? m += " (blocking)" : 2 === callType ? m += " (non-blocking)" : 3 === callType && (m += " (non-blocking, no-side-effect)");
391
- return m.trim();
392
- })(instance, $applyPath$, callType);
393
- buffer && 3 !== callType && console.error("buffer must be sent NonBlockingNoSideEffect");
394
- if (3 === callType) {
395
- webWorkerCtx.$postMessage$([ 12, {
396
- $msgId$: randomId(),
397
- $tasks$: [ ...taskQueue ]
398
- } ], buffer ? [ buffer instanceof ArrayBuffer ? buffer : buffer.buffer ] : void 0);
399
- taskQueue.length = 0;
400
- } else if (1 === callType) {
401
- return sendToMain(true);
402
- }
403
- webWorkerCtx.$asyncMsgTimer$ = setTimeout(sendToMain, 20);
1051
+ deleteRule(index) {
1052
+ callMethod(this.ownerNode, ["sheet", "deleteRule"], [index], 2);
1053
+ getCssRules(this.ownerNode).splice(index, 1);
1054
+ logDimensionCacheClearMethod(this.ownerNode, "deleteRule");
1055
+ cachedDimensions.clear();
404
1056
  }
405
- };
406
- const sendToMain = isBlocking => {
407
- clearTimeout(webWorkerCtx.$asyncMsgTimer$);
408
- if (len(taskQueue)) {
409
- webWorkerCtx.$config$.logMainAccess && logWorker(`Main access, tasks sent: ${taskQueue.length}`);
410
- const endTask = taskQueue[len(taskQueue) - 1];
411
- const accessReq = {
412
- $msgId$: randomId(),
413
- $tasks$: [ ...taskQueue ]
414
- };
415
- taskQueue.length = 0;
416
- if (isBlocking) {
417
- const accessRsp = ((webWorkerCtx, accessReq) => {
418
- const sharedDataBuffer = webWorkerCtx.$sharedDataBuffer$;
419
- const sharedData = new Int32Array(sharedDataBuffer);
420
- Atomics.store(sharedData, 0, 0);
421
- webWorkerCtx.$postMessage$([ 11, accessReq ]);
422
- Atomics.wait(sharedData, 0, 0);
423
- let dataLength = Atomics.load(sharedData, 0);
424
- let accessRespStr = "";
425
- let i = 0;
426
- for (;i < dataLength; i++) {
427
- accessRespStr += String.fromCharCode(sharedData[i + 1]);
428
- }
429
- return JSON.parse(accessRespStr);
430
- })(webWorkerCtx, accessReq);
431
- const isPromise = accessRsp.$isPromise$;
432
- const rtnValue = deserializeFromMain(endTask.$winId$, endTask.$instanceId$, endTask.$applyPath$, accessRsp.$rtnValue$);
433
- if (accessRsp.$error$) {
434
- if (isPromise) {
435
- return Promise.reject(accessRsp.$error$);
436
- }
437
- throw new Error(accessRsp.$error$);
438
- }
439
- return isPromise ? Promise.resolve(rtnValue) : rtnValue;
440
- }
441
- webWorkerCtx.$postMessage$([ 12, accessReq ]);
1057
+ get type() {
1058
+ return "text/css";
442
1059
  }
1060
+ },
1061
+ cssStyleSheetCstrName
1062
+ );
1063
+ const HTMLStyleDescriptorMap = {
1064
+ sheet: {
1065
+ get() {
1066
+ return new win[cssStyleSheetCstrName](this);
1067
+ },
1068
+ },
443
1069
  };
444
- const getter = (instance, applyPath, groupedGetters, rtnValue) => {
445
- if (webWorkerCtx.$config$.get) {
446
- rtnValue = webWorkerCtx.$config$.get(createHookOptions(instance, applyPath));
447
- if (rtnValue !== HookContinue) {
448
- return rtnValue;
449
- }
450
- }
451
- rtnValue = queue(instance, applyPath, 1, void 0, groupedGetters);
452
- ((target, applyPath, rtnValue, restrictedToWorker = false, groupedGetters = false) => {
453
- if (webWorkerCtx.$config$.logGetters) {
454
- try {
455
- const msg = `Get ${getTargetProp(target, applyPath)}, returned: ${getLogValue(applyPath, rtnValue)}${restrictedToWorker ? " (restricted to worker)" : ""}${groupedGetters ? " (grouped getter)" : ""}`;
456
- msg.includes("Symbol(") || logWorker(msg, target[WinIdKey]);
457
- } catch (e) {}
458
- }
459
- })(instance, applyPath, rtnValue, false, !!groupedGetters);
460
- return rtnValue;
1070
+ definePrototypePropertyDescriptor(
1071
+ win.HTMLStyleElement,
1072
+ HTMLStyleDescriptorMap
1073
+ );
1074
+ };
1075
+ const getCssRules = (ownerNode, cssRules) => {
1076
+ cssRules = getInstanceStateValue(ownerNode, 2);
1077
+ if (!cssRules) {
1078
+ cssRules = getter(ownerNode, ["sheet", "cssRules"]);
1079
+ setInstanceStateValue(ownerNode, 2, cssRules);
1080
+ }
1081
+ return cssRules;
1082
+ };
1083
+ const getCssRule = (ownerNode, index, cssRules) => {
1084
+ cssRules = getCssRules(ownerNode);
1085
+ 0 === cssRules[index] &&
1086
+ (cssRules[index] = getter(ownerNode, [
1087
+ "sheet",
1088
+ "cssRules",
1089
+ parseInt(index, 10),
1090
+ ]));
1091
+ return cssRules[index];
1092
+ };
1093
+ const runScriptContent = (
1094
+ env,
1095
+ instanceId,
1096
+ scriptContent,
1097
+ winId,
1098
+ errorMsg
1099
+ ) => {
1100
+ try {
1101
+ webWorkerCtx.$config$.logScriptExecution &&
1102
+ logWorker(
1103
+ `Execute script: ${scriptContent
1104
+ .substring(0, 100)
1105
+ .split("\n")
1106
+ .map((l) => l.trim())
1107
+ .join(" ")
1108
+ .trim()
1109
+ .substring(0, 60)}...`,
1110
+ winId
1111
+ );
1112
+ env.$currentScriptId$ = instanceId;
1113
+ run(env, scriptContent);
1114
+ } catch (contentError) {
1115
+ console.error(scriptContent, contentError);
1116
+ errorMsg = String(contentError.stack || contentError);
1117
+ }
1118
+ env.$currentScriptId$ = "";
1119
+ return errorMsg;
1120
+ };
1121
+ const run = (env, scriptContent, scriptUrl) => {
1122
+ env.$runWindowLoadEvent$ = 1;
1123
+ scriptContent =
1124
+ `with(this){${scriptContent
1125
+ .replace(/\bthis\b/g, "(thi$(this)?window:this)")
1126
+ .replace(/\/\/# so/g, "//Xso")}\n;function thi$(t){return t===this}};${(
1127
+ webWorkerCtx.$config$.globalFns || []
1128
+ )
1129
+ .filter((globalFnName) => /[a-zA-Z_$][0-9a-zA-Z_$]*/.test(globalFnName))
1130
+ .map((g) => `(typeof ${g}=='function'&&(this.${g}=${g}))`)
1131
+ .join(";")};` + (scriptUrl ? "\n//# sourceURL=" + scriptUrl : "");
1132
+ env.$isSameOrigin$ ||
1133
+ (scriptContent = scriptContent.replace(
1134
+ /.postMessage\(/g,
1135
+ `.postMessage('${env.$winId$}',`
1136
+ ));
1137
+ new Function(scriptContent).call(env.$window$);
1138
+ env.$runWindowLoadEvent$ = 0;
1139
+ };
1140
+ const runStateLoadHandlers = (instance, type, handlers) => {
1141
+ handlers = getInstanceStateValue(instance, type);
1142
+ handlers &&
1143
+ setTimeout(() =>
1144
+ handlers.map((cb) =>
1145
+ cb({
1146
+ type: type,
1147
+ })
1148
+ )
1149
+ );
1150
+ };
1151
+ const resolveToUrl = (
1152
+ env,
1153
+ url,
1154
+ type,
1155
+ baseLocation,
1156
+ resolvedUrl,
1157
+ configResolvedUrl
1158
+ ) => {
1159
+ baseLocation = env.$location$;
1160
+ while (!baseLocation.host) {
1161
+ env = environments[env.$parentWinId$];
1162
+ baseLocation = env.$location$;
1163
+ if (env.$winId$ === env.$parentWinId$) {
1164
+ break;
1165
+ }
1166
+ }
1167
+ resolvedUrl = new URL(url || "", baseLocation);
1168
+ if (type && webWorkerCtx.$config$.resolveUrl) {
1169
+ configResolvedUrl = webWorkerCtx.$config$.resolveUrl(
1170
+ resolvedUrl,
1171
+ baseLocation,
1172
+ type
1173
+ );
1174
+ if (configResolvedUrl) {
1175
+ return configResolvedUrl;
1176
+ }
1177
+ }
1178
+ return resolvedUrl;
1179
+ };
1180
+ const resolveUrl = (env, url, type) => resolveToUrl(env, url, type) + "";
1181
+ const getPartytownScript = () =>
1182
+ `<script src="${partytownLibUrl("partytown.js?v=0.7.5")}"><\/script>`;
1183
+ const createImageConstructor = (env) =>
1184
+ class HTMLImageElement {
1185
+ constructor() {
1186
+ this.s = "";
1187
+ this.l = [];
1188
+ this.e = [];
1189
+ this.style = {};
1190
+ }
1191
+ get src() {
1192
+ return this.s;
1193
+ }
1194
+ set src(src) {
1195
+ webWorkerCtx.$config$.logImageRequests &&
1196
+ logWorker(
1197
+ `Image() request: ${resolveUrl(env, src, "image")}`,
1198
+ env.$winId$
1199
+ );
1200
+ this.s = src;
1201
+ fetch(resolveUrl(env, src, "image"), {
1202
+ mode: "no-cors",
1203
+ credentials: "include",
1204
+ keepalive: true,
1205
+ }).then(
1206
+ (rsp) => {
1207
+ rsp.ok || 0 === rsp.status
1208
+ ? this.l.map((cb) =>
1209
+ cb({
1210
+ type: "load",
1211
+ })
1212
+ )
1213
+ : this.e.map((cb) =>
1214
+ cb({
1215
+ type: "error",
1216
+ })
1217
+ );
1218
+ },
1219
+ () =>
1220
+ this.e.forEach((cb) =>
1221
+ cb({
1222
+ type: "error",
1223
+ })
1224
+ )
1225
+ );
1226
+ }
1227
+ addEventListener(eventName, cb) {
1228
+ "load" === eventName && this.l.push(cb);
1229
+ "error" === eventName && this.e.push(cb);
1230
+ }
1231
+ get onload() {
1232
+ return this.l[0];
1233
+ }
1234
+ set onload(cb) {
1235
+ this.l = [cb];
1236
+ }
1237
+ get onerror() {
1238
+ return this.e[0];
1239
+ }
1240
+ set onerror(cb) {
1241
+ this.e = [cb];
1242
+ }
461
1243
  };
462
- const setter = (instance, applyPath, value, hookSetterValue) => {
463
- if (webWorkerCtx.$config$.set) {
464
- hookSetterValue = webWorkerCtx.$config$.set({
465
- value: value,
466
- prevent: HookPrevent,
467
- ...createHookOptions(instance, applyPath)
468
- });
469
- if (hookSetterValue === HookPrevent) {
470
- return;
471
- }
472
- hookSetterValue !== HookContinue && (value = hookSetterValue);
473
- }
474
- if (dimensionChangingSetterNames.some((s => applyPath.includes(s)))) {
475
- cachedDimensions.clear();
476
- ((target, propName) => {
477
- (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logSetters) && logWorker(`Dimension cache cleared from setter "${propName}"`, target[WinIdKey]);
478
- })(instance, applyPath[applyPath.length - 1]);
479
- }
480
- applyPath = [ ...applyPath, serializeInstanceForMain(instance, value), 0 ];
481
- ((target, applyPath, value, restrictedToWorker = false) => {
482
- if (webWorkerCtx.$config$.logSetters) {
483
- try {
484
- applyPath = applyPath.slice(0, applyPath.length - 2);
485
- logWorker(`Set ${getTargetProp(target, applyPath)}, value: ${getLogValue(applyPath, value)}${restrictedToWorker ? " (restricted to worker)" : ""}`, target[WinIdKey]);
486
- } catch (e) {}
487
- }
488
- })(instance, applyPath, value);
489
- queue(instance, applyPath, 2);
1244
+ const HTMLSrcElementDescriptorMap = {
1245
+ addEventListener: {
1246
+ value(...args) {
1247
+ const eventName = args[0];
1248
+ const callbacks = getInstanceStateValue(this, eventName) || [];
1249
+ callbacks.push(args[1]);
1250
+ setInstanceStateValue(this, eventName, callbacks);
1251
+ },
1252
+ },
1253
+ async: {
1254
+ get: noop,
1255
+ set: noop,
1256
+ },
1257
+ defer: {
1258
+ get: noop,
1259
+ set: noop,
1260
+ },
1261
+ onload: {
1262
+ get() {
1263
+ let callbacks = getInstanceStateValue(this, "load");
1264
+ return (callbacks && callbacks[0]) || null;
1265
+ },
1266
+ set(cb) {
1267
+ setInstanceStateValue(this, "load", cb ? [cb] : null);
1268
+ },
1269
+ },
1270
+ onerror: {
1271
+ get() {
1272
+ let callbacks = getInstanceStateValue(this, "error");
1273
+ return (callbacks && callbacks[0]) || null;
1274
+ },
1275
+ set(cb) {
1276
+ setInstanceStateValue(this, "error", cb ? [cb] : null);
1277
+ },
1278
+ },
1279
+ getAttribute: {
1280
+ value(attrName) {
1281
+ return "src" === attrName
1282
+ ? this.src
1283
+ : callMethod(this, ["getAttribute"], [attrName]);
1284
+ },
1285
+ },
1286
+ setAttribute: {
1287
+ value(attrName, attrValue) {
1288
+ scriptAttrPropNames.includes(attrName)
1289
+ ? (this[attrName] = attrValue)
1290
+ : callMethod(this, ["setAttribute"], [attrName, attrValue]);
1291
+ },
1292
+ },
1293
+ };
1294
+ const scriptAttrPropNames = commaSplit("src,type");
1295
+ const patchHTMLScriptElement = (WorkerHTMLScriptElement, env) => {
1296
+ const HTMLScriptDescriptorMap = {
1297
+ innerHTML: innerHTMLDescriptor,
1298
+ innerText: innerHTMLDescriptor,
1299
+ src: {
1300
+ get() {
1301
+ return getInstanceStateValue(this, 4) || "";
1302
+ },
1303
+ set(url) {
1304
+ const orgUrl = resolveUrl(env, url, null);
1305
+ const config = webWorkerCtx.$config$;
1306
+ url = resolveUrl(env, url, "script");
1307
+ setInstanceStateValue(this, 4, url);
1308
+ setter(this, ["src"], url);
1309
+ orgUrl !== url && setter(this, ["dataset", "ptsrc"], orgUrl);
1310
+ if (this.type && config.loadScriptsOnMainThread) {
1311
+ const shouldExecuteScriptViaMainThread =
1312
+ config.loadScriptsOnMainThread.some(
1313
+ (scriptUrl) => scriptUrl === url
1314
+ );
1315
+ shouldExecuteScriptViaMainThread &&
1316
+ setter(this, ["type"], "text/javascript");
1317
+ }
1318
+ },
1319
+ },
1320
+ textContent: innerHTMLDescriptor,
1321
+ type: {
1322
+ get() {
1323
+ return getter(this, ["type"]);
1324
+ },
1325
+ set(type) {
1326
+ if (!isScriptJsType(type)) {
1327
+ setInstanceStateValue(this, 5, type);
1328
+ setter(this, ["type"], type);
1329
+ }
1330
+ },
1331
+ },
1332
+ ...HTMLSrcElementDescriptorMap,
490
1333
  };
491
- const callMethod = (instance, applyPath, args, callType, assignInstanceId, buffer, rtnValue, methodName) => {
492
- if (webWorkerCtx.$config$.apply) {
493
- rtnValue = webWorkerCtx.$config$.apply({
494
- args: args,
495
- ...createHookOptions(instance, applyPath)
496
- });
497
- if (rtnValue !== HookContinue) {
498
- return rtnValue;
499
- }
500
- }
501
- methodName = applyPath[len(applyPath) - 1];
502
- applyPath = [ ...applyPath, serializeInstanceForMain(instance, args) ];
503
- callType = callType || (nonBlockingMethods.includes(methodName) ? 2 : 1);
504
- if ("setAttribute" === methodName && hasInstanceStateValue(instance, args[0])) {
505
- setInstanceStateValue(instance, args[0], args[1]);
506
- } else if (structureChangingMethodNames.includes(methodName)) {
507
- cachedDimensions.clear();
508
- cachedStructure.clear();
509
- ((target, methodName) => {
510
- (webWorkerCtx.$config$.logGetters || webWorkerCtx.$config$.logCalls) && logWorker(`Dimension and DOM structure cache cleared from method call ${methodName}()`, target[WinIdKey]);
511
- })(instance, methodName);
512
- } else if (dimensionChangingMethodNames.includes(methodName)) {
513
- callType = 2;
514
- cachedDimensions.clear();
515
- logDimensionCacheClearMethod(instance, methodName);
1334
+ definePrototypePropertyDescriptor(
1335
+ WorkerHTMLScriptElement,
1336
+ HTMLScriptDescriptorMap
1337
+ );
1338
+ };
1339
+ const innerHTMLDescriptor = {
1340
+ get() {
1341
+ const type = getter(this, ["type"]);
1342
+ return isScriptJsType(type)
1343
+ ? getInstanceStateValue(this, 3) || ""
1344
+ : getter(this, ["innerHTML"]);
1345
+ },
1346
+ set(scriptContent) {
1347
+ setInstanceStateValue(this, 3, scriptContent);
1348
+ },
1349
+ };
1350
+ const isScriptJsType = (scriptType) =>
1351
+ !scriptType || "text/javascript" === scriptType;
1352
+ const createNodeCstr = (win, env, WorkerBase) => {
1353
+ const config = webWorkerCtx.$config$;
1354
+ const WorkerNode = defineConstructorName(
1355
+ class extends WorkerBase {
1356
+ appendChild(node) {
1357
+ return this.insertBefore(node, null);
516
1358
  }
517
- rtnValue = queue(instance, applyPath, callType, assignInstanceId, void 0, buffer);
518
- ((target, applyPath, args, rtnValue) => {
519
- if (webWorkerCtx.$config$.logCalls) {
520
- try {
521
- applyPath = applyPath.slice(0, applyPath.length - 1);
522
- logWorker(`Call ${getTargetProp(target, applyPath)}(${args.map((v => getLogValue(applyPath, v))).join(", ")}), returned: ${getLogValue(applyPath, rtnValue)}`, target[WinIdKey]);
523
- } catch (e) {}
524
- }
525
- })(instance, applyPath, args, rtnValue);
526
- return rtnValue;
527
- };
528
- const constructGlobal = (instance, cstrName, args) => {
529
- ((target, cstrName, args) => {
530
- if (webWorkerCtx.$config$.logCalls) {
531
- try {
532
- logWorker(`Construct new ${cstrName}(${args.map((v => getLogValue([], v))).join(", ")})`, target[WinIdKey]);
533
- } catch (e) {}
534
- }
535
- })(instance, cstrName, args);
536
- queue(instance, [ 1, cstrName, serializeInstanceForMain(instance, args) ], 1);
537
- };
538
- const createHookOptions = (instance, applyPath) => ({
539
- name: applyPath.join("."),
540
- continue: HookContinue,
541
- nodeName: instance[InstanceDataKey],
542
- constructor: getConstructorName(instance),
543
- instance: instance,
544
- window: environments[instance[WinIdKey]].$window$
545
- });
546
- const addStorageApi = (win, storageName, storages, isSameOrigin, env) => {
547
- let getItems = items => {
548
- items = storages.get(win.origin);
549
- items || storages.set(win.origin, items = []);
550
- return items;
551
- };
552
- let getIndexByKey = key => getItems().findIndex((i => i[STORAGE_KEY] === key));
553
- let index;
554
- let item;
555
- let storage = {
556
- getItem(key) {
557
- index = getIndexByKey(key);
558
- return index > -1 ? getItems()[index][STORAGE_VALUE] : null;
559
- },
560
- setItem(key, value) {
561
- index = getIndexByKey(key);
562
- index > -1 ? getItems()[index][STORAGE_VALUE] = value : getItems().push([ key, value ]);
563
- isSameOrigin ? callMethod(win, [ storageName, "setItem" ], [ key, value ], 2) : warnCrossOrgin("set", storageName, env);
564
- },
565
- removeItem(key) {
566
- index = getIndexByKey(key);
567
- index > -1 && getItems().splice(index, 1);
568
- isSameOrigin ? callMethod(win, [ storageName, "removeItem" ], [ key ], 2) : warnCrossOrgin("remove", storageName, env);
569
- },
570
- key(index) {
571
- item = getItems()[index];
572
- return item ? item[STORAGE_KEY] : null;
573
- },
574
- clear() {
575
- getItems().length = 0;
576
- isSameOrigin ? callMethod(win, [ storageName, "clear" ], EMPTY_ARRAY, 2) : warnCrossOrgin("clear", storageName, env);
577
- },
578
- get length() {
579
- return getItems().length;
580
- }
581
- };
582
- win[storageName] = new Proxy(storage, {
583
- get: (target, key) => Reflect.has(target, key) ? Reflect.get(target, key) : target.getItem(key),
584
- set(target, key, value) {
585
- target.setItem(key, value);
586
- return true;
587
- },
588
- has: (target, key) => !!Reflect.has(target, key) || "string" == typeof key && null !== target.getItem(key),
589
- deleteProperty(target, key) {
590
- target.removeItem(key);
591
- return true;
592
- }
593
- });
594
- };
595
- const STORAGE_KEY = 0;
596
- const STORAGE_VALUE = 1;
597
- const createCSSStyleDeclarationCstr = (win, WorkerBase, cstrName) => {
598
- win[cstrName] = defineConstructorName(class extends WorkerBase {
599
- constructor(winId, instanceId, applyPath, styles) {
600
- super(winId, instanceId, applyPath, styles || {});
601
- return new Proxy(this, {
602
- get(target, propName) {
603
- if (target[propName]) {
604
- return target[propName];
605
- }
606
- target[propName] || "string" != typeof propName || target[InstanceDataKey][propName] || (target[InstanceDataKey][propName] = getter(target, [ propName ]));
607
- return target[InstanceDataKey][propName];
608
- },
609
- set(target, propName, propValue) {
610
- target[InstanceDataKey][propName] = propValue;
611
- setter(target, [ propName ], propValue);
612
- logDimensionCacheClearStyle(target, propName);
613
- cachedDimensions.clear();
614
- return true;
615
- }
616
- });
617
- }
618
- setProperty(...args) {
619
- this[InstanceDataKey][args[0]] = args[1];
620
- callMethod(this, [ "setProperty" ], args, 2);
621
- logDimensionCacheClearStyle(this, args[0]);
622
- cachedDimensions.clear();
623
- }
624
- getPropertyValue(propName) {
625
- return this[propName];
626
- }
627
- removeProperty(propName) {
628
- let value = this[InstanceDataKey][propName];
629
- callMethod(this, [ "removeProperty" ], [ propName ], 2);
630
- logDimensionCacheClearStyle(this, propName);
631
- cachedDimensions.clear();
632
- this[InstanceDataKey][propName] = void 0;
633
- return value;
634
- }
635
- }, cstrName);
636
- };
637
- const createCSSStyleSheetConstructor = (win, cssStyleSheetCstrName) => {
638
- win[cssStyleSheetCstrName] = defineConstructorName(class {
639
- constructor(ownerNode) {
640
- this.ownerNode = ownerNode;
641
- }
642
- get cssRules() {
643
- const ownerNode = this.ownerNode;
644
- return new Proxy({}, {
645
- get(target, propKey) {
646
- const propName = String(propKey);
647
- return "item" === propName ? index => getCssRule(ownerNode, index) : "length" === propName ? getCssRules(ownerNode).length : isNaN(propName) ? target[propKey] : getCssRule(ownerNode, propName);
648
- }
649
- });
650
- }
651
- insertRule(ruleText, index) {
652
- const cssRules = getCssRules(this.ownerNode);
653
- index = void 0 === index ? 0 : index;
654
- if (index >= 0 && index <= cssRules.length) {
655
- callMethod(this.ownerNode, [ "sheet", "insertRule" ], [ ruleText, index ], 2);
656
- cssRules.splice(index, 0, 0);
1359
+ get href() {}
1360
+ set href(_) {}
1361
+ insertBefore(newNode, referenceNode) {
1362
+ var _a, _b;
1363
+ const winId = (newNode[WinIdKey] = this[WinIdKey]);
1364
+ const instanceId = newNode[InstanceIdKey];
1365
+ const nodeName = newNode[InstanceDataKey];
1366
+ const isScript = "SCRIPT" === nodeName;
1367
+ const isIFrame = "INPUT" === nodeName;
1368
+ if (isScript) {
1369
+ const scriptContent = getInstanceStateValue(newNode, 3);
1370
+ const scriptType = getInstanceStateValue(newNode, 5);
1371
+ if (scriptContent) {
1372
+ if (isScriptJsType(scriptType)) {
1373
+ const scriptId = newNode.id;
1374
+ const loadOnMainThread =
1375
+ scriptId &&
1376
+ (null ===
1377
+ (_b =
1378
+ null === (_a = config.loadScriptsOnMainThread) ||
1379
+ void 0 === _a
1380
+ ? void 0
1381
+ : _a.includes) || void 0 === _b
1382
+ ? void 0
1383
+ : _b.call(_a, scriptId));
1384
+ if (loadOnMainThread) {
1385
+ setter(newNode, ["type"], "text/javascript");
1386
+ } else {
1387
+ const errorMsg = runScriptContent(
1388
+ env,
1389
+ instanceId,
1390
+ scriptContent,
1391
+ winId,
1392
+ ""
1393
+ );
1394
+ const datasetType = errorMsg ? "pterror" : "ptid";
1395
+ const datasetValue = errorMsg || instanceId;
1396
+ setter(newNode, ["type"], "text/partytown-x");
1397
+ setter(newNode, ["dataset", datasetType], datasetValue);
657
1398
  }
658
- logDimensionCacheClearMethod(this.ownerNode, "insertRule");
659
- cachedDimensions.clear();
660
- return index;
661
- }
662
- deleteRule(index) {
663
- callMethod(this.ownerNode, [ "sheet", "deleteRule" ], [ index ], 2);
664
- getCssRules(this.ownerNode).splice(index, 1);
665
- logDimensionCacheClearMethod(this.ownerNode, "deleteRule");
666
- cachedDimensions.clear();
667
- }
668
- get type() {
669
- return "text/css";
670
- }
671
- }, cssStyleSheetCstrName);
672
- const HTMLStyleDescriptorMap = {
673
- sheet: {
674
- get() {
675
- return new win[cssStyleSheetCstrName](this);
1399
+ }
1400
+ setter(newNode, ["innerHTML"], scriptContent);
1401
+ }
1402
+ }
1403
+ callMethod(this, ["insertBefore"], [newNode, referenceNode], 2);
1404
+ if (isIFrame) {
1405
+ const src = getInstanceStateValue(newNode, 0);
1406
+ if (src && src.startsWith("javascript:")) {
1407
+ const scriptContent = src.split("javascript:")[1];
1408
+ runScriptContent(env, instanceId, scriptContent, winId, "");
1409
+ }
1410
+ ((winId, iframe) => {
1411
+ let i = 0;
1412
+ let type;
1413
+ let handlers;
1414
+ let callback = () => {
1415
+ if (
1416
+ environments[winId] &&
1417
+ environments[winId].$isInitialized$ &&
1418
+ !environments[winId].$isLoading$
1419
+ ) {
1420
+ type = getInstanceStateValue(iframe, 1) ? "error" : "load";
1421
+ handlers = getInstanceStateValue(iframe, type);
1422
+ handlers &&
1423
+ handlers.map((handler) =>
1424
+ handler({
1425
+ type: type,
1426
+ })
1427
+ );
1428
+ } else if (i++ > 2e3) {
1429
+ handlers = getInstanceStateValue(iframe, "error");
1430
+ handlers &&
1431
+ handlers.map((handler) =>
1432
+ handler({
1433
+ type: "error",
1434
+ })
1435
+ );
1436
+ } else {
1437
+ setTimeout(callback, 9);
676
1438
  }
677
- }
678
- };
679
- definePrototypePropertyDescriptor(win.HTMLStyleElement, HTMLStyleDescriptorMap);
680
- };
681
- const getCssRules = (ownerNode, cssRules) => {
682
- cssRules = getInstanceStateValue(ownerNode, 2);
683
- if (!cssRules) {
684
- cssRules = getter(ownerNode, [ "sheet", "cssRules" ]);
685
- setInstanceStateValue(ownerNode, 2, cssRules);
686
- }
687
- return cssRules;
688
- };
689
- const getCssRule = (ownerNode, index, cssRules) => {
690
- cssRules = getCssRules(ownerNode);
691
- 0 === cssRules[index] && (cssRules[index] = getter(ownerNode, [ "sheet", "cssRules", parseInt(index, 10) ]));
692
- return cssRules[index];
693
- };
694
- const runScriptContent = (env, instanceId, scriptContent, winId, errorMsg) => {
695
- try {
696
- webWorkerCtx.$config$.logScriptExecution && logWorker(`Execute script: ${scriptContent.substring(0, 100).split("\n").map((l => l.trim())).join(" ").trim().substring(0, 60)}...`, winId);
697
- env.$currentScriptId$ = instanceId;
698
- run(env, scriptContent);
699
- } catch (contentError) {
700
- console.error(scriptContent, contentError);
701
- errorMsg = String(contentError.stack || contentError);
702
- }
703
- env.$currentScriptId$ = "";
704
- return errorMsg;
705
- };
706
- const run = (env, scriptContent, scriptUrl) => {
707
- env.$runWindowLoadEvent$ = 1;
708
- scriptContent = `with(this){${scriptContent.replace(/\bthis\b/g, "(thi$(this)?window:this)").replace(/\/\/# so/g, "//Xso")}\n;function thi$(t){return t===this}};${(webWorkerCtx.$config$.globalFns || []).filter((globalFnName => /[a-zA-Z_$][0-9a-zA-Z_$]*/.test(globalFnName))).map((g => `(typeof ${g}=='function'&&(this.${g}=${g}))`)).join(";")};` + (scriptUrl ? "\n//# sourceURL=" + scriptUrl : "");
709
- env.$isSameOrigin$ || (scriptContent = scriptContent.replace(/.postMessage\(/g, `.postMessage('${env.$winId$}',`));
710
- new Function(scriptContent).call(env.$window$);
711
- env.$runWindowLoadEvent$ = 0;
712
- };
713
- const runStateLoadHandlers = (instance, type, handlers) => {
714
- handlers = getInstanceStateValue(instance, type);
715
- handlers && setTimeout((() => handlers.map((cb => cb({
716
- type: type
717
- })))));
718
- };
719
- const resolveToUrl = (env, url, type, baseLocation, resolvedUrl, configResolvedUrl) => {
720
- baseLocation = env.$location$;
721
- while (!baseLocation.host) {
722
- env = environments[env.$parentWinId$];
723
- baseLocation = env.$location$;
724
- if (env.$winId$ === env.$parentWinId$) {
725
- break;
726
- }
727
- }
728
- resolvedUrl = new URL(url || "", baseLocation);
729
- if (type && webWorkerCtx.$config$.resolveUrl) {
730
- configResolvedUrl = webWorkerCtx.$config$.resolveUrl(resolvedUrl, baseLocation, type);
731
- if (configResolvedUrl) {
732
- return configResolvedUrl;
733
- }
734
- }
735
- return resolvedUrl;
736
- };
737
- const resolveUrl = (env, url, type) => resolveToUrl(env, url, type) + "";
738
- const getPartytownScript = () => `<script src="${partytownLibUrl("partytown.js?v=0.7.5")}"><\/script>`;
739
- const createImageConstructor = env => class HTMLImageElement {
740
- constructor() {
741
- this.s = "";
742
- this.l = [];
743
- this.e = [];
744
- this.style = {};
745
- }
746
- get src() {
747
- return this.s;
748
- }
749
- set src(src) {
750
- webWorkerCtx.$config$.logImageRequests && logWorker(`Image() request: ${resolveUrl(env, src, "image")}`, env.$winId$);
751
- this.s = src;
752
- fetch(resolveUrl(env, src, "image"), {
753
- mode: "no-cors",
754
- credentials: "include",
755
- keepalive: true
756
- }).then((rsp => {
757
- rsp.ok || 0 === rsp.status ? this.l.map((cb => cb({
758
- type: "load"
759
- }))) : this.e.map((cb => cb({
760
- type: "error"
761
- })));
762
- }), (() => this.e.forEach((cb => cb({
763
- type: "error"
764
- })))));
765
- }
766
- addEventListener(eventName, cb) {
767
- "load" === eventName && this.l.push(cb);
768
- "error" === eventName && this.e.push(cb);
1439
+ };
1440
+ callback();
1441
+ })(instanceId, newNode);
1442
+ }
1443
+ if (isScript) {
1444
+ sendToMain(true);
1445
+ webWorkerCtx.$postMessage$([7, winId]);
1446
+ }
1447
+ return newNode;
769
1448
  }
770
- get onload() {
771
- return this.l[0];
772
- }
773
- set onload(cb) {
774
- this.l = [ cb ];
1449
+ get nodeName() {
1450
+ return "#s" === this[InstanceDataKey]
1451
+ ? "#document-fragment"
1452
+ : this[InstanceDataKey];
775
1453
  }
776
- get onerror() {
777
- return this.e[0];
1454
+ get nodeType() {
1455
+ return 3;
778
1456
  }
779
- set onerror(cb) {
780
- this.e = [ cb ];
1457
+ get ownerDocument() {
1458
+ return env.$document$;
781
1459
  }
782
- };
783
- const HTMLSrcElementDescriptorMap = {
784
- addEventListener: {
785
- value(...args) {
786
- const eventName = args[0];
787
- const callbacks = getInstanceStateValue(this, eventName) || [];
788
- callbacks.push(args[1]);
789
- setInstanceStateValue(this, eventName, callbacks);
790
- }
1460
+ },
1461
+ "Node"
1462
+ );
1463
+ cachedTreeProps(
1464
+ WorkerNode,
1465
+ commaSplit(
1466
+ "childNodes,firstChild,isConnected,lastChild,nextSibling,parentElement,parentNode,previousSibling"
1467
+ )
1468
+ );
1469
+ win.Node = WorkerNode;
1470
+ };
1471
+ const htmlMedia = commaSplit("AUDIO,CANVAS,VIDEO");
1472
+ const windowMediaConstructors = commaSplit("Audio,MediaSource");
1473
+ const patchDocument = (WorkerDocument, env, isDocumentImplementation) => {
1474
+ const DocumentDescriptorMap = {
1475
+ body: {
1476
+ get: () => env.$body$,
1477
+ },
1478
+ cookie: {
1479
+ get() {
1480
+ if (env.$isSameOrigin$) {
1481
+ return getter(this, ["cookie"]);
1482
+ }
1483
+ warnCrossOrgin("get", "cookie", env);
1484
+ return "";
791
1485
  },
792
- async: {
793
- get: noop,
794
- set: noop
1486
+ set(value) {
1487
+ if (env.$isSameOrigin$) {
1488
+ setter(this, ["cookie"], value);
1489
+ } else {
1490
+ warnCrossOrgin("set", "cookie", env);
1491
+ }
795
1492
  },
796
- defer: {
797
- get: noop,
798
- set: noop
1493
+ },
1494
+ createElement: {
1495
+ value(tagName) {
1496
+ tagName = tagName.toUpperCase();
1497
+ if (!IS_TAG_REG.test(tagName)) {
1498
+ throw tagName + " not valid";
1499
+ }
1500
+ const isIframe = "DIV" === tagName;
1501
+ const winId = this[WinIdKey];
1502
+ const instanceId = (isIframe ? "f_" : "") + randomId();
1503
+ callMethod(this, ["createElement"], [tagName], 2, instanceId);
1504
+ const elm = getOrCreateNodeInstance(winId, instanceId, tagName);
1505
+ if (isIframe) {
1506
+ const env = createEnvironment(
1507
+ {
1508
+ $winId$: instanceId,
1509
+ $parentWinId$: winId,
1510
+ $url$: "about:blank",
1511
+ },
1512
+ true
1513
+ );
1514
+ env.$window$.fetch = fetch;
1515
+ setter(elm, ["srcdoc"], getPartytownScript());
1516
+ } else if ("SCRIPT" === tagName) {
1517
+ const scriptType = getInstanceStateValue(elm, 5);
1518
+ isScriptJsType(scriptType) &&
1519
+ setter(elm, ["type"], "text/partytown");
1520
+ }
1521
+ return elm;
799
1522
  },
800
- onload: {
801
- get() {
802
- let callbacks = getInstanceStateValue(this, "load");
803
- return callbacks && callbacks[0] || null;
804
- },
805
- set(cb) {
806
- setInstanceStateValue(this, "load", cb ? [ cb ] : null);
807
- }
1523
+ },
1524
+ createElementNS: {
1525
+ value(namespace, tagName) {
1526
+ const instanceId = randomId();
1527
+ const nsElm = getOrCreateNodeInstance(
1528
+ this[WinIdKey],
1529
+ instanceId,
1530
+ tagName,
1531
+ namespace
1532
+ );
1533
+ callMethod(
1534
+ this,
1535
+ ["createElementNS"],
1536
+ [namespace, tagName],
1537
+ 2,
1538
+ instanceId
1539
+ );
1540
+ return nsElm;
808
1541
  },
809
- onerror: {
810
- get() {
811
- let callbacks = getInstanceStateValue(this, "error");
812
- return callbacks && callbacks[0] || null;
813
- },
814
- set(cb) {
815
- setInstanceStateValue(this, "error", cb ? [ cb ] : null);
816
- }
1542
+ },
1543
+ createTextNode: {
1544
+ value(text) {
1545
+ const winId = this[WinIdKey];
1546
+ const instanceId = randomId();
1547
+ const textNode = getOrCreateNodeInstance(winId, instanceId, "#text");
1548
+ callMethod(this, ["createTextNode"], [text], 2, instanceId);
1549
+ return textNode;
817
1550
  },
818
- getAttribute: {
819
- value(attrName) {
820
- return "src" === attrName ? this.src : callMethod(this, [ "getAttribute" ], [ attrName ]);
821
- }
1551
+ },
1552
+ createEvent: {
1553
+ value: (type) => new Event(type),
1554
+ },
1555
+ currentScript: {
1556
+ get() {
1557
+ return env.$currentScriptId$
1558
+ ? getOrCreateNodeInstance(
1559
+ this[WinIdKey],
1560
+ env.$currentScriptId$,
1561
+ "SCRIPT"
1562
+ )
1563
+ : null;
822
1564
  },
823
- setAttribute: {
824
- value(attrName, attrValue) {
825
- scriptAttrPropNames.includes(attrName) ? this[attrName] = attrValue : callMethod(this, [ "setAttribute" ], [ attrName, attrValue ]);
826
- }
827
- }
828
- };
829
- const scriptAttrPropNames = commaSplit("src,type");
830
- const patchHTMLScriptElement = (WorkerHTMLScriptElement, env) => {
831
- const HTMLScriptDescriptorMap = {
832
- innerHTML: innerHTMLDescriptor,
833
- innerText: innerHTMLDescriptor,
834
- src: {
835
- get() {
836
- return getInstanceStateValue(this, 4) || "";
837
- },
838
- set(url) {
839
- const orgUrl = resolveUrl(env, url, null);
840
- const config = webWorkerCtx.$config$;
841
- url = resolveUrl(env, url, "script");
842
- setInstanceStateValue(this, 4, url);
843
- setter(this, [ "src" ], url);
844
- orgUrl !== url && setter(this, [ "dataset", "ptsrc" ], orgUrl);
845
- if (this.type && config.loadScriptsOnMainThread) {
846
- const shouldExecuteScriptViaMainThread = config.loadScriptsOnMainThread.some((scriptUrl => scriptUrl === url));
847
- shouldExecuteScriptViaMainThread && setter(this, [ "type" ], "text/javascript");
848
- }
1565
+ },
1566
+ defaultView: {
1567
+ get: () => (isDocumentImplementation ? null : env.$window$),
1568
+ },
1569
+ documentElement: {
1570
+ get: () => env.$documentElement$,
1571
+ },
1572
+ getElementsByTagName: {
1573
+ value(tagName) {
1574
+ tagName = tagName.toUpperCase();
1575
+ return "BODY" === tagName
1576
+ ? [env.$body$]
1577
+ : "HEAD" === tagName
1578
+ ? [env.$head$]
1579
+ : callMethod(this, ["getElementsByTagName"], [tagName]);
1580
+ },
1581
+ },
1582
+ head: {
1583
+ get: () => env.$head$,
1584
+ },
1585
+ images: {
1586
+ get() {
1587
+ return getter(this, ["images"]);
1588
+ },
1589
+ },
1590
+ implementation: {
1591
+ get() {
1592
+ return {
1593
+ hasFeature: () => true,
1594
+ createHTMLDocument: (title) => {
1595
+ const $winId$ = randomId();
1596
+ callMethod(
1597
+ this,
1598
+ ["implementation", "createHTMLDocument"],
1599
+ [title],
1600
+ 1,
1601
+ {
1602
+ $winId$: $winId$,
849
1603
  }
850
- },
851
- textContent: innerHTMLDescriptor,
852
- type: {
853
- get() {
854
- return getter(this, [ "type" ]);
1604
+ );
1605
+ const docEnv = createEnvironment(
1606
+ {
1607
+ $winId$: $winId$,
1608
+ $parentWinId$: $winId$,
1609
+ $url$: env.$location$ + "",
1610
+ $visibilityState$: "hidden",
855
1611
  },
856
- set(type) {
857
- if (!isScriptJsType(type)) {
858
- setInstanceStateValue(this, 5, type);
859
- setter(this, [ "type" ], type);
860
- }
861
- }
1612
+ true,
1613
+ true
1614
+ );
1615
+ return docEnv.$document$;
862
1616
  },
863
- ...HTMLSrcElementDescriptorMap
864
- };
865
- definePrototypePropertyDescriptor(WorkerHTMLScriptElement, HTMLScriptDescriptorMap);
1617
+ };
1618
+ },
1619
+ },
1620
+ location: {
1621
+ get: () => env.$location$,
1622
+ set(url) {
1623
+ env.$location$.href = url + "";
1624
+ },
1625
+ },
1626
+ nodeType: {
1627
+ value: 9,
1628
+ },
1629
+ parentNode: {
1630
+ value: null,
1631
+ },
1632
+ parentElement: {
1633
+ value: null,
1634
+ },
1635
+ readyState: {
1636
+ value: "complete",
1637
+ },
1638
+ visibilityState: {
1639
+ get: () => env.$visibilityState$ || "visible",
1640
+ },
866
1641
  };
867
- const innerHTMLDescriptor = {
1642
+ definePrototypePropertyDescriptor(WorkerDocument, DocumentDescriptorMap);
1643
+ cachedProps(WorkerDocument, "compatMode,referrer,forms");
1644
+ };
1645
+ const patchDocumentElementChild = (WokerDocumentElementChild, env) => {
1646
+ const DocumentElementChildDescriptorMap = {
1647
+ parentElement: {
868
1648
  get() {
869
- const type = getter(this, [ "type" ]);
870
- return isScriptJsType(type) ? getInstanceStateValue(this, 3) || "" : getter(this, [ "innerHTML" ]);
1649
+ return this.parentNode;
871
1650
  },
872
- set(scriptContent) {
873
- setInstanceStateValue(this, 3, scriptContent);
874
- }
1651
+ },
1652
+ parentNode: {
1653
+ get: () => env.$documentElement$,
1654
+ },
875
1655
  };
876
- const isScriptJsType = scriptType => !scriptType || "text/javascript" === scriptType;
877
- const createNodeCstr = (win, env, WorkerBase) => {
878
- const config = webWorkerCtx.$config$;
879
- const WorkerNode = defineConstructorName(class extends WorkerBase {
880
- appendChild(node) {
881
- return this.insertBefore(node, null);
882
- }
883
- get href() {}
884
- set href(_) {}
885
- insertBefore(newNode, referenceNode) {
886
- var _a, _b;
887
- const winId = newNode[WinIdKey] = this[WinIdKey];
888
- const instanceId = newNode[InstanceIdKey];
889
- const nodeName = newNode[InstanceDataKey];
890
- const isScript = "SCRIPT" === nodeName;
891
- const isIFrame = "IFRAME" === nodeName;
892
- if (isScript) {
893
- const scriptContent = getInstanceStateValue(newNode, 3);
894
- const scriptType = getInstanceStateValue(newNode, 5);
895
- if (scriptContent) {
896
- if (isScriptJsType(scriptType)) {
897
- const scriptId = newNode.id;
898
- const loadOnMainThread = scriptId && (null === (_b = null === (_a = config.loadScriptsOnMainThread) || void 0 === _a ? void 0 : _a.includes) || void 0 === _b ? void 0 : _b.call(_a, scriptId));
899
- if (loadOnMainThread) {
900
- setter(newNode, [ "type" ], "text/javascript");
901
- } else {
902
- const errorMsg = runScriptContent(env, instanceId, scriptContent, winId, "");
903
- const datasetType = errorMsg ? "pterror" : "ptid";
904
- const datasetValue = errorMsg || instanceId;
905
- setter(newNode, [ "type" ], "text/partytown-x");
906
- setter(newNode, [ "dataset", datasetType ], datasetValue);
907
- }
908
- }
909
- setter(newNode, [ "innerHTML" ], scriptContent);
910
- }
911
- }
912
- callMethod(this, [ "insertBefore" ], [ newNode, referenceNode ], 2);
913
- if (isIFrame) {
914
- const src = getInstanceStateValue(newNode, 0);
915
- if (src && src.startsWith("javascript:")) {
916
- const scriptContent = src.split("javascript:")[1];
917
- runScriptContent(env, instanceId, scriptContent, winId, "");
918
- }
919
- ((winId, iframe) => {
920
- let i = 0;
921
- let type;
922
- let handlers;
923
- let callback = () => {
924
- if (environments[winId] && environments[winId].$isInitialized$ && !environments[winId].$isLoading$) {
925
- type = getInstanceStateValue(iframe, 1) ? "error" : "load";
926
- handlers = getInstanceStateValue(iframe, type);
927
- handlers && handlers.map((handler => handler({
928
- type: type
929
- })));
930
- } else if (i++ > 2e3) {
931
- handlers = getInstanceStateValue(iframe, "error");
932
- handlers && handlers.map((handler => handler({
933
- type: "error"
934
- })));
935
- } else {
936
- setTimeout(callback, 9);
937
- }
938
- };
939
- callback();
940
- })(instanceId, newNode);
941
- }
942
- if (isScript) {
943
- sendToMain(true);
944
- webWorkerCtx.$postMessage$([ 7, winId ]);
945
- }
946
- return newNode;
947
- }
948
- get nodeName() {
949
- return "#s" === this[InstanceDataKey] ? "#document-fragment" : this[InstanceDataKey];
950
- }
951
- get nodeType() {
952
- return 3;
953
- }
954
- get ownerDocument() {
955
- return env.$document$;
956
- }
957
- }, "Node");
958
- cachedTreeProps(WorkerNode, commaSplit("childNodes,firstChild,isConnected,lastChild,nextSibling,parentElement,parentNode,previousSibling"));
959
- win.Node = WorkerNode;
1656
+ definePrototypePropertyDescriptor(
1657
+ WokerDocumentElementChild,
1658
+ DocumentElementChildDescriptorMap
1659
+ );
1660
+ };
1661
+ const patchElement = (WorkerElement, WorkerHTMLElement) => {
1662
+ const ElementDescriptorMap = {
1663
+ localName: {
1664
+ get() {
1665
+ return this[InstanceDataKey].toLowerCase();
1666
+ },
1667
+ },
1668
+ namespaceURI: {
1669
+ get() {
1670
+ return this[NamespaceKey] || "http://www.w3.org/1999/xhtml";
1671
+ },
1672
+ },
1673
+ nodeType: {
1674
+ value: 1,
1675
+ },
1676
+ tagName: {
1677
+ get() {
1678
+ return this[InstanceDataKey];
1679
+ },
1680
+ },
960
1681
  };
961
- const htmlMedia = commaSplit("AUDIO,CANVAS,VIDEO");
962
- const windowMediaConstructors = commaSplit("Audio,MediaSource");
963
- const patchDocument = (WorkerDocument, env, isDocumentImplementation) => {
964
- const DocumentDescriptorMap = {
965
- body: {
966
- get: () => env.$body$
967
- },
968
- cookie: {
969
- get() {
970
- if (env.$isSameOrigin$) {
971
- return getter(this, [ "cookie" ]);
972
- }
973
- warnCrossOrgin("get", "cookie", env);
974
- return "";
975
- },
976
- set(value) {
977
- if (env.$isSameOrigin$) {
978
- setter(this, [ "cookie" ], value);
979
- } else {
980
- warnCrossOrgin("set", "cookie", env);
981
- }
982
- }
983
- },
984
- createElement: {
985
- value(tagName) {
986
- tagName = tagName.toUpperCase();
987
- if (!IS_TAG_REG.test(tagName)) {
988
- throw tagName + " not valid";
989
- }
990
- const isIframe = "IFRAME" === tagName;
991
- const winId = this[WinIdKey];
992
- const instanceId = (isIframe ? "f_" : "") + randomId();
993
- callMethod(this, [ "createElement" ], [ tagName ], 2, instanceId);
994
- const elm = getOrCreateNodeInstance(winId, instanceId, tagName);
995
- if (isIframe) {
996
- const env = createEnvironment({
997
- $winId$: instanceId,
998
- $parentWinId$: winId,
999
- $url$: "about:blank"
1000
- }, true);
1001
- env.$window$.fetch = fetch;
1002
- setter(elm, [ "srcdoc" ], getPartytownScript());
1003
- } else if ("SCRIPT" === tagName) {
1004
- const scriptType = getInstanceStateValue(elm, 5);
1005
- isScriptJsType(scriptType) && setter(elm, [ "type" ], "text/partytown");
1006
- }
1007
- return elm;
1008
- }
1009
- },
1010
- createElementNS: {
1011
- value(namespace, tagName) {
1012
- const instanceId = randomId();
1013
- const nsElm = getOrCreateNodeInstance(this[WinIdKey], instanceId, tagName, namespace);
1014
- callMethod(this, [ "createElementNS" ], [ namespace, tagName ], 2, instanceId);
1015
- return nsElm;
1016
- }
1017
- },
1018
- createTextNode: {
1019
- value(text) {
1020
- const winId = this[WinIdKey];
1021
- const instanceId = randomId();
1022
- const textNode = getOrCreateNodeInstance(winId, instanceId, "#text");
1023
- callMethod(this, [ "createTextNode" ], [ text ], 2, instanceId);
1024
- return textNode;
1025
- }
1026
- },
1027
- createEvent: {
1028
- value: type => new Event(type)
1029
- },
1030
- currentScript: {
1031
- get() {
1032
- return env.$currentScriptId$ ? getOrCreateNodeInstance(this[WinIdKey], env.$currentScriptId$, "SCRIPT") : null;
1033
- }
1034
- },
1035
- defaultView: {
1036
- get: () => isDocumentImplementation ? null : env.$window$
1037
- },
1038
- documentElement: {
1039
- get: () => env.$documentElement$
1040
- },
1041
- getElementsByTagName: {
1042
- value(tagName) {
1043
- tagName = tagName.toUpperCase();
1044
- return "BODY" === tagName ? [ env.$body$ ] : "HEAD" === tagName ? [ env.$head$ ] : callMethod(this, [ "getElementsByTagName" ], [ tagName ]);
1045
- }
1046
- },
1047
- head: {
1048
- get: () => env.$head$
1049
- },
1050
- images: {
1051
- get() {
1052
- return getter(this, [ "images" ]);
1682
+ definePrototypePropertyDescriptor(WorkerElement, ElementDescriptorMap);
1683
+ cachedTreeProps(WorkerElement, elementStructurePropNames);
1684
+ cachedProps(WorkerElement, "id");
1685
+ cachedDimensionProps(WorkerHTMLElement);
1686
+ cachedDimensionMethods(
1687
+ WorkerHTMLElement,
1688
+ commaSplit("getClientRects,getBoundingClientRect")
1689
+ );
1690
+ };
1691
+ const patchHTMLAnchorElement = (WorkerHTMLAnchorElement, env) => {
1692
+ const HTMLAnchorDescriptorMap = {};
1693
+ commaSplit(
1694
+ "hash,host,hostname,href,origin,pathname,port,protocol,search"
1695
+ ).map((anchorProp) => {
1696
+ HTMLAnchorDescriptorMap[anchorProp] = {
1697
+ get() {
1698
+ let value = getInstanceStateValue(this, 4);
1699
+ let href;
1700
+ if ("string" != typeof value) {
1701
+ href = getter(this, ["href"]);
1702
+ setInstanceStateValue(this, 4, href);
1703
+ value = new URL(href)[anchorProp];
1704
+ }
1705
+ return resolveToUrl(env, value, null)[anchorProp];
1706
+ },
1707
+ set(value) {
1708
+ let url;
1709
+ if ("href" === anchorProp) {
1710
+ if (
1711
+ ((url) => {
1712
+ try {
1713
+ new URL(url);
1714
+ return true;
1715
+ } catch (_) {
1716
+ return false;
1053
1717
  }
1054
- },
1055
- implementation: {
1056
- get() {
1057
- return {
1058
- hasFeature: () => true,
1059
- createHTMLDocument: title => {
1060
- const $winId$ = randomId();
1061
- callMethod(this, [ "implementation", "createHTMLDocument" ], [ title ], 1, {
1062
- $winId$: $winId$
1063
- });
1064
- const docEnv = createEnvironment({
1065
- $winId$: $winId$,
1066
- $parentWinId$: $winId$,
1067
- $url$: env.$location$ + "",
1068
- $visibilityState$: "hidden"
1069
- }, true, true);
1070
- return docEnv.$document$;
1718
+ })(value)
1719
+ ) {
1720
+ url = new URL(value);
1721
+ } else {
1722
+ const baseHref = env.$location$.href;
1723
+ url = resolveToUrl(env, baseHref, null);
1724
+ url.href = new URL(value + "", url.href);
1725
+ }
1726
+ } else {
1727
+ url = resolveToUrl(env, this.href, null);
1728
+ url[anchorProp] = value;
1729
+ }
1730
+ setInstanceStateValue(this, 4, url.href);
1731
+ setter(this, ["href"], url.href);
1732
+ },
1733
+ };
1734
+ });
1735
+ definePrototypePropertyDescriptor(
1736
+ WorkerHTMLAnchorElement,
1737
+ HTMLAnchorDescriptorMap
1738
+ );
1739
+ };
1740
+ const patchHTMLIFrameElement = (WorkerHTMLIFrameElement, env) => {
1741
+ const HTMLIFrameDescriptorMap = {
1742
+ contentDocument: {
1743
+ get() {
1744
+ return getIframeEnv(this).$document$;
1745
+ },
1746
+ },
1747
+ contentWindow: {
1748
+ get() {
1749
+ return getIframeEnv(this).$window$;
1750
+ },
1751
+ },
1752
+ src: {
1753
+ get() {
1754
+ let src = getInstanceStateValue(this, 0);
1755
+ if (src && src.startsWith("javascript:")) {
1756
+ return src;
1757
+ }
1758
+ src = getIframeEnv(this).$location$.href;
1759
+ return src.startsWith("about:") ? "" : src;
1760
+ },
1761
+ set(src) {
1762
+ if (src) {
1763
+ if (src.startsWith("javascript:")) {
1764
+ setInstanceStateValue(this, 0, src);
1765
+ } else if (!src.startsWith("about:")) {
1766
+ let xhr = new XMLHttpRequest();
1767
+ let xhrStatus;
1768
+ let env = getIframeEnv(this);
1769
+ env.$location$.href = src = resolveUrl(env, src, "div");
1770
+ env.$isLoading$ = 1;
1771
+ setInstanceStateValue(this, 1, void 0);
1772
+ xhr.open("GET", src, false);
1773
+ xhr.send();
1774
+ xhrStatus = xhr.status;
1775
+ if (xhrStatus > 199 && xhrStatus < 300) {
1776
+ setter(
1777
+ this,
1778
+ ["srcdoc"],
1779
+ `<base href="${src}">` +
1780
+ (function (text) {
1781
+ return text.replace(SCRIPT_TAG_REGEXP, (_, attrs) => {
1782
+ const parts = [];
1783
+ let hasType = false;
1784
+ let match;
1785
+ while ((match = ATTR_REGEXP.exec(attrs))) {
1786
+ let [keyValue] = match;
1787
+ if (keyValue.startsWith("type=")) {
1788
+ hasType = true;
1789
+ keyValue = keyValue.replace(
1790
+ /(application|text)\/javascript/,
1791
+ SCRIPT_TYPE
1792
+ );
1793
+ }
1794
+ parts.push(keyValue);
1071
1795
  }
1072
- };
1073
- }
1074
- },
1075
- location: {
1076
- get: () => env.$location$,
1077
- set(url) {
1078
- env.$location$.href = url + "";
1079
- }
1080
- },
1081
- nodeType: {
1082
- value: 9
1083
- },
1084
- parentNode: {
1085
- value: null
1086
- },
1087
- parentElement: {
1088
- value: null
1089
- },
1090
- readyState: {
1091
- value: "complete"
1092
- },
1093
- visibilityState: {
1094
- get: () => env.$visibilityState$ || "visible"
1095
- }
1096
- };
1097
- definePrototypePropertyDescriptor(WorkerDocument, DocumentDescriptorMap);
1098
- cachedProps(WorkerDocument, "compatMode,referrer,forms");
1099
- };
1100
- const patchDocumentElementChild = (WokerDocumentElementChild, env) => {
1101
- const DocumentElementChildDescriptorMap = {
1102
- parentElement: {
1103
- get() {
1104
- return this.parentNode;
1105
- }
1106
- },
1107
- parentNode: {
1108
- get: () => env.$documentElement$
1109
- }
1110
- };
1111
- definePrototypePropertyDescriptor(WokerDocumentElementChild, DocumentElementChildDescriptorMap);
1796
+ hasType || parts.push('type="text/partytown"');
1797
+ return `<script ${parts.join(" ")}>`;
1798
+ });
1799
+ })(xhr.responseText) +
1800
+ getPartytownScript()
1801
+ );
1802
+ sendToMain(true);
1803
+ webWorkerCtx.$postMessage$([7, env.$winId$]);
1804
+ } else {
1805
+ setInstanceStateValue(this, 1, xhrStatus);
1806
+ env.$isLoading$ = 0;
1807
+ }
1808
+ }
1809
+ }
1810
+ },
1811
+ },
1812
+ ...HTMLSrcElementDescriptorMap,
1112
1813
  };
1113
- const patchElement = (WorkerElement, WorkerHTMLElement) => {
1114
- const ElementDescriptorMap = {
1115
- localName: {
1116
- get() {
1117
- return this[InstanceDataKey].toLowerCase();
1118
- }
1119
- },
1120
- namespaceURI: {
1121
- get() {
1122
- return this[NamespaceKey] || "http://www.w3.org/1999/xhtml";
1123
- }
1124
- },
1125
- nodeType: {
1126
- value: 1
1127
- },
1128
- tagName: {
1129
- get() {
1130
- return this[InstanceDataKey];
1131
- }
1132
- }
1133
- };
1134
- definePrototypePropertyDescriptor(WorkerElement, ElementDescriptorMap);
1135
- cachedTreeProps(WorkerElement, elementStructurePropNames);
1136
- cachedProps(WorkerElement, "id");
1137
- cachedDimensionProps(WorkerHTMLElement);
1138
- cachedDimensionMethods(WorkerHTMLElement, commaSplit("getClientRects,getBoundingClientRect"));
1814
+ definePrototypePropertyDescriptor(
1815
+ WorkerHTMLIFrameElement,
1816
+ HTMLIFrameDescriptorMap
1817
+ );
1818
+ };
1819
+ const ATTR_REGEXP_STR =
1820
+ "((?:\\w|-)+(?:=(?:(?:\\w|-)+|'[^']*'|\"[^\"]*\")?)?)";
1821
+ const SCRIPT_TAG_REGEXP = new RegExp(
1822
+ `<script\\s*((${ATTR_REGEXP_STR}\\s*)*)>`,
1823
+ "mg"
1824
+ );
1825
+ const ATTR_REGEXP = new RegExp(ATTR_REGEXP_STR, "mg");
1826
+ const getIframeEnv = (iframe) => {
1827
+ const $winId$ = iframe[InstanceIdKey];
1828
+ environments[$winId$] ||
1829
+ createEnvironment(
1830
+ {
1831
+ $winId$: $winId$,
1832
+ $parentWinId$: iframe[WinIdKey],
1833
+ $url$: getter(iframe, ["src"]) || "about:blank",
1834
+ },
1835
+ true
1836
+ );
1837
+ return environments[$winId$];
1838
+ };
1839
+ const patchSvgElement = (WorkerSVGGraphicsElement) => {
1840
+ const getMatrix = (elm, methodName) => {
1841
+ const {
1842
+ a: a,
1843
+ b: b,
1844
+ c: c,
1845
+ d: d,
1846
+ e: e,
1847
+ f: f,
1848
+ } = callMethod(elm, [methodName], EMPTY_ARRAY);
1849
+ return new DOMMatrixReadOnly([a, b, c, d, e, f]);
1139
1850
  };
1140
- const patchHTMLAnchorElement = (WorkerHTMLAnchorElement, env) => {
1141
- const HTMLAnchorDescriptorMap = {};
1142
- commaSplit("hash,host,hostname,href,origin,pathname,port,protocol,search").map((anchorProp => {
1143
- HTMLAnchorDescriptorMap[anchorProp] = {
1144
- get() {
1145
- let value = getInstanceStateValue(this, 4);
1146
- let href;
1147
- if ("string" != typeof value) {
1148
- href = getter(this, [ "href" ]);
1149
- setInstanceStateValue(this, 4, href);
1150
- value = new URL(href)[anchorProp];
1151
- }
1152
- return resolveToUrl(env, value, null)[anchorProp];
1153
- },
1154
- set(value) {
1155
- let url;
1156
- if ("href" === anchorProp) {
1157
- if ((url => {
1158
- try {
1159
- new URL(url);
1160
- return true;
1161
- } catch (_) {
1162
- return false;
1163
- }
1164
- })(value)) {
1165
- url = new URL(value);
1166
- } else {
1167
- const baseHref = env.$location$.href;
1168
- url = resolveToUrl(env, baseHref, null);
1169
- url.href = new URL(value + "", url.href);
1170
- }
1171
- } else {
1172
- url = resolveToUrl(env, this.href, null);
1173
- url[anchorProp] = value;
1174
- }
1175
- setInstanceStateValue(this, 4, url.href);
1176
- setter(this, [ "href" ], url.href);
1177
- }
1178
- };
1179
- }));
1180
- definePrototypePropertyDescriptor(WorkerHTMLAnchorElement, HTMLAnchorDescriptorMap);
1851
+ const SVGGraphicsElementDescriptorMap = {
1852
+ ...WorkerSVGGraphicsElement,
1853
+ getCTM: {
1854
+ value: function () {
1855
+ return getMatrix(this, "getCTM");
1856
+ },
1857
+ },
1858
+ getScreenCTM: {
1859
+ value: function () {
1860
+ return getMatrix(this, "getScreenCTM");
1861
+ },
1862
+ },
1181
1863
  };
1182
- const patchHTMLIFrameElement = (WorkerHTMLIFrameElement, env) => {
1183
- const HTMLIFrameDescriptorMap = {
1184
- contentDocument: {
1185
- get() {
1186
- return getIframeEnv(this).$document$;
1187
- }
1188
- },
1189
- contentWindow: {
1190
- get() {
1191
- return getIframeEnv(this).$window$;
1192
- }
1864
+ definePrototypePropertyDescriptor(
1865
+ WorkerSVGGraphicsElement,
1866
+ SVGGraphicsElementDescriptorMap
1867
+ );
1868
+ };
1869
+ const createNamedNodeMapCstr = (win, WorkerBase) => {
1870
+ win.NamedNodeMap = defineConstructorName(
1871
+ class NamedNodeMap extends WorkerBase {
1872
+ constructor(winId, instanceId, applyPath) {
1873
+ super(winId, instanceId, applyPath);
1874
+ return new Proxy(this, {
1875
+ get(target, propName) {
1876
+ const handler = NAMED_NODE_MAP_HANDLERS[propName];
1877
+ return handler
1878
+ ? handler.bind(target, [propName])
1879
+ : getter(target, [propName]);
1193
1880
  },
1194
- src: {
1195
- get() {
1196
- let src = getInstanceStateValue(this, 0);
1197
- if (src && src.startsWith("javascript:")) {
1198
- return src;
1199
- }
1200
- src = getIframeEnv(this).$location$.href;
1201
- return src.startsWith("about:") ? "" : src;
1202
- },
1203
- set(src) {
1204
- if (src) {
1205
- if (src.startsWith("javascript:")) {
1206
- setInstanceStateValue(this, 0, src);
1207
- } else if (!src.startsWith("about:")) {
1208
- let xhr = new XMLHttpRequest;
1209
- let xhrStatus;
1210
- let env = getIframeEnv(this);
1211
- env.$location$.href = src = resolveUrl(env, src, "iframe");
1212
- env.$isLoading$ = 1;
1213
- setInstanceStateValue(this, 1, void 0);
1214
- xhr.open("GET", src, false);
1215
- xhr.send();
1216
- xhrStatus = xhr.status;
1217
- if (xhrStatus > 199 && xhrStatus < 300) {
1218
- setter(this, [ "srcdoc" ], `<base href="${src}">` + function(text) {
1219
- return text.replace(SCRIPT_TAG_REGEXP, ((_, attrs) => {
1220
- const parts = [];
1221
- let hasType = false;
1222
- let match;
1223
- while (match = ATTR_REGEXP.exec(attrs)) {
1224
- let [keyValue] = match;
1225
- if (keyValue.startsWith("type=")) {
1226
- hasType = true;
1227
- keyValue = keyValue.replace(/(application|text)\/javascript/, SCRIPT_TYPE);
1228
- }
1229
- parts.push(keyValue);
1230
- }
1231
- hasType || parts.push('type="text/partytown"');
1232
- return `<script ${parts.join(" ")}>`;
1233
- }));
1234
- }(xhr.responseText) + getPartytownScript());
1235
- sendToMain(true);
1236
- webWorkerCtx.$postMessage$([ 7, env.$winId$ ]);
1237
- } else {
1238
- setInstanceStateValue(this, 1, xhrStatus);
1239
- env.$isLoading$ = 0;
1240
- }
1241
- }
1242
- }
1243
- }
1881
+ set(target, propName, propValue) {
1882
+ const handler = NAMED_NODE_MAP_HANDLERS[propName];
1883
+ if (handler) {
1884
+ throw new Error(
1885
+ "Can't set read-only property: " + String(propName)
1886
+ );
1887
+ }
1888
+ setter(target, [propName], propValue);
1889
+ return true;
1244
1890
  },
1245
- ...HTMLSrcElementDescriptorMap
1246
- };
1247
- definePrototypePropertyDescriptor(WorkerHTMLIFrameElement, HTMLIFrameDescriptorMap);
1891
+ });
1892
+ }
1893
+ },
1894
+ "NamedNodeMap"
1895
+ );
1896
+ };
1897
+ function method(applyPath, ...args) {
1898
+ return callMethod(this, applyPath, args, 1);
1899
+ }
1900
+ const NAMED_NODE_MAP_HANDLERS = {
1901
+ getNamedItem: method,
1902
+ getNamedItemNS: method,
1903
+ item: method,
1904
+ removeNamedItem: method,
1905
+ removeNamedItemNS: method,
1906
+ setNamedItem: method,
1907
+ setNamedItemNS: method,
1908
+ };
1909
+ const createWindow = (
1910
+ $winId$,
1911
+ $parentWinId$,
1912
+ url,
1913
+ $visibilityState$,
1914
+ isIframeWindow,
1915
+ isDocumentImplementation
1916
+ ) => {
1917
+ let cstrInstanceId;
1918
+ let cstrNodeName;
1919
+ let cstrNamespace;
1920
+ const WorkerBase = class {
1921
+ constructor(winId, instanceId, applyPath, instanceData, namespace) {
1922
+ this[WinIdKey] = winId || $winId$;
1923
+ this[InstanceIdKey] = instanceId || cstrInstanceId || randomId();
1924
+ this[ApplyPathKey] = applyPath || [];
1925
+ this[InstanceDataKey] = instanceData || cstrNodeName;
1926
+ this[NamespaceKey] = namespace || cstrNamespace;
1927
+ this[InstanceStateKey] = {};
1928
+ cstrInstanceId = cstrNodeName = cstrNamespace = void 0;
1929
+ }
1248
1930
  };
1249
- const ATTR_REGEXP_STR = "((?:\\w|-)+(?:=(?:(?:\\w|-)+|'[^']*'|\"[^\"]*\")?)?)";
1250
- const SCRIPT_TAG_REGEXP = new RegExp(`<script\\s*((${ATTR_REGEXP_STR}\\s*)*)>`, "mg");
1251
- const ATTR_REGEXP = new RegExp(ATTR_REGEXP_STR, "mg");
1252
- const getIframeEnv = iframe => {
1253
- const $winId$ = iframe[InstanceIdKey];
1254
- environments[$winId$] || createEnvironment({
1255
- $winId$: $winId$,
1256
- $parentWinId$: iframe[WinIdKey],
1257
- $url$: getter(iframe, [ "src" ]) || "about:blank"
1258
- }, true);
1259
- return environments[$winId$];
1931
+ const WorkerLocation = defineConstructorName(
1932
+ class extends URL {
1933
+ assign() {
1934
+ logWorker("location.assign(), noop");
1935
+ }
1936
+ reload() {
1937
+ logWorker("location.reload(), noop");
1938
+ }
1939
+ replace() {
1940
+ logWorker("location.replace(), noop");
1941
+ }
1942
+ },
1943
+ "Location"
1944
+ );
1945
+ const $location$ = new WorkerLocation(url);
1946
+ const $isSameOrigin$ =
1947
+ $location$.origin === webWorkerCtx.$origin$ ||
1948
+ "about:blank" === $location$.origin;
1949
+ const $isTopWindow$ = $parentWinId$ === $winId$;
1950
+ const env = {};
1951
+ const getChildEnvs = () => {
1952
+ let childEnv = [];
1953
+ let envWinId;
1954
+ let otherEnv;
1955
+ for (envWinId in environments) {
1956
+ otherEnv = environments[envWinId];
1957
+ otherEnv.$parentWinId$ !== $winId$ ||
1958
+ otherEnv.$isTopWindow$ ||
1959
+ childEnv.push(otherEnv);
1960
+ }
1961
+ return childEnv;
1260
1962
  };
1261
- const patchSvgElement = WorkerSVGGraphicsElement => {
1262
- const getMatrix = (elm, methodName) => {
1263
- const {a: a, b: b, c: c, d: d, e: e, f: f} = callMethod(elm, [ methodName ], EMPTY_ARRAY);
1264
- return new DOMMatrixReadOnly([ a, b, c, d, e, f ]);
1265
- };
1266
- const SVGGraphicsElementDescriptorMap = {
1267
- ...WorkerSVGGraphicsElement,
1268
- getCTM: {
1269
- value: function() {
1270
- return getMatrix(this, "getCTM");
1963
+ const WorkerWindow = defineConstructorName(
1964
+ class extends WorkerBase {
1965
+ constructor() {
1966
+ super($winId$, $winId$);
1967
+ let win = this;
1968
+ let value;
1969
+ let historyState;
1970
+ let hasInitializedMedia = 0;
1971
+ let initWindowMedia = () => {
1972
+ if (!hasInitializedMedia) {
1973
+ (() => {
1974
+ if (!webWorkerCtx.$initWindowMedia$) {
1975
+ self.$bridgeToMedia$ = [
1976
+ getter,
1977
+ setter,
1978
+ callMethod,
1979
+ constructGlobal,
1980
+ definePrototypePropertyDescriptor,
1981
+ randomId,
1982
+ WinIdKey,
1983
+ InstanceIdKey,
1984
+ ApplyPathKey,
1985
+ ];
1986
+ webWorkerCtx.$importScripts$(
1987
+ partytownLibUrl("partytown-media.js?v=0.7.5")
1988
+ );
1989
+ webWorkerCtx.$initWindowMedia$ = self.$bridgeFromMedia$;
1990
+ delete self.$bridgeFromMedia$;
1271
1991
  }
1272
- },
1273
- getScreenCTM: {
1274
- value: function() {
1275
- return getMatrix(this, "getScreenCTM");
1992
+ return webWorkerCtx.$initWindowMedia$;
1993
+ })()(
1994
+ WorkerBase,
1995
+ WorkerEventTargetProxy,
1996
+ env,
1997
+ win,
1998
+ windowMediaConstructors
1999
+ );
2000
+ hasInitializedMedia = 1;
2001
+ }
2002
+ };
2003
+ let nodeCstrs = {};
2004
+ let $createNode$ = (nodeName, instanceId, namespace) => {
2005
+ htmlMedia.includes(nodeName) && initWindowMedia();
2006
+ const NodeCstr = nodeCstrs[nodeName]
2007
+ ? nodeCstrs[nodeName]
2008
+ : nodeName.includes("-")
2009
+ ? nodeCstrs.UNKNOWN
2010
+ : nodeCstrs.I;
2011
+ cstrInstanceId = instanceId;
2012
+ cstrNodeName = nodeName;
2013
+ cstrNamespace = namespace;
2014
+ return new NodeCstr();
2015
+ };
2016
+ win.Window = WorkerWindow;
2017
+ win.name = name + `${normalizedWinId($winId$)} (${$winId$})`;
2018
+ createNodeCstr(win, env, WorkerBase);
2019
+ ((win) => {
2020
+ win.NodeList = defineConstructorName(NodeList, "NodeList");
2021
+ })(win);
2022
+ createNamedNodeMapCstr(win, WorkerBase);
2023
+ createCSSStyleDeclarationCstr(win, WorkerBase, "CSSStyleDeclaration");
2024
+ ((win, WorkerBase, cstrName) => {
2025
+ win[cstrName] = defineConstructorName(
2026
+ class extends WorkerBase {
2027
+ now() {
2028
+ return performance.now();
1276
2029
  }
1277
- }
1278
- };
1279
- definePrototypePropertyDescriptor(WorkerSVGGraphicsElement, SVGGraphicsElementDescriptorMap);
1280
- };
1281
- const createNamedNodeMapCstr = (win, WorkerBase) => {
1282
- win.NamedNodeMap = defineConstructorName(class NamedNodeMap extends WorkerBase {
1283
- constructor(winId, instanceId, applyPath) {
1284
- super(winId, instanceId, applyPath);
1285
- return new Proxy(this, {
1286
- get(target, propName) {
1287
- const handler = NAMED_NODE_MAP_HANDLERS[propName];
1288
- return handler ? handler.bind(target, [ propName ]) : getter(target, [ propName ]);
1289
- },
1290
- set(target, propName, propValue) {
1291
- const handler = NAMED_NODE_MAP_HANDLERS[propName];
1292
- if (handler) {
1293
- throw new Error("Can't set read-only property: " + String(propName));
1294
- }
1295
- setter(target, [ propName ], propValue);
1296
- return true;
1297
- }
1298
- });
1299
- }
1300
- }, "NamedNodeMap");
1301
- };
1302
- function method(applyPath, ...args) {
1303
- return callMethod(this, applyPath, args, 1);
1304
- }
1305
- const NAMED_NODE_MAP_HANDLERS = {
1306
- getNamedItem: method,
1307
- getNamedItemNS: method,
1308
- item: method,
1309
- removeNamedItem: method,
1310
- removeNamedItemNS: method,
1311
- setNamedItem: method,
1312
- setNamedItemNS: method
1313
- };
1314
- const createWindow = ($winId$, $parentWinId$, url, $visibilityState$, isIframeWindow, isDocumentImplementation) => {
1315
- let cstrInstanceId;
1316
- let cstrNodeName;
1317
- let cstrNamespace;
1318
- const WorkerBase = class {
1319
- constructor(winId, instanceId, applyPath, instanceData, namespace) {
1320
- this[WinIdKey] = winId || $winId$;
1321
- this[InstanceIdKey] = instanceId || cstrInstanceId || randomId();
1322
- this[ApplyPathKey] = applyPath || [];
1323
- this[InstanceDataKey] = instanceData || cstrNodeName;
1324
- this[NamespaceKey] = namespace || cstrNamespace;
1325
- this[InstanceStateKey] = {};
1326
- cstrInstanceId = cstrNodeName = cstrNamespace = void 0;
1327
- }
1328
- };
1329
- const WorkerLocation = defineConstructorName(class extends URL {
1330
- assign() {
1331
- logWorker("location.assign(), noop");
1332
- }
1333
- reload() {
1334
- logWorker("location.reload(), noop");
1335
- }
1336
- replace() {
1337
- logWorker("location.replace(), noop");
1338
- }
1339
- }, "Location");
1340
- const $location$ = new WorkerLocation(url);
1341
- const $isSameOrigin$ = $location$.origin === webWorkerCtx.$origin$ || "about:blank" === $location$.origin;
1342
- const $isTopWindow$ = $parentWinId$ === $winId$;
1343
- const env = {};
1344
- const getChildEnvs = () => {
1345
- let childEnv = [];
1346
- let envWinId;
1347
- let otherEnv;
1348
- for (envWinId in environments) {
1349
- otherEnv = environments[envWinId];
1350
- otherEnv.$parentWinId$ !== $winId$ || otherEnv.$isTopWindow$ || childEnv.push(otherEnv);
1351
- }
1352
- return childEnv;
1353
- };
1354
- const WorkerWindow = defineConstructorName(class extends WorkerBase {
1355
- constructor() {
1356
- super($winId$, $winId$);
1357
- let win = this;
1358
- let value;
1359
- let historyState;
1360
- let hasInitializedMedia = 0;
1361
- let initWindowMedia = () => {
1362
- if (!hasInitializedMedia) {
1363
- (() => {
1364
- if (!webWorkerCtx.$initWindowMedia$) {
1365
- self.$bridgeToMedia$ = [ getter, setter, callMethod, constructGlobal, definePrototypePropertyDescriptor, randomId, WinIdKey, InstanceIdKey, ApplyPathKey ];
1366
- webWorkerCtx.$importScripts$(partytownLibUrl("partytown-media.js?v=0.7.5"));
1367
- webWorkerCtx.$initWindowMedia$ = self.$bridgeFromMedia$;
1368
- delete self.$bridgeFromMedia$;
1369
- }
1370
- return webWorkerCtx.$initWindowMedia$;
1371
- })()(WorkerBase, WorkerEventTargetProxy, env, win, windowMediaConstructors);
1372
- hasInitializedMedia = 1;
2030
+ },
2031
+ cstrName
2032
+ );
2033
+ })(win, WorkerBase, "Performance");
2034
+ ((win, nodeCstrs) => {
2035
+ const registry = new Map();
2036
+ win.customElements = {
2037
+ define(tagName, Cstr, opts) {
2038
+ registry.set(tagName, Cstr);
2039
+ nodeCstrs[tagName.toUpperCase()] = Cstr;
2040
+ const ceData = [Cstr.name, Cstr.observedAttributes];
2041
+ callMethod(
2042
+ win,
2043
+ ["customElements", "define"],
2044
+ [tagName, ceData, opts]
2045
+ );
2046
+ },
2047
+ get: (tagName) =>
2048
+ registry.get(tagName) ||
2049
+ callMethod(win, ["customElements", "get"], [tagName]),
2050
+ whenDefined: (tagName) =>
2051
+ registry.has(tagName)
2052
+ ? Promise.resolve()
2053
+ : callMethod(
2054
+ win,
2055
+ ["customElements", "whenDefined"],
2056
+ [tagName]
2057
+ ),
2058
+ upgrade: (elm) =>
2059
+ callMethod(win, ["customElements", "upgrade"], [elm]),
2060
+ };
2061
+ })(win, nodeCstrs);
2062
+ webWorkerCtx.$interfaces$.map(
2063
+ ([cstrName, superCstrName, members, interfaceType, nodeName]) => {
2064
+ const SuperCstr = TrapConstructors[cstrName]
2065
+ ? WorkerTrapProxy
2066
+ : "EventTarget" === superCstrName
2067
+ ? WorkerEventTargetProxy
2068
+ : "Object" === superCstrName
2069
+ ? WorkerBase
2070
+ : win[superCstrName];
2071
+ const Cstr = (win[cstrName] = defineConstructorName(
2072
+ 12 === interfaceType
2073
+ ? class extends WorkerBase {
2074
+ constructor(...args) {
2075
+ super();
2076
+ constructGlobal(this, cstrName, args);
2077
+ }
1373
2078
  }
1374
- };
1375
- let nodeCstrs = {};
1376
- let $createNode$ = (nodeName, instanceId, namespace) => {
1377
- htmlMedia.includes(nodeName) && initWindowMedia();
1378
- const NodeCstr = nodeCstrs[nodeName] ? nodeCstrs[nodeName] : nodeName.includes("-") ? nodeCstrs.UNKNOWN : nodeCstrs.I;
1379
- cstrInstanceId = instanceId;
1380
- cstrNodeName = nodeName;
1381
- cstrNamespace = namespace;
1382
- return new NodeCstr;
1383
- };
1384
- win.Window = WorkerWindow;
1385
- win.name = name + `${normalizedWinId($winId$)} (${$winId$})`;
1386
- createNodeCstr(win, env, WorkerBase);
1387
- (win => {
1388
- win.NodeList = defineConstructorName(NodeList, "NodeList");
1389
- })(win);
1390
- createNamedNodeMapCstr(win, WorkerBase);
1391
- createCSSStyleDeclarationCstr(win, WorkerBase, "CSSStyleDeclaration");
1392
- ((win, WorkerBase, cstrName) => {
1393
- win[cstrName] = defineConstructorName(class extends WorkerBase {
1394
- now() {
1395
- return performance.now();
1396
- }
1397
- }, cstrName);
1398
- })(win, WorkerBase, "Performance");
1399
- ((win, nodeCstrs) => {
1400
- const registry = new Map;
1401
- win.customElements = {
1402
- define(tagName, Cstr, opts) {
1403
- registry.set(tagName, Cstr);
1404
- nodeCstrs[tagName.toUpperCase()] = Cstr;
1405
- const ceData = [ Cstr.name, Cstr.observedAttributes ];
1406
- callMethod(win, [ "customElements", "define" ], [ tagName, ceData, opts ]);
2079
+ : win[cstrName] || class extends SuperCstr {},
2080
+ cstrName
2081
+ ));
2082
+ nodeName && (nodeCstrs[nodeName] = Cstr);
2083
+ members.map(([memberName, memberType, staticValue]) => {
2084
+ memberName in Cstr.prototype ||
2085
+ memberName in SuperCstr.prototype ||
2086
+ ("string" == typeof memberType
2087
+ ? definePrototypeProperty(Cstr, memberName, {
2088
+ get() {
2089
+ if (!hasInstanceStateValue(this, memberName)) {
2090
+ const instanceId = this[InstanceIdKey];
2091
+ const applyPath = [
2092
+ ...this[ApplyPathKey],
2093
+ memberName,
2094
+ ];
2095
+ const PropCstr = win[memberType];
2096
+ PropCstr &&
2097
+ setInstanceStateValue(
2098
+ this,
2099
+ memberName,
2100
+ new PropCstr($winId$, instanceId, applyPath)
2101
+ );
2102
+ }
2103
+ return getInstanceStateValue(this, memberName);
1407
2104
  },
1408
- get: tagName => registry.get(tagName) || callMethod(win, [ "customElements", "get" ], [ tagName ]),
1409
- whenDefined: tagName => registry.has(tagName) ? Promise.resolve() : callMethod(win, [ "customElements", "whenDefined" ], [ tagName ]),
1410
- upgrade: elm => callMethod(win, [ "customElements", "upgrade" ], [ elm ])
1411
- };
1412
- })(win, nodeCstrs);
1413
- webWorkerCtx.$interfaces$.map((([cstrName, superCstrName, members, interfaceType, nodeName]) => {
1414
- const SuperCstr = TrapConstructors[cstrName] ? WorkerTrapProxy : "EventTarget" === superCstrName ? WorkerEventTargetProxy : "Object" === superCstrName ? WorkerBase : win[superCstrName];
1415
- const Cstr = win[cstrName] = defineConstructorName(12 === interfaceType ? class extends WorkerBase {
1416
- constructor(...args) {
1417
- super();
1418
- constructGlobal(this, cstrName, args);
2105
+ set(value) {
2106
+ setInstanceStateValue(this, memberName, value);
2107
+ },
2108
+ })
2109
+ : 5 === memberType
2110
+ ? definePrototypeValue(
2111
+ Cstr,
2112
+ memberName,
2113
+ function (...args) {
2114
+ return callMethod(this, [memberName], args);
1419
2115
  }
1420
- } : win[cstrName] || class extends SuperCstr {}, cstrName);
1421
- nodeName && (nodeCstrs[nodeName] = Cstr);
1422
- members.map((([memberName, memberType, staticValue]) => {
1423
- memberName in Cstr.prototype || memberName in SuperCstr.prototype || ("string" == typeof memberType ? definePrototypeProperty(Cstr, memberName, {
2116
+ )
2117
+ : memberType > 0 &&
2118
+ (void 0 !== staticValue
2119
+ ? definePrototypeValue(Cstr, memberName, staticValue)
2120
+ : definePrototypeProperty(Cstr, memberName, {
1424
2121
  get() {
1425
- if (!hasInstanceStateValue(this, memberName)) {
1426
- const instanceId = this[InstanceIdKey];
1427
- const applyPath = [ ...this[ApplyPathKey], memberName ];
1428
- const PropCstr = win[memberType];
1429
- PropCstr && setInstanceStateValue(this, memberName, new PropCstr($winId$, instanceId, applyPath));
1430
- }
1431
- return getInstanceStateValue(this, memberName);
2122
+ return getter(this, [memberName]);
1432
2123
  },
1433
2124
  set(value) {
1434
- setInstanceStateValue(this, memberName, value);
1435
- }
1436
- }) : 5 === memberType ? definePrototypeValue(Cstr, memberName, (function(...args) {
1437
- return callMethod(this, [ memberName ], args);
1438
- })) : memberType > 0 && (void 0 !== staticValue ? definePrototypeValue(Cstr, memberName, staticValue) : definePrototypeProperty(Cstr, memberName, {
1439
- get() {
1440
- return getter(this, [ memberName ]);
2125
+ return setter(this, [memberName], value);
1441
2126
  },
1442
- set(value) {
1443
- return setter(this, [ memberName ], value);
1444
- }
1445
- })));
1446
- }));
1447
- }));
1448
- commaSplit("atob,btoa,crypto,indexedDB,setTimeout,setInterval,clearTimeout,clearInterval").map((globalName => {
1449
- delete WorkerWindow.prototype[globalName];
1450
- if (!(globalName in win)) {
1451
- value = self[globalName];
1452
- null != value && (win[globalName] = "function" != typeof value || value.toString().startsWith("class") ? value : value.bind(self));
1453
- }
1454
- }));
1455
- Object.getOwnPropertyNames(self).map((globalName => {
1456
- globalName in win || (win[globalName] = self[globalName]);
1457
- }));
1458
- windowMediaConstructors.map((cstrName => defineProperty(win, cstrName, {
1459
- get() {
1460
- initWindowMedia();
1461
- return win[cstrName];
1462
- }
1463
- })));
1464
- "trustedTypes" in self && (win.trustedTypes = self.trustedTypes);
1465
- patchElement(win.Element, win.HTMLElement);
1466
- patchDocument(win.Document, env, isDocumentImplementation);
1467
- (WorkerDocumentFragment => {
1468
- definePrototypeNodeType(WorkerDocumentFragment, 11);
1469
- cachedTreeProps(WorkerDocumentFragment, elementStructurePropNames);
1470
- })(win.DocumentFragment);
1471
- patchHTMLAnchorElement(win.HTMLAnchorElement, env);
1472
- (WorkerHTMLFormElement => {
1473
- definePrototypePropertyDescriptor(WorkerHTMLFormElement, {});
1474
- cachedProps(WorkerHTMLFormElement, "elements");
1475
- })(win.HTMLFormElement);
1476
- patchHTMLIFrameElement(win.HTMLIFrameElement);
1477
- patchHTMLScriptElement(win.HTMLScriptElement, env);
1478
- patchSvgElement(win.SVGGraphicsElement);
1479
- patchDocumentElementChild(win.HTMLHeadElement, env);
1480
- patchDocumentElementChild(win.HTMLBodyElement, env);
1481
- ((WorkerHTMLHtmlElement, env) => {
1482
- const DocumentElementDescriptorMap = {
1483
- parentElement: {
1484
- value: null
1485
- },
1486
- parentNode: {
1487
- get: () => env.$document$
1488
- }
1489
- };
1490
- definePrototypePropertyDescriptor(WorkerHTMLHtmlElement, DocumentElementDescriptorMap);
1491
- })(win.HTMLHtmlElement, env);
1492
- createCSSStyleSheetConstructor(win, "CSSStyleSheet");
1493
- definePrototypeNodeType(win.Comment, 8);
1494
- definePrototypeNodeType(win.DocumentType, 10);
1495
- Object.assign(env, {
1496
- $winId$: $winId$,
1497
- $parentWinId$: $parentWinId$,
1498
- $window$: new Proxy(win, {
1499
- get: (win, propName) => {
1500
- var _a;
1501
- if ("string" != typeof propName || isNaN(propName)) {
1502
- return (null === (_a = webWorkerCtx.$config$.mainWindowAccessors) || void 0 === _a ? void 0 : _a.includes(propName)) ? getter(this, [ propName ]) : win[propName];
1503
- }
1504
- {
1505
- let frame = getChildEnvs()[propName];
1506
- return frame ? frame.$window$ : void 0;
1507
- }
1508
- },
1509
- has: () => true
1510
- }),
1511
- $document$: $createNode$("#document", $winId$ + ".d"),
1512
- $documentElement$: $createNode$("HTML", $winId$ + ".e"),
1513
- $head$: $createNode$("HEAD", $winId$ + ".h"),
1514
- $body$: $createNode$("BODY", $winId$ + ".b"),
1515
- $location$: $location$,
1516
- $visibilityState$: $visibilityState$,
1517
- $isSameOrigin$: $isSameOrigin$,
1518
- $isTopWindow$: $isTopWindow$,
1519
- $createNode$: $createNode$
1520
- });
1521
- win.requestAnimationFrame = cb => setTimeout((() => cb(performance.now())), 9);
1522
- win.cancelAnimationFrame = id => clearTimeout(id);
1523
- win.requestIdleCallback = (cb, start) => {
1524
- start = Date.now();
1525
- return setTimeout((() => cb({
1526
- didTimeout: false,
1527
- timeRemaining: () => Math.max(0, 50 - (Date.now() - start))
1528
- })), 1);
1529
- };
1530
- win.cancelIdleCallback = id => clearTimeout(id);
1531
- addStorageApi(win, "localStorage", webWorkerlocalStorage, $isSameOrigin$, env);
1532
- addStorageApi(win, "sessionStorage", webWorkerSessionStorage, $isSameOrigin$, env);
1533
- $isSameOrigin$ || (win.indexeddb = void 0);
1534
- if (isIframeWindow) {
1535
- historyState = {};
1536
- win.history = {
1537
- pushState(stateObj) {
1538
- historyState = stateObj;
1539
- },
1540
- replaceState(stateObj) {
1541
- historyState = stateObj;
1542
- },
1543
- get state() {
1544
- return historyState;
1545
- },
1546
- length: 0
1547
- };
1548
- win.indexeddb = void 0;
1549
- } else {
1550
- const originalPushState = win.history.pushState.bind(win.history);
1551
- const originalReplaceState = win.history.replaceState.bind(win.history);
1552
- win.history.pushState = (stateObj, _, newUrl) => {
1553
- false !== env.$propagateHistoryChange$ && originalPushState(stateObj, _, newUrl);
1554
- };
1555
- win.history.replaceState = (stateObj, _, newUrl) => {
1556
- false !== env.$propagateHistoryChange$ && originalReplaceState(stateObj, _, newUrl);
1557
- };
2127
+ })));
2128
+ });
2129
+ }
2130
+ );
2131
+ commaSplit(
2132
+ "atob,btoa,crypto,indexedDB,setTimeout,setInterval,clearTimeout,clearInterval"
2133
+ ).map((globalName) => {
2134
+ delete WorkerWindow.prototype[globalName];
2135
+ if (!(globalName in win)) {
2136
+ value = self[globalName];
2137
+ null != value &&
2138
+ (win[globalName] =
2139
+ "function" != typeof value ||
2140
+ value.toString().startsWith("class")
2141
+ ? value
2142
+ : value.bind(self));
2143
+ }
2144
+ });
2145
+ Object.getOwnPropertyNames(self).map((globalName) => {
2146
+ globalName in win || (win[globalName] = self[globalName]);
2147
+ });
2148
+ windowMediaConstructors.map((cstrName) =>
2149
+ defineProperty(win, cstrName, {
2150
+ get() {
2151
+ initWindowMedia();
2152
+ return win[cstrName];
2153
+ },
2154
+ })
2155
+ );
2156
+ "trustedTypes" in self && (win.trustedTypes = self.trustedTypes);
2157
+ patchElement(win.Element, win.HTMLElement);
2158
+ patchDocument(win.Document, env, isDocumentImplementation);
2159
+ ((WorkerDocumentFragment) => {
2160
+ definePrototypeNodeType(WorkerDocumentFragment, 11);
2161
+ cachedTreeProps(WorkerDocumentFragment, elementStructurePropNames);
2162
+ })(win.DocumentFragment);
2163
+ patchHTMLAnchorElement(win.HTMLAnchorElement, env);
2164
+ ((WorkerHTMLFormElement) => {
2165
+ definePrototypePropertyDescriptor(WorkerHTMLFormElement, {});
2166
+ cachedProps(WorkerHTMLFormElement, "elements");
2167
+ })(win.HTMLFormElement);
2168
+ patchHTMLIFrameElement(win.HTMLIFrameElement);
2169
+ patchHTMLScriptElement(win.HTMLScriptElement, env);
2170
+ patchSvgElement(win.SVGGraphicsElement);
2171
+ patchDocumentElementChild(win.HTMLHeadElement, env);
2172
+ patchDocumentElementChild(win.HTMLBodyElement, env);
2173
+ ((WorkerHTMLHtmlElement, env) => {
2174
+ const DocumentElementDescriptorMap = {
2175
+ parentElement: {
2176
+ value: null,
2177
+ },
2178
+ parentNode: {
2179
+ get: () => env.$document$,
2180
+ },
2181
+ };
2182
+ definePrototypePropertyDescriptor(
2183
+ WorkerHTMLHtmlElement,
2184
+ DocumentElementDescriptorMap
2185
+ );
2186
+ })(win.HTMLHtmlElement, env);
2187
+ createCSSStyleSheetConstructor(win, "CSSStyleSheet");
2188
+ definePrototypeNodeType(win.Comment, 8);
2189
+ definePrototypeNodeType(win.DocumentType, 10);
2190
+ Object.assign(env, {
2191
+ $winId$: $winId$,
2192
+ $parentWinId$: $parentWinId$,
2193
+ $window$: new Proxy(win, {
2194
+ get: (win, propName) => {
2195
+ var _a;
2196
+ if ("string" != typeof propName || isNaN(propName)) {
2197
+ return (
2198
+ null === (_a = webWorkerCtx.$config$.mainWindowAccessors) ||
2199
+ void 0 === _a
2200
+ ? void 0
2201
+ : _a.includes(propName)
2202
+ )
2203
+ ? getter(this, [propName])
2204
+ : win[propName];
1558
2205
  }
1559
- win.Worker = void 0;
1560
- }
1561
- addEventListener(...args) {
1562
- "load" === args[0] ? env.$runWindowLoadEvent$ && setTimeout((() => args[1]({
1563
- type: "load"
1564
- }))) : callMethod(this, [ "addEventListener" ], args, 2);
1565
- }
1566
- get body() {
1567
- return env.$body$;
1568
- }
1569
- get document() {
1570
- return env.$document$;
1571
- }
1572
- get documentElement() {
1573
- return env.$documentElement$;
1574
- }
1575
- fetch(input, init) {
1576
- input = "string" == typeof input || input instanceof URL ? String(input) : input.url;
1577
- return fetch(resolveUrl(env, input, "fetch"), init);
1578
- }
1579
- get frames() {
1580
- return env.$window$;
1581
- }
1582
- get frameElement() {
1583
- return $isTopWindow$ ? null : getOrCreateNodeInstance($parentWinId$, $winId$, "IFRAME");
1584
- }
1585
- get globalThis() {
1586
- return env.$window$;
1587
- }
1588
- get head() {
1589
- return env.$head$;
1590
- }
1591
- get length() {
1592
- return getChildEnvs().length;
1593
- }
1594
- get location() {
1595
- return $location$;
1596
- }
1597
- set location(loc) {
1598
- $location$.href = loc + "";
1599
- }
1600
- get Image() {
1601
- return createImageConstructor(env);
1602
- }
1603
- get navigator() {
1604
- return (env => {
1605
- let key;
1606
- let nav = {
1607
- sendBeacon: (url, body) => {
1608
- if (webWorkerCtx.$config$.logSendBeaconRequests) {
1609
- try {
1610
- logWorker(`sendBeacon: ${resolveUrl(env, url, null)}${body ? ", data: " + JSON.stringify(body) : ""}`);
1611
- } catch (e) {
1612
- console.error(e);
1613
- }
1614
- }
1615
- try {
1616
- fetch(resolveUrl(env, url, null), {
1617
- method: "POST",
1618
- body: body,
1619
- mode: "no-cors",
1620
- keepalive: true
1621
- });
1622
- return true;
1623
- } catch (e) {
1624
- console.error(e);
1625
- return false;
1626
- }
1627
- }
1628
- };
1629
- for (key in navigator) {
1630
- nav[key] = navigator[key];
1631
- }
1632
- return nav;
1633
- })(env);
1634
- }
1635
- get origin() {
1636
- return $location$.origin;
1637
- }
1638
- set origin(_) {}
1639
- get parent() {
1640
- for (let envWinId in environments) {
1641
- if (environments[envWinId].$winId$ === $parentWinId$) {
1642
- return environments[envWinId].$window$;
1643
- }
2206
+ {
2207
+ let frame = getChildEnvs()[propName];
2208
+ return frame ? frame.$window$ : void 0;
1644
2209
  }
1645
- return env.$window$;
1646
- }
1647
- postMessage(...args) {
1648
- if (environments[args[0]]) {
1649
- len(postMessages) > 50 && postMessages.splice(0, 5);
1650
- postMessages.push({
1651
- $winId$: args[0],
1652
- $data$: JSON.stringify(args[1])
1653
- });
1654
- args = args.slice(1);
2210
+ },
2211
+ has: () => true,
2212
+ }),
2213
+ $document$: $createNode$("#document", $winId$ + ".d"),
2214
+ $documentElement$: $createNode$("HTML", $winId$ + ".e"),
2215
+ $head$: $createNode$("HEAD", $winId$ + ".h"),
2216
+ $body$: $createNode$("BODY", $winId$ + ".b"),
2217
+ $location$: $location$,
2218
+ $visibilityState$: $visibilityState$,
2219
+ $isSameOrigin$: $isSameOrigin$,
2220
+ $isTopWindow$: $isTopWindow$,
2221
+ $createNode$: $createNode$,
2222
+ });
2223
+ win.requestAnimationFrame = (cb) =>
2224
+ setTimeout(() => cb(performance.now()), 9);
2225
+ win.cancelAnimationFrame = (id) => clearTimeout(id);
2226
+ win.requestIdleCallback = (cb, start) => {
2227
+ start = Date.now();
2228
+ return setTimeout(
2229
+ () =>
2230
+ cb({
2231
+ didTimeout: false,
2232
+ timeRemaining: () => Math.max(0, 50 - (Date.now() - start)),
2233
+ }),
2234
+ 1
2235
+ );
2236
+ };
2237
+ win.cancelIdleCallback = (id) => clearTimeout(id);
2238
+ addStorageApi(
2239
+ win,
2240
+ "localStorage",
2241
+ webWorkerlocalStorage,
2242
+ $isSameOrigin$,
2243
+ env
2244
+ );
2245
+ addStorageApi(
2246
+ win,
2247
+ "sessionStorage",
2248
+ webWorkerSessionStorage,
2249
+ $isSameOrigin$,
2250
+ env
2251
+ );
2252
+ $isSameOrigin$ || (win.indexeddb = void 0);
2253
+ if (isIframeWindow) {
2254
+ historyState = {};
2255
+ win.history = {
2256
+ pushState(stateObj) {
2257
+ historyState = stateObj;
2258
+ },
2259
+ replaceState(stateObj) {
2260
+ historyState = stateObj;
2261
+ },
2262
+ get state() {
2263
+ return historyState;
2264
+ },
2265
+ length: 0,
2266
+ };
2267
+ win.indexeddb = void 0;
2268
+ } else {
2269
+ const originalPushState = win.history.pushState.bind(win.history);
2270
+ const originalReplaceState = win.history.replaceState.bind(
2271
+ win.history
2272
+ );
2273
+ win.history.pushState = (stateObj, _, newUrl) => {
2274
+ false !== env.$propagateHistoryChange$ &&
2275
+ originalPushState(stateObj, _, newUrl);
2276
+ };
2277
+ win.history.replaceState = (stateObj, _, newUrl) => {
2278
+ false !== env.$propagateHistoryChange$ &&
2279
+ originalReplaceState(stateObj, _, newUrl);
2280
+ };
2281
+ }
2282
+ win.Worker = void 0;
2283
+ }
2284
+ addEventListener(...args) {
2285
+ "load" === args[0]
2286
+ ? env.$runWindowLoadEvent$ &&
2287
+ setTimeout(() =>
2288
+ args[1]({
2289
+ type: "load",
2290
+ })
2291
+ )
2292
+ : callMethod(this, ["addEventListener"], args, 2);
2293
+ }
2294
+ get body() {
2295
+ return env.$body$;
2296
+ }
2297
+ get document() {
2298
+ return env.$document$;
2299
+ }
2300
+ get documentElement() {
2301
+ return env.$documentElement$;
2302
+ }
2303
+ fetch(input, init) {
2304
+ input =
2305
+ "string" == typeof input || input instanceof URL
2306
+ ? String(input)
2307
+ : input.url;
2308
+ return fetch(resolveUrl(env, input, "fetch"), init);
2309
+ }
2310
+ get frames() {
2311
+ return env.$window$;
2312
+ }
2313
+ get frameElement() {
2314
+ return $isTopWindow$
2315
+ ? null
2316
+ : getOrCreateNodeInstance($parentWinId$, $winId$, "INPUT");
2317
+ }
2318
+ get globalThis() {
2319
+ return env.$window$;
2320
+ }
2321
+ get head() {
2322
+ return env.$head$;
2323
+ }
2324
+ get length() {
2325
+ return getChildEnvs().length;
2326
+ }
2327
+ get location() {
2328
+ return $location$;
2329
+ }
2330
+ set location(loc) {
2331
+ $location$.href = loc + "";
2332
+ }
2333
+ get Image() {
2334
+ return createImageConstructor(env);
2335
+ }
2336
+ get navigator() {
2337
+ return ((env) => {
2338
+ let key;
2339
+ let nav = {
2340
+ sendBeacon: (url, body) => {
2341
+ if (webWorkerCtx.$config$.logSendBeaconRequests) {
2342
+ try {
2343
+ logWorker(
2344
+ `sendBeacon: ${resolveUrl(env, url, null)}${
2345
+ body ? ", data: " + JSON.stringify(body) : ""
2346
+ }`
2347
+ );
2348
+ } catch (e) {
2349
+ console.error(e);
2350
+ }
1655
2351
  }
1656
- callMethod(this, [ "postMessage" ], args, 3);
1657
- }
1658
- get self() {
1659
- return env.$window$;
1660
- }
1661
- get top() {
1662
- for (let envWinId in environments) {
1663
- if (environments[envWinId].$isTopWindow$) {
1664
- return environments[envWinId].$window$;
1665
- }
2352
+ try {
2353
+ fetch(resolveUrl(env, url, null), {
2354
+ method: "POST",
2355
+ body: body,
2356
+ mode: "no-cors",
2357
+ keepalive: true,
2358
+ });
2359
+ return true;
2360
+ } catch (e) {
2361
+ console.error(e);
2362
+ return false;
1666
2363
  }
1667
- return env.$window$;
1668
- }
1669
- get window() {
1670
- return env.$window$;
1671
- }
1672
- get XMLHttpRequest() {
1673
- const Xhr = XMLHttpRequest;
1674
- const str = String(Xhr);
1675
- const ExtendedXhr = defineConstructorName(class extends Xhr {
1676
- open(...args) {
1677
- args[1] = resolveUrl(env, args[1], "xhr");
1678
- super.open(...args);
1679
- }
1680
- set withCredentials(_) {}
1681
- toString() {
1682
- return str;
1683
- }
1684
- }, getConstructorName(Xhr));
1685
- ExtendedXhr.prototype.constructor.toString = () => str;
1686
- return ExtendedXhr;
1687
- }
1688
- }, "Window");
1689
- const WorkerTrapProxy = class extends WorkerBase {
1690
- constructor(winId, instanceId, applyPath, nodeName) {
1691
- super(winId, instanceId, applyPath, nodeName);
1692
- return new Proxy(this, {
1693
- get: (instance, propName) => getter(instance, [ propName ]),
1694
- set(instance, propName, propValue) {
1695
- setter(instance, [ propName ], propValue);
1696
- return true;
1697
- }
1698
- });
2364
+ },
2365
+ };
2366
+ for (key in navigator) {
2367
+ nav[key] = navigator[key];
1699
2368
  }
1700
- };
1701
- const WorkerEventTargetProxy = class extends WorkerBase {};
1702
- eventTargetMethods.map((methodName => WorkerEventTargetProxy.prototype[methodName] = function(...args) {
1703
- return callMethod(this, [ methodName ], args, 2);
1704
- }));
1705
- cachedProps(WorkerWindow, "devicePixelRatio");
1706
- cachedDimensionProps(WorkerWindow);
1707
- cachedDimensionMethods(WorkerWindow, [ "getComputedStyle" ]);
1708
- new WorkerWindow;
1709
- return env;
1710
- };
1711
- const TrapConstructors = {
1712
- DOMStringMap: 1,
1713
- NamedNodeMap: 1
1714
- };
1715
- const createEnvironment = ({$winId$: $winId$, $parentWinId$: $parentWinId$, $url$: $url$, $visibilityState$: $visibilityState$}, isIframeWindow, isDocumentImplementation) => {
1716
- if (!environments[$winId$]) {
1717
- environments[$winId$] = createWindow($winId$, $parentWinId$, $url$, $visibilityState$, isIframeWindow, isDocumentImplementation);
1718
- {
1719
- const winType = $winId$ === $parentWinId$ ? "top" : "iframe";
1720
- logWorker(`Created ${winType} window ${normalizedWinId($winId$)} environment`, $winId$);
2369
+ return nav;
2370
+ })(env);
2371
+ }
2372
+ get origin() {
2373
+ return $location$.origin;
2374
+ }
2375
+ set origin(_) {}
2376
+ get parent() {
2377
+ for (let envWinId in environments) {
2378
+ if (environments[envWinId].$winId$ === $parentWinId$) {
2379
+ return environments[envWinId].$window$;
2380
+ }
2381
+ }
2382
+ return env.$window$;
2383
+ }
2384
+ postMessage(...args) {
2385
+ if (environments[args[0]]) {
2386
+ len(postMessages) > 50 && postMessages.splice(0, 5);
2387
+ postMessages.push({
2388
+ $winId$: args[0],
2389
+ $data$: JSON.stringify(args[1]),
2390
+ });
2391
+ args = args.slice(1);
2392
+ }
2393
+ callMethod(this, ["postMessage"], args, 3);
2394
+ }
2395
+ get self() {
2396
+ return env.$window$;
2397
+ }
2398
+ get top() {
2399
+ for (let envWinId in environments) {
2400
+ if (environments[envWinId].$isTopWindow$) {
2401
+ return environments[envWinId].$window$;
1721
2402
  }
2403
+ }
2404
+ return env.$window$;
2405
+ }
2406
+ get window() {
2407
+ return env.$window$;
2408
+ }
2409
+ get XMLHttpRequest() {
2410
+ const Xhr = XMLHttpRequest;
2411
+ const str = String(Xhr);
2412
+ const ExtendedXhr = defineConstructorName(
2413
+ class extends Xhr {
2414
+ open(...args) {
2415
+ args[1] = resolveUrl(env, args[1], "xhr");
2416
+ super.open(...args);
2417
+ }
2418
+ set withCredentials(_) {}
2419
+ toString() {
2420
+ return str;
2421
+ }
2422
+ },
2423
+ getConstructorName(Xhr)
2424
+ );
2425
+ ExtendedXhr.prototype.constructor.toString = () => str;
2426
+ return ExtendedXhr;
1722
2427
  }
1723
- webWorkerCtx.$postMessage$([ 7, $winId$ ]);
1724
- return environments[$winId$];
2428
+ },
2429
+ "Window"
2430
+ );
2431
+ const WorkerTrapProxy = class extends WorkerBase {
2432
+ constructor(winId, instanceId, applyPath, nodeName) {
2433
+ super(winId, instanceId, applyPath, nodeName);
2434
+ return new Proxy(this, {
2435
+ get: (instance, propName) => getter(instance, [propName]),
2436
+ set(instance, propName, propValue) {
2437
+ setter(instance, [propName], propValue);
2438
+ return true;
2439
+ },
2440
+ });
2441
+ }
1725
2442
  };
1726
- const queuedEvents = [];
1727
- const receiveMessageFromSandboxToWorker = ev => {
1728
- const msg = ev.data;
1729
- const msgType = msg[0];
1730
- const msgValue = msg[1];
1731
- if (webWorkerCtx.$isInitialized$) {
1732
- if (7 === msgType) {
1733
- (async initScript => {
1734
- let winId = initScript.$winId$;
1735
- let instanceId = initScript.$instanceId$;
1736
- let instance = getOrCreateNodeInstance(winId, instanceId, "SCRIPT");
1737
- let scriptContent = initScript.$content$;
1738
- let scriptSrc = initScript.$url$;
1739
- let scriptOrgSrc = initScript.$orgUrl$;
1740
- let errorMsg = "";
1741
- let env = environments[winId];
1742
- let rsp;
1743
- let javascriptContentTypes = [ "text/jscript", "text/javascript", "text/x-javascript", "application/javascript", "application/x-javascript", "text/ecmascript", "text/x-ecmascript", "application/ecmascript" ];
1744
- if (scriptSrc) {
1745
- try {
1746
- scriptSrc = resolveToUrl(env, scriptSrc, "script") + "";
1747
- setInstanceStateValue(instance, 4, scriptSrc);
1748
- webWorkerCtx.$config$.logScriptExecution && logWorker(`Execute script src: ${scriptOrgSrc}`, winId);
1749
- rsp = await fetch(scriptSrc);
1750
- if (rsp.ok) {
1751
- let responseContentType = rsp.headers.get("content-type");
1752
- let shouldExecute = javascriptContentTypes.some((ct => {
1753
- var _a, _b, _c;
1754
- return null === (_c = null === (_a = null == responseContentType ? void 0 : responseContentType.toLowerCase) || void 0 === _a ? void 0 : (_b = _a.call(responseContentType)).includes) || void 0 === _c ? void 0 : _c.call(_b, ct);
1755
- }));
1756
- if (shouldExecute) {
1757
- scriptContent = await rsp.text();
1758
- env.$currentScriptId$ = instanceId;
1759
- run(env, scriptContent, scriptOrgSrc || scriptSrc);
1760
- }
1761
- runStateLoadHandlers(instance, "load");
1762
- } else {
1763
- errorMsg = rsp.statusText;
1764
- runStateLoadHandlers(instance, "error");
1765
- }
1766
- } catch (urlError) {
1767
- console.error(urlError);
1768
- errorMsg = String(urlError.stack || urlError);
1769
- runStateLoadHandlers(instance, "error");
1770
- }
1771
- } else {
1772
- scriptContent && (errorMsg = runScriptContent(env, instanceId, scriptContent, winId, errorMsg));
1773
- }
1774
- env.$currentScriptId$ = "";
1775
- webWorkerCtx.$postMessage$([ 6, winId, instanceId, errorMsg ]);
1776
- })(msgValue);
1777
- } else if (9 === msgType) {
1778
- (({$winId$: $winId$, $instanceId$: $instanceId$, $refId$: $refId$, $thisArg$: $thisArg$, $args$: $args$}) => {
1779
- if (webWorkerRefsByRefId[$refId$]) {
1780
- try {
1781
- webWorkerRefsByRefId[$refId$].apply(deserializeFromMain($winId$, $instanceId$, [], $thisArg$), deserializeFromMain($winId$, $instanceId$, [], $args$));
1782
- } catch (e) {
1783
- console.error(e);
1784
- }
1785
- }
1786
- })(msgValue);
1787
- } else if (10 === msgType) {
1788
- (({$winId$: $winId$, $forward$: $forward$, $args$: $args$}) => {
1789
- try {
1790
- let target = environments[$winId$].$window$;
1791
- let i = 0;
1792
- let l = len($forward$);
1793
- for (;i < l; i++) {
1794
- i + 1 < l ? target = target[$forward$[i]] : target[$forward$[i]].apply(target, deserializeFromMain(null, $winId$, [], $args$));
1795
- }
1796
- } catch (e) {
1797
- console.error(e);
1798
- }
1799
- })(msgValue);
1800
- } else if (5 === msgType) {
1801
- createEnvironment(msgValue);
1802
- } else if (8 === msgType) {
1803
- if (1 !== environments[msgValue].$isInitialized$) {
1804
- const winId = msgValue;
1805
- const env = environments[winId];
1806
- const winType = env.$winId$ === env.$parentWinId$ ? "top" : "iframe";
1807
- logWorker(`Initialized ${winType} window ${normalizedWinId(winId)} environment 🎉`, winId);
2443
+ const WorkerEventTargetProxy = class extends WorkerBase {};
2444
+ eventTargetMethods.map(
2445
+ (methodName) =>
2446
+ (WorkerEventTargetProxy.prototype[methodName] = function (...args) {
2447
+ return callMethod(this, [methodName], args, 2);
2448
+ })
2449
+ );
2450
+ cachedProps(WorkerWindow, "devicePixelRatio");
2451
+ cachedDimensionProps(WorkerWindow);
2452
+ cachedDimensionMethods(WorkerWindow, ["getComputedStyle"]);
2453
+ new WorkerWindow();
2454
+ return env;
2455
+ };
2456
+ const TrapConstructors = {
2457
+ DOMStringMap: 1,
2458
+ NamedNodeMap: 1,
2459
+ };
2460
+ const createEnvironment = (
2461
+ {
2462
+ $winId$: $winId$,
2463
+ $parentWinId$: $parentWinId$,
2464
+ $url$: $url$,
2465
+ $visibilityState$: $visibilityState$,
2466
+ },
2467
+ isIframeWindow,
2468
+ isDocumentImplementation
2469
+ ) => {
2470
+ if (!environments[$winId$]) {
2471
+ environments[$winId$] = createWindow(
2472
+ $winId$,
2473
+ $parentWinId$,
2474
+ $url$,
2475
+ $visibilityState$,
2476
+ isIframeWindow,
2477
+ isDocumentImplementation
2478
+ );
2479
+ {
2480
+ const winType = $winId$ === $parentWinId$ ? "top" : "input";
2481
+ logWorker(
2482
+ `Created ${winType} window ${normalizedWinId($winId$)} environment`,
2483
+ $winId$
2484
+ );
2485
+ }
2486
+ }
2487
+ webWorkerCtx.$postMessage$([7, $winId$]);
2488
+ return environments[$winId$];
2489
+ };
2490
+ const queuedEvents = [];
2491
+ const receiveMessageFromSandboxToWorker = (ev) => {
2492
+ const msg = ev.data;
2493
+ const msgType = msg[0];
2494
+ const msgValue = msg[1];
2495
+ if (webWorkerCtx.$isInitialized$) {
2496
+ if (7 === msgType) {
2497
+ (async (initScript) => {
2498
+ let winId = initScript.$winId$;
2499
+ let instanceId = initScript.$instanceId$;
2500
+ let instance = getOrCreateNodeInstance(winId, instanceId, "SCRIPT");
2501
+ let scriptContent = initScript.$content$;
2502
+ let scriptSrc = initScript.$url$;
2503
+ let scriptOrgSrc = initScript.$orgUrl$;
2504
+ let errorMsg = "";
2505
+ let env = environments[winId];
2506
+ let rsp;
2507
+ let javascriptContentTypes = [
2508
+ "text/jscript",
2509
+ "text/javascript",
2510
+ "text/x-javascript",
2511
+ "application/javascript",
2512
+ "application/x-javascript",
2513
+ "text/ecmascript",
2514
+ "text/x-ecmascript",
2515
+ "application/ecmascript",
2516
+ ];
2517
+ if (scriptSrc) {
2518
+ try {
2519
+ scriptSrc = resolveToUrl(env, scriptSrc, "script") + "";
2520
+ setInstanceStateValue(instance, 4, scriptSrc);
2521
+ webWorkerCtx.$config$.logScriptExecution &&
2522
+ logWorker(`Execute script src: ${scriptOrgSrc}`, winId);
2523
+ rsp = await fetch(scriptSrc);
2524
+ if (rsp.ok) {
2525
+ let responseContentType = rsp.headers.get("content-type");
2526
+ let shouldExecute = javascriptContentTypes.some((ct) => {
2527
+ var _a, _b, _c;
2528
+ return null ===
2529
+ (_c =
2530
+ null ===
2531
+ (_a =
2532
+ null == responseContentType
2533
+ ? void 0
2534
+ : responseContentType.toLowerCase) || void 0 === _a
2535
+ ? void 0
2536
+ : (_b = _a.call(responseContentType)).includes) ||
2537
+ void 0 === _c
2538
+ ? void 0
2539
+ : _c.call(_b, ct);
2540
+ });
2541
+ if (shouldExecute) {
2542
+ scriptContent = await rsp.text();
2543
+ env.$currentScriptId$ = instanceId;
2544
+ run(env, scriptContent, scriptOrgSrc || scriptSrc);
1808
2545
  }
1809
- environments[msgValue].$isInitialized$ = 1;
1810
- environments[msgValue].$isLoading$ = 0;
1811
- } else if (14 === msgType) {
1812
- environments[msgValue].$visibilityState$ = msg[2];
1813
- } else if (13 === msgType) {
1814
- const $winId$ = msgValue.$winId$;
1815
- const env = environments[$winId$];
1816
- env.$location$.href = msgValue.url;
1817
- !function($winId$, env, data) {
1818
- const history = env.$window$.history;
1819
- switch (data.type) {
1820
- case 0:
1821
- env.$propagateHistoryChange$ = false;
1822
- try {
1823
- history.pushState(data.state, "", data.newUrl);
1824
- } catch (e) {}
1825
- env.$propagateHistoryChange$ = true;
1826
- break;
1827
-
1828
- case 1:
1829
- env.$propagateHistoryChange$ = false;
1830
- try {
1831
- history.replaceState(data.state, "", data.newUrl);
1832
- } catch (e) {}
1833
- env.$propagateHistoryChange$ = true;
1834
- }
1835
- }(msgValue.$winId$, env, msgValue);
1836
- } else {
1837
- 15 === msgType && ((_type, winId, instanceId, callbackName, args) => {
1838
- const elm = getOrCreateNodeInstance(winId, instanceId);
1839
- elm && "function" == typeof elm[callbackName] && elm[callbackName].apply(elm, args);
1840
- })(...msg);
1841
- }
1842
- } else if (1 === msgType) {
1843
- (initWebWorkerData => {
1844
- const config = webWorkerCtx.$config$ = JSON.parse(initWebWorkerData.$config$);
1845
- const locOrigin = initWebWorkerData.$origin$;
1846
- webWorkerCtx.$importScripts$ = importScripts.bind(self);
1847
- webWorkerCtx.$interfaces$ = initWebWorkerData.$interfaces$;
1848
- webWorkerCtx.$libPath$ = initWebWorkerData.$libPath$;
1849
- webWorkerCtx.$origin$ = locOrigin;
1850
- webWorkerCtx.$postMessage$ = postMessage.bind(self);
1851
- webWorkerCtx.$sharedDataBuffer$ = initWebWorkerData.$sharedDataBuffer$;
1852
- webWorkerlocalStorage.set(locOrigin, initWebWorkerData.$localStorage$);
1853
- webWorkerSessionStorage.set(locOrigin, initWebWorkerData.$sessionStorage$);
1854
- self.importScripts = void 0;
1855
- delete self.postMessage;
1856
- delete self.WorkerGlobalScope;
1857
- commaSplit("resolveUrl,get,set,apply").map((configName => {
1858
- config[configName] && (config[configName] = new Function("return " + config[configName])());
1859
- }));
1860
- })(msgValue);
1861
- webWorkerCtx.$postMessage$([ 2 ]);
1862
- } else if (3 === msgType) {
1863
- webWorkerCtx.$interfaces$ = [ ...webWorkerCtx.$interfaces$, ...msgValue ];
1864
- webWorkerCtx.$isInitialized$ = 1;
1865
- logWorker("Initialized web worker");
1866
- webWorkerCtx.$postMessage$([ 4 ]);
1867
- queuedEvents.length && logWorker(`Queued ready messages: ${queuedEvents.length}`);
1868
- [ ...queuedEvents ].map(receiveMessageFromSandboxToWorker);
1869
- queuedEvents.length = 0;
1870
- } else {
1871
- queuedEvents.push(ev);
2546
+ runStateLoadHandlers(instance, "load");
2547
+ } else {
2548
+ errorMsg = rsp.statusText;
2549
+ runStateLoadHandlers(instance, "error");
2550
+ }
2551
+ } catch (urlError) {
2552
+ console.error(urlError);
2553
+ errorMsg = String(urlError.stack || urlError);
2554
+ runStateLoadHandlers(instance, "error");
2555
+ }
2556
+ } else {
2557
+ scriptContent &&
2558
+ (errorMsg = runScriptContent(
2559
+ env,
2560
+ instanceId,
2561
+ scriptContent,
2562
+ winId,
2563
+ errorMsg
2564
+ ));
2565
+ }
2566
+ env.$currentScriptId$ = "";
2567
+ webWorkerCtx.$postMessage$([6, winId, instanceId, errorMsg]);
2568
+ })(msgValue);
2569
+ } else if (9 === msgType) {
2570
+ (({
2571
+ $winId$: $winId$,
2572
+ $instanceId$: $instanceId$,
2573
+ $refId$: $refId$,
2574
+ $thisArg$: $thisArg$,
2575
+ $args$: $args$,
2576
+ }) => {
2577
+ if (webWorkerRefsByRefId[$refId$]) {
2578
+ try {
2579
+ webWorkerRefsByRefId[$refId$].apply(
2580
+ deserializeFromMain($winId$, $instanceId$, [], $thisArg$),
2581
+ deserializeFromMain($winId$, $instanceId$, [], $args$)
2582
+ );
2583
+ } catch (e) {
2584
+ console.error(e);
2585
+ }
2586
+ }
2587
+ })(msgValue);
2588
+ } else if (10 === msgType) {
2589
+ (({ $winId$: $winId$, $forward$: $forward$, $args$: $args$ }) => {
2590
+ try {
2591
+ let target = environments[$winId$].$window$;
2592
+ let i = 0;
2593
+ let l = len($forward$);
2594
+ for (; i < l; i++) {
2595
+ i + 1 < l
2596
+ ? (target = target[$forward$[i]])
2597
+ : target[$forward$[i]].apply(
2598
+ target,
2599
+ deserializeFromMain(null, $winId$, [], $args$)
2600
+ );
2601
+ }
2602
+ } catch (e) {
2603
+ console.error(e);
2604
+ }
2605
+ })(msgValue);
2606
+ } else if (5 === msgType) {
2607
+ createEnvironment(msgValue);
2608
+ } else if (8 === msgType) {
2609
+ if (1 !== environments[msgValue].$isInitialized$) {
2610
+ const winId = msgValue;
2611
+ const env = environments[winId];
2612
+ const winType = env.$winId$ === env.$parentWinId$ ? "top" : "input";
2613
+ logWorker(
2614
+ `Initialized ${winType} window ${normalizedWinId(
2615
+ winId
2616
+ )} environment 🎉`,
2617
+ winId
2618
+ );
1872
2619
  }
1873
- };
1874
- self.onmessage = receiveMessageFromSandboxToWorker;
1875
- postMessage([ 0 ]);
2620
+ environments[msgValue].$isInitialized$ = 1;
2621
+ environments[msgValue].$isLoading$ = 0;
2622
+ } else if (14 === msgType) {
2623
+ environments[msgValue].$visibilityState$ = msg[2];
2624
+ } else if (13 === msgType) {
2625
+ const $winId$ = msgValue.$winId$;
2626
+ const env = environments[$winId$];
2627
+ env.$location$.href = msgValue.url;
2628
+ !(function ($winId$, env, data) {
2629
+ const history = env.$window$.history;
2630
+ switch (data.type) {
2631
+ case 0:
2632
+ env.$propagateHistoryChange$ = false;
2633
+ try {
2634
+ history.pushState(data.state, "", data.newUrl);
2635
+ } catch (e) {}
2636
+ env.$propagateHistoryChange$ = true;
2637
+ break;
2638
+
2639
+ case 1:
2640
+ env.$propagateHistoryChange$ = false;
2641
+ try {
2642
+ history.replaceState(data.state, "", data.newUrl);
2643
+ } catch (e) {}
2644
+ env.$propagateHistoryChange$ = true;
2645
+ }
2646
+ })(msgValue.$winId$, env, msgValue);
2647
+ } else {
2648
+ 15 === msgType &&
2649
+ ((_type, winId, instanceId, callbackName, args) => {
2650
+ const elm = getOrCreateNodeInstance(winId, instanceId);
2651
+ elm &&
2652
+ "function" == typeof elm[callbackName] &&
2653
+ elm[callbackName].apply(elm, args);
2654
+ })(...msg);
2655
+ }
2656
+ } else if (1 === msgType) {
2657
+ ((initWebWorkerData) => {
2658
+ const config = (webWorkerCtx.$config$ = JSON.parse(
2659
+ initWebWorkerData.$config$
2660
+ ));
2661
+ const locOrigin = initWebWorkerData.$origin$;
2662
+ webWorkerCtx.$importScripts$ = importScripts.bind(self);
2663
+ webWorkerCtx.$interfaces$ = initWebWorkerData.$interfaces$;
2664
+ webWorkerCtx.$libPath$ = initWebWorkerData.$libPath$;
2665
+ webWorkerCtx.$origin$ = locOrigin;
2666
+ webWorkerCtx.$postMessage$ = postMessage.bind(self);
2667
+ webWorkerCtx.$sharedDataBuffer$ = initWebWorkerData.$sharedDataBuffer$;
2668
+ webWorkerlocalStorage.set(locOrigin, initWebWorkerData.$localStorage$);
2669
+ webWorkerSessionStorage.set(
2670
+ locOrigin,
2671
+ initWebWorkerData.$sessionStorage$
2672
+ );
2673
+ self.importScripts = void 0;
2674
+ delete self.postMessage;
2675
+ delete self.WorkerGlobalScope;
2676
+ commaSplit("resolveUrl,get,set,apply").map((configName) => {
2677
+ config[configName] &&
2678
+ (config[configName] = new Function(
2679
+ "return " + config[configName]
2680
+ )());
2681
+ });
2682
+ })(msgValue);
2683
+ webWorkerCtx.$postMessage$([2]);
2684
+ } else if (3 === msgType) {
2685
+ webWorkerCtx.$interfaces$ = [...webWorkerCtx.$interfaces$, ...msgValue];
2686
+ webWorkerCtx.$isInitialized$ = 1;
2687
+ logWorker("Initialized web worker");
2688
+ webWorkerCtx.$postMessage$([4]);
2689
+ queuedEvents.length &&
2690
+ logWorker(`Queued ready messages: ${queuedEvents.length}`);
2691
+ [...queuedEvents].map(receiveMessageFromSandboxToWorker);
2692
+ queuedEvents.length = 0;
2693
+ } else {
2694
+ queuedEvents.push(ev);
2695
+ }
2696
+ };
2697
+ self.onmessage = receiveMessageFromSandboxToWorker;
2698
+ postMessage([0]);
1876
2699
  })(self);