Skip to content

Commit e85af98

Browse files
committed
feat: improve id assignment
1 parent 5619089 commit e85af98

31 files changed

+228
-190
lines changed

src/lib/log.ts

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
import { ApplyPath, CallType, InterfaceType, NodeName, PlatformInstanceId } from './types';
1+
import {
2+
ApplyPath,
3+
CallType,
4+
InstanceId,
5+
InterfaceType,
6+
NodeName,
7+
PlatformInstanceId,
8+
WinId,
9+
} from './types';
210
import {
311
ApplyPathKey,
412
InstanceDataKey,
@@ -18,7 +26,7 @@ export const logMain = (msg: string) => {
1826
}
1927
};
2028

21-
export const logWorker = (msg: string, winId = -1) => {
29+
export const logWorker = (msg: string, winId?: WinId) => {
2230
if (debug) {
2331
try {
2432
const config = webWorkerCtx.$config$;
@@ -31,7 +39,7 @@ export const logWorker = (msg: string, winId = -1) => {
3139

3240
let prefix: string;
3341
let color: string;
34-
if (winId > -1) {
42+
if (winId) {
3543
prefix = `Worker (${normalizedWinId(winId)}) 🎉`;
3644
color = winColor(winId);
3745
} else {
@@ -51,15 +59,15 @@ export const logWorker = (msg: string, winId = -1) => {
5159
}
5260
};
5361

54-
const winIds: number[] = [];
55-
export const normalizedWinId = (winId: number) => {
62+
const winIds: WinId[] = [];
63+
export const normalizedWinId = (winId: WinId) => {
5664
if (!winIds.includes(winId)) {
5765
winIds.push(winId);
5866
}
5967
return winIds.indexOf(winId) + 1;
6068
};
6169

62-
const winColor = (winId: number) => {
70+
const winColor = (winId: WinId) => {
6371
const colors = ['#00309e', '#ea3655', '#eea727'];
6472
const index = normalizedWinId(winId) - 1;
6573
return colors[index] || colors[colors.length - 1];
@@ -212,8 +220,8 @@ const getLogValue = (applyPath: ApplyPath, v: any): string => {
212220
return `[${v.map(getLogValue).join(', ')}]`;
213221
}
214222
if (type === 'object') {
215-
const instanceId: number = v[InstanceIdKey];
216-
if (typeof instanceId === 'number') {
223+
const instanceId: InstanceId = v[InstanceIdKey];
224+
if (typeof instanceId === 'string') {
217225
if (instanceId === PlatformInstanceId.body) {
218226
return `<body>`;
219227
}

src/lib/main/snippet-entry.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
import { snippet } from './snippet';
22

3-
snippet(window as any, document, navigator, top!, top!.crossOriginIsolated);
3+
snippet(window as any, document, navigator, top!, window!.crossOriginIsolated);

src/lib/main/snippet.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
1-
import { debug, PT_IFRAME_APPENDED, PT_INITIALIZED_EVENT, SCRIPT_TYPE } from '../utils';
1+
import { debug } from '../utils';
22
import type { MainWindow, PartytownConfig } from '../types';
3-
import { VERSION } from '../build-modules/version';
43

54
export function snippet(
65
win: MainWindow,
@@ -30,15 +29,15 @@ export function snippet(
3029

3130
if (libPath[0] == '/') {
3231
// grab all the partytown scripts
33-
scripts = doc.querySelectorAll(`script[type="${SCRIPT_TYPE}"]`);
32+
scripts = doc.querySelectorAll('script[type="text/partytown"]');
3433

3534
if (top != win) {
3635
// this is an iframe
37-
top!.dispatchEvent(new CustomEvent(PT_IFRAME_APPENDED, { detail: win }));
36+
top!.dispatchEvent(new CustomEvent('pt1', { detail: win }));
3837
} else if (scripts!.length) {
3938
// set a timeout to fire if PT hasn't initialized in Xms
4039
timeout = setTimeout(fallback, 10000);
41-
doc.addEventListener(PT_INITIALIZED_EVENT, clearFallback);
40+
doc.addEventListener('pt0', clearFallback);
4241

4342
if (useAtomics) {
4443
// atomics support
@@ -84,7 +83,7 @@ export function snippet(
8483
sandbox.src =
8584
libPath +
8685
'partytown-' +
87-
(isAtomics ? 'atomics.js?v=' + VERSION : 'sandbox-sw.html?' + Date.now());
86+
(isAtomics ? 'atomics.js?v=_VERSION_' : 'sandbox-sw.html?' + Date.now());
8887
doc.body.appendChild(sandbox);
8988
}
9089

src/lib/sandbox/index.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { debug, PT_IFRAME_APPENDED } from '../utils';
1+
import { debug } from '../utils';
22
import { getAndSetInstanceId } from './main-instances';
33
import { libPath, mainWindow } from './main-globals';
44
import { logMain } from '../log';
@@ -49,8 +49,8 @@ syncCreateMessenger(receiveMessage).then((onMessageHandler) => {
4949
worker.onerror = (ev) => console.error(`Web Worker Error`, ev);
5050
}
5151

52-
mainWindow.addEventListener<any>(PT_IFRAME_APPENDED, (ev: CustomEvent) =>
53-
registerWindow(worker, getAndSetInstanceId(ev.detail.frameElement), ev.detail)
52+
mainWindow.addEventListener<any>('pt1', (ev: CustomEvent) =>
53+
registerWindow(worker, getAndSetInstanceId(ev.detail.frameElement)!, ev.detail)
5454
);
5555
}
5656
});

src/lib/sandbox/main-access-handler.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
MainAccessResponse,
66
MainAccessTask,
77
PartytownWebWorker,
8+
WinId,
89
} from '../types';
910
import { debug, isPromise, len } from '../utils';
1011
import { deserializeFromWorker, serializeForWorker } from './main-serialization';
@@ -22,7 +23,7 @@ export const mainAccessHandler = async (
2223
let totalTasks = len(accessReq.$tasks$);
2324
let i = 0;
2425
let task: MainAccessTask;
25-
let winId: number;
26+
let winId: WinId;
2627
let applyPath: ApplyPath;
2728
let instance: any;
2829
let rtnValue: any;
@@ -78,7 +79,7 @@ export const mainAccessHandler = async (
7879
if (debug) {
7980
accessRsp.$error$ = `Error finding instance "${
8081
task.$instanceId$
81-
}" on window ${normalizedWinId(winId)} (${winId})`;
82+
}" on window ${normalizedWinId(winId)}`;
8283
console.error(accessRsp.$error$, task);
8384
} else {
8485
accessRsp.$error$ = task.$instanceId$ + ' not found';

src/lib/sandbox/main-constants.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import type { MainWindow, MainWindowContext, WinId } from '../types';
1+
import type { InstanceId, MainWindow, MainWindowContext, WinId } from '../types';
22

33
export const InstanceIdKey = /*#__PURE__*/ Symbol();
44
export const CreatedKey = /*#__PURE__*/ Symbol();
5-
export const instances = /*#__PURE__*/ new Map<number, any>();
6-
export const mainRefs = /*#__PURE__*/ new Map<number, Function>();
5+
export const instances = /*#__PURE__*/ new Map<InstanceId, any>();
6+
export const mainRefs = /*#__PURE__*/ new Map<InstanceId, Function>();
77
export const winCtxs: { [winId: WinId]: MainWindowContext | undefined } = {};
8-
export const windowIds = /*#__PURE__*/ new WeakMap<MainWindow, number>();
8+
export const windowIds = /*#__PURE__*/ new WeakMap<MainWindow, WinId>();

src/lib/sandbox/main-forward-trigger.ts

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,8 @@
11
import { len } from '../utils';
2-
import { MainWindow, PartytownWebWorker, WorkerMessageType } from '../types';
2+
import { MainWindow, PartytownWebWorker, WinId, WorkerMessageType } from '../types';
33
import { serializeForWorker } from './main-serialization';
44

5-
export const mainForwardTrigger = (
6-
worker: PartytownWebWorker,
7-
$winId$: number,
8-
win: MainWindow
9-
) => {
5+
export const mainForwardTrigger = (worker: PartytownWebWorker, $winId$: WinId, win: MainWindow) => {
106
let queuedForwardCalls = win._ptf;
117
let forwards = (win.partytown || {}).forward || [];
128
let i: number;

src/lib/sandbox/main-instances.ts

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
11
import { CreatedKey, InstanceIdKey, instances, winCtxs } from './main-constants';
2-
import { MainWindow, MainWindowContext, NodeName, PlatformInstanceId } from '../types';
2+
import {
3+
InstanceId,
4+
MainWindow,
5+
MainWindowContext,
6+
NodeName,
7+
PlatformInstanceId,
8+
WinId,
9+
} from '../types';
310
import { randomId } from '../utils';
411

5-
export const getAndSetInstanceId = (instance: any, instanceId?: number, nodeName?: string) => {
12+
export const getAndSetInstanceId = (instance: any, instanceId?: InstanceId, nodeName?: string) => {
613
if (instance) {
714
if (instance === (instance as any).window) {
815
return PlatformInstanceId.window;
@@ -21,17 +28,16 @@ export const getAndSetInstanceId = (instance: any, instanceId?: number, nodeName
2128
return PlatformInstanceId.body;
2229
}
2330

24-
if (typeof (instanceId = instance[InstanceIdKey]) !== 'number') {
31+
if (!(instanceId = instance[InstanceIdKey])) {
2532
setInstanceId(instance, (instanceId = randomId()));
2633
}
2734
return instanceId;
2835
}
29-
return -1;
3036
};
3137

3238
export const getInstance = <T = any>(
33-
winId: number,
34-
instanceId: number,
39+
winId: WinId,
40+
instanceId: InstanceId,
3541
winCtx?: MainWindowContext,
3642
win?: MainWindow,
3743
doc?: Document
@@ -61,7 +67,7 @@ export const getInstance = <T = any>(
6167
}
6268
};
6369

64-
export const setInstanceId = (instance: any, instanceId: number, now?: number) => {
70+
export const setInstanceId = (instance: any, instanceId: InstanceId, now?: number) => {
6571
if (instance) {
6672
instances.set(instanceId, instance);
6773
instance[InstanceIdKey] = instanceId;

src/lib/sandbox/main-register-window.ts

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,11 @@
11
import { debug } from '../utils';
2-
import {
3-
InitializeEnvironmentData,
4-
MainWindow,
5-
PartytownWebWorker,
6-
WorkerMessageType,
7-
} from '../types';
82
import { logMain, normalizedWinId } from '../log';
3+
import { MainWindow, PartytownWebWorker, WinId, WorkerMessageType } from '../types';
94
import { winCtxs, windowIds } from './main-constants';
105

116
export const registerWindow = (
127
worker: PartytownWebWorker,
13-
$winId$: number,
8+
$winId$: WinId,
149
$window$: MainWindow
1510
) => {
1611
if (!windowIds.has($window$)) {
@@ -62,7 +57,7 @@ export const registerWindow = (
6257

6358
if (debug) {
6459
const winType = $winId$ === $parentWinId$ ? 'top' : 'iframe';
65-
logMain(`Registered ${winType} window ${normalizedWinId($winId$)} (${$winId$})`);
60+
logMain(`Registered ${winType} window ${normalizedWinId($winId$)}`);
6661
}
6762

6863
if (doc.readyState === 'complete') {

src/lib/sandbox/main-serialization.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,12 @@ import {
1010
SerializedRefTransferData,
1111
SerializedTransfer,
1212
SerializedType,
13+
WinId,
1314
WorkerMessageType,
1415
} from '../types';
1516

1617
export const serializeForWorker = (
17-
$winId$: number,
18+
$winId$: WinId,
1819
value: any,
1920
added?: Set<any>,
2021
type?: string,
@@ -71,7 +72,7 @@ export const serializeForWorker = (
7172
SerializedType.Instance,
7273
{
7374
$winId$,
74-
$instanceId$: getAndSetInstanceId(value),
75+
$instanceId$: getAndSetInstanceId(value)!,
7576
$nodeName$: value.nodeName,
7677
},
7778
];
@@ -87,7 +88,7 @@ export const serializeForWorker = (
8788
};
8889

8990
const serializeObjectForWorker = (
90-
winId: number,
91+
winId: WinId,
9192
obj: any,
9293
added: Set<any>,
9394
includeFunctions?: boolean,

src/lib/sandbox/read-main-platform.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ export const readMainPlatform = () => {
9292
$config$,
9393
$libPath$: new URL(libPath, mainWindow.location as any) + '',
9494
$interfaces$,
95+
$origin$: origin,
9596
$localStorage$: readStorage('localStorage'),
9697
$sessionStorage$: readStorage('sessionStorage'),
9798
};

src/lib/sandbox/read-main-scripts.ts

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
import { debug, PT_INITIALIZED_EVENT, SCRIPT_TYPE, SCRIPT_TYPE_EXEC } from '../utils';
1+
import { debug, SCRIPT_TYPE, SCRIPT_TYPE_EXEC } from '../utils';
22
import { getAndSetInstanceId } from './main-instances';
33
import {
44
InitializeScriptData,
5+
InstanceId,
56
MainWindowContext,
67
PartytownWebWorker,
78
WorkerMessageType,
@@ -16,7 +17,7 @@ export const readNextScript = (worker: PartytownWebWorker, winCtx: MainWindowCon
1617
let scriptSelector = `script[type="${SCRIPT_TYPE}"]:not([data-ptid]):not([data-pterror])`;
1718
let blockingScriptSelector = scriptSelector + `:not([async]):not([defer])`;
1819
let scriptElm: HTMLScriptElement | null;
19-
let $instanceId$: number;
20+
let $instanceId$: InstanceId;
2021
let scriptData: InitializeScriptData;
2122

2223
if (doc && doc.body) {
@@ -57,7 +58,7 @@ export const readNextScript = (worker: PartytownWebWorker, winCtx: MainWindowCon
5758

5859
mainForwardTrigger(worker, $winId$, win);
5960

60-
doc.dispatchEvent(new CustomEvent(PT_INITIALIZED_EVENT));
61+
doc.dispatchEvent(new CustomEvent('pt0'));
6162

6263
if (debug) {
6364
const winType = win === win.top ? 'top' : 'iframe';
@@ -80,18 +81,21 @@ export const readNextScript = (worker: PartytownWebWorker, winCtx: MainWindowCon
8081
export const initializedWorkerScript = (
8182
worker: PartytownWebWorker,
8283
winCtx: MainWindowContext,
83-
instanceId: number,
84+
instanceId: InstanceId,
8485
errorMsg: string,
85-
script?: HTMLScriptElement | null
86+
scriptElm?: HTMLScriptElement | null
8687
) => {
87-
script = winCtx.$window$.document.querySelector<HTMLScriptElement>(`[data-ptid="${instanceId}"]`);
88+
scriptElm = winCtx.$window$.document.querySelector<HTMLScriptElement>(
89+
`[data-ptid="${instanceId}"]`
90+
);
8891

89-
if (script) {
92+
if (scriptElm) {
9093
if (errorMsg) {
91-
script.dataset.pterror = errorMsg;
94+
scriptElm.dataset.pterror = errorMsg;
9295
} else {
93-
script.type += SCRIPT_TYPE_EXEC;
96+
scriptElm.type += SCRIPT_TYPE_EXEC;
9497
}
98+
delete scriptElm.dataset.ptid;
9599
}
96100

97101
readNextScript(worker, winCtx);

src/lib/service-worker/fetch.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export const onFetchServiceWorkerRequest = (ev: FetchEvent) => {
2020
}
2121
};
2222

23-
const resolves = new Map<number, MessageResolve>();
23+
const resolves = new Map<string, MessageResolve>();
2424

2525
export const receiveMessageFromSandboxToServiceWorker = (ev: ExtendableMessageEvent) => {
2626
const accessRsp: MainAccessResponse = ev.data;

0 commit comments

Comments
 (0)