The headless browser for AI agents and web scraping
fix(js): expose ECMAScript builtins and web APIs as properties of the worker scope
flolep2607e4f11dbabe9f
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 6cc50bee..e3125b4c 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -16512,6 +16512,21 @@ navigator.wakeLock = { request() { return Promise.reject(new DOMException('Not aglobalThis.opener = null;+const WORKER_GLOBALS = [+ 'Object', 'Function', 'Array', 'Number', 'parseFloat', 'parseInt', 'Infinity', 'NaN', 'undefined',+ 'Boolean', 'String', 'Symbol', 'Date', 'Promise', 'RegExp', 'Error', 'AggregateError', 'EvalError',+ 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError', 'JSON', 'Math', 'Intl',+ 'ArrayBuffer', 'SharedArrayBuffer', 'Atomics', 'Uint8Array', 'Int8Array', 'Uint16Array', 'Int16Array',+ 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array', 'Uint8ClampedArray', 'BigUint64Array',+ 'BigInt64Array', 'DataView', 'Map', 'BigInt', 'Set', 'WeakMap', 'WeakSet', 'WeakRef',+ 'FinalizationRegistry', 'Proxy', 'Reflect', 'WebAssembly', 'decodeURI', 'decodeURIComponent',+ 'encodeURI', 'encodeURIComponent', 'escape', 'unescape', 'isFinite', 'isNaN',+ 'queueMicrotask', 'structuredClone', 'URL', 'URLSearchParams', 'Blob', 'File', 'FormData', 'Headers',+ 'Request', 'Response', 'AbortController', 'AbortSignal', 'Event', 'CustomEvent', 'EventTarget',+ 'MessageChannel', 'MessagePort', 'BroadcastChannel', 'ReadableStream', 'WritableStream',+ 'TransformStream', 'XMLHttpRequest', 'WebSocket', 'indexedDB', 'navigator', 'DOMException',+];+globalThis.Worker = class Worker {constructor(url) {this.onmessage = null;@@ -16581,6 +16596,19 @@ globalThis.Worker = class Worker {location: globalThis.location,};scope.self = scope;+ // A worker global carries the ECMAScript builtins and the worker-visible+ // web APIs as properties. Bare identifiers already resolved through the+ // page global via `with (scope)`, but code that treats `self` as the global+ // object (Go's wasm_exec runs with `global = self`, reading `self.Object`,+ // `self.Promise`, `self.JSON`, ...) saw undefined and the wasm panicked with+ // "syscall/js: call of Value.Invoke on undefined".+ for (const name of WORKER_GLOBALS) {+ if (!(name in scope) && name in globalThis) {+ Object.defineProperty(scope, name, { value: globalThis[name], writable: true, configurable: true });+ }+ }+ // Bare `globalThis` inside a worker is the worker scope, not the page window.+ Object.defineProperty(scope, 'globalThis', { value: scope, writable: true, configurable: true });return scope;}_autoRun() {diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex c0c1c715..f47641c2 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -6309,6 +6309,47 @@ mod tests {.unwrap();}+ #[tokio::test(flavor = "current_thread")]+ async fn worker_scope_exposes_builtins_as_properties() {+ // Go's wasm_exec uses `self` as its global object and reads+ // self.Object / self.Promise / self.JSON; an undefined one makes the+ // wasm panic with "call of Value.Invoke on undefined".+ let mut rt = setup_runtime("<html><body></body></html>");+ rt.execute_script(+ "worker-scope-builtins",+ r#"+ globalThis.__workerReplies = [];+ const source = `+ const names = ['Object', 'Array', 'Promise', 'JSON', 'Uint8Array', 'Date', 'Reflect', 'WebAssembly', 'Headers', 'AbortController'];+ postMessage({+ missing: names.filter(n => typeof self[n] === 'undefined'),+ viaGlobalThis: names.filter(n => typeof globalThis[n] === 'undefined'),+ sameObject: self.Object === Object && self.Promise === Promise,+ globalThisIsSelf: globalThis === self,+ noDocument: typeof self.document === 'undefined' && typeof self.window === 'undefined',+ callable: self.JSON.stringify(new self.Promise(() => {}) instanceof self.Promise),+ });+ `;+ const url = URL.createObjectURL(new Blob([source], { type: 'application/javascript' }));+ const worker = new Worker(url);+ worker.onmessage = event => {+ __workerReplies.push(event.data);+ worker.terminate();+ URL.revokeObjectURL(url);+ };+ "#,+ )+ .unwrap();+ rt.run_event_loop_bounded(100).await.unwrap();+ assert_eq!(+ rt.evaluate("__workerReplies").unwrap(),+ serde_json::json!([{+ "missing": [], "viaGlobalThis": [], "sameObject": true,+ "globalThisIsSelf": true, "noDocument": true, "callable": "true",+ }])+ );+ }+#[tokio::test(flavor = "current_thread")]async fn worker_initialization_error_does_not_rerun_source() {let mut rt = setup_runtime("<html><body></body></html>");