UNPKG

@stevenleep/sandbox

Version:

A powerful JavaScript sandbox library that provides multiple sandbox implementation options for safely executing untrusted code in browser environments.

9 lines (8 loc) 46.4 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).sandbox={})}(this,(function(e){"use strict";function t(e,t,o,r){return new(o||(o=Promise))((function(n,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof o?t:new o((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))}var o;e.SandboxType=void 0,(o=e.SandboxType||(e.SandboxType={})).Proxy="Proxy",o.WithEval="WithEval",o.ShadowRealm="ShadowRealm",o.Snapshot="Snapshot";class r{constructor(e,t){this.memoryUsage=[],this.cpuUsage=[],this.startTime=0,this.memoryLimit=0,this.timeLimit=0,this.collectMetrics=!1,this.sandboxName=e,this.memoryLimit=(null==t?void 0:t.memoryLimit)||0,this.timeLimit=(null==t?void 0:t.timeLimit)||0,this.collectMetrics=(null==t?void 0:t.collectMetrics)||!1}start(){this.startTime=performance.now(),this.recordMemoryUsage()}stop(){const e=performance.now(),t=e-this.startTime,o=this.getCurrentMemoryUsage(),r=this.checkLimits(t,o);return this.collectMetrics&&(this.cpuUsage.push({timestamp:e,duration:t}),this.recordMemoryUsage()),{executionTime:t,memoryUsage:o,exceededLimits:r}}recordMemoryUsage(){if(!this.collectMetrics)return;const e=this.getCurrentMemoryUsage();this.memoryUsage.push({timestamp:performance.now(),bytes:e})}getCurrentMemoryUsage(){const e=performance.memory;return e?e.usedJSHeapSize:0}checkLimits(e,t){return this.timeLimit>0&&e>this.timeLimit?(console.warn(`[ResourceMonitor] Sandbox ${this.sandboxName} exceeded time limit: ${e}ms > ${this.timeLimit}ms`),!0):this.memoryLimit>0&&t>this.memoryLimit&&(console.warn(`[ResourceMonitor] Sandbox ${this.sandboxName} exceeded memory limit: ${t} bytes > ${this.memoryLimit} bytes`),!0)}getMetrics(){return{sandboxName:this.sandboxName,memoryUsage:this.memoryUsage,cpuUsage:this.cpuUsage,memoryLimit:this.memoryLimit,timeLimit:this.timeLimit}}reset(){this.memoryUsage=[],this.cpuUsage=[],this.startTime=0}}function n(e,o){return t(this,void 0,void 0,(function*(){return new Promise(((t,r)=>{const n=setTimeout((()=>{r(new Error(`Execution timed out after ${o}ms`))}),o);try{const o=e();o instanceof Promise?o.then((e=>{clearTimeout(n),t(e)})).catch((e=>{clearTimeout(n),r(e)})):(clearTimeout(n),t(o))}catch(e){clearTimeout(n),r(e)}}))}))}const i=new class{constructor(){this.monitors=new Map}getMonitor(e,t){return this.monitors.has(e)||this.monitors.set(e,new r(e,t)),this.monitors.get(e)}removeMonitor(e){this.monitors.delete(e)}getAllMonitors(){return this.monitors}resetAllMonitors(){this.monitors.forEach((e=>e.reset()))}};class s{static preventPrototypePollution(){try{Object.freeze(Object.prototype),Object.freeze(Array.prototype),Object.freeze(Function.prototype),Object.freeze(String.prototype),Object.freeze(Number.prototype),Object.freeze(Boolean.prototype),Object.freeze(RegExp.prototype),Object.freeze(Date.prototype),Object.freeze(Error.prototype),Object.freeze(Map.prototype),Object.freeze(Set.prototype),Object.freeze(Promise.prototype),Object.freeze(Symbol.prototype)}catch(e){console.warn("[SecurityHelper] Failed to freeze prototypes:",e)}}static getDefaultRestrictedProperties(){return new Set(["localStorage","sessionStorage","indexedDB","caches","fetch","XMLHttpRequest","WebSocket","navigator","sendBeacon","Request","Response","Headers","location","history","document","Document","HTMLElement","Element","Node","cookie","parent","opener","frames","top","postMessage","eval","WebAssembly","Reflect","Proxy","constructor","__proto__","prototype","Worker","ServiceWorker","SharedWorker","crypto","Notification","geolocation","camera","microphone","Bluetooth","USB","Serial","PaymentRequest","Credential","PasswordCredential"])}static getSecureFunction(e=0){return function(...t){const o=t.pop()||"",r=t,n=`"use strict";\n${o}`,i=Function.apply(null,[...r,n]);return e>0?function(...t){let o,r=!1;const n=new Promise(((t,o)=>{setTimeout((()=>{r||o(new Error(`Function execution timed out after ${e}ms`))}),e)})),s=new Promise((e=>{o=i.apply(this,t),r=!0,e(o)}));return Promise.race([s,n]).catch((e=>console.error("Secure function execution error:",e))),o}:i}}static validateCode(e){const t=[];return[/\[\s*['"]constructor['"]\s*\]\s*\(\s*['"]return\s+.*Function/,/\[\s*['"]eval['"]\s*\]/,/\.__proto__\s*=/,/\.prototype\s*=/,/\bparent\b\s*\./,/\btop\b\s*\./,/\bwindow\b\s*\.\s*\bparent\b/,/\bwindow\b\s*\.\s*\btop\b/,/\bdocument\b\s*\.\s*\bwrite\b/,/\bdocument\b\s*\.\s*\bwriteln\b/].forEach((o=>{o.test(e)&&t.push(`Code contains potentially unsafe pattern: ${o}`)})),{safe:0===t.length,issues:t}}}function a(){return{Object:Object,Array:Array,String:String,Number:Number,Boolean:Boolean,Math:Math,Date:Date,RegExp:RegExp,Error:Error,Map:Map,Set:Set,WeakMap:WeakMap,WeakSet:WeakSet,JSON:JSON,Promise:Promise,Symbol:Symbol,parseInt:parseInt,parseFloat:parseFloat,isNaN:isNaN,isFinite:isFinite,decodeURI:decodeURI,decodeURIComponent:decodeURIComponent,encodeURI:encodeURI,encodeURIComponent:encodeURIComponent,console:console,setTimeout:setTimeout.bind(window),clearTimeout:clearTimeout.bind(window),setInterval:setInterval.bind(window),clearInterval:clearInterval.bind(window)}}class c{constructor(){this.sandboxRefs=new Map,this.cleanupIntervalId=null,this.cleanupInterval=6e4,this.startCleanup()}register(e,t){if(this.sandboxRefs.set(e,new WeakRef(t)),"undefined"!=typeof FinalizationRegistry){new FinalizationRegistry((e=>{console.log(`[MemoryManager] Sandbox ${e} was garbage collected`),this.sandboxRefs.delete(e)})).register(t,e)}}unregister(e){this.sandboxRefs.delete(e)}startCleanup(){null===this.cleanupIntervalId&&(this.cleanupIntervalId=window.setInterval((()=>{this.cleanup()}),this.cleanupInterval))}stopCleanup(){null!==this.cleanupIntervalId&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null)}cleanup(){for(const[e,t]of this.sandboxRefs.entries())t.deref()||(console.log(`[MemoryManager] Removing dead reference to sandbox ${e}`),this.sandboxRefs.delete(e))}destroyAll(){this.sandboxRefs.forEach(((e,t)=>{const o=e.deref();if(o&&"function"==typeof o.destroy)try{o.destroy()}catch(e){console.error(`[MemoryManager] Failed to destroy sandbox ${t}:`,e)}})),this.sandboxRefs.clear()}isAlive(e){const t=this.sandboxRefs.get(e);return!!t&&!!t.deref()}static breakCircularReferences(e,t=new WeakSet){if(e&&"object"==typeof e&&!t.has(e)){t.add(e);for(const o of Object.keys(e)){const r=e[o];"window"!==o&&"self"!==o&&"globalThis"!==o&&"parent"!==o||r!==e?r&&"object"==typeof r&&c.breakCircularReferences(r,t):e[o]=null}}}}const l=new c;class d extends Error{constructor(e,t,o,r){super(`[Sandbox Error] ${e}`),this.name="SandboxError",this.originalError=t,this.sandboxName=o,this.code=r,t.stack&&(this.stack=`SandboxError: ${e}\nSandbox: ${o}\n${t.stack}`)}}function h(e,t,o){return e instanceof d?e:e instanceof SyntaxError?new d(`Syntax error: ${e.message}`,e,t,o):e instanceof ReferenceError?new d(`Reference error: ${e.message}`,e,t,o):new d(`Execution error: ${e.message}`,e,t,o)}function u(e,t,o){try{return e()}catch(e){throw h(e,t,o)}}class p{constructor(t){var o,n;this.type=e.SandboxType.Proxy,this.sandboxContext={},this.active=!1,this.name=t.name,this.options=t,this.strictMode=null===(o=t.strictMode)||void 0===o||o,this.blacklist=new Set([...s.getDefaultRestrictedProperties(),...t.blacklist||[]]),this.whitelist=t.whitelist?new Set(t.whitelist):null,this.resourceMonitor=new r(this.name,{timeLimit:t.timeLimit||0,memoryLimit:t.memoryLimit||0,collectMetrics:t.enablePerformanceMeasure||!1}),l.register(this.name,this),(null===(n=t.security)||void 0===n?void 0:n.preventPrototypePollution)&&s.preventPrototypePollution(),this.initSandboxContext(),this.proxy=this.createProxy()}initSandboxContext(){const e=a();Object.assign(this.sandboxContext,e);for(const e of Object.getOwnPropertyNames(window))if(!this.blacklist.has(e)&&(!this.whitelist||this.whitelist.has(e)))try{const t=Object.getOwnPropertyDescriptor(window,e);if(t&&t.get)continue;if(e.startsWith("__"))continue;if(e in this.sandboxContext)continue;this.sandboxContext[e]=window[e]}catch(t){console.warn(`[ProxySandbox] Cannot copy window property: ${String(e)}`,t)}this.sandboxContext.window=this.sandboxContext,this.sandboxContext.self=this.sandboxContext,this.sandboxContext.globalThis=this.sandboxContext}createProxy(){const{blacklist:e,whitelist:t}=this,o=this;return new Proxy(this.sandboxContext,{get:(o,r)=>e.has(r)||t&&!t.has(r)?window[r]:r in o?o[r]:window[r],set:(r,n,i)=>!o.active||(e.has(n)&&o.strictMode?(console.warn(`[ProxySandbox] Cannot modify blacklisted property: ${String(n)}`),!0):t&&!t.has(n)&&o.strictMode?(console.warn(`[ProxySandbox] Cannot modify non-whitelisted property: ${String(n)}`),!0):(r[n]=i,!0)),deleteProperty:(t,r)=>!o.active||(e.has(r)&&o.strictMode?(console.warn(`[ProxySandbox] Cannot delete blacklisted property: ${String(r)}`),!0):(r in t&&delete t[r],!0)),defineProperty:(t,r,n)=>!o.active||(e.has(r)&&o.strictMode?(console.warn(`[ProxySandbox] Cannot define blacklisted property: ${String(r)}`),!0):(Object.defineProperty(t,r,n),!0)),getOwnPropertyDescriptor:(e,t)=>t in e?Object.getOwnPropertyDescriptor(e,t):Object.getOwnPropertyDescriptor(window,t),ownKeys:e=>Reflect.ownKeys(e),has:(e,t)=>t in e||t in window})}activate(){this.active=!0}deactivate(){this.active=!1}execScript(e,t){var o;const r=this.active;r||this.activate(),this.resourceMonitor.start();try{if(this.strictMode){const t=s.validateCode(e);if(!t.safe)throw new d(`Code validation failed: ${t.issues.join(", ")}`,new Error("Security validation error"),this.name,e)}if(t&&t>0)return this.execScriptWithTimeout(e,t);const o=s.getSecureFunction()("window","self","globalThis",`\n "use strict";\n with (window) {\n return (function() {\n ${e}\n }).call(window);\n }\n `);return u((()=>o.call(this.proxy,this.proxy,this.proxy,this.proxy)),this.name,e)}catch(t){const r=h(t,this.name,e);throw console.error(`[ProxySandbox] Error executing code in sandbox ${this.name}:`,r),"function"==typeof(null===(o=this.options)||void 0===o?void 0:o.errorHandler)&&this.options.errorHandler(r,e),r}finally{const e=this.resourceMonitor.stop();e.exceededLimits&&console.warn(`[ProxySandbox] Resource limits exceeded in sandbox ${this.name}: \n Execution time: ${e.executionTime}ms, \n Memory usage: ${e.memoryUsage} bytes`),r||this.deactivate()}}execScriptWithTimeout(e,t){return n((()=>new Function("window","self","globalThis",`\n with (window) {\n return (function() {\n "use strict";\n ${e}\n }).call(window);\n }\n `).call(this.proxy,this.proxy,this.proxy,this.proxy)),t)}execScriptAsync(e,o){var r;return t(this,void 0,void 0,(function*(){const i=this.active;i||this.activate(),this.resourceMonitor.start();try{if(this.strictMode){const t=s.validateCode(e);if(!t.safe)throw new d(`Code validation failed: ${t.issues.join(", ")}`,new Error("Security validation error"),this.name,e)}const r=Object.getPrototypeOf((function(){return t(this,void 0,void 0,(function*(){}))})).constructor,i=new r("window","self","globalThis",`\n "use strict";\n return (async function() {\n try {\n return await (async () => {\n ${e}\n })();\n } catch (error) {\n // Ensure errors are properly propagated\n throw error;\n }\n }).call(window);\n `);return o&&o>0?yield n((()=>i.call(this.proxy,this.proxy,this.proxy,this.proxy)),o):yield i.call(this.proxy,this.proxy,this.proxy,this.proxy)}catch(t){const o=h(t,this.name,e);throw console.error(`[ProxySandbox] Error executing async code in sandbox ${this.name}:`,o),"function"==typeof(null===(r=this.options)||void 0===r?void 0:r.errorHandler)&&this.options.errorHandler(o,e),o}finally{const e=this.resourceMonitor.stop();e.exceededLimits&&console.warn(`[ProxySandbox] Resource limits exceeded in sandbox ${this.name}: \n Execution time: ${e.executionTime}ms, \n Memory usage: ${e.memoryUsage} bytes`),i||this.deactivate()}}))}reset(){const e=Object.keys(this.sandboxContext);for(const t of e)"window"!==t&&"self"!==t&&"globalThis"!==t&&delete this.sandboxContext[t];this.initSandboxContext()}destroy(){this.deactivate(),this.resourceMonitor&&this.resourceMonitor.reset(),l.unregister(this.name),c.breakCircularReferences(this.sandboxContext),this.reset(),this.sandboxContext&&(this.sandboxContext.window=null,this.sandboxContext.self=null,this.sandboxContext.globalThis=null),console.log(`[ProxySandbox] Sandbox ${this.name} destroyed`)}}class m{constructor(t){var o;this.type=e.SandboxType.WithEval,this.context={},this.active=!1,this.unscopables={undefined:!0,Array:!0,Object:!0,String:!0,Boolean:!0,Math:!0,Number:!0,Symbol:!0,parseFloat:!0,parseInt:!0,Infinity:!0,NaN:!0,isNaN:!0,isFinite:!0,Date:!0,Promise:!0,RegExp:!0,Error:!0,EvalError:!0,RangeError:!0,ReferenceError:!0,SyntaxError:!0,TypeError:!0,URIError:!0,JSON:!0,Function:!0},this.name=t.name,this.options=t,this.strictMode=null===(o=t.strictMode)||void 0===o||o,this.resourceMonitor=new r(this.name,{timeLimit:t.timeLimit||0,memoryLimit:t.memoryLimit||0,collectMetrics:t.enablePerformanceMeasure||!1}),l.register(this.name,this),this.strictMode&&s.preventPrototypePollution(),this.context=this.initContext(t),this.proxy=this.createProxy()}initContext(e){const t=a();if(t.window=t,t.self=t,t.globalThis=t,e.unscopables&&Object.assign(this.unscopables,e.unscopables),!0!==e.allowNetwork){["fetch","XMLHttpRequest","WebSocket"].forEach((e=>this.unscopables[e]=!0))}const o=this.copyWindowProperties();return Object.assign(Object.assign(Object.assign({},t),o),e.globals||{})}activate(){this.active=!0}deactivate(){this.active=!1}execScript(e,t){var o,r;this.active||(console.warn(`[WithEvalSandbox] Sandbox ${this.name} is not active, activating before executing code`),this.activate()),this.resourceMonitor.start();try{if(null===(o=this.options)||void 0===o?void 0:o.validateCode){const t=s.validateCode(e);if(!t.safe)throw new d(`Code validation failed: ${t.issues.join(", ")}`,new Error("Security validation error"),this.name,e)}if(t&&t>0)return this.execScriptWithTimeout(e,t);const r=this.createExecuter(e);return u((()=>r.call(this.proxy,this.proxy)),this.name,e)}catch(t){const o=h(t,this.name,e);throw console.error(`[WithEvalSandbox] Error executing code in sandbox ${this.name}:`,o),"function"==typeof(null===(r=this.options)||void 0===r?void 0:r.errorHandler)&&this.options.errorHandler(o,e),o}finally{const e=this.resourceMonitor.stop();e.exceededLimits&&console.warn(`[WithEvalSandbox] Resource limits exceeded in sandbox ${this.name}: \n Execution time: ${e.executionTime}ms, \n Memory usage: ${e.memoryUsage} bytes`)}}execScriptWithTimeout(e,t){return n((()=>this.createExecuter(e).call(this.proxy,this.proxy)),t)}createExecuter(e){return s.getSecureFunction()("sandbox",`\n "use strict";\n with (sandbox) {\n return (function() {\n // Execute code in strict mode to prevent variables from leaking\n ${e}\n }).call(sandbox);\n }\n `)}copyWindowProperties(){const e={};return Object.getOwnPropertyNames(window).forEach((t=>{if(!this.unscopables[t])try{const o=Object.getOwnPropertyDescriptor(window,t);if(o&&o.get)return;e[t]=window[t]}catch(e){console.warn(`[WithEvalSandbox] Cannot copy window property: ${t}`,e)}})),e}createProxy(){const e=this;return new Proxy(this.context,{get:(t,o)=>o in t?t[o]:("string"==typeof o&&e.unscopables[o],window[o]),set(t,o,r){if(!e.active)return!0;if(e.strictMode)return t[o]=r,!0;t[o]=r;try{window[o]=r}catch(e){console.warn(`[WithEvalSandbox] Cannot set window property: ${String(o)}`,e)}return!0},deleteProperty(t,o){if(!e.active)return!0;if(o in t&&delete t[o],!e.strictMode)try{delete window[o]}catch(e){console.warn(`[WithEvalSandbox] Cannot delete window property: ${String(o)}`,e)}return!0},has:(e,t)=>t in e||t in window,getOwnPropertyDescriptor:(e,t)=>t in e?Object.getOwnPropertyDescriptor(e,t):Object.getOwnPropertyDescriptor(window,t),defineProperty(t,o,r){if(!e.active)return!0;if(Object.defineProperty(t,o,r),!e.strictMode)try{Object.defineProperty(window,o,r)}catch(e){console.warn(`[WithEvalSandbox] Cannot define window property: ${String(o)}`,e)}return!0},ownKeys:e=>Reflect.ownKeys(e)})}reset(){const e=this.copyWindowProperties(),t={window:this.context.window,self:this.context.self,globalThis:this.context.globalThis};Object.keys(this.context).forEach((e=>{"window"!==e&&"self"!==e&&"globalThis"!==e&&delete this.context[e]})),Object.assign(this.context,e,t)}destroy(){this.deactivate(),this.resourceMonitor&&this.resourceMonitor.reset(),l.unregister(this.name),c.breakCircularReferences(this.context),this.reset(),this.context&&(this.context.window=null,this.context.self=null,this.context.globalThis=null),console.log(`[WithEvalSandbox] Sandbox ${this.name} destroyed`)}execScriptAsync(e,o){var r,i;return t(this,void 0,void 0,(function*(){this.active||(console.warn(`[WithEvalSandbox] Sandbox ${this.name} is not active, activating before executing code`),this.activate()),this.resourceMonitor.start();try{if(null===(r=this.options)||void 0===r?void 0:r.validateCode){const t=s.validateCode(e);if(!t.safe)throw new d(`Code validation failed: ${t.issues.join(", ")}`,new Error("Security validation error"),this.name,e)}const i=new(0,Object.getPrototypeOf((function(){return t(this,void 0,void 0,(function*(){}))})).constructor)("sandbox",`\n "use strict";\n with (sandbox) {\n return (async function() {\n try {\n return await (async () => {\n ${e}\n })();\n } catch (error) {\n // Ensure errors are properly propagated\n throw error;\n }\n }).call(sandbox);\n }\n `);return o&&o>0?yield n((()=>i.call(this.proxy,this.proxy)),o):yield i.call(this.proxy,this.proxy)}catch(t){const o=h(t,this.name,e);throw console.error(`[WithEvalSandbox] Error executing async code in sandbox ${this.name}:`,o),"function"==typeof(null===(i=this.options)||void 0===i?void 0:i.errorHandler)&&this.options.errorHandler(o,e),o}finally{const e=this.resourceMonitor.stop();e.exceededLimits&&console.warn(`[WithEvalSandbox] Resource limits exceeded in sandbox ${this.name}: \n Execution time: ${e.executionTime}ms, \n Memory usage: ${e.memoryUsage} bytes`)}}))}} /** * shadowrealm-api@0.8.3 * ShadowRealm polyfill for browser * @author Ambit Tsai <ambit_tsai@qq.com> * @license Apache-2.0 * @see {@link https://github.com/ambit-tsai/shadowrealm-api#readme} */var f,w=window,y=Object.defineProperty,b={debug:!1},x=console.log,v=console.warn;function g(e){b.debug&&(x("[DEBUG]"),E(e)?v(e):x(e))}if(w.Reflect)f=Reflect.apply;else{var S=Function.prototype.apply;f=function(e,t,o){return S.call(e,t,o)}}var M=String.prototype.replace;function E(e){return!!e&&"object"==typeof e}var R=Object.assign,P=Object.keys;function $(){var e,t=params,o=t[0],r=t[1],n=t[2],i=t[3];try{for(var s=arguments,a=[],c=0,l=s.length;c<l;++c){var d=i.getWrappedValue(n,s[c],o,i);a.push(d)}e=i.apply(r,n.globalObject,a)}catch(e){throw i.wrapError(e,o)}return i.getWrappedValue(o,e,n,i)}R||(R=function(e){for(var t=arguments,o=1,r=t.length;o<r;++o){var n=t[o];if(E(n))for(var i=0,s=P(n);i<s.length;i++){var a=s[i];e[a]=n[a]}}return e});var C=Object.freeze({__proto__:null,GLOBAL:w,define:y,_:b,log:g,get apply(){return f},replace:function(e){for(var t=[],o=1;o<arguments.length;o++)t[o-1]=arguments[o];return f(M,e,t)},isObject:E,get assign(){return R},keys:P,wrapError:function(e,t,o){var r=t.intrinsics;if(void 0===o&&(o=!1),g(e),o){if(!e._)return new r[e.name](e.message);e=e._}var n=r.TypeError,i="Cross-Realm Error: ";return E(e)?new n(i+e.name+": "+e.message):new n(i+e)},getWrappedValue:function(e,t,o,r){if("function"==typeof t)try{return function(e,t,o,r){var n=t.length,i=t.name;("number"!=typeof n||n<0)&&(n=0),"string"!=typeof i&&(i="");var s=e.intrinsics.Function("params","return "+$.toString())(arguments);return y(s,"length",{value:n}),y(s,"name",{value:i}),s}(e,t,o,r)}catch(t){throw r.wrapError(t,e)}else if(E(t))throw new e.intrinsics.TypeError("need primitive or callable, got "+t);return t},globalReservedProps:["globalThis","Infinity","NaN","undefined","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","AggregateError","Array","ArrayBuffer","Atomics","BigInt","BigInt64Array","BigUint64Array","Boolean","DataView","Date","Error","EvalError","FinalizationRegistry","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Number","Object","Promise","Proxy","RangeError","ReferenceError","RegExp","Set","SharedArrayBuffer","String","Symbol","SyntaxError","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","URIError","WeakMap","WeakRef","WeakSet","Atomics","JSON","Math","Reflect","atob","btoa","console","crypto","Crypto","SubtleCrypto","TextDecoder","TextEncoder"]});function O(e,t){var o,r=e.globalObject,n=e.intrinsics,i=t.apply,s=t.define,a=t.GLOBAL,c=n.Array.prototype.push,l=n.Object.create,d=n.Promise,h=n.Symbol,u=a.fetch,p=a.URL,m=d.all,f=d.prototype.then,w={};function y(e){var o=w[e];if(o)return o.promise;var r=u(e,{credentials:"same-origin"}).then((function(t){if(200===t.status)return t.text();throw{_:new n.TypeError("Failed to fetch dynamically imported module: "+e)}})).then((function(o){for(var r=t.transformEsmSyntax(o),n=r[0],s=r[1],a=[],l=0,h=s.length;l<h;++l){var u=new p(s[l],e).href;s[l]=u,i(c,a,[y(u)])}var w=i(m,d,[a]);return i(f,w,[function(t){for(var o=0,r=t.length;o<r;++o)b(s[o],t[o]);return'var __meta={url:"'+e+'"};'+n}])}),(function(e){if(e._)throw e._;throw new n[e.name](e.message)}));return o=w[e]={promise:r},r}function b(e,t){o=l(null),h&&h.toStringTag&&s(o,h.toStringTag,{value:"Module"}),r.eval(t);var n=w[e];return n.exports=o,o=void 0,n.exports}s(r,"__import",{value:function(e,t){void 0===t&&(t=a.location.href);var o=new p(e,t).href;return new d((function(e,t){var r=w[o];if(r&&r.exports)return e(r.exports);y(o).then((function(t){e(b(o,t))})).catch(t)}))}}),s(r,"__from",{value:function(e,t){var o=new p(e,t).href,r=w[o];if(r&&r.exports)return r.exports;throw new n.Error("Module does not exist ("+e+")")}}),s(r,"__export",{set:function(e){return t.assign(o,e)}}),s(r,"__default",{set:function(e){return o.default=e}})}function T(e){var t,o=window,r=o.Function,n=o.Object,i=o.Symbol,s=n.getOwnPropertyNames,a=e.apply,c=e.define,l=e.dynamicImportPattern,d=e.dynamicImportReplacer,h=e.replace,u={},p={};i&&i.unscopables&&c(p,i.unscopables,{value:n.seal(n.create(null))});for(var m=0,f=s(o);m<f.length;m++){var w=f[m];u[w]=o[w];var y=-1!==e.globalReservedProps.indexOf(w),b=n.getOwnPropertyDescriptor(o,w);"eval"===w?M():y&&c(p,w,b),b.configurable?delete o[w]:b.writable?o[w]=t:y||c(p,w,{value:t})}if(u.EventTarget)for(var x=0,v=s(u.EventTarget.prototype);x<v.length;x++)"constructor"!==(w=v[x])&&c(o,w,{value:t});p.globalThis=p,p.Function=function(){var t=r.toString,n=function(){var n=a(r,null,arguments),i=a(t,n,[]);i='with(this)return function(){"use strict";return '+(i=h(i,l,d))+"}()",e.log(i);var s=r(i),c=a(s,p,[]);return function(){return a(c,this===o?void 0:this,arguments)}};return(n.prototype=r.prototype).constructor=n,n}();var g=r("with(this)return eval(arguments[0])"),S={intrinsics:u,globalObject:p,evalInContext:g};return e.defineShadowRealmCtor(S,e),e.addEsModuleHelpers(S,e),S;function M(){var t=!1,o=function(t){return t='"use strict";undefined;'+h(t,l,d),e.log(t),p.eval=u,a(g,p,[t])};c(p,"eval",{get:function(){return t?(t=!1,u.eval):o},set:function(e){t=e===u}})}}function j(e,t){var o=e.intrinsics.eval("("+_.toString()+")")(e,t);return t.define(o,"__debug",{get:function(){return t._.debug},set:function(e){return t._.debug=e}}),o}function _(e,t){var o=e.intrinsics,r=o.Function,n=o.Promise,i=o.String,s=o.Symbol,a=o.TypeError,c=t.apply,l=t.define,d=t.getWrappedValue,h=t.isObject,u=t.replace,p=t.wrapError,m=r.toString,f=function(){if(!(this instanceof f))throw new a("Constructor requires a new operator");var o=t.createRealmRecord(e,t);l(this,"__realm",{value:o})},w=f.prototype,y=!0;return l(w,"evaluate",{configurable:y,writable:y,value:function(o){var n,i=h(this)?this.__realm:{};if(!i.intrinsics)throw new a("must be called on ShadowRealm object");if("string"!=typeof o)throw new a("evaluate expects a string");try{n=function(e,o){e=u(e,t.dynamicImportPattern,t.dynamicImportReplacer),e=c(m,r(e),[]),e='"use strict";undefined;try'+u(e,/[^{]+/,"")+"catch(e){throw{_:e}}",t.log(e);var n=o.globalObject;return n.eval=o.intrinsics,c(o.evalInContext,n,[e])}(o,i)}catch(t){throw p(t,e,y)}return d(e,n,i,t)}}),l(w,"importValue",{configurable:y,writable:y,value:function(o,r){var s=h(this)?this.__realm:{};if(!s.intrinsics)throw new a("must be called on ShadowRealm object");if(o=i(o),"string"!=typeof r)throw new a("bindingName is not string");return new n((function(n,i){s.globalObject.__import(o).then((function(i){if(!(r in i))throw new a('"'+o+'" has no export named "'+r+'"');var c=d(e,i[r],s,t);n(c)})).catch((function(t){var o=p(t,e);i(o)}))}))}}),s&&s.toStringTag&&l(w,s.toStringTag,{configurable:y,value:"ShadowRealm"}),f}var I=[],L=[],k=/(^|[^.$])(\bimport\s*(\(|\/[/*]))/g,W=/([^\s,]+)\s+as\s+([^\s,]+)/g,F=[{p:RegExp("\\bexport\\b(\\s+((var|let|const)\\s+([^;]+)|(async\\s+)?function(\\s+|\\s*\\*\\s*)([^\\s(]+)|class\\s+([^\\s{]+)|default\\s+((async\\s+)?function(\\s+|\\s*\\*\\s*)([^\\s(]+)|class\\s+([^\\s{]+)|)?)|\\s*(\\*\\s*(as\\s+(\\S+)\\s+)?from\\s*(\"[^\"]+\"|'[^']+'|`[^`]+`)|{([^}]+)}(\\s*from\\s*(\"[^\"]+\"|'[^']+'|`[^`]+`))?))|\\bimport\\b(\\s*(({([^}]+)}\\s*|\\*\\s*as\\s+(\\S+)\\s+)from\\s*)?|\\s+([^{*\"'`]+)(\\s+from|\\s*,\\s*({([^}]+)}\\s*|\\*\\s*as\\s+(\\S+)\\s+)from)\\s*)(\"[^\"]+\"|'[^']+'|`[^`]+`)","g"),r:function(e,t,o,r,n,i,s,a,c,l,d,h,u,p,m,f,w,y,b,x,v,g,S,M,E,R,P,$,C,O,T,j){if(n){for(var _=0,k=n.split(",");_<k.length;_++)k[_].replace(/^\s*([^\s={}:]+)\s*($|=|})|[:{]\s*([^\s={}:]+)\s*($|=|})/,(function(e,t,o,r){return L.push(t||r),e}));return o}if(a)return"__export={"+a+":"+a+"};"+o;if(c)return L.push(c),o;if(u)return"__default="+u+";"+l;if(p)return L.push(p),o;if(o)return o.replace(/^default/,"__default=");if(y)return I.push(y),w?"__export={"+w+":__from("+y+",__meta.url)}":"__export=__from("+y+",__meta.url)";if(v){I.push(v);var F=[];return b.replace(/([^\s,]+)(\s+as\s+([^\s,]+))?/g,(function(e,t,o,r){return F.push((r||t)+":m."+t),e})),";(function(){var m=__from("+v+",__meta.url);__export={"+F.join()+"}}())"}if(b)return"__export={"+b.replace(W,"$2:$1")+"}";if(j){I.push(j);var A="=__from("+j+",__meta.url)";return E?"const{"+E.replace(W,"$1:$2")+"}"+A:R?"var "+R+A:O?"const{"+O.replace(W,"$1:$2")+"}"+A+","+P+A+".default":T?"var "+T+A+","+P+"="+T+".default":P?"var "+P+A+".default":j}}},{p:/\bimport\.meta\b/g,r:"__meta"},{p:k,r:"$1__$2"}],A=R({addEsModuleHelpers:function(e,t){e.intrinsics.eval("("+O.toString()+")")(e,t)},createRealmRecord:function(e,t){var o=e.intrinsics.document,r=o.createElement("iframe");return r.name="ShadowRealm",o.head.appendChild(r),r.contentWindow.eval("("+T.toString()+")")(t)},createShadowRealmCtor:j,defineShadowRealmCtor:function(e,t){t.define(e.globalObject,"ShadowRealm",{configurable:!0,writable:!0,value:j(e,t)})},dynamicImportPattern:k,dynamicImportReplacer:"$1__$2",transformEsmSyntax:function(e){for(var t=0,o=F;t<o.length;t++){var r=o[t],n=r.p,i=r.r;e=e.replace(n,i)}if(L.length){for(var s=L.length-1;s>=0;--s)L[s]+=":"+L[s];e+=";__export={"+L.join()+"}",L.length=0}for(var a=[],c=(s=0,I.length);s<c;++s){var l=I[s];a.push(l.substring(1,l.length-1))}return I.length=0,[e,a]}},C),U=w.ShadowRealm||j({intrinsics:w},A);class N{constructor(t){this.type=e.SandboxType.ShadowRealm,this.active=!1,this.exports=new Map,this.name=t.name,this.options=t,this.proxy=this.createProxy(),this.resourceMonitor=i.getMonitor(this.name,{timeLimit:t.timeLimit||0,memoryLimit:t.memoryLimit||0,collectMetrics:t.enablePerformanceMeasure||!1}),this.initializeShadowRealm(t.initScript),l.register(this.name,this)}initializeShadowRealm(e){var t;try{if(this.options.forcePolyfill)this.realm=new U,console.log(`[ShadowRealmSandbox] Sandbox ${this.name} initialized with ShadowRealm polyfill (forced)`);else{if(this.options.forceIframe)return void this.usePolyfill();"function"==typeof window.ShadowRealm?(this.realm=new window.ShadowRealm,console.log(`[ShadowRealmSandbox] Sandbox ${this.name} initialized with native ShadowRealm`)):(this.realm=new U,console.log(`[ShadowRealmSandbox] Sandbox ${this.name} initialized with ShadowRealm polyfill`))}if(null===(t=this.options.security)||void 0===t?void 0:t.preventSensitiveAPIs){const e=this.generateSecuritySetupScript();this.realm.evaluate(e)}e&&this.realm.evaluate(e)}catch(e){console.error("[ShadowRealmSandbox] Initialization failed:",e),this.usePolyfill()}}generateSecuritySetupScript(){var e,t;return`\n "use strict";\n // Freeze critical prototypes to prevent prototype pollution\n Object.freeze(Object.prototype);\n Object.freeze(Array.prototype);\n Object.freeze(Function.prototype);\n \n // Restrict access to sensitive APIs if specified\n ${(null===(e=this.options.security)||void 0===e?void 0:e.preventSensitiveAPIs)?this.generateRestrictedAPIsScript():""}\n \n // Block network access if not allowed\n ${(null===(t=this.options.security)||void 0===t?void 0:t.allowNetwork)?"":this.generateNetworkBlockingScript()}\n \n // Signal successful setup\n "Security setup complete";\n `}generateRestrictedAPIsScript(){return"\n // List of properties to restrict\n const restricted = [\n 'fetch', 'XMLHttpRequest', 'WebSocket', \n 'eval', 'Function', 'setTimeout', 'setInterval',\n 'document', 'parent', 'top', 'window'\n ];\n \n // Override or delete these properties from globalThis\n restricted.forEach(prop => {\n try {\n if (prop in globalThis) {\n delete globalThis[prop];\n // For properties that can't be deleted, override them\n if (prop in globalThis) {\n globalThis[prop] = function() { \n throw new Error(\"Access to \" + prop + \" is restricted in this sandbox\"); \n };\n }\n }\n } catch (e) {\n // Ignore errors during restriction\n }\n });\n "}generateNetworkBlockingScript(){return"\n // Block network APIs\n const networkApis = ['fetch', 'XMLHttpRequest', 'WebSocket'];\n networkApis.forEach(api => {\n if (api in globalThis) {\n globalThis[api] = function() { \n throw new Error(\"Network access via \" + api + \" is restricted in this sandbox\"); \n };\n }\n });\n "}usePolyfill(){var e,t;console.warn("[ShadowRealmSandbox] Using iframe as fallback ShadowRealm implementation");const o=document.createElement("iframe");o.style.display="none",o.sandbox.add("allow-scripts"),document.body.appendChild(o);const r=o.contentWindow;if(!r)throw new Error("Failed to create iframe as ShadowRealm fallback");if(null===(e=this.options.security)||void 0===e?void 0:e.preventSensitiveAPIs)try{const e=document.createElement("script");e.textContent=this.generateSecuritySetupScript(),null===(t=o.contentDocument)||void 0===t||t.head.appendChild(e)}catch(e){console.error("[ShadowRealmSandbox] Failed to apply security restrictions to iframe:",e)}this.realm={evaluate:e=>{try{const t=this.prepareCodeForExecution(e);return this.executeWithTimeout((()=>new Function("return "+t).call(r)))}catch(e){throw console.error("[ShadowRealmSandbox] Failed to evaluate code:",e),e}},importValue:(e,t)=>(console.warn(`[ShadowRealmSandbox] importValue not fully supported: ${e}, ${t}`),r[t])},this.iframe=o}createProxy(){const e=this,t=Object.assign(Object.assign({},a()),{exportFunction:(t,o)=>e.exportFunction(t,o),importFunction:t=>e.importFunction(t)});return this.options.errorHandler&&(t.onError=this.options.errorHandler),new Proxy(t,{get:(t,o)=>o in t?t[o]:"string"==typeof o&&e.exports.has(o)?e.exports.get(o):void 0,set(t,o,r){var n;if(!e.active)return console.warn(`[ShadowRealmSandbox] Attempted to modify property "${String(o)}" when sandbox is inactive`),!0;const i=s.getDefaultRestrictedProperties();return(null===(n=e.options.security)||void 0===n?void 0:n.preventSensitiveAPIs)&&i.has(o)?(console.warn(`[ShadowRealmSandbox] Attempted to set restricted property "${String(o)}"`),!0):(t[o]=r,!0)}})}activate(){this.active=!0}deactivate(){this.active=!1}execScript(e,t){if(this.active||(console.warn(`[ShadowRealmSandbox] Sandbox ${this.name} is not active, activating before execution`),this.activate()),!this.realm)throw new Error("ShadowRealm not initialized");try{const o=this.prepareCodeForExecution(e);if((t||this.options.timeLimit||0)>0)return this.executeWithTimeout((()=>this.realm.evaluate(o)));this.resourceMonitor.start();try{return this.realm.evaluate(o)}finally{this.resourceMonitor.stop()}}catch(t){throw console.error(`[ShadowRealmSandbox] Error executing code in sandbox ${this.name}:`,t),this.options.errorHandler&&this.options.errorHandler(t,e),t}}exportFunction(e,t){this.active||(console.warn(`[ShadowRealmSandbox] Sandbox ${this.name} is not active, activating before exporting function`),this.activate()),this.exports.set(e,t);const o=`globalThis.${e} = ${t.toString()};`;this.realm.evaluate(o)}importFunction(e){this.active||(console.warn(`[ShadowRealmSandbox] Sandbox ${this.name} is not active, activating before importing function`),this.activate());try{const t=`\n (function() {\n const originalFn = globalThis.${e};\n if (typeof originalFn !== 'function') {\n throw new Error('Function ${e} not found in ShadowRealm');\n }\n return function wrapper() {\n return originalFn.apply(globalThis, arguments);\n };\n })()\n `,o=this.realm.evaluate(t);return this.exports.set(e,o),o}catch(t){throw console.error(`[ShadowRealmSandbox] Failed to import function ${e}:`,t),t}}destroy(){this.deactivate(),c.breakCircularReferences(this.proxy),this.exports.clear(),this.iframe&&(this.iframe.remove(),delete this.iframe),i.removeMonitor(this.name),l.unregister(this.name),this.realm=null}prepareCodeForExecution(e){var t;const o=e.trim().startsWith('"use strict"')||e.trim().startsWith("'use strict'")?e:`"use strict";\n${e}`;if(null===(t=this.options.security)||void 0===t?void 0:t.preventSensitiveAPIs){const e=s.validateCode(o);if(!e.safe)throw console.error("[ShadowRealmSandbox] Code validation failed:",e.issues),new Error(`Code validation failed: ${e.issues.join(", ")}`)}return o}executeWithTimeout(e){const t=this.options.timeLimit||0;if(t<=0){this.resourceMonitor.start();try{return e()}finally{this.resourceMonitor.stop()}}let o,r=!1;this.resourceMonitor.start();try{const n=setTimeout((()=>{if(!r)throw new Error(`Execution timed out after ${t}ms`)}),t);try{return o=e(),r=!0,clearTimeout(n),o}catch(e){throw clearTimeout(n),e}}finally{this.resourceMonitor.stop()}}execScriptAsync(e,o){return t(this,void 0,void 0,(function*(){if(this.active||(console.warn(`[ShadowRealmSandbox] Sandbox ${this.name} is not active, activating before execution`),this.activate()),!this.realm)throw new Error("ShadowRealm not initialized");const t=o||this.options.timeLimit||0;try{const o=this.prepareCodeForExecution(e);return yield n((()=>this.realm.evaluate(o)),t)}catch(t){throw console.error(`[ShadowRealmSandbox] Error executing code asynchronously in sandbox ${this.name}:`,t),this.options.errorHandler&&this.options.errorHandler(t,e),t}}))}}class z{constructor(t){var o;this.type=e.SandboxType.Snapshot,this.windowSnapshot=new Map,this.modifiedPropsMap=new Map,this.isolatedContext={},this.active=!1,this.name=t.name,this.options=t,this.strictMode=null===(o=t.strictMode)||void 0===o||o,this.resourceMonitor=new r(this.name,{timeLimit:t.timeLimit||0,memoryLimit:t.memoryLimit||0,collectMetrics:t.enablePerformanceMeasure||!1}),l.register(this.name,this),this.ignoreProperties=new Set(["top","window","self","globalThis","document",...s.getDefaultRestrictedProperties(),...t.ignoreProperties||[]]),this.strictMode?(s.preventPrototypePollution(),this.initIsolatedContext(),this.proxy=this.createIsolatedProxy()):this.proxy=window}initIsolatedContext(){const e=a();e.window=e,e.self=e,e.globalThis=e,Object.getOwnPropertyNames(window).forEach((t=>{if(!this.ignoreProperties.has(t)&&!(t in e)&&!t.startsWith("__"))try{const o=Object.getOwnPropertyDescriptor(window,t);if(o&&o.get)return;e[t]=window[t]}catch(e){console.warn(`[SnapshotSandbox] Cannot copy window property: ${String(t)}`,e)}})),this.isolatedContext=e}createIsolatedProxy(){const e=this;return new Proxy(this.isolatedContext,{get:(e,t)=>t in e?e[t]:window[t],set:(t,o,r)=>!e.active||(t[o]=r,e.modifiedPropsMap.set(o,r),!0),deleteProperty:(t,o)=>!e.active||(o in t&&(delete t[o],e.modifiedPropsMap.set(o,void 0)),!0),has:(e,t)=>t in e||t in window,getOwnPropertyDescriptor:(e,t)=>t in e?Object.getOwnPropertyDescriptor(e,t):Object.getOwnPropertyDescriptor(window,t),defineProperty:(t,o,r)=>!e.active||(Object.defineProperty(t,o,r),e.modifiedPropsMap.set(o,r.value),!0),ownKeys:e=>Reflect.ownKeys(e)})}activate(){this.active||(this.strictMode||(this.windowSnapshot=this.takeWindowSnapshot(),this.restoreSandboxSnapshot()),this.active=!0)}deactivate(){this.active&&(this.strictMode||(this.recordWindowSnapshot(),this.restoreWindowSnapshot()),this.active=!1)}execScript(e,t){var o,r;const n=this.active;n||this.activate(),this.resourceMonitor.start();try{if(null===(o=this.options)||void 0===o?void 0:o.validateCode){const t=s.validateCode(e);if(!t.safe)throw new d(`Code validation failed: ${t.issues.join(", ")}`,new Error("Security validation error"),this.name,e)}if(t&&t>0)return this.execScriptWithTimeout(e,t);if(this.strictMode){const t=s.getSecureFunction()("window","self","globalThis",`\n "use strict";\n with (window) {\n return (function() {\n ${e}\n }).call(window);\n }\n `);return u((()=>t.call(this.proxy,this.proxy,this.proxy,this.proxy)),this.name,e)}{const t=new Function("window","self","globalThis",`\n "use strict";\n return (function() {\n ${e}\n }).call(window);\n `);return u((()=>t.call(window,window,window,window)),this.name,e)}}catch(t){const o=h(t,this.name,e);throw console.error(`[SnapshotSandbox] Error executing code in sandbox ${this.name}:`,o),"function"==typeof(null===(r=this.options)||void 0===r?void 0:r.errorHandler)&&this.options.errorHandler(o,e),o}finally{const e=this.resourceMonitor.stop();e.exceededLimits&&console.warn(`[SnapshotSandbox] Resource limits exceeded in sandbox ${this.name}: \n Execution time: ${e.executionTime}ms, \n Memory usage: ${e.memoryUsage} bytes`),n||this.deactivate()}}execScriptAsync(e,o){var r,i;return t(this,void 0,void 0,(function*(){const a=this.active;a||this.activate(),this.resourceMonitor.start();try{if(null===(r=this.options)||void 0===r?void 0:r.validateCode){const t=s.validateCode(e);if(!t.safe)throw new d(`Code validation failed: ${t.issues.join(", ")}`,new Error("Security validation error"),this.name,e)}const i=Object.getPrototypeOf((function(){return t(this,void 0,void 0,(function*(){}))})).constructor,a=`\n "use strict";\n return (async function() {\n try {\n return await (async () => {\n ${e}\n })();\n } catch (error) {\n // Ensure errors are properly propagated\n throw error;\n }\n }).call(this);\n `;if(o&&o>0)return yield n((()=>t(this,void 0,void 0,(function*(){if(this.strictMode){const e=new i("window","self","globalThis",a);return yield e.call(this.proxy,this.proxy,this.proxy,this.proxy)}{const e=new i("window","self","globalThis",a);return yield e.call(window,window,window,window)}}))),o);if(this.strictMode){const e=new i("window","self","globalThis",a);return yield e.call(this.proxy,this.proxy,this.proxy,this.proxy)}{const e=new i("window","self","globalThis",a);return yield e.call(window,window,window,window)}}catch(t){const o=h(t,this.name,e);throw console.error(`[SnapshotSandbox] Error executing async code in sandbox ${this.name}:`,o),"function"==typeof(null===(i=this.options)||void 0===i?void 0:i.errorHandler)&&this.options.errorHandler(o,e),o}finally{const e=this.resourceMonitor.stop();e.exceededLimits&&console.warn(`[SnapshotSandbox] Resource limits exceeded in sandbox ${this.name}: \n Execution time: ${e.executionTime}ms, \n Memory usage: ${e.memoryUsage} bytes`),a||this.deactivate()}}))}execScriptWithTimeout(e,t){return n((()=>{if(this.strictMode){return new Function("window","self","globalThis",`\n with (window) {\n return (function() {\n "use strict";\n ${e}\n }).call(window);\n }\n `).call(this.proxy,this.proxy,this.proxy,this.proxy)}return new Function("window","self","globalThis",`\n "use strict";\n return (function() {\n ${e}\n }).call(window);\n `).call(window,window,window,window)}),t)}destroy(){this.active&&this.deactivate(),this.resourceMonitor&&this.resourceMonitor.reset(),l.unregister(this.name),this.windowSnapshot.clear(),this.modifiedPropsMap.clear(),this.strictMode&&(c.breakCircularReferences(this.isolatedContext),Object.keys(this.isolatedContext).forEach((e=>{"window"!==e&&"self"!==e&&"globalThis"!==e&&delete this.isolatedContext[e]})),this.isolatedContext.window=null,this.isolatedContext.self=null,this.isolatedContext.globalThis=null),console.log(`[SnapshotSandbox] Sandbox ${this.name} destroyed`)}takeWindowSnapshot(){const e=new Map;return Object.getOwnPropertyNames(window).forEach((t=>{this.ignoreProperties.has(t)||e.set(t,window[t])})),e}recordWindowSnapshot(){const e=window;this.windowSnapshot.forEach(((t,o)=>{e[o]!==t&&this.modifiedPropsMap.set(o,e[o])})),Object.getOwnPropertyNames(e).forEach((t=>{this.ignoreProperties.has(t)||this.windowSnapshot.has(t)||this.modifiedPropsMap.set(t,e[t])}))}restoreWindowSnapshot(){this.modifiedPropsMap.forEach(((e,t)=>{this.windowSnapshot.has(t)?window[t]=this.windowSnapshot.get(t):delete window[t]}))}restoreSandboxSnapshot(){this.modifiedPropsMap.forEach(((e,t)=>{window[t]=e}))}}const D=new class{constructor(){this.listeners=new Map}addEventListener(e,t,o,r,n){t.addEventListener.call(t,o,r,n),this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push({target:t,type:o,listener:r,options:n})}removeEventListener(e,t,o,r,n){if(t.removeEventListener.call(t,o,r,n),this.listeners.has(e)){const n=this.listeners.get(e),i=n.findIndex((e=>e.target===t&&e.type===o&&e.listener===r));-1!==i&&n.splice(i,1)}}clearAllEventListeners(e){if(!this.listeners.has(e))return;this.listeners.get(e).forEach((({target:e,type:t,listener:o,options:r})=>{e.removeEventListener(t,o,r)})),this.listeners.delete(e)}destroy(){for(const e of this.listeners.keys())this.clearAllEventListeners(e);this.listeners.clear()}};const H=new class{constructor(){this.measures=new Map,this.enabled=!1}enable(){this.enabled=!0}disable(){this.enabled=!1}measure(e,t,o){if(!this.enabled)return o();const r=performance.now(),n=o(),i=performance.now()-r;return this.recordMeasure(e,t,i),n}recordMeasure(e,t,o){this.measures.has(t)||this.measures.set(t,[]),this.measures.get(t).push({name:e,duration:o,timestamp:Date.now()})}getMeasures(e){if(e)return{category:e,measures:this.measures.get(e)||[]};const t={};return this.measures.forEach(((e,o)=>{t[o]=e})),t}getAverageDuration(e,t){const o=this.measures.get(e);if(!o||0===o.length)return 0;const r=t?o.filter((e=>e.name===t)):o;if(0===r.length)return 0;const n=r.reduce(((e,t)=>e+t.duration),0);return n/r.length}clearMeasures(e){e?this.measures.delete(e):this.measures.clear()}};const B=new class{constructor(){this.modules=new Map,this.moduleCache=new Map}loadModule(e){return t(this,void 0,void 0,(function*(){if(this.moduleCache.has(e))return this.moduleCache.get(e);const t=this.fetchAndEvaluateModule(e);return this.moduleCache.set(e,t),t}))}registerModule(e,t){this.modules.set(e,t)}getModule(e){return this.modules.get(e)}clearModules(){this.modules.clear(),this.moduleCache.clear()}fetchAndEvaluateModule(e){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(e);if(!t.ok)throw new Error(`Failed to load module: ${e}, status: ${t.status}`);const o=yield t.text(),r=new Blob([o],{type:"text/javascript"}),n=URL.createObjectURL(r);try{const t=yield import(n),o=this.extractModuleName(e);return this.registerModule(o,t),t}finally{URL.revokeObjectURL(n)}}catch(t){throw console.error(`[ESModuleLoader] Failed to load module ${e}:`,t),t}}))}extractModuleName(e){const t=e.split("?")[0].split("#")[0].split("/");return t[t.length-1].replace(/\.[^/.]+$/,"")}};function V(t,o){const r=Object.assign(Object.assign({strictMode:!0,validateCode:!0,timeLimit:1e4,memoryLimit:0},o),{security:Object.assign({preventPrototypePollution:!0,preventSensitiveAPIs:!0,logViolations:!0},o.security||{})});switch(t){case e.SandboxType.Proxy:return new p(r);case e.SandboxType.WithEval:return new m(r);case e.SandboxType.ShadowRealm:return new N(r);case e.SandboxType.Snapshot:return new z(r);default:throw new Error(`Unsupported sandbox type: ${t}`)}}const q=()=>{if("function"==typeof window.ShadowRealm)return!0;try{return"function"==typeof globalThis.ShadowRealm}catch(e){return!1}};e.MemoryManager=c,e.ProxySandbox=p,e.ResourceMonitor=r,e.SandboxError=d,e.SecurityHelper=s,e.ShadowRealmSandbox=N,e.SnapshotSandbox=z,e.WithEvalSandbox=m,e.createSandbox=V,e.default=V,e.eventManager=D,e.executeWithTimeout=n,e.formatError=h,e.getBestSandboxType=()=>q()?e.SandboxType.ShadowRealm:e.SandboxType.Proxy,e.getDefaultSandboxGlobals=a,e.isShadowRealmSupported=q,e.memoryManager=l,e.moduleLoader=B,e.performanceMeasure=H,e.resourceLimiter=i,e.wrapExecution=u,Object.defineProperty(e,"__esModule",{value:!0})}));