leobalter / shadowrealms-polyfill

MIT License
58 stars 0 forks source link

Realm running module code to cover import #5

Open leobalter opened 3 years ago

leobalter commented 3 years ago

does having import implies Realm code is module code?

littledan commented 3 years ago

I don't think so, since inside that module, you can use eval, which doesn't run module code.

mhofman commented 3 years ago

Currently the proposal does require that the "bootstrap" is either module code, or using realm.eval(), with the latter subject to string evaluation and CSP complications in browsers. Maybe there could be an executeScript(specifier): Promise<void>, which compatible hosts (e.g. browsers) could implement by interpreting the specifier as a path? The call would be async, and resolve to undefined, or reject.

~Update: I guess the inability to return a value would require the usage of eval or module bindings anyway, so I guess there isn't much benefit to an "executeScript".~

mhofman commented 3 years ago

Actually maybe there could be something like getGlobalPropertyValue(name): PrimitiveValueOrCallable? Combined with an executeScript, that should allow executing non module code without the need of eval, while avoiding exposing the realm's globalThis directly.

Edit: for completeness, here is an example:

// my-script.js
globalThis.timesTwo = (x) => x * 2;

// main.js
const r = new Realm();
await r.executeScript('./my-script.js');

const redFunction = r.getGlobalPropertyValue('timesTwo');
redFunction(21); // yields 42