/**
 * 基于 Proxy 的沙箱实现
 *
 * 这个模块提供了一个安全的代码执行环境，通过 Proxy 劫持全局对象的访问，
 * 防止恶意代码对宿主环境造成破坏，同时提供受控的 API 访问。
 *
 * 主要特性：
 * - 全局对象隔离
 * - API 访问控制
 * - 内存管理
 * - 错误捕获和处理
 * - 执行超时控制
 *
 * @author md-editor
 * @version 1.0.0
 */ /**
 * 沙箱配置接口
 */ function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _array_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _async_to_generator(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
function _class_call_check(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
    }
}
function _defineProperties(target, props) {
    for(var i = 0; i < props.length; i++){
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor) descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
    }
}
function _create_class(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _instanceof(left, right) {
    if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
        return !!right[Symbol.hasInstance](left);
    } else {
        return left instanceof right;
    }
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _non_iterable_spread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
function _ts_generator(thisArg, body) {
    var f, y, t, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
    return d(g, "next", {
        value: verb(0)
    }), d(g, "throw", {
        value: verb(1)
    }), d(g, "return", {
        value: verb(2)
    }), typeof Symbol === "function" && d(g, Symbol.iterator, {
        value: function() {
            return this;
        }
    }), g;
    function verb(n) {
        return function(v) {
            return step([
                n,
                v
            ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while(g && (g = 0, op[0] && (_ = 0)), _)try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [
                op[0] & 2,
                t.value
            ];
            switch(op[0]){
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [
                        0
                    ];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
}
/**
 * 默认的危险全局对象列表
 */ // 危险的全局变量（完全禁止访问）
var DANGEROUS_GLOBALS = [
    'eval',
    'Function',
    'constructor',
    '__proto__',
    'prototype',
    'global',
    'globalThis',
    'self',
    'parent',
    'top',
    'frames',
    'location',
    'history',
    'navigator',
    'screen',
    'localStorage',
    'sessionStorage',
    'indexedDB',
    'WebSocket',
    'XMLHttpRequest',
    'fetch',
    'Request',
    'Response',
    'Headers',
    'URL',
    'URLSearchParams',
    'Blob',
    'File',
    'FileReader',
    'FormData',
    'Worker',
    'SharedWorker',
    'ServiceWorker',
    'MessageChannel',
    'MessagePort',
    'BroadcastChannel',
    'WebRTC',
    'MediaStream',
    'process',
    'require',
    'module',
    'exports',
    'Buffer',
    'global',
    'setImmediate',
    'clearImmediate',
    'setInterval',
    'clearInterval',
    'setTimeout',
    'clearTimeout',
    'queueMicrotask',
    'requestAnimationFrame',
    'cancelAnimationFrame',
    'requestIdleCallback',
    'cancelIdleCallback',
    'crypto',
    'SubtleCrypto',
    'performance',
    'PerformanceObserver',
    'IntersectionObserver',
    'MutationObserver',
    'ResizeObserver',
    'AbortController',
    'AbortSignal',
    'EventSource',
    'CloseEvent',
    'CustomEvent',
    'ErrorEvent',
    'Event',
    'EventTarget',
    'MessageEvent',
    'ProgressEvent',
    'PromiseRejectionEvent',
    'alert',
    'confirm',
    'prompt',
    'open',
    'close',
    'print',
    'focus',
    'blur',
    'getSelection',
    'getComputedStyle',
    'matchMedia',
    'moveBy',
    'moveTo',
    'resizeBy',
    'resizeTo',
    'scroll',
    'scrollBy',
    'scrollTo',
    'stop',
    'Notification',
    'webkitNotifications',
    'external',
    'chrome',
    'safari',
    'opera',
    'moz'
];
/**
 * 安全的全局对象列表
 */ var SAFE_GLOBALS = [
    'console',
    'setTimeout',
    'setInterval',
    'clearTimeout',
    'clearInterval',
    'Math',
    'Date',
    'JSON',
    'parseInt',
    'parseFloat',
    'isNaN',
    'isFinite',
    'encodeURIComponent',
    'decodeURIComponent',
    'encodeURI',
    'decodeURI',
    'String',
    'Number',
    'Boolean',
    'Array',
    'Object',
    'RegExp',
    'Error',
    'TypeError',
    'ReferenceError',
    'SyntaxError'
];
/**
 * 基于 Proxy 的沙箱类
 */ export var ProxySandbox = /*#__PURE__*/ function() {
    "use strict";
    function ProxySandbox() {
        var config = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
        _class_call_check(this, ProxySandbox);
        var _config_allowConsole, _config_allowTimers, _config_strictMode, _config_allowDOM;
        _define_property(this, "config", void 0);
        _define_property(this, "globalProxy", void 0);
        _define_property(this, "sandboxGlobal", void 0);
        _define_property(this, "isActive", false);
        _define_property(this, "timeoutId", null);
        _define_property(this, "startTime", 0);
        this.config = {
            allowedGlobals: config.allowedGlobals || SAFE_GLOBALS,
            forbiddenGlobals: config.forbiddenGlobals || DANGEROUS_GLOBALS,
            allowConsole: (_config_allowConsole = config.allowConsole) !== null && _config_allowConsole !== void 0 ? _config_allowConsole : true,
            allowTimers: (_config_allowTimers = config.allowTimers) !== null && _config_allowTimers !== void 0 ? _config_allowTimers : true,
            timeout: config.timeout || 5000,
            strictMode: (_config_strictMode = config.strictMode) !== null && _config_strictMode !== void 0 ? _config_strictMode : true,
            customGlobals: config.customGlobals || {},
            allowDOM: (_config_allowDOM = config.allowDOM) !== null && _config_allowDOM !== void 0 ? _config_allowDOM : false,
            maxMemoryUsage: config.maxMemoryUsage || 10 * 1024 * 1024
        };
        this.sandboxGlobal = this.createSandboxGlobal();
        this.globalProxy = this.createGlobalProxy();
    }
    _create_class(ProxySandbox, [
        {
            key: "createSafeDocument",
            value: /**
   * 创建安全的 document 代理对象
   * 允许访问 document 但限制敏感操作
   */ function createSafeDocument() {
                // 创建基础的安全 document 对象
                var safeDocument = {};
                // 安全的只读属性
                safeDocument.title = 'Sandbox Document';
                safeDocument.readyState = 'complete';
                safeDocument.documentURI = 'about:blank';
                safeDocument.URL = 'about:blank';
                safeDocument.domain = '';
                safeDocument.origin = 'null';
                // 安全的文档信息
                safeDocument.doctype = null;
                safeDocument.documentElement = null;
                safeDocument.body = null;
                safeDocument.head = null;
                // 模拟安全的 cookie（空）
                Object.defineProperty(safeDocument, 'cookie', {
                    get: function get() {
                        return '';
                    },
                    set: function set() {},
                    enumerable: true,
                    configurable: false
                });
                // 提供安全的查询方法（返回 null 或空结果）
                safeDocument.getElementById = function() {
                    return null;
                };
                safeDocument.getElementsByClassName = function() {
                    return [];
                };
                safeDocument.getElementsByTagName = function() {
                    return [];
                };
                safeDocument.getElementsByName = function() {
                    return [];
                };
                safeDocument.querySelector = function() {
                    return null;
                };
                safeDocument.querySelectorAll = function() {
                    return [];
                };
                // 提供安全的创建方法（返回模拟元素）
                safeDocument.createElement = function(tagName) {
                    return {
                        tagName: tagName.toUpperCase(),
                        id: '',
                        className: '',
                        innerHTML: '',
                        textContent: '',
                        setAttribute: function setAttribute() {},
                        getAttribute: function getAttribute() {
                            return null;
                        },
                        removeAttribute: function removeAttribute() {},
                        appendChild: function appendChild() {},
                        removeChild: function removeChild() {},
                        addEventListener: function addEventListener() {},
                        removeEventListener: function removeEventListener() {}
                    };
                };
                safeDocument.createTextNode = function(data) {
                    return {
                        nodeType: 3,
                        textContent: data,
                        data: data
                    };
                };
                safeDocument.createDocumentFragment = function() {
                    return {
                        nodeType: 11,
                        appendChild: function appendChild() {},
                        querySelector: function querySelector() {
                            return null;
                        },
                        querySelectorAll: function querySelectorAll() {
                            return [];
                        }
                    };
                };
                // 创建代理来拦截其他属性访问
                return new Proxy(safeDocument, {
                    get: function get(target, prop, receiver) {
                        var propStr = String(prop);
                        // 阻止访问危险属性
                        var dangerousDocumentProps = [
                            'location',
                            'defaultView',
                            'parentWindow',
                            'implementation',
                            'documentURI',
                            'execCommand',
                            'write',
                            'writeln',
                            'open',
                            'close',
                            'evaluate',
                            'createRange',
                            'getSelection',
                            'elementsFromPoint',
                            'elementFromPoint',
                            'hasFocus',
                            'hidden',
                            'visibilityState'
                        ];
                        if (dangerousDocumentProps.includes(propStr)) {
                            return undefined;
                        }
                        // 对于已定义的安全属性，返回实际值
                        if (propStr in target) {
                            return Reflect.get(target, prop, receiver);
                        }
                        // 对于其他属性，返回 undefined
                        return undefined;
                    },
                    set: function set(target, prop, value, receiver) {
                        var propStr = String(prop);
                        // 阻止设置敏感属性
                        var readOnlyProps = [
                            'title',
                            'readyState',
                            'documentURI',
                            'URL',
                            'domain',
                            'origin'
                        ];
                        if (readOnlyProps.includes(propStr)) {
                            return false; // 静默失败
                        }
                        // 允许设置其他属性（在沙箱对象内）
                        return Reflect.set(target, prop, value, receiver);
                    },
                    has: function has(target, prop) {
                        var propStr = String(prop);
                        // 危险属性始终返回 false
                        var dangerousDocumentProps = [
                            'location',
                            'defaultView',
                            'parentWindow',
                            'implementation',
                            'execCommand',
                            'write',
                            'writeln',
                            'open',
                            'close'
                        ];
                        if (dangerousDocumentProps.includes(propStr)) {
                            return false;
                        }
                        return Reflect.has(target, prop);
                    }
                });
            }
        },
        {
            key: "createSafeWindow",
            value: /**
   * 创建安全的 window 代理对象
   * 允许访问 window 但限制敏感信息
   */ function createSafeWindow(safeDocument) {
                // 敏感属性列表（将被设置为空或限制访问）
                var sensitiveProperties = [
                    'cookie',
                    'localStorage',
                    'sessionStorage',
                    'indexedDB',
                    'location',
                    'history',
                    'navigator',
                    'parent',
                    'top',
                    'frames',
                    'opener',
                    'external',
                    'chrome',
                    'safari',
                    'opera',
                    'moz'
                ];
                // 创建基础的安全对象
                var safeWindow = {};
                // 如果在浏览器环境中，添加一些安全的 window 属性
                if (typeof window !== 'undefined') {
                    // 添加安全的尺寸信息
                    safeWindow.innerWidth = 1024; // 默认值
                    safeWindow.innerHeight = 768;
                    safeWindow.outerWidth = 1024;
                    safeWindow.outerHeight = 768;
                    safeWindow.devicePixelRatio = 1;
                    // 添加安全的 screen 信息（静态值）
                    safeWindow.screen = {
                        width: 1920,
                        height: 1080,
                        availWidth: 1920,
                        availHeight: 1040,
                        colorDepth: 24,
                        pixelDepth: 24
                    };
                }
                // 添加标准的 JavaScript 全局对象
                safeWindow.Array = Array;
                safeWindow.Object = Object;
                safeWindow.String = String;
                safeWindow.Number = Number;
                safeWindow.Boolean = Boolean;
                safeWindow.Date = Date;
                safeWindow.Math = Math;
                safeWindow.JSON = JSON;
                safeWindow.RegExp = RegExp;
                safeWindow.Error = Error;
                safeWindow.TypeError = TypeError;
                safeWindow.ReferenceError = ReferenceError;
                safeWindow.SyntaxError = SyntaxError;
                safeWindow.parseInt = parseInt;
                safeWindow.parseFloat = parseFloat;
                safeWindow.isNaN = isNaN;
                safeWindow.isFinite = isFinite;
                safeWindow.encodeURIComponent = encodeURIComponent;
                safeWindow.decodeURIComponent = decodeURIComponent;
                safeWindow.encodeURI = encodeURI;
                safeWindow.decodeURI = decodeURI;
                // 添加安全的 document 对象（使用传入的或创建新的）
                safeWindow.document = safeDocument || this.createSafeDocument();
                // 提供安全的控制台（如果允许）
                if (this.config.allowConsole) {
                    safeWindow.console = {
                        log: console.log.bind(console),
                        warn: console.warn.bind(console),
                        error: console.error.bind(console),
                        info: console.info.bind(console),
                        debug: console.debug.bind(console)
                    };
                }
                // 创建代理来拦截属性访问
                return new Proxy(safeWindow, {
                    get: function get(target, prop, receiver) {
                        var propStr = String(prop);
                        // 检查是否是敏感属性
                        if (sensitiveProperties.includes(propStr)) {
                            // 为敏感属性返回空或安全的默认值
                            switch(propStr){
                                case 'cookie':
                                    return ''; // 空 cookie
                                case 'localStorage':
                                case 'sessionStorage':
                                    // 返回一个模拟的空存储对象
                                    return {
                                        length: 0,
                                        getItem: function getItem() {
                                            return null;
                                        },
                                        setItem: function setItem() {},
                                        removeItem: function removeItem() {},
                                        clear: function clear() {},
                                        key: function key() {
                                            return null;
                                        }
                                    };
                                case 'location':
                                    return {
                                        href: 'about:blank',
                                        origin: 'null',
                                        protocol: 'about:',
                                        host: '',
                                        hostname: '',
                                        port: '',
                                        pathname: 'blank',
                                        search: '',
                                        hash: ''
                                    };
                                case 'navigator':
                                    return {
                                        userAgent: 'Sandbox/1.0',
                                        language: 'en-US',
                                        languages: [
                                            'en-US'
                                        ],
                                        platform: 'Sandbox',
                                        cookieEnabled: false,
                                        onLine: true
                                    };
                                default:
                                    return undefined;
                            }
                        }
                        // 对于安全属性，返回实际值
                        if (propStr in target) {
                            return Reflect.get(target, prop, receiver);
                        }
                        // 对于其他属性，返回 undefined
                        return undefined;
                    },
                    set: function set(target, prop, value, receiver) {
                        var propStr = String(prop);
                        // 禁止设置敏感属性
                        if (sensitiveProperties.includes(propStr)) {
                            return false; // 静默失败
                        }
                        // 允许设置其他属性（在沙箱对象内）
                        return Reflect.set(target, prop, value, receiver);
                    },
                    has: function has(target, prop) {
                        var propStr = String(prop);
                        // 敏感属性始终返回 false
                        if (sensitiveProperties.includes(propStr)) {
                            return false;
                        }
                        return Reflect.has(target, prop);
                    },
                    ownKeys: function ownKeys(target) {
                        // 只返回安全属性的键
                        var allKeys = Reflect.ownKeys(target);
                        return allKeys.filter(function(key) {
                            return !sensitiveProperties.includes(String(key));
                        });
                    },
                    getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, prop) {
                        var propStr = String(prop);
                        if (sensitiveProperties.includes(propStr)) {
                            return undefined;
                        }
                        return Reflect.getOwnPropertyDescriptor(target, prop);
                    }
                });
            }
        },
        {
            key: "createSandboxGlobal",
            value: /**
   * 创建安全的沙箱全局对象
   */ function createSandboxGlobal() {
                var sandboxGlobal = {};
                var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                try {
                    // 添加允许的全局对象
                    for(var _iterator = this.config.allowedGlobals[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                        var globalName = _step.value;
                        if (globalName in globalThis) {
                            sandboxGlobal[globalName] = globalThis[globalName];
                        }
                    }
                } catch (err) {
                    _didIteratorError = true;
                    _iteratorError = err;
                } finally{
                    try {
                        if (!_iteratorNormalCompletion && _iterator.return != null) {
                            _iterator.return();
                        }
                    } finally{
                        if (_didIteratorError) {
                            throw _iteratorError;
                        }
                    }
                }
                // 添加自定义全局变量
                Object.assign(sandboxGlobal, this.config.customGlobals);
                // 创建安全的 document 对象（确保只创建一次）
                var safeDocument = this.createSafeDocument();
                // 添加安全的 window 对象（总是可用）
                var safeWindow = this.createSafeWindow(safeDocument);
                sandboxGlobal.window = safeWindow;
                // 添加安全的 document 对象（总是可用）
                sandboxGlobal.document = safeDocument;
                // 条件性添加 console
                if (this.config.allowConsole) {
                    sandboxGlobal.console = this.createSafeConsole();
                }
                // 条件性添加定时器
                if (this.config.allowTimers) {
                    sandboxGlobal.setTimeout = this.createSafeTimeout();
                    sandboxGlobal.setInterval = this.createSafeInterval();
                    sandboxGlobal.clearTimeout = clearTimeout;
                    sandboxGlobal.clearInterval = clearInterval;
                }
                // 添加指令检查函数（用于超时控制）
                sandboxGlobal.__checkInstructions = function() {
                // 这个函数会在 executeWithInstructionLimit 中被替换
                };
                return sandboxGlobal;
            }
        },
        {
            key: "createSafeConsole",
            value: /**
   * 创建安全的 console 对象
   */ function createSafeConsole() {
                var _console, _console1, _console2, _console3, _console4;
                return {
                    log: function log() {
                        for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
                            args[_key] = arguments[_key];
                        }
                        return (_console = console).log.apply(_console, [
                            '[Sandbox]'
                        ].concat(_to_consumable_array(args)));
                    },
                    warn: function warn() {
                        for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
                            args[_key] = arguments[_key];
                        }
                        return (_console1 = console).warn.apply(_console1, [
                            '[Sandbox]'
                        ].concat(_to_consumable_array(args)));
                    },
                    error: function error() {
                        for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
                            args[_key] = arguments[_key];
                        }
                        return (_console2 = console).error.apply(_console2, [
                            '[Sandbox]'
                        ].concat(_to_consumable_array(args)));
                    },
                    info: function info() {
                        for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
                            args[_key] = arguments[_key];
                        }
                        return (_console3 = console).info.apply(_console3, [
                            '[Sandbox]'
                        ].concat(_to_consumable_array(args)));
                    },
                    debug: function debug() {
                        for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
                            args[_key] = arguments[_key];
                        }
                        return (_console4 = console).debug.apply(_console4, [
                            '[Sandbox]'
                        ].concat(_to_consumable_array(args)));
                    }
                };
            }
        },
        {
            key: "createSafeTimeout",
            value: /**
   * 创建安全的 setTimeout
   */ function createSafeTimeout() {
                return function(callback, delay) {
                    for(var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++){
                        args[_key - 2] = arguments[_key];
                    }
                    if (typeof callback !== 'function') {
                        throw new TypeError('Callback must be a function');
                    }
                    var safeCallback = function safeCallback() {
                        try {
                            callback.apply(null, args);
                        } catch (error) {
                            console.error('[Sandbox] Timer callback error:', error);
                        }
                    };
                    return setTimeout(safeCallback, Math.min(delay, 1000)); // 最大延迟1秒
                };
            }
        },
        {
            key: "createSafeInterval",
            value: /**
   * 创建安全的 setInterval
   */ function createSafeInterval() {
                return function(callback, delay) {
                    for(var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++){
                        args[_key - 2] = arguments[_key];
                    }
                    if (typeof callback !== 'function') {
                        throw new TypeError('Callback must be a function');
                    }
                    var safeCallback = function safeCallback() {
                        try {
                            callback.apply(null, args);
                        } catch (error) {
                            console.error('[Sandbox] Interval callback error:', error);
                        }
                    };
                    return setInterval(safeCallback, Math.max(delay, 100)); // 最小间隔100ms
                };
            }
        },
        {
            key: "createGlobalProxy",
            value: /**
   * 创建全局对象的 Proxy
   */ function createGlobalProxy() {
                var _this = this;
                return new Proxy(this.sandboxGlobal, {
                    get: function get(target, prop, receiver) {
                        var propStr = String(prop);
                        // 检查是否在禁止列表中
                        if (_this.config.forbiddenGlobals.includes(propStr)) {
                            throw new ReferenceError("Access to '".concat(propStr, "' is not allowed in sandbox"));
                        }
                        // 允许访问内部功能函数
                        if (propStr === '__checkInstructions') {
                            return Reflect.get(target, prop, receiver);
                        }
                        // 检查是否在允许列表中
                        if (_this.config.allowedGlobals.includes(propStr)) {
                            if (propStr in target) {
                                return Reflect.get(target, prop, receiver);
                            }
                            // 某些特殊的全局对象需要特殊处理
                            if (propStr === 'window' || propStr === 'global' || propStr === 'globalThis') {
                                return receiver; // 返回代理对象本身
                            }
                        }
                        // 检查自定义全局变量
                        if (propStr in _this.config.customGlobals) {
                            return Reflect.get(target, prop, receiver);
                        }
                        // 如果不在任何允许的列表中，返回 undefined
                        return undefined;
                    },
                    set: function set(target, prop, value, receiver) {
                        var propStr = String(prop);
                        // 检查是否在禁止列表中
                        if (_this.config.forbiddenGlobals.includes(propStr)) {
                            throw new ReferenceError("Setting '".concat(propStr, "' is not allowed in sandbox"));
                        }
                        // 只允许设置已存在的属性或新的变量
                        return Reflect.set(target, prop, value, receiver);
                    },
                    has: function has(target, prop) {
                        var propStr = String(prop);
                        // 如果在禁止列表中，返回 false
                        if (_this.config.forbiddenGlobals.includes(propStr)) {
                            return false;
                        }
                        // 如果在允许列表中或目标对象中，返回 true
                        return _this.config.allowedGlobals.includes(propStr) || Reflect.has(target, prop);
                    },
                    ownKeys: function ownKeys(target) {
                        // 只返回允许的属性键
                        var allKeys = Reflect.ownKeys(target);
                        return allKeys.filter(function(key) {
                            return !_this.config.forbiddenGlobals.includes(String(key));
                        });
                    },
                    getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, prop) {
                        var propStr = String(prop);
                        if (_this.config.forbiddenGlobals.includes(propStr)) {
                            return undefined;
                        }
                        return Reflect.getOwnPropertyDescriptor(target, prop);
                    }
                });
            }
        },
        {
            key: "execute",
            value: /**
   * 在沙箱中执行代码
   */ function execute(code, injectedParams) {
                return _async_to_generator(function() {
                    var result, error, success, err, executionTime;
                    return _ts_generator(this, function(_state) {
                        switch(_state.label){
                            case 0:
                                this.startTime = performance.now();
                                this.isActive = true;
                                success = false;
                                _state.label = 1;
                            case 1:
                                _state.trys.push([
                                    1,
                                    8,
                                    9,
                                    10
                                ]);
                                if (!(typeof Worker !== 'undefined' && typeof URL !== 'undefined')) return [
                                    3,
                                    3
                                ];
                                return [
                                    4,
                                    this.executeWithWorker(code, injectedParams)
                                ];
                            case 2:
                                result = _state.sent();
                                return [
                                    3,
                                    7
                                ];
                            case 3:
                                if (!this.isObviousInfiniteLoop(code)) return [
                                    3,
                                    5
                                ];
                                return [
                                    4,
                                    this.executeWithInstructionLimit(code, injectedParams)
                                ];
                            case 4:
                                // 只对明显的死循环使用指令计数
                                result = _state.sent();
                                return [
                                    3,
                                    7
                                ];
                            case 5:
                                return [
                                    4,
                                    this.executeWithTimeout(code, injectedParams)
                                ];
                            case 6:
                                // 对正常代码直接执行，但有超时保护
                                result = _state.sent();
                                _state.label = 7;
                            case 7:
                                success = true;
                                return [
                                    3,
                                    10
                                ];
                            case 8:
                                err = _state.sent();
                                error = _instanceof(err, Error) ? err : new Error(String(err));
                                success = false;
                                return [
                                    3,
                                    10
                                ];
                            case 9:
                                this.cleanup();
                                return [
                                    7
                                ];
                            case 10:
                                executionTime = performance.now() - this.startTime;
                                return [
                                    2,
                                    {
                                        result: result,
                                        success: success,
                                        error: error,
                                        executionTime: executionTime,
                                        memoryUsage: this.getMemoryUsage()
                                    }
                                ];
                        }
                    });
                }).call(this);
            }
        },
        {
            key: "isObviousInfiniteLoop",
            value: /**
   * 检查是否是明显的死循环
   */ function isObviousInfiniteLoop(code) {
                // 简单的模式匹配检测明显的死循环
                var infiniteLoopPatterns = [
                    /while\s*\(\s*true\s*\)/,
                    /for\s*\(\s*;\s*;\s*\)/,
                    /while\s*\(\s*1\s*\)/,
                    /while\s*\(\s*!false\s*\)/,
                    /do\s*\{[^}]*\}\s*while\s*\(\s*true\s*\)/,
                    /do\s*\{[^}]*\}\s*while\s*\(\s*1\s*\)/
                ];
                return infiniteLoopPatterns.some(function(pattern) {
                    return pattern.test(code);
                });
            }
        },
        {
            key: "executeWithTimeout",
            value: /**
   * 带超时的普通执行
   * 注意：对于同步死循环，setTimeout 无法中断，需要使用 Worker 或指令计数
   * 这个方法只适用于不包含死循环的代码
   */ function executeWithTimeout(code, injectedParams) {
                return _async_to_generator(function() {
                    var _this;
                    return _ts_generator(this, function(_state) {
                        _this = this;
                        return [
                            2,
                            new Promise(function(resolve, reject) {
                                var timeoutId = setTimeout(function() {
                                    reject(new Error("Code execution timeout after ".concat(_this.config.timeout, "ms")));
                                }, _this.config.timeout);
                                try {
                                    var result = _this.executeCode(code, injectedParams);
                                    clearTimeout(timeoutId);
                                    resolve(result);
                                } catch (error) {
                                    clearTimeout(timeoutId);
                                    reject(error);
                                }
                            })
                        ];
                    });
                }).call(this);
            }
        },
        {
            key: "executeWithInstructionLimit",
            value: /**
   * 使用指令计数限制执行时间
   * 这是处理同步死循环的唯一方法（在不使用 Worker 的情况下）
   */ function executeWithInstructionLimit(code, injectedParams) {
                return _async_to_generator(function() {
                    var _this;
                    return _ts_generator(this, function(_state) {
                        _this = this;
                        return [
                            2,
                            new Promise(function(resolve, reject) {
                                var maxInstructions = 10000; // 降低最大指令数，更快检测死循环
                                var instructionCount = 0;
                                var startTime = performance.now();
                                var timeoutId = null;
                                // 注入指令计数器
                                var instrumentedCode = _this.instrumentCode(code);
                                // 创建全局计数器函数
                                var originalGlobal = _this.sandboxGlobal.__checkInstructions;
                                _this.sandboxGlobal.__checkInstructions = function() {
                                    instructionCount++;
                                    var elapsed = performance.now() - startTime;
                                    // 检查时间超时
                                    if (elapsed > _this.config.timeout) {
                                        throw new Error("Code execution timeout after ".concat(_this.config.timeout, "ms"));
                                    }
                                    // 如果指令数超过限制，说明可能是死循环
                                    if (instructionCount > maxInstructions) {
                                        throw new Error("Code execution exceeded maximum instruction limit (".concat(maxInstructions, ")"));
                                    }
                                };
                                // 设置超时保护，防止指令检查没有被调用
                                timeoutId = setTimeout(function() {
                                    reject(new Error("Code execution timeout after ".concat(_this.config.timeout, "ms")));
                                }, _this.config.timeout);
                                try {
                                    var result = _this.executeCode(instrumentedCode, injectedParams);
                                    if (timeoutId) clearTimeout(timeoutId);
                                    resolve(result);
                                } catch (error) {
                                    if (timeoutId) clearTimeout(timeoutId);
                                    reject(error);
                                } finally{
                                    // 恢复原始状态
                                    if (originalGlobal) {
                                        _this.sandboxGlobal.__checkInstructions = originalGlobal;
                                    } else {
                                        delete _this.sandboxGlobal.__checkInstructions;
                                    }
                                }
                            })
                        ];
                    });
                }).call(this);
            }
        },
        {
            key: "instrumentCode",
            value: /**
   * 在代码中注入指令计数器
   * 在循环体内部注入检查点，确保死循环能够被检测到
   */ function instrumentCode(code) {
                // 简化的指令注入，在循环结构中添加检查
                var instrumented = code;
                // 为 for 循环体注入检查（在开括号后）
                instrumented = instrumented.replace(/(\bfor\s*\([^)]*\)\s*\{)/g, '$1\n  __checkInstructions();');
                // 为 while 循环体注入检查（在开括号后）
                instrumented = instrumented.replace(/(\bwhile\s*\([^)]*\)\s*\{)/g, '$1\n  __checkInstructions();');
                // 为 do-while 循环体注入检查
                instrumented = instrumented.replace(/(\bdo\s*\{)/g, '$1\n  __checkInstructions();');
                // 在代码开始处插入检查，确保即使没有循环也能检测超时
                return "__checkInstructions();\n".concat(instrumented);
            }
        },
        {
            key: "executeWithWorker",
            value: /**
   * 使用 Worker 执行代码以实现真正的超时控制
   */ function executeWithWorker(code, injectedParams) {
                var _this = this;
                return new Promise(function(resolve, reject) {
                    // 尝试序列化参数，失败则回退
                    var serializableParams = _this.trySerializeParams(injectedParams, code, resolve, reject);
                    if (!serializableParams) return; // 已经回退处理
                    // 创建 Worker
                    var _this_createWorkerInstance = _this.createWorkerInstance(code, serializableParams, resolve, reject), worker = _this_createWorkerInstance.worker, workerUrl = _this_createWorkerInstance.workerUrl, timeoutId = _this_createWorkerInstance.timeoutId;
                    // Worker 创建失败，已经回退
                    if (!worker) return;
                    // 设置消息处理
                    _this.setupWorkerHandlers(worker, workerUrl, timeoutId, resolve, reject);
                });
            }
        },
        {
            key: "trySerializeParams",
            value: /**
   * 尝试序列化参数，失败则回退到同步执行
   */ function trySerializeParams(injectedParams, code, resolve, reject) {
                if (!injectedParams) return {};
                var serializableParams = {};
                var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                try {
                    for(var _iterator = Object.entries(injectedParams)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                        var _step_value = _sliced_to_array(_step.value, 2), key = _step_value[0], value = _step_value[1];
                        try {
                            JSON.stringify(value);
                            serializableParams[key] = value;
                        } catch (unused) {
                            console.warn('无法序列化注入参数 "'.concat(key, '"，回退到同步执行'));
                            this.fallbackToSyncExecution(code, injectedParams, resolve, reject);
                            return null;
                        }
                    }
                } catch (err) {
                    _didIteratorError = true;
                    _iteratorError = err;
                } finally{
                    try {
                        if (!_iteratorNormalCompletion && _iterator.return != null) {
                            _iterator.return();
                        }
                    } finally{
                        if (_didIteratorError) {
                            throw _iteratorError;
                        }
                    }
                }
                return serializableParams;
            }
        },
        {
            key: "fallbackToSyncExecution",
            value: /**
   * 回退到同步执行
   */ function fallbackToSyncExecution(code, injectedParams, resolve, reject) {
                // 检查是否是死循环，如果是则使用指令计数方法
                if (this.isObviousInfiniteLoop(code)) {
                    this.executeWithInstructionLimit(code, injectedParams).then(resolve).catch(reject);
                    return;
                }
                // 对正常代码使用超时保护
                this.executeWithTimeout(code, injectedParams).then(resolve).catch(reject);
            }
        },
        {
            key: "createWorkerInstance",
            value: /**
   * 创建 Worker 实例
   */ function createWorkerInstance(code, serializableParams, resolve, reject) {
                var workerCode = this.generateWorkerCode();
                var blob = new Blob([
                    workerCode
                ], {
                    type: 'application/javascript'
                });
                var workerUrl = URL.createObjectURL(blob);
                try {
                    var worker = new Worker(workerUrl);
                    var timeoutId = this.setupWorkerTimeout(worker, workerUrl, reject);
                    // 发送代码到 Worker
                    worker.postMessage({
                        code: code,
                        config: this.config,
                        injectedParams: serializableParams
                    });
                    return {
                        worker: worker,
                        workerUrl: workerUrl,
                        timeoutId: timeoutId
                    };
                } catch (error) {
                    URL.revokeObjectURL(workerUrl);
                    console.warn('Worker 创建失败，回退到同步执行');
                    this.fallbackToSyncExecution(code, serializableParams, resolve, reject);
                    return {
                        worker: null,
                        workerUrl: workerUrl,
                        timeoutId: 0
                    };
                }
            }
        },
        {
            key: "generateWorkerCode",
            value: /**
   * 生成 Worker 代码
   */ function generateWorkerCode() {
                return "\n      self.onmessage = function(e) {\n        const { code, config, injectedParams } = e.data;\n        \n        try {\n          // 创建安全的执行环境\n          const safeGlobals = {\n            Math, Date, JSON, parseInt, parseFloat, isNaN, isFinite,\n            encodeURIComponent, decodeURIComponent, encodeURI, decodeURI,\n            String, Number, Boolean, Array, Object, RegExp,\n            Error, TypeError, ReferenceError, SyntaxError\n          };\n          \n          // 添加自定义全局变量\n          Object.assign(safeGlobals, config.customGlobals || {});\n          \n          // 添加注入的参数\n          Object.assign(safeGlobals, injectedParams || {});\n          \n          // 添加 console（如果允许）\n          if (config.allowConsole) {\n            safeGlobals.console = {\n              log: (...args) => self.postMessage({ type: 'log', data: args }),\n              warn: (...args) => self.postMessage({ type: 'warn', data: args }),\n              error: (...args) => self.postMessage({ type: 'error', data: args }),\n              info: (...args) => self.postMessage({ type: 'info', data: args }),\n              debug: (...args) => self.postMessage({ type: 'debug', data: args })\n            };\n          }\n          \n          // 创建执行函数\n          const wrappedCode = config.strictMode ? \"'use strict';\\n\" + code : code;\n          const func = new Function(...Object.keys(safeGlobals), 'return (function() { ' + wrappedCode + ' })()');\n          \n          // 执行代码\n          const result = func(...Object.values(safeGlobals));\n          \n          self.postMessage({ type: 'result', data: result });\n        } catch (error) {\n          self.postMessage({ type: 'error', data: { message: error.message, stack: error.stack } });\n        }\n      };\n    ";
            }
        },
        {
            key: "setupWorkerTimeout",
            value: /**
   * 设置 Worker 超时
   */ function setupWorkerTimeout(worker, workerUrl, reject) {
                var _this = this;
                return window.setTimeout(function() {
                    worker.terminate();
                    URL.revokeObjectURL(workerUrl);
                    reject(new Error("Code execution timeout after ".concat(_this.config.timeout, "ms")));
                }, this.config.timeout);
            }
        },
        {
            key: "setupWorkerHandlers",
            value: /**
   * 设置 Worker 消息处理器
   */ function setupWorkerHandlers(worker, workerUrl, timeoutId, resolve, reject) {
                var _this = this;
                worker.onmessage = function(e) {
                    var _e_data = e.data, type = _e_data.type, data = _e_data.data;
                    if (type === 'result') {
                        _this.cleanupWorker(worker, workerUrl, timeoutId);
                        resolve(data);
                        return;
                    }
                    if (type === 'error') {
                        _this.cleanupWorker(worker, workerUrl, timeoutId);
                        reject(new Error(data.message));
                        return;
                    }
                    // 处理控制台输出
                    _this.handleConsoleMessage(type, data);
                };
                worker.onerror = function(error) {
                    _this.cleanupWorker(worker, workerUrl, timeoutId);
                    reject(new Error("Worker error: ".concat(error.message)));
                };
            }
        },
        {
            key: "handleConsoleMessage",
            value: /**
   * 处理控制台消息
   */ function handleConsoleMessage(type, data) {
                if (!this.config.allowConsole) return;
                var consoleTypes = [
                    'log',
                    'warn',
                    'error',
                    'info',
                    'debug'
                ];
                if (!consoleTypes.includes(type)) return;
                var consoleMethod = console[type];
                if (typeof consoleMethod === 'function') {
                    consoleMethod.apply(void 0, [
                        '[Sandbox]'
                    ].concat(_to_consumable_array(data)));
                }
            }
        },
        {
            key: "cleanupWorker",
            value: /**
   * 清理 Worker 资源
   */ function cleanupWorker(worker, workerUrl, timeoutId) {
                clearTimeout(timeoutId);
                worker.terminate();
                URL.revokeObjectURL(workerUrl);
            }
        },
        {
            key: "executeCode",
            value: /**
   * 执行代码的核心方法（同步版本）
   */ function executeCode(code, injectedParams) {
                // 添加严格模式
                var wrappedCode = this.config.strictMode ? "'use strict';\n".concat(code) : code;
                // 预处理代码以检测和阻止危险操作
                this.validateCode(wrappedCode);
                // 获取允许的全局变量名和值
                // 合并沙箱全局变量、自定义全局变量和注入参数
                var allGlobals = _object_spread({}, this.sandboxGlobal, this.config.customGlobals, injectedParams || {});
                var allowedKeys = Object.keys(allGlobals);
                var allowedValues = allowedKeys.map(function(key) {
                    return allGlobals[key];
                });
                // 创建安全的执行环境
                // 通过参数传递的方式提供沙箱全局变量，而不是通过全局对象访问
                var funcCode = "\n      return (function(".concat(allowedKeys.join(', '), ") {\n        ").concat(wrappedCode, "\n      })(").concat(allowedKeys.map(function(_, index) {
                    return "arguments[".concat(index, "]");
                }).join(', '), ");\n    ");
                try {
                    // 使用 Function 构造函数创建执行函数
                    // 不传递任何全局变量名，强制代码只能使用参数提供的变量
                    var func = new Function(funcCode);
                    // 执行函数，传入沙箱全局变量
                    return func.apply(null, allowedValues);
                } catch (error) {
                    // 检查是否是因为试图访问被禁止的全局变量
                    if (_instanceof(error, ReferenceError)) {
                        var match = error.message.match(/(\w+) is not defined/);
                        if (match) {
                            var varName = match[1];
                            if (this.config.forbiddenGlobals.includes(varName)) {
                                throw new ReferenceError("Access to '".concat(varName, "' is not allowed in sandbox"));
                            }
                        }
                    }
                    throw error;
                }
            }
        },
        {
            key: "validateCode",
            value: /**
   * 验证代码安全性
   */ function validateCode(code) {
                // 检查是否包含危险的模式
                var dangerousPatterns = [
                    /\beval\s*\(/,
                    /\bFunction\s*\(/,
                    /new\s+Function\s*\(/,
                    /\.constructor/,
                    /\.__proto__/,
                    /\.prototype\./,
                    /\bglobal\s*[.[]/,
                    /\bself\s*[.[]/,
                    /\bprocess\s*[.[]/,
                    /\brequire\s*\(/,
                    /\bimport\s*\(/,
                    /\bimportScripts\s*\(/
                ];
                // 对于 globalThis，只在直接访问属性时才阻止，允许 typeof 检查
                // 检查是否有恶意的 globalThis 访问（排除 typeof 检查）
                var globalThisPatterns = [
                    /\bglobalThis\s*\.\s*[a-zA-Z_$]/,
                    /\bglobalThis\s*\[/,
                    /=\s*globalThis\b/,
                    /\breturn\s+globalThis\b/
                ];
                var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                try {
                    for(var _iterator = globalThisPatterns[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                        var pattern = _step.value;
                        if (pattern.test(code)) {
                            throw new Error('Code contains dangerous pattern: globalThis property access');
                        }
                    }
                } catch (err) {
                    _didIteratorError = true;
                    _iteratorError = err;
                } finally{
                    try {
                        if (!_iteratorNormalCompletion && _iterator.return != null) {
                            _iterator.return();
                        }
                    } finally{
                        if (_didIteratorError) {
                            throw _iteratorError;
                        }
                    }
                }
                var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
                try {
                    for(var _iterator1 = dangerousPatterns[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
                        var pattern1 = _step1.value;
                        if (pattern1.test(code)) {
                            throw new Error("Code contains dangerous pattern: ".concat(pattern1.source));
                        }
                    }
                } catch (err) {
                    _didIteratorError1 = true;
                    _iteratorError1 = err;
                } finally{
                    try {
                        if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
                            _iterator1.return();
                        }
                    } finally{
                        if (_didIteratorError1) {
                            throw _iteratorError1;
                        }
                    }
                }
                // 检查特定的被禁止的全局变量名（只检查明确的危险变量）
                var criticalForbiddenGlobals = [
                    'eval',
                    'Function',
                    'constructor',
                    '__proto__',
                    'global',
                    'self',
                    'process',
                    'require',
                    'module',
                    'exports',
                    'Buffer',
                    'XMLHttpRequest',
                    'fetch',
                    'WebSocket',
                    'Worker',
                    'SharedArrayBuffer',
                    'Atomics',
                    'WebAssembly'
                ];
                var _iteratorNormalCompletion2 = true, _didIteratorError2 = false, _iteratorError2 = undefined;
                try {
                    for(var _iterator2 = criticalForbiddenGlobals[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true){
                        var forbiddenGlobal = _step2.value;
                        // 只检查作为独立标识符或对象访问的情况
                        var patterns = [
                            new RegExp("\\b".concat(forbiddenGlobal, "\\s*\\("), 'g'),
                            new RegExp("\\b".concat(forbiddenGlobal, "\\s*\\."), 'g'),
                            new RegExp("\\b".concat(forbiddenGlobal, "\\s*\\["), 'g'),
                            new RegExp("\\breturn\\s+".concat(forbiddenGlobal, "\\b"), 'g'),
                            new RegExp("=\\s*".concat(forbiddenGlobal, "\\b"), 'g')
                        ];
                        var _iteratorNormalCompletion3 = true, _didIteratorError3 = false, _iteratorError3 = undefined;
                        try {
                            for(var _iterator3 = patterns[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true){
                                var pattern2 = _step3.value;
                                if (pattern2.test(code)) {
                                    throw new ReferenceError("Access to '".concat(forbiddenGlobal, "' is not allowed in sandbox"));
                                }
                            }
                        } catch (err) {
                            _didIteratorError3 = true;
                            _iteratorError3 = err;
                        } finally{
                            try {
                                if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
                                    _iterator3.return();
                                }
                            } finally{
                                if (_didIteratorError3) {
                                    throw _iteratorError3;
                                }
                            }
                        }
                    }
                } catch (err) {
                    _didIteratorError2 = true;
                    _iteratorError2 = err;
                } finally{
                    try {
                        if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
                            _iterator2.return();
                        }
                    } finally{
                        if (_didIteratorError2) {
                            throw _iteratorError2;
                        }
                    }
                }
            }
        },
        {
            key: "getMemoryUsage",
            value: /**
   * 获取内存使用情况
   */ function getMemoryUsage() {
                if ('memory' in performance) {
                    return performance.memory.usedJSHeapSize;
                }
                return 0;
            }
        },
        {
            key: "cleanup",
            value: /**
   * 清理资源
   */ function cleanup() {
                this.isActive = false;
                if (this.timeoutId !== null) {
                    clearTimeout(this.timeoutId);
                    this.timeoutId = null;
                }
            }
        },
        {
            /**
   * 销毁沙箱
   */ key: "destroy",
            value: function destroy() {
                var _this = this;
                this.cleanup();
                // 清理全局对象
                Object.keys(this.sandboxGlobal).forEach(function(key) {
                    delete _this.sandboxGlobal[key];
                });
            }
        },
        {
            /**
   * 检查沙箱是否处于活动状态
   */ key: "isRunning",
            value: function isRunning() {
                return this.isActive;
            }
        },
        {
            /**
   * 添加自定义全局变量
   */ key: "addGlobal",
            value: function addGlobal(name, value) {
                if (this.config.forbiddenGlobals.includes(name)) {
                    throw new Error("Cannot add forbidden global: ".concat(name));
                }
                this.sandboxGlobal[name] = value;
                this.config.customGlobals[name] = value;
            }
        },
        {
            /**
   * 移除自定义全局变量
   */ key: "removeGlobal",
            value: function removeGlobal(name) {
                delete this.sandboxGlobal[name];
                delete this.config.customGlobals[name];
            }
        },
        {
            /**
   * 获取沙箱配置
   */ key: "getConfig",
            value: function getConfig() {
                return _object_spread({}, this.config);
            }
        }
    ]);
    return ProxySandbox;
}();
/**
 * 创建沙箱实例的工厂函数
 */ export function createSandbox(config) {
    return new ProxySandbox(config);
}
/**
 * 快速执行代码的工具函数
 */ export function runInSandbox(code, config, injectedParams) {
    return _async_to_generator(function() {
        var sandbox;
        return _ts_generator(this, function(_state) {
            switch(_state.label){
                case 0:
                    sandbox = createSandbox(config);
                    _state.label = 1;
                case 1:
                    _state.trys.push([
                        1,
                        ,
                        3,
                        4
                    ]);
                    return [
                        4,
                        sandbox.execute(code, injectedParams)
                    ];
                case 2:
                    return [
                        2,
                        _state.sent()
                    ];
                case 3:
                    sandbox.destroy();
                    return [
                        7
                    ];
                case 4:
                    return [
                        2
                    ];
            }
        });
    })();
}
