Skip to content

Commit

Permalink
feat: improve id assignment
Browse files Browse the repository at this point in the history
  • Loading branch information
adamdbradley committed Mar 2, 2022
1 parent 5619089 commit e85af98
Show file tree
Hide file tree
Showing 31 changed files with 228 additions and 190 deletions.
24 changes: 16 additions & 8 deletions src/lib/log.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import { ApplyPath, CallType, InterfaceType, NodeName, PlatformInstanceId } from './types';
import {
ApplyPath,
CallType,
InstanceId,
InterfaceType,
NodeName,
PlatformInstanceId,
WinId,
} from './types';
import {
ApplyPathKey,
InstanceDataKey,
Expand All @@ -18,7 +26,7 @@ export const logMain = (msg: string) => {
}
};

export const logWorker = (msg: string, winId = -1) => {
export const logWorker = (msg: string, winId?: WinId) => {
if (debug) {
try {
const config = webWorkerCtx.$config$;
Expand All @@ -31,7 +39,7 @@ export const logWorker = (msg: string, winId = -1) => {

let prefix: string;
let color: string;
if (winId > -1) {
if (winId) {
prefix = `Worker (${normalizedWinId(winId)}) 🎉`;
color = winColor(winId);
} else {
Expand All @@ -51,15 +59,15 @@ export const logWorker = (msg: string, winId = -1) => {
}
};

const winIds: number[] = [];
export const normalizedWinId = (winId: number) => {
const winIds: WinId[] = [];
export const normalizedWinId = (winId: WinId) => {
if (!winIds.includes(winId)) {
winIds.push(winId);
}
return winIds.indexOf(winId) + 1;
};

const winColor = (winId: number) => {
const winColor = (winId: WinId) => {
const colors = ['#00309e', '#ea3655', '#eea727'];
const index = normalizedWinId(winId) - 1;
return colors[index] || colors[colors.length - 1];
Expand Down Expand Up @@ -212,8 +220,8 @@ const getLogValue = (applyPath: ApplyPath, v: any): string => {
return `[${v.map(getLogValue).join(', ')}]`;
}
if (type === 'object') {
const instanceId: number = v[InstanceIdKey];
if (typeof instanceId === 'number') {
const instanceId: InstanceId = v[InstanceIdKey];
if (typeof instanceId === 'string') {
if (instanceId === PlatformInstanceId.body) {
return `<body>`;
}
Expand Down
2 changes: 1 addition & 1 deletion src/lib/main/snippet-entry.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { snippet } from './snippet';

snippet(window as any, document, navigator, top!, top!.crossOriginIsolated);
snippet(window as any, document, navigator, top!, window!.crossOriginIsolated);
11 changes: 5 additions & 6 deletions src/lib/main/snippet.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { debug, PT_IFRAME_APPENDED, PT_INITIALIZED_EVENT, SCRIPT_TYPE } from '../utils';
import { debug } from '../utils';
import type { MainWindow, PartytownConfig } from '../types';
import { VERSION } from '../build-modules/version';

export function snippet(
win: MainWindow,
Expand Down Expand Up @@ -30,15 +29,15 @@ export function snippet(

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

if (top != win) {
// this is an iframe
top!.dispatchEvent(new CustomEvent(PT_IFRAME_APPENDED, { detail: win }));
top!.dispatchEvent(new CustomEvent('pt1', { detail: win }));
} else if (scripts!.length) {
// set a timeout to fire if PT hasn't initialized in Xms
timeout = setTimeout(fallback, 10000);
doc.addEventListener(PT_INITIALIZED_EVENT, clearFallback);
doc.addEventListener('pt0', clearFallback);

if (useAtomics) {
// atomics support
Expand Down Expand Up @@ -84,7 +83,7 @@ export function snippet(
sandbox.src =
libPath +
'partytown-' +
(isAtomics ? 'atomics.js?v=' + VERSION : 'sandbox-sw.html?' + Date.now());
(isAtomics ? 'atomics.js?v=_VERSION_' : 'sandbox-sw.html?' + Date.now());
doc.body.appendChild(sandbox);
}

Expand Down
6 changes: 3 additions & 3 deletions src/lib/sandbox/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { debug, PT_IFRAME_APPENDED } from '../utils';
import { debug } from '../utils';
import { getAndSetInstanceId } from './main-instances';
import { libPath, mainWindow } from './main-globals';
import { logMain } from '../log';
Expand Down Expand Up @@ -49,8 +49,8 @@ syncCreateMessenger(receiveMessage).then((onMessageHandler) => {
worker.onerror = (ev) => console.error(`Web Worker Error`, ev);
}

mainWindow.addEventListener<any>(PT_IFRAME_APPENDED, (ev: CustomEvent) =>
registerWindow(worker, getAndSetInstanceId(ev.detail.frameElement), ev.detail)
mainWindow.addEventListener<any>('pt1', (ev: CustomEvent) =>
registerWindow(worker, getAndSetInstanceId(ev.detail.frameElement)!, ev.detail)
);
}
});
5 changes: 3 additions & 2 deletions src/lib/sandbox/main-access-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
MainAccessResponse,
MainAccessTask,
PartytownWebWorker,
WinId,
} from '../types';
import { debug, isPromise, len } from '../utils';
import { deserializeFromWorker, serializeForWorker } from './main-serialization';
Expand All @@ -22,7 +23,7 @@ export const mainAccessHandler = async (
let totalTasks = len(accessReq.$tasks$);
let i = 0;
let task: MainAccessTask;
let winId: number;
let winId: WinId;
let applyPath: ApplyPath;
let instance: any;
let rtnValue: any;
Expand Down Expand Up @@ -78,7 +79,7 @@ export const mainAccessHandler = async (
if (debug) {
accessRsp.$error$ = `Error finding instance "${
task.$instanceId$
}" on window ${normalizedWinId(winId)} (${winId})`;
}" on window ${normalizedWinId(winId)}`;
console.error(accessRsp.$error$, task);
} else {
accessRsp.$error$ = task.$instanceId$ + ' not found';
Expand Down
8 changes: 4 additions & 4 deletions src/lib/sandbox/main-constants.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { MainWindow, MainWindowContext, WinId } from '../types';
import type { InstanceId, MainWindow, MainWindowContext, WinId } from '../types';

export const InstanceIdKey = /*#__PURE__*/ Symbol();
export const CreatedKey = /*#__PURE__*/ Symbol();
export const instances = /*#__PURE__*/ new Map<number, any>();
export const mainRefs = /*#__PURE__*/ new Map<number, Function>();
export const instances = /*#__PURE__*/ new Map<InstanceId, any>();
export const mainRefs = /*#__PURE__*/ new Map<InstanceId, Function>();
export const winCtxs: { [winId: WinId]: MainWindowContext | undefined } = {};
export const windowIds = /*#__PURE__*/ new WeakMap<MainWindow, number>();
export const windowIds = /*#__PURE__*/ new WeakMap<MainWindow, WinId>();
8 changes: 2 additions & 6 deletions src/lib/sandbox/main-forward-trigger.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import { len } from '../utils';
import { MainWindow, PartytownWebWorker, WorkerMessageType } from '../types';
import { MainWindow, PartytownWebWorker, WinId, WorkerMessageType } from '../types';
import { serializeForWorker } from './main-serialization';

export const mainForwardTrigger = (
worker: PartytownWebWorker,
$winId$: number,
win: MainWindow
) => {
export const mainForwardTrigger = (worker: PartytownWebWorker, $winId$: WinId, win: MainWindow) => {
let queuedForwardCalls = win._ptf;
let forwards = (win.partytown || {}).forward || [];
let i: number;
Expand Down
20 changes: 13 additions & 7 deletions src/lib/sandbox/main-instances.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { CreatedKey, InstanceIdKey, instances, winCtxs } from './main-constants';
import { MainWindow, MainWindowContext, NodeName, PlatformInstanceId } from '../types';
import {
InstanceId,
MainWindow,
MainWindowContext,
NodeName,
PlatformInstanceId,
WinId,
} from '../types';
import { randomId } from '../utils';

export const getAndSetInstanceId = (instance: any, instanceId?: number, nodeName?: string) => {
export const getAndSetInstanceId = (instance: any, instanceId?: InstanceId, nodeName?: string) => {
if (instance) {
if (instance === (instance as any).window) {
return PlatformInstanceId.window;
Expand All @@ -21,17 +28,16 @@ export const getAndSetInstanceId = (instance: any, instanceId?: number, nodeName
return PlatformInstanceId.body;
}

if (typeof (instanceId = instance[InstanceIdKey]) !== 'number') {
if (!(instanceId = instance[InstanceIdKey])) {
setInstanceId(instance, (instanceId = randomId()));
}
return instanceId;
}
return -1;
};

export const getInstance = <T = any>(
winId: number,
instanceId: number,
winId: WinId,
instanceId: InstanceId,
winCtx?: MainWindowContext,
win?: MainWindow,
doc?: Document
Expand Down Expand Up @@ -61,7 +67,7 @@ export const getInstance = <T = any>(
}
};

export const setInstanceId = (instance: any, instanceId: number, now?: number) => {
export const setInstanceId = (instance: any, instanceId: InstanceId, now?: number) => {
if (instance) {
instances.set(instanceId, instance);
instance[InstanceIdKey] = instanceId;
Expand Down
11 changes: 3 additions & 8 deletions src/lib/sandbox/main-register-window.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
import { debug } from '../utils';
import {
InitializeEnvironmentData,
MainWindow,
PartytownWebWorker,
WorkerMessageType,
} from '../types';
import { logMain, normalizedWinId } from '../log';
import { MainWindow, PartytownWebWorker, WinId, WorkerMessageType } from '../types';
import { winCtxs, windowIds } from './main-constants';

export const registerWindow = (
worker: PartytownWebWorker,
$winId$: number,
$winId$: WinId,
$window$: MainWindow
) => {
if (!windowIds.has($window$)) {
Expand Down Expand Up @@ -62,7 +57,7 @@ export const registerWindow = (

if (debug) {
const winType = $winId$ === $parentWinId$ ? 'top' : 'iframe';
logMain(`Registered ${winType} window ${normalizedWinId($winId$)} (${$winId$})`);
logMain(`Registered ${winType} window ${normalizedWinId($winId$)}`);
}

if (doc.readyState === 'complete') {
Expand Down
7 changes: 4 additions & 3 deletions src/lib/sandbox/main-serialization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ import {
SerializedRefTransferData,
SerializedTransfer,
SerializedType,
WinId,
WorkerMessageType,
} from '../types';

export const serializeForWorker = (
$winId$: number,
$winId$: WinId,
value: any,
added?: Set<any>,
type?: string,
Expand Down Expand Up @@ -71,7 +72,7 @@ export const serializeForWorker = (
SerializedType.Instance,
{
$winId$,
$instanceId$: getAndSetInstanceId(value),
$instanceId$: getAndSetInstanceId(value)!,
$nodeName$: value.nodeName,
},
];
Expand All @@ -87,7 +88,7 @@ export const serializeForWorker = (
};

const serializeObjectForWorker = (
winId: number,
winId: WinId,
obj: any,
added: Set<any>,
includeFunctions?: boolean,
Expand Down
1 change: 1 addition & 0 deletions src/lib/sandbox/read-main-platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ export const readMainPlatform = () => {
$config$,
$libPath$: new URL(libPath, mainWindow.location as any) + '',
$interfaces$,
$origin$: origin,
$localStorage$: readStorage('localStorage'),
$sessionStorage$: readStorage('sessionStorage'),
};
Expand Down
22 changes: 13 additions & 9 deletions src/lib/sandbox/read-main-scripts.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { debug, PT_INITIALIZED_EVENT, SCRIPT_TYPE, SCRIPT_TYPE_EXEC } from '../utils';
import { debug, SCRIPT_TYPE, SCRIPT_TYPE_EXEC } from '../utils';
import { getAndSetInstanceId } from './main-instances';
import {
InitializeScriptData,
InstanceId,
MainWindowContext,
PartytownWebWorker,
WorkerMessageType,
Expand All @@ -16,7 +17,7 @@ export const readNextScript = (worker: PartytownWebWorker, winCtx: MainWindowCon
let scriptSelector = `script[type="${SCRIPT_TYPE}"]:not([data-ptid]):not([data-pterror])`;
let blockingScriptSelector = scriptSelector + `:not([async]):not([defer])`;
let scriptElm: HTMLScriptElement | null;
let $instanceId$: number;
let $instanceId$: InstanceId;
let scriptData: InitializeScriptData;

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

mainForwardTrigger(worker, $winId$, win);

doc.dispatchEvent(new CustomEvent(PT_INITIALIZED_EVENT));
doc.dispatchEvent(new CustomEvent('pt0'));

if (debug) {
const winType = win === win.top ? 'top' : 'iframe';
Expand All @@ -80,18 +81,21 @@ export const readNextScript = (worker: PartytownWebWorker, winCtx: MainWindowCon
export const initializedWorkerScript = (
worker: PartytownWebWorker,
winCtx: MainWindowContext,
instanceId: number,
instanceId: InstanceId,
errorMsg: string,
script?: HTMLScriptElement | null
scriptElm?: HTMLScriptElement | null
) => {
script = winCtx.$window$.document.querySelector<HTMLScriptElement>(`[data-ptid="${instanceId}"]`);
scriptElm = winCtx.$window$.document.querySelector<HTMLScriptElement>(
`[data-ptid="${instanceId}"]`
);

if (script) {
if (scriptElm) {
if (errorMsg) {
script.dataset.pterror = errorMsg;
scriptElm.dataset.pterror = errorMsg;
} else {
script.type += SCRIPT_TYPE_EXEC;
scriptElm.type += SCRIPT_TYPE_EXEC;
}
delete scriptElm.dataset.ptid;
}

readNextScript(worker, winCtx);
Expand Down
2 changes: 1 addition & 1 deletion src/lib/service-worker/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const onFetchServiceWorkerRequest = (ev: FetchEvent) => {
}
};

const resolves = new Map<number, MessageResolve>();
const resolves = new Map<string, MessageResolve>();

export const receiveMessageFromSandboxToServiceWorker = (ev: ExtendableMessageEvent) => {
const accessRsp: MainAccessResponse = ev.data;
Expand Down
Loading

1 comment on commit e85af98

@vercel
Copy link

@vercel vercel bot commented on e85af98 Mar 2, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.