-
Notifications
You must be signed in to change notification settings - Fork 443
/
types.ts
769 lines (669 loc) · 20.1 KB
/
types.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
export type CreateWorker = (workerName: string) => Worker;
export type Messenger = (
receiveMessage: MessengerRequestCallback
) => Promise<MessengerHandler | null>;
export type MessengerRequestCallback = (
accessReq: MainAccessRequest,
responseCallback: MessengerResponseCallback
) => void;
export type MessengerHandler = (
worker: PartytownWebWorker,
msg: MessageFromWorkerToSandbox
) => void;
export type MessengerResponseCallback = (accessRsp: MainAccessResponse) => void;
export type WinId = string;
export type InstanceId = string;
export type RefId = string;
export interface AssignWinInstanceId {
$winId$: WinId;
}
export type AssignInstanceId = InstanceId | AssignWinInstanceId;
export type MessageFromWorkerToSandbox =
| [type: WorkerMessageType.MainDataRequestFromWorker]
| [type: WorkerMessageType.MainInterfacesRequestFromWorker]
| [type: WorkerMessageType.InitializedWebWorker]
| [
type: WorkerMessageType.InitializedEnvironmentScript,
winid: WinId,
instanceId: InstanceId,
errorMsg: string
]
| [type: WorkerMessageType.InitializeNextScript, winId: WinId]
| [type: WorkerMessageType.ForwardWorkerAccessRequest, accessReq: MainAccessRequest]
| [type: WorkerMessageType.AsyncAccessRequest, accessReq: MainAccessRequest];
export type MessageFromSandboxToWorker =
| [type: WorkerMessageType.MainDataResponseToWorker, initWebWorkerData: InitWebWorkerData]
| [type: WorkerMessageType.MainInterfacesResponseToWorker, interfaces: InterfaceInfo[]]
| [type: WorkerMessageType.InitializeEnvironment, initEnvData: InitializeEnvironmentData]
| [type: WorkerMessageType.InitializeNextScript, initScriptData: InitializeScriptData]
| [type: WorkerMessageType.InitializedScripts, winId: WinId]
| [type: WorkerMessageType.RefHandlerCallback, callbackData: RefHandlerCallbackData]
| [type: WorkerMessageType.ForwardMainTrigger, triggerData: ForwardMainTriggerData]
| [type: WorkerMessageType.LocationUpdate, locationChangeData: LocationUpdateData]
| [type: WorkerMessageType.DocumentVisibilityState, winId: WinId, visibilityState: string]
| [
type: WorkerMessageType.CustomElementCallback,
winId: WinId,
instanceId: InstanceId,
callbackName: string,
args: any[]
];
export const enum WorkerMessageType {
MainDataRequestFromWorker,
MainDataResponseToWorker,
MainInterfacesRequestFromWorker,
MainInterfacesResponseToWorker,
InitializedWebWorker,
InitializeEnvironment,
InitializedEnvironmentScript,
InitializeNextScript,
InitializedScripts,
RefHandlerCallback,
ForwardMainTrigger,
ForwardWorkerAccessRequest,
AsyncAccessRequest,
LocationUpdate,
DocumentVisibilityState,
CustomElementCallback,
}
export const enum LocationUpdateType {
PushState,
ReplaceState,
PopState,
HashChange,
}
export interface LocationUpdateData {
$winId$: WinId;
type: LocationUpdateType;
state: object;
url: string;
newUrl?: string;
oldUrl?: string;
}
export interface ForwardMainTriggerData {
$winId$: WinId;
$forward$: string[];
$args$: SerializedTransfer | undefined;
}
export interface RefHandlerCallbackData {
$winId$: WinId;
$instanceId$: InstanceId;
$refId$: RefId;
$thisArg$: SerializedTransfer | undefined;
$args$: SerializedTransfer | undefined;
}
export type PostMessageToWorker = (msg: MessageFromSandboxToWorker) => void;
export interface MainWindowContext {
$winId$: WinId;
$isInitialized$?: number;
$startTime$?: number;
$window$: MainWindow;
}
export interface PartytownWebWorker extends Worker {
postMessage: PostMessageToWorker;
}
export interface InitWebWorkerData {
$config$: string;
$interfaces$: InterfaceInfo[];
$libPath$: string;
$sharedDataBuffer$?: SharedArrayBuffer;
$origin$: string;
$tabId$?: number;
}
/**
* [0] Constructor name
* [1] Prototype parent constructor name
* [2] InterfaceMember[]
* [3]? InterfaceType
* [4]? Node Name
*/
export type InterfaceInfo =
| [string, string, InterfaceMember[], InterfaceType, string]
| [string, string, InterfaceMember[], InterfaceType]
| [string, string, InterfaceMember[]];
/**
* [0] Member name
* [1] Constructor name or interface type
* [2]? If there's a value it's a static prop
*/
export type InterfaceMember =
| [string, string]
| [string, InterfaceType.Function]
| [string, InterfaceType.Property]
| [string, InterfaceType.Property, string | number | boolean];
export interface WebWorkerContext {
$asyncMsgTimer$?: any;
$config$: PartytownInternalConfig;
$importScripts$: (...urls: string[]) => void;
$initWindowMedia$?: InitWindowMedia;
$interfaces$: InterfaceInfo[];
$indexedDB$: any;
$isInitialized$?: number;
$libPath$: string;
$origin$: string;
$postMessage$: (msg: MessageFromWorkerToSandbox, arr?: any[]) => void;
$sharedDataBuffer$?: SharedArrayBuffer;
lastLog?: string;
$tabId$?: number;
}
export interface InitializeEnvironmentData {
$winId$: WinId;
$parentWinId$: WinId;
$url$: string;
$visibilityState$?: string;
}
export interface WebWorkerEnvironment {
$winId$: WinId;
$parentWinId$: WinId;
$window$: Window;
$document$: Document;
$documentElement$: HTMLElement;
$head$: HTMLElement;
$body$: HTMLElement;
$location$: Location;
$visibilityState$?: string;
$createNode$: (
nodeName: string,
instanceId: InstanceId,
namespace?: string,
prevInstance?: WorkerNode
) => WorkerNode;
$currentScriptId$?: InstanceId;
$isInitialized$?: number;
$isLoading$?: number;
$runWindowLoadEvent$?: number;
$isSameOrigin$?: boolean;
$isTopWindow$?: boolean;
$propagateHistoryChange$?: boolean;
}
export interface MembersInterfaceTypeInfo {
[memberName: string]: InterfaceType;
}
export const enum InterfaceType {
// NodeType 0 not used, so using for Window interface
Window = 0,
// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
Element = 1,
AttributeNode = 2,
TextNode = 3,
CDataSectionNode = 4,
// NodeType 5 and 6 not used in the standards
Function = 5,
Property = 6,
ProcessingInstructionNode = 7,
CommentNode = 8,
Document = 9,
DocumentTypeNode = 10,
DocumentFragmentNode = 11,
// Global Constructors and window function implementations
EnvGlobalConstructor = 12,
}
export const enum WinDocId {
document = 'd',
documentElement = 'e',
head = 'h',
body = 'b',
}
export interface InitializeScriptData {
$winId$: WinId;
$instanceId$: InstanceId;
$content$?: string;
$url$?: string;
$orgUrl$?: string;
}
export interface MainAccessRequest {
$msgId$: string;
$tasks$: MainAccessTask[];
}
export interface MainAccessTask {
$winId$: WinId;
$instanceId$: InstanceId;
$applyPath$: ApplyPath;
$groupedGetters$?: string[];
$assignInstanceId$?: AssignInstanceId;
$debug$?: string;
}
export interface MainAccessResponse {
$msgId$: string;
$error$?: string;
$rtnValue$?: SerializedTransfer;
$isPromise$?: any;
}
export const enum ApplyPathType {
SetValue,
GlobalConstructor,
}
export type ApplyPath = any[];
export const enum SerializedType {
Primitive,
Array,
Object,
Instance,
Ref,
Event,
Function,
NodeList,
ArrayBuffer,
ArrayBufferView,
Attr,
CSSRule,
CSSRuleList,
CSSStyleDeclaration,
Error,
}
export type SerializedArrayTransfer = [SerializedType.Array, (SerializedTransfer | undefined)[]];
export type SerializedArrayBufferTransfer = [SerializedType.ArrayBuffer, any];
export type SerializedArrayBufferViewTransfer = [SerializedType.ArrayBufferView, any, string];
export type SerializedAttrTransfer = [SerializedType.Attr, SerializedAttr];
export type SerializedCSSRuleTransfer = [SerializedType.CSSRule, SerializedCSSRule];
export type SerializedCSSRuleListTransfer = [SerializedType.CSSRuleList, SerializedCSSRule[]];
export type SerializedCSSStyleDeclarationTransfer = [
SerializedType.CSSStyleDeclaration,
{ [key: string]: SerializedTransfer | undefined }
];
export type SerializedErrorTransfer = [SerializedType.Error, Error];
export type SerializedEventTransfer = [SerializedType.Event, SerializedObject];
export type SerializedFunctionTransfer = [SerializedType.Function];
export type SerializedInstanceTransfer = [SerializedType.Instance, SerializedInstance];
export type SerializedNodeListTransfer = [
SerializedType.NodeList,
(SerializedTransfer | undefined)[]
];
export type SerializedObjectTransfer = [
SerializedType.Object,
{ [key: string]: SerializedTransfer | undefined }
];
export type SerializedAttr = [string, string];
export type SerializedCSSRule = { [key: string]: string };
export type SerializedPrimitiveTransfer =
| [SerializedType.Primitive, string | number | boolean | null | undefined]
| [SerializedType.Primitive];
export type SerializedRefTransfer = [SerializedType.Ref, SerializedRefTransferData];
export interface SerializedRefTransferData {
$winId$: WinId;
$instanceId$: InstanceId;
$refId$: RefId;
$nodeName$?: string;
}
export type SerializedTransfer =
| SerializedArrayTransfer
| SerializedArrayBufferTransfer
| SerializedArrayBufferViewTransfer
| SerializedAttrTransfer
| SerializedCSSRuleTransfer
| SerializedCSSRuleListTransfer
| SerializedCSSStyleDeclarationTransfer
| SerializedEventTransfer
| SerializedFunctionTransfer
| SerializedInstanceTransfer
| SerializedNodeListTransfer
| SerializedObjectTransfer
| SerializedPrimitiveTransfer
| SerializedRefTransfer
| SerializedErrorTransfer
| [];
export interface SerializedObject {
[key: string]: SerializedTransfer | undefined;
}
export type SerializedInstance =
| [type: WinId, type: InstanceId]
| [
type: WinId,
type: InstanceId,
/**
* Node name for Node instances
*/
type: string,
type?: string
];
/**
* @public
*/
export type ResolveUrlType = 'fetch' | 'xhr' | 'script' | 'iframe' | 'image';
/**
* @public
*/
export type SendBeaconParameters = Pick<
RequestInit,
'keepalive' | 'mode' | 'headers' | 'signal' | 'cache'
>;
/**
* https://partytown.qwik.dev/configuration
*
* @public
*/
export interface PartytownConfig {
/**
* The `resolveUrl()` hook can be used to modify the URL about to be
* requested, which could be used to rewrite urls so they go through a proxy.
*
* https://partytown.qwik.dev/proxying-requests
*
* @param url - The URL to be resolved. This is a URL https://developer.mozilla.org/en-US/docs/Web/API/URL, not a string.
* @param location - The current window location.
* @param type - The type of resource the url is being resolved for. For example, `fetch` is the value when resolving for `fetch()`, and `a` would be the value when resolving for an anchor element's `href`.
* @returns The returned value must be a URL interface, otherwise the default resolved URL is used.
*/
resolveUrl?(url: URL, location: Location, type: ResolveUrlType): URL | undefined | null;
/**
* The `resolveSendBeaconRequestParameters()` hook can be used to modify the RequestInit parameters
* being used by the fetch request that polyfills the navigator.sendBeacon API in the worker context.
*
* @param url - The URL to be resolved. This is a URL https://developer.mozilla.org/en-US/docs/Web/API/URL, not a string.
* @param location - The current window location.
* @returns The returned value must be a SendBeaconParameters interface, otherwise the default parameters are used.
*/
resolveSendBeaconRequestParameters?(
url: URL,
location: Location
): SendBeaconParameters | undefined | null;
/**
* When set to `true`, Partytown scripts are not inlined and not minified.
*
* https://partytown.qwik.dev/debugging
*/
debug?: boolean;
/**
* Many third-party scripts provide a global variable which user code calls
* in order to send data to the service. For example, Google Tag Manager uses
* a [Data Layer](https://developers.google.com/tag-manager/devguide) array,
* and by pushing data to the array, the data is then sent on to GTM. Because
* we're moving third-party scripts to a web worker, the main thread needs to
* know which variables to patch first, and when Partytown loads, it can then
* forward the event data on to the service.
*
* Below is an example of Google Tag Manager and Facebook Pixel:
*
* ```js
* ['dataLayer.push', 'fbq']
* ```
*
* https://partytown.qwik.dev/forwarding-events
*/
forward?: PartytownForwardProperty[];
/**
* Timeout in ms before the initialization considered failed and the fallback solution is executed
* Default: 9999
*/
fallbackTimeout?: number;
/**
* The css selector where the sandbox should be placed.
* Default: body
*/
sandboxParent?: string;
mainWindowAccessors?: string[];
/**
* Rarely, a script will add a named function to the global scope with the
* intent that other scripts can call the named function (like Adobe Launch).
* Due to how Partytown scopes each script, these named functions do not get
* added to `window`. The `globalFns` config can be used to manually ensure
* each function is added to the global scope. Consider this an escape hatch
* when a third-party script rudely pollutes `window` with functions.
*/
globalFns?: string[];
/**
* This array can be used to filter which script are executed via
* Partytown and which you would like to execute on the main thread.
*
* @example loadScriptsOnMainThread:['https://test.com/analytics.js', 'inline-script-id', /regex-matched-script\.js/]
* // Loads the `https://test.com/analytics.js` script on the main thread
*/
loadScriptsOnMainThread?: (string | RegExp)[];
get?: GetHook;
set?: SetHook;
apply?: ApplyHook;
/**
* When set to true, the Partytown Web Worker will respect the `withCredentials` option of XMLHttpRequests.
* Default: false
*/
allowXhrCredentials?: boolean;
/**
* An absolute path to the root directory which Partytown library files
* can be found. The library path must start and end with a `/`.
* By default the files will load from the server's `/~partytown/` directory.
* Note that the library path must be on the same origin as the html document,
* and is also used as the `scope` of the Partytown service worker.
*/
lib?: string;
/**
* Log method calls (debug mode required)
*/
logCalls?: boolean;
/**
* Log getter calls (debug mode required)
*/
logGetters?: boolean;
/**
* Log setter calls (debug mode required)
*/
logSetters?: boolean;
/**
* Log Image() src requests (debug mode required)
*/
logImageRequests?: boolean;
/**
* Log calls to main access, which also shows how many tasks were sent per message (debug mode required)
*/
logMainAccess?: boolean;
/**
* Log script executions (debug mode required)
*/
logScriptExecution?: boolean;
/**
* Log navigator.sendBeacon() requests (debug mode required)
*/
logSendBeaconRequests?: boolean;
/**
* Log stack traces (debug mode required)
*/
logStackTraces?: boolean;
/**
* Path to the service worker file. Defaults to `partytown-sw.js`.
*/
swPath?: string;
/**
* The nonce property may be set on script elements created by Partytown.
* This should be set only when dealing with content security policies
* and when the use of `unsafe-inline` is disabled (using `nonce-*` instead).
*
* Given the following example:
* ```html
* <head>
* <script nonce="THIS_SHOULD_BE_REPLACED">
* partytown = {
* nonce: 'THIS_SHOULD_BE_REPLACED'
* };
* </script>
* </head>
* ```
*
* The `nonce` property should be generated by the server, and it should be unique
* for each request. You can leave a placeholder, as shown in the above example,
* to facilitate replacement through a regular expression on the server side.
* For instance, you can use the following code:
*
* ```js
* html.replace(/THIS_SHOULD_BE_REPLACED/g, nonce);
* ```
*/
nonce?: string;
}
export type PartytownInternalConfig = Omit<PartytownConfig, 'loadScriptsOnMainThread'> & {
loadScriptsOnMainThread?: ['regexp' | 'string', string][];
};
/**
* @public
*/
export type PartytownForwardPropertySettings = {
preserveBehavior?: boolean;
};
/**
* @public
*/
export type PartytownForwardPropertyWithSettings = [string, PartytownForwardPropertySettings?];
/**
* A forward property to patch on `window`. The forward config property is an string,
* representing the call to forward, such as `dataLayer.push` or `fbq`.
*
* https://partytown.qwik.dev/forwarding-events
*
* @public
*/
export type PartytownForwardProperty = string | PartytownForwardPropertyWithSettings;
/**
* @public
*/
export type GetHook = (opts: GetHookOptions) => any;
/**
* @public
*/
export type SetHook = (opts: SetHookOptions) => any;
/**
* @public
*/
export type ApplyHook = (opts: ApplyHookOptions) => any;
export interface HookOptions {
name: string;
continue: Symbol;
nodeName: string | undefined;
constructor: string | undefined;
instance: WorkerInstance;
window: Window;
}
/**
* @public
*/
export interface GetHookOptions extends HookOptions {}
/**
* @public
*/
export interface SetHookOptions extends HookOptions {
value: any;
prevent: Symbol;
}
/**
* @public
*/
export interface ApplyHookOptions extends HookOptions {
args: any[];
}
export type StringIndexable = {
[key: string]: any;
};
export interface MainWindow extends Window, StringIndexable {
partytown?: PartytownConfig;
_ptf?: any[];
_pttab?: number;
}
export const enum NodeName {
Body = 'BODY',
Comment = '#comment',
Document = '#document',
/**
* <html>
*/
DocumentElement = 'HTML',
/**
* <!DOCTYPE html>
*/
DocumentTypeNode = 'html',
DocumentFragment = '#document-fragment',
IFrame = 'IFRAME',
Head = 'HEAD',
Script = 'SCRIPT',
Text = '#text',
}
export const enum StateProp {
errorHandlers = 'error',
loadHandlers = 'load',
src = 0,
loadErrorStatus = 1,
cssRules = 2,
innerHTML = 3,
url = 4,
type = 5,
}
export type EventHandler = (ev: any) => void;
export type RefHandler = (...args: any[]) => void;
export type StateMap = Record<number, StateRecord>;
export type StateRecord = Record<string | number, any>;
export const enum CallType {
Blocking = 1,
NonBlocking = 2,
NonBlockingNoSideEffect = 3,
}
export type Getter = (instance: any, applyPath: ApplyPath, groupedGetters?: string[]) => any;
export type Setter = (instance: any, applyPath: ApplyPath, value: any) => void;
export type CallMethod = (
instance: any,
applyPath: ApplyPath,
args: any[],
callType?: CallType,
assignInstanceId?: AssignInstanceId,
buffer?: ArrayBuffer | ArrayBufferView
) => any;
export type ConstructGlobal = (instance: any, cstrName: string, args: any[]) => void;
export type DefinePrototypePropertyDescriptor = (Cstr: any, propertyDescriptorMap: any) => void;
export type RandomId = () => string;
import type {
ApplyPathKey,
InstanceDataKey,
InstanceIdKey,
InstanceStateKey,
NamespaceKey,
WinIdKey,
} from './web-worker/worker-constants';
export type LazyBridge = [
Getter,
Setter,
CallMethod,
ConstructGlobal,
DefinePrototypePropertyDescriptor,
RandomId,
typeof WinIdKey,
typeof InstanceIdKey,
typeof ApplyPathKey
];
export type InitWindowMedia = (
WorkerBase: WorkerConstructor,
WorkerEventTargetProxy: WorkerConstructor,
env: WebWorkerEnvironment,
win: WorkerWindow,
windowMediaConstructors: string[]
) => any;
export interface MediaSelf {
$bridgeToMedia$?: LazyBridge;
$bridgeFromMedia$?: InitWindowMedia;
}
export interface PostMessageData {
$winId$: WinId;
$data$: string;
}
export interface WorkerConstructor {
new (
winId?: WinId,
instanceId?: InstanceId,
applyPath?: ApplyPath,
instanceData?: any,
namespace?: string
): WorkerInstance;
}
export interface WorkerInstance {
[WinIdKey]: WinId;
[InstanceIdKey]: InstanceId;
[ApplyPathKey]: string[];
[InstanceDataKey]: string | undefined;
[NamespaceKey]: string | undefined;
[InstanceStateKey]: { [key: string]: any };
}
export interface WorkerNode extends WorkerInstance, Node {
id?: string | undefined | null;
type: string | undefined;
}
export interface WorkerWindow extends WorkerInstance {
[key: string]: any;
}
export interface WorkerNodeConstructors {
[tagName: string]: WorkerConstructor;
}
export type CustomElementData = [cstrName: string, observedAttributes: string[]];