Skip to content

Commit

Permalink
chore: minification updates
Browse files Browse the repository at this point in the history
  • Loading branch information
adamdbradley committed Jan 15, 2022
1 parent 851455a commit 052c284
Show file tree
Hide file tree
Showing 6 changed files with 56 additions and 50 deletions.
11 changes: 5 additions & 6 deletions src/lib/sandbox/init-sandbox.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { debug, logMain, PT_IFRAME_APPENDED } from '../utils';
import { debug, PT_IFRAME_APPENDED } from '../utils';
import { getAndSetInstanceId } from './main-instances';
import { logMain } from '../log';
import { mainAccessHandler } from './main-access-handler';
import {
MainWindow,
Expand Down Expand Up @@ -51,10 +52,8 @@ export const initSandbox = async (sandboxWindow: any) => {
worker.onerror = (ev) => console.error(`Web Worker Error`, ev);
}

mainWindow.addEventListener<any>(PT_IFRAME_APPENDED, (ev: CustomEvent) => {
const win: MainWindow = ev.detail;
const winId = getAndSetInstanceId(win.frameElement);
registerWindow(worker, winId, win);
});
mainWindow.addEventListener<any>(PT_IFRAME_APPENDED, (ev: CustomEvent) =>
registerWindow(worker, getAndSetInstanceId(ev.detail.frameElement), ev.detail)
);
}
};
63 changes: 39 additions & 24 deletions src/lib/sandbox/main-access-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,42 @@ import {
ApplyPathType,
MainAccessRequest,
MainAccessResponse,
MainAccessTask,
PartytownWebWorker,
} from '../types';
import { debug, isPromise, len, normalizedWinId } from '../utils';
import { debug, isPromise, len } from '../utils';
import { deserializeFromWorker, serializeForWorker } from './main-serialization';
import { getInstance, setInstanceId } from './main-instances';
import { normalizedWinId } from '../log';
import { winCtxs } from './main-constants';

export const mainAccessHandler = async (
worker: PartytownWebWorker,
accessReq: MainAccessRequest
) => {
const accessRsp: MainAccessResponse = {
let accessRsp: MainAccessResponse = {
$msgId$: accessReq.$msgId$,
};
const totalTasks = len(accessReq.$tasks$);
let totalTasks = len(accessReq.$tasks$);
let i = 0;
let task: MainAccessTask;
let winId: number;
let applyPath: ApplyPath;
let instance: any;
let rtnValue: any;

for (let i = 0; i < totalTasks; i++) {
for (; i < totalTasks; i++) {
try {
let task = accessReq.$tasks$[i];
let winId = task.$winId$;
let instanceId = task.$instanceId$;
let applyPath = task.$applyPath$;
let instance: any;
let rtnValue: any;
task = accessReq.$tasks$[i];
winId = task.$winId$;
applyPath = task.$applyPath$;

if (!winCtxs[winId]) {
// window (iframe) hasn't finished loading yet
await new Promise<void>((resolve) => {
let i = 0;
let check = 0;
let callback = () => {
if (winCtxs[winId] || i++ > 999) {
if (winCtxs[winId] || check++ > 999) {
resolve();
} else {
setTimeout(callback, 9);
Expand All @@ -47,14 +52,15 @@ export const mainAccessHandler = async (
applyPath[0] === ApplyPathType.GlobalConstructor &&
applyPath[1] in winCtxs[winId]!.$window$
) {
// create a new instance of a global constructor
const constructedInstance = new (winCtxs[winId]!.$window$ as any)[applyPath[1]](
...deserializeFromWorker(worker, applyPath[2])
setInstanceId(
new (winCtxs[winId]!.$window$ as any)[applyPath[1]](
...deserializeFromWorker(worker, applyPath[2])
),
task.$instanceId$
);
setInstanceId(constructedInstance, instanceId);
} else {
// get the existing instance
instance = getInstance(winId, instanceId);
instance = getInstance(winId, task.$instanceId$);
if (instance) {
rtnValue = applyToInstance(worker, instance, applyPath, task.$groupedGetters$);

Expand All @@ -69,12 +75,12 @@ export const mainAccessHandler = async (
accessRsp.$rtnValue$ = serializeForWorker(winId, rtnValue);
} else {
if (debug) {
accessRsp.$error$ = `Error finding instance "${instanceId}" on window ${normalizedWinId(
winId
)} (${winId})`;
console.error(accessRsp.$error$);
accessRsp.$error$ = `Error finding instance "${
task.$instanceId$
}" on window ${normalizedWinId(winId)} (${winId})`;
console.error(accessRsp.$error$, task);
} else {
accessRsp.$error$ = instanceId + ' not found';
accessRsp.$error$ = task.$instanceId$ + ' not found';
}
}
}
Expand Down Expand Up @@ -105,6 +111,7 @@ const applyToInstance = (
let current: any;
let previous: any;
let args: any[];
let groupedRtnValues: any;

for (; i < l; i++) {
current = applyPath[i];
Expand All @@ -118,7 +125,7 @@ const applyToInstance = (
if (i + 1 === l && groupedGetters) {
// instead of getting one property, we actually want to get many properties
// This is useful for getting all dimensions of an element in one call
const groupedRtnValues: any = {};
groupedRtnValues = {};
groupedGetters.map((propName) => (groupedRtnValues[propName] = instance[propName]));
return groupedRtnValues;
}
Expand Down Expand Up @@ -147,11 +154,19 @@ const applyToInstance = (
args[1] = len(instance.cssRules);
}
}

instance = instance[previous].apply(instance, args);
if (previous === 'play') {
return Promise.resolve();
}
}
}
} catch (err) {
console.warn(err);
if (debug) {
console.debug(`Non-blocking setter error:`, err);
} else {
console.debug(err);
}
}
}

Expand Down
15 changes: 7 additions & 8 deletions src/lib/sandbox/on-messenge-from-worker.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { initializedWorkerScript, readNextScript } from './read-main-scripts';
import {
MainWindow,
MainWindowContext,
MessageFromWorkerToSandbox,
PartytownWebWorker,
WinId,
Expand All @@ -13,21 +14,19 @@ import { winCtxs } from './main-constants';
export const onMessageFromWebWorker = (
worker: PartytownWebWorker,
mainWindow: MainWindow,
msg: MessageFromWorkerToSandbox
msg: MessageFromWorkerToSandbox,
winCtx?: MainWindowContext
) => {
const msgType = msg[0];

if (msgType === WorkerMessageType.InitializedWebWorker) {
if (msg[0] === WorkerMessageType.InitializedWebWorker) {
// web worker has finished initializing and ready to run scripts
registerWindow(worker, randomId(), mainWindow);
} else {
const winId = msg[1] as WinId;
const winCtx = winCtxs[winId]!;
winCtx = winCtxs[msg[1] as WinId]!;
if (winCtx) {
if (msgType === WorkerMessageType.InitializeNextScript) {
if (msg[0] === WorkerMessageType.InitializeNextScript) {
// web worker has been initialized with the main data
readNextScript(worker, winCtx);
} else if (msgType === WorkerMessageType.InitializedEnvironmentScript) {
} else if (msg[0] === WorkerMessageType.InitializedEnvironmentScript) {
// web worker has finished initializing the script, and has another one to do
// doing this postMessage back-and-forth so we don't have long running tasks
initializedWorkerScript(worker, winCtx, msg[2], msg[3]);
Expand Down
11 changes: 3 additions & 8 deletions src/lib/service-worker/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ export const onFetchServiceWorkerRequest = (ev: FetchEvent) => {
const url = new URL(req.url);
const pathname = url.pathname;
const isolated = false;
if (debug && pathname.endsWith('debug/partytown-sandbox-sw.html')) {
if (debug && pathname.endsWith('sw.html')) {
// debug version (sandbox and web worker are not inlined)
ev.respondWith(response(SandboxDebug, isolated));
} else if (!debug && pathname.endsWith('partytown-sandbox-sw.html')) {
} else if (!debug && pathname.endsWith('sw.html')) {
// sandbox and webworker, minified and inlined
ev.respondWith(response(Sandbox, isolated));
} else if (pathname.endsWith('proxytown')) {
Expand Down Expand Up @@ -54,7 +54,7 @@ const sendMessageToSandboxFromServiceWorker = (accessReq: MainAccessRequest) =>
resolves.set(accessReq.$msgId$, msgResolve);
client.postMessage(accessReq);
} else {
resolve(swMessageError(accessReq, `No Party`));
resolve(swMessageError(accessReq, `NoParty`));
}
});

Expand Down Expand Up @@ -84,8 +84,3 @@ const response = (body: string, isolated: boolean, contentType?: string) => {
headers,
});
};

const enum ContentType {
HTML,
JSON,
}
3 changes: 1 addition & 2 deletions src/lib/service-worker/sync-create-messenger-sw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ const createMessengerServiceWorker: Messenger = async (sandboxWindow, receiveMes
mainWindow: MainWindow,
msg: MessageFromWorkerToSandbox
) => {
const msgType = msg[0];
if (msgType === WorkerMessageType.MainDataRequestFromWorker) {
if (msg[0] === WorkerMessageType.MainDataRequestFromWorker) {
// web worker has requested data from the main thread
// collect up all the info about the main thread interfaces
// send the main thread interface data to the web worker
Expand Down
3 changes: 1 addition & 2 deletions src/lib/service-worker/sync-send-message-to-main-sw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ const syncSendMessageToMainServiceWorker = (
accessReq: MainAccessRequest
): MainAccessResponse => {
const xhr = new XMLHttpRequest();
const url = webWorkerCtx.$libPath$ + 'proxytown';
xhr.open('POST', url, false);
xhr.open('POST', webWorkerCtx.$libPath$ + 'proxytown', false);
xhr.send(JSON.stringify(accessReq));
// look ma, i'm synchronous (•‿•)
return JSON.parse(xhr.responseText);
Expand Down

0 comments on commit 052c284

Please sign in to comment.