"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { EvaluationError: () => EvaluationError, IoError: () => IoError, LogLevelKind: () => LogLevelKind, MaxOpDurationExceededError: () => MaxOpDurationExceededError, MaxOpsExceededError: () => MaxOpsExceededError, MissingCatchOrFinallyAfterTryError: () => MissingCatchOrFinallyAfterTryError, ModuleNotFoundError: () => ModuleNotFoundError, NetworkError: () => NetworkError, NonDeterministicError: () => NonDeterministicError, NotCallableError: () => NotCallableError, PolicyError: () => PolicyError, ProcessError: () => ProcessError, UndefinedIdentifierError: () => UndefinedIdentifierError, UndefinedLeftValueError: () => UndefinedLeftValueError, UnexpectedNodeError: () => UnexpectedNodeError, UnexpectedSyntaxError: () => UnexpectedSyntaxError, evaluate: () => evaluate, isEvaluationError: () => isEvaluationError }); module.exports = __toCommonJS(src_exports); // node_modules/.pnpm/tsup@8.3.0_tsx@4.19.1_typescript@5.6.3/node_modules/tsup/assets/cjs_shims.js var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href; var importMetaUrl = /* @__PURE__ */ getImportMetaUrl(); // src/interpreter/evaluate.ts var TSModule = __toESM(require("typescript"), 1); // src/interpreter/lexical-environment/lexical-environment.ts var import_object_path = __toESM(require("object-path"), 1); // src/interpreter/environment/ecma/ecma-globals.ts var ECMA_GLOBALS = () => { const base = { Infinity: Infinity, NaN: NaN, undefined: void 0, isNaN, parseFloat, parseInt, decodeURI, decodeURIComponent, encodeURI, encodeURIComponent, Array, Boolean, Date, Error, EvalError, Number, Object, RangeError, ReferenceError, RegExp, String, SyntaxError, TypeError, URIError, JSON, Math, escape, unescape, // eslint-disable-next-line no-eval eval, Function /* eslint-enable @typescript-eslint/naming-convention */ }; try { base.AggregateError = AggregateError; } catch { } try { base.FinalizationRegistry = FinalizationRegistry; } catch { } try { base.WeakRef = WeakRef; } catch { } try { base.BigInt = BigInt; } catch { } try { base.Reflect = Reflect; } catch { } try { base.WeakMap = WeakMap; } catch { } try { base.WeakSet = WeakSet; } catch { } try { base.Set = Set; } catch { } try { base.Map = Map; } catch { } try { base.Uint8Array = Uint8Array; } catch { } try { base.BigUint64Array = BigUint64Array; } catch { } try { base.BigInt64Array = BigInt64Array; } catch { } try { base.Atomics = Atomics; } catch { } try { base.SharedArrayBuffer = SharedArrayBuffer; } catch { } try { base.WebAssembly = WebAssembly; } catch { } try { base.Uint8ClampedArray = Uint8ClampedArray; } catch { } try { base.Uint16Array = Uint16Array; } catch { } try { base.Uint32Array = Uint32Array; } catch { } try { base.Intl = Intl; } catch { } try { base.Int8Array = Int8Array; } catch { } try { base.Int16Array = Int16Array; } catch { } try { base.Int32Array = Int32Array; } catch { } try { base.Float32Array = Float32Array; } catch { } try { base.Float64Array = Float64Array; } catch { } try { base.ArrayBuffer = ArrayBuffer; } catch { } try { base.DataView = DataView; } catch { } try { base.isFinite = isFinite; } catch { } try { base.Promise = Promise; } catch { } try { base.Proxy = Proxy; } catch { } try { base.Symbol = Symbol; } catch { } return base; }; // src/interpreter/util/descriptor/merge-descriptors.ts function mergeDescriptors(a, b, c) { const newObj = {}; const normalizedB = b ?? {}; const normalizedC = c ?? {}; [a, normalizedB, normalizedC].forEach((item) => Object.defineProperties(newObj, Object.getOwnPropertyDescriptors(item))); return newObj; } // src/interpreter/util/object/subtract.ts function subtract(a, b) { const newA = {}; Object.getOwnPropertyNames(a).forEach((name) => { if (!(name in b)) { Object.defineProperty(newA, name, Object.getOwnPropertyDescriptor(a, name)); } }); return newA; } // src/interpreter/environment/node/node-cjs-globals.ts var import_crosspath = __toESM(require("crosspath"), 1); // src/interpreter/util/loader/require-module.ts var import_module = require("module"); var requireModule = (0, import_module.createRequire)(importMetaUrl); // src/interpreter/environment/node/node-cjs-globals.ts var NODE_CJS_GLOBALS = () => { const ecmaGlobals = ECMA_GLOBALS(); const merged = mergeDescriptors(subtract(global, ecmaGlobals), ecmaGlobals, { require: requireModule, process, __dirname: (fileName) => import_crosspath.default.native.normalize(import_crosspath.default.native.dirname(fileName)), __filename: (fileName) => import_crosspath.default.native.normalize(fileName) }); Object.defineProperties(merged, { global: { get() { return merged; } }, globalThis: { get() { return merged; } } }); return merged; }; // src/interpreter/environment/browser/lib/raf.ts function rafImplementation(global2) { let lastTime = 0; const _requestAnimationFrame = function requestAnimationFrame(callback) { const currTime = (/* @__PURE__ */ new Date()).getTime(); const timeToCall = Math.max(0, 16 - (currTime - lastTime)); const id = global2.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; const _cancelAnimationFrame = function cancelAnimationFrame(id) { clearTimeout(id); }; return { requestAnimationFrame: _requestAnimationFrame, cancelAnimationFrame: _cancelAnimationFrame }; } // src/interpreter/util/loader/optional-peer-dependency-loader.ts var jsdomModule; function loadJsdom(required = false) { return jsdomModule ??= loadModules("evaluate against a browser environment", required, "jsdom"); } function loadModules(description, required, moduleSpecifier = description) { try { return requireModule(moduleSpecifier); } catch { if (required) { throw new ReferenceError(`You must install the peer dependency '${moduleSpecifier}' in order to ${description} with ts-evaluator`); } return void 0; } } // src/interpreter/environment/browser/browser-globals.ts var BROWSER_GLOBALS = () => { const { JSDOM } = loadJsdom(true); const { window } = new JSDOM("", { url: "https://example.com" }); const ecmaGlobals = ECMA_GLOBALS(); if (window.requestAnimationFrame == null) { const raf = rafImplementation(window); Object.defineProperties(window, Object.getOwnPropertyDescriptors(raf)); } const missingEcmaGlobals = subtract(ecmaGlobals, window); if (Object.keys(missingEcmaGlobals).length > 0) { Object.defineProperties(window, Object.getOwnPropertyDescriptors(ecmaGlobals)); } return window; }; // src/interpreter/util/return/return-symbol.ts var RETURN_SYMBOL = "[return]"; // src/interpreter/util/break/break-symbol.ts var BREAK_SYMBOL = "[break]"; // src/interpreter/util/continue/continue-symbol.ts var CONTINUE_SYMBOL = "[continue]"; // src/interpreter/util/this/this-symbol.ts var THIS_SYMBOL = "this"; // src/interpreter/util/super/super-symbol.ts var SUPER_SYMBOL = "super"; // src/interpreter/environment/node/node-esm-globals.ts var import_crosspath2 = __toESM(require("crosspath"), 1); var NODE_ESM_GLOBALS = () => { const ecmaGlobals = ECMA_GLOBALS(); const merged = mergeDescriptors(subtract(global, ecmaGlobals), ecmaGlobals, { import: { meta: { url: (fileName) => { const normalized = import_crosspath2.default.normalize(fileName); return `file:///${normalized.startsWith(`/`) ? normalized.slice(1) : normalized}`; } } }, process }); Object.defineProperties(merged, { global: { get() { return merged; } }, globalThis: { get() { return merged; } } }); return merged; }; // src/interpreter/util/declaration/is-declaration.ts function isDeclaration(node, typescript) { return typescript.isDeclaration(node); } function isNamedDeclaration(node, typescript) { if (typescript.isPropertyAccessExpression(node)) return false; return "name" in node && node.name != null; } // src/interpreter/util/flags/is-var-declaration.ts function isVarDeclaration(declarationList, typescript) { return declarationList.flags !== typescript.NodeFlags.Const && declarationList.flags !== typescript.NodeFlags.Let; } // src/interpreter/error/evaluation-error/evaluation-error.ts var EvaluationError = class extends Error { /** * The node that caused or thew the error */ node; environment; constructor({ node, environment, message }) { super(message); Error.captureStackTrace(this, this.constructor); this.node = node; this.environment = environment; } }; function isEvaluationError(item) { return typeof item === "object" && item != null && item instanceof EvaluationError; } // src/interpreter/error/module-not-found-error/module-not-found-error.ts var ModuleNotFoundError = class extends EvaluationError { /** * The path/moduleName that could not be resolved */ path; constructor({ path: path4, node, environment, message = `Module '${path4}' could not be resolved'` }) { super({ message, environment, node }); this.path = path4; } }; // src/interpreter/error/unexpected-node-error/unexpected-node-error.ts var UnexpectedNodeError = class extends EvaluationError { constructor({ node, environment, typescript, message = `Unexpected Node: '${typescript.SyntaxKind[node.kind]}'` }) { super({ message, node, environment }); } }; // src/interpreter/util/declaration/get-declaration-name.ts function getDeclarationName(options) { const { node, evaluate: evaluate2, environment, typescript, throwError } = options; const name = typescript.getNameOfDeclaration(node); if (name == null) return void 0; if (typescript.isIdentifier(name)) { return name.text; } else if (typescript.isPrivateIdentifier?.(name)) { return name.text; } else if (typescript.isStringLiteralLike(name)) { return name.text; } else if (typescript.isNumericLiteral(name)) { return Number(name.text); } else if (typescript.isComputedPropertyName(name)) { return evaluate2.expression(name.expression, options); } else { return throwError(new UnexpectedNodeError({ node: name, environment, typescript })); } } // src/interpreter/util/module/get-resolved-module-name.ts var import_crosspath3 = __toESM(require("crosspath"), 1); function getResolvedModuleName(moduleSpecifier, options) { const { node, typescript } = options; if (!typescript.isExternalModuleNameRelative(moduleSpecifier)) { return moduleSpecifier; } const parentPath = node.getSourceFile().fileName; return import_crosspath3.default.join(import_crosspath3.default.dirname(parentPath), moduleSpecifier); } // src/interpreter/util/module/get-implementation-for-declaration-within-declaration-file.ts function getImplementationForDeclarationWithinDeclarationFile(options) { const { node, typescript, throwError, environment } = options; const name = getDeclarationName(options); if (isEvaluationError(name)) { return name; } if (name == null) { return throwError(new UnexpectedNodeError({ node, environment, typescript })); } const matchInLexicalEnvironment = getFromLexicalEnvironment(node, options.environment, name); if (matchInLexicalEnvironment?.literal != null) { return matchInLexicalEnvironment.literal; } const require2 = getFromLexicalEnvironment(node, options.environment, "require").literal; const moduleDeclaration = typescript.isModuleDeclaration(node) ? node : findNearestParentNodeOfKind(node, typescript.SyntaxKind.ModuleDeclaration, typescript); if (moduleDeclaration == null) { return throwError(new UnexpectedNodeError({ node, environment, typescript })); } const moduleSpecifier = moduleDeclaration.name.text; const resolvedModuleSpecifier = getResolvedModuleName(moduleSpecifier, options); try { const module2 = options.moduleOverrides?.[moduleSpecifier] ?? options.moduleOverrides?.[resolvedModuleSpecifier] ?? require2(resolvedModuleSpecifier); return typescript.isModuleDeclaration(node) ? module2 : module2[name] ?? module2; } catch (ex) { if (isEvaluationError(ex)) return ex; else return throwError(new ModuleNotFoundError({ node: moduleDeclaration, environment, path: resolvedModuleSpecifier })); } } function getImplementationFromExternalFile(name, moduleSpecifier, options) { const { node, throwError, environment } = options; const require2 = getFromLexicalEnvironment(node, options.environment, "require").literal; const resolvedModuleSpecifier = getResolvedModuleName(moduleSpecifier, options); try { const module2 = options.moduleOverrides?.[moduleSpecifier] ?? options.moduleOverrides?.[resolvedModuleSpecifier] ?? require2(resolvedModuleSpecifier); return module2[name] ?? module2.default ?? module2; } catch (ex) { if (isEvaluationError(ex)) return ex; else return throwError(new ModuleNotFoundError({ node, environment, path: resolvedModuleSpecifier })); } } // src/interpreter/util/node/find-nearest-parent-node-of-kind.ts function findNearestParentNodeOfKind(from, kind, typescript) { let currentParent = from; while (true) { currentParent = currentParent.parent; if (currentParent == null) return void 0; if (currentParent.kind === kind) { const combinedNodeFlags = typescript.getCombinedNodeFlags(currentParent); const isNamespace = (combinedNodeFlags & typescript.NodeFlags.Namespace) !== 0 || (combinedNodeFlags & typescript.NodeFlags.NestedNamespace) !== 0; if (!isNamespace) return currentParent; } if (typescript.isSourceFile(currentParent)) return void 0; } } function findNearestParentNodeWithName(from, name, options, visitedRoots = /* @__PURE__ */ new WeakSet()) { const { typescript } = options; let result; function visit(nextNode, nestingLayer = 0) { if (visitedRoots.has(nextNode)) return false; visitedRoots.add(nextNode); if (typescript.isIdentifier(nextNode)) { if (nextNode.text === name) { result = nextNode; return true; } } else if (typescript.isShorthandPropertyAssignment(nextNode)) { return false; } else if (typescript.isPropertyAssignment(nextNode)) { return false; } else if (typescript.isImportDeclaration(nextNode)) { if (nextNode.importClause != null) { if (nextNode.importClause.name != null && visit(nextNode.importClause.name)) { const moduleSpecifier = nextNode.moduleSpecifier; if (moduleSpecifier != null && typescript.isStringLiteralLike(moduleSpecifier)) { result = getImplementationFromExternalFile(name, moduleSpecifier.text, options); return true; } } else if (nextNode.importClause.namedBindings != null && visit(nextNode.importClause.namedBindings)) { return true; } } return false; } else if (typescript.isImportEqualsDeclaration(nextNode)) { if (nextNode.name != null && visit(nextNode.name)) { if (typescript.isIdentifier(nextNode.moduleReference)) { result = findNearestParentNodeWithName(nextNode.parent, nextNode.moduleReference.text, options, visitedRoots); return result != null; } else if (typescript.isQualifiedName(nextNode.moduleReference)) { return false; } else { const moduleSpecifier = nextNode.moduleReference.expression; if (moduleSpecifier != null && typescript.isStringLiteralLike(moduleSpecifier)) { result = getImplementationFromExternalFile(name, moduleSpecifier.text, options); return true; } } } return false; } else if (typescript.isNamespaceImport(nextNode)) { if (visit(nextNode.name)) { const moduleSpecifier = nextNode.parent?.parent?.moduleSpecifier; if (moduleSpecifier == null || !typescript.isStringLiteralLike(moduleSpecifier)) { return false; } result = getImplementationFromExternalFile(name, moduleSpecifier.text, options); return true; } } else if (typescript.isNamedImports(nextNode)) { for (const importSpecifier of nextNode.elements) { if (visit(importSpecifier)) { return true; } } } else if (typescript.isImportSpecifier(nextNode)) { if (visit(nextNode.name)) { const moduleSpecifier = nextNode.parent?.parent?.parent?.moduleSpecifier; if (moduleSpecifier == null || !typescript.isStringLiteralLike(moduleSpecifier)) { return false; } result = getImplementationFromExternalFile(name, moduleSpecifier.text, options); return true; } } else if (typescript.isSourceFile(nextNode)) { for (const statement of nextNode.statements) { if (visit(statement)) { return true; } } } else if (typescript.isVariableStatement(nextNode)) { for (const declaration of nextNode.declarationList.declarations) { if (visit(declaration) && (isVarDeclaration(nextNode.declarationList, typescript) || nestingLayer < 1)) { return true; } } } else if (typescript.isBlock(nextNode)) { for (const statement of nextNode.statements) { if (visit(statement, nestingLayer + 1)) { return true; } } } else if (isNamedDeclaration(nextNode, typescript)) { if (nextNode.name != null && visit(nextNode.name)) { result = nextNode; return true; } } return false; } const suceeded = typescript.findAncestor(from, (nextNode) => visit(nextNode)); return !suceeded ? void 0 : result; } function getStatementContext(from, typescript) { let currentParent = from; while (true) { currentParent = currentParent.parent; if (currentParent == null) return void 0; if (isDeclaration(currentParent, typescript) || typescript.isSourceFile(currentParent)) { return currentParent; } } } // src/interpreter/util/proxy/can-be-observed.ts function isObjectLike(value) { return value != null && (typeof value === "function" || typeof value === "object"); } function canBeObserved(value) { return isObjectLike(value); } // src/interpreter/util/function/is-bind-call-apply.ts function isBindCallApply(func, environment) { switch (func) { case Function.prototype.bind: case Function.prototype.call: case Function.prototype.apply: return true; } if (environment != null) { const _Function = getFromLexicalEnvironment(void 0, environment, "Function").literal; switch (func) { case _Function.prototype.bind: case _Function.prototype.call: case _Function.prototype.apply: return true; } } return false; } // src/interpreter/policy/policy-trap-kind.ts function stringifyPolicyTrapKindOnPath(kind, path4) { switch (kind) { case "__$$_PROXY_GET" /* GET */: return `get ${path4}`; case "__$$_PROXY_APPLY" /* APPLY */: return `${path4}(...)`; case "__$$_PROXY_CONSTRUCT" /* CONSTRUCT */: return `new ${path4}(...)`; } } // src/interpreter/error/evaluation-error/evaluation-error-intent.ts var EvaluationErrorIntent = class { constructor(intent) { this.intent = intent; } construct(node, options) { return this.intent(node, options); } }; function isEvaluationErrorIntent(item) { return typeof item === "object" && item != null && item instanceof EvaluationErrorIntent; } function maybeThrow(node, options, value) { return isEvaluationErrorIntent(value) ? options.throwError(value.construct(node, options)) : value; } // src/interpreter/proxy/create-policy-proxy.ts function stringifyPath(path4) { return path4.map((part) => typeof part === "symbol" ? part.description : part).join("."); } function createPolicyProxy({ hook, item, scope, policy }) { function createAccessTrap(inputPath, currentItem) { const handleHookResult = (result, successCallback) => { if (result === false) return; if (isEvaluationErrorIntent(result) || isEvaluationError(result)) return result; return successCallback(); }; return !canBeObserved(currentItem) || isBindCallApply(currentItem) ? currentItem : new Proxy(currentItem, { /** * Constructs a new instance of the given target */ construct(target, argArray, newTarget) { return handleHookResult( hook({ kind: "__$$_PROXY_CONSTRUCT" /* CONSTRUCT */, policy, newTarget, argArray, target, path: stringifyPath(inputPath) }), () => Reflect.construct(target, argArray, newTarget) ); }, /** * A trap for a function call. Used to create new proxies for methods on the retrieved module objects */ apply(target, thisArg, argArray = []) { return handleHookResult( hook({ kind: "__$$_PROXY_APPLY" /* APPLY */, policy, thisArg, argArray, target, path: stringifyPath(inputPath) }), () => Reflect.apply(target, thisArg, argArray) ); }, /** * Gets a trap for 'get' accesses */ get(target, property, receiver) { const newPath = [...inputPath, property]; return handleHookResult( hook({ kind: "__$$_PROXY_GET" /* GET */, policy, path: stringifyPath(newPath), target }), () => { const match = Reflect.get(target, property, receiver); const config = Reflect.getOwnPropertyDescriptor(currentItem, property); if (config != null && config.configurable === false && config.writable === false) { return currentItem[property]; } return createAccessTrap(newPath, match); } ); } }); } return !canBeObserved(item) ? item : createAccessTrap([scope], item); } // src/interpreter/policy/network/network-map.ts var NETWORK_MAP = { "node:http2": "http2", http2: { connect: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, createSecureServer: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, createServer: { ["__$$_PROXY_APPLY" /* APPLY */]: true } }, "node:https": "https", https: { createServer: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, request: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, get: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, Server: { ["__$$_PROXY_CONSTRUCT" /* CONSTRUCT */]: true }, globalAgent: { destroy: { ["__$$_PROXY_APPLY" /* APPLY */]: true } }, Agent: { ["__$$_PROXY_CONSTRUCT" /* CONSTRUCT */]: true } }, "node:http": "http", http: { createServer: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, request: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, get: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, Server: { ["__$$_PROXY_CONSTRUCT" /* CONSTRUCT */]: true }, ClientRequest: { ["__$$_PROXY_CONSTRUCT" /* CONSTRUCT */]: true }, globalAgent: { destroy: { ["__$$_PROXY_APPLY" /* APPLY */]: true } }, Agent: { ["__$$_PROXY_CONSTRUCT" /* CONSTRUCT */]: true } }, "node:dgram": "dgram", dgram: { createSocket: { ["__$$_PROXY_APPLY" /* APPLY */]: true } }, "node:dns": "dns", dns: { lookup: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, lookupService: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, resolve: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, resolve4: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, resolve6: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, resolveAny: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, resolveCname: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, resolveMx: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, resolveNaptr: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, resolveNs: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, resolvePtr: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, resolveSoa: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, resolveSrv: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, resolveTxt: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, reverse: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, Resolver: { ["__$$_PROXY_CONSTRUCT" /* CONSTRUCT */]: true } }, "node:net": "net", net: { createServer: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, createConnection: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, connect: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, Server: { ["__$$_PROXY_CONSTRUCT" /* CONSTRUCT */]: true } }, "node:tls": "tls", tls: { createServer: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, createSecureContext: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, connect: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, Server: { ["__$$_PROXY_CONSTRUCT" /* CONSTRUCT */]: true }, TLSSocket: { ["__$$_PROXY_CONSTRUCT" /* CONSTRUCT */]: true } } }; // src/interpreter/policy/nondeterministic/nondeterministic-map.ts var NONDETERMINISTIC_MAP = { // Any network operation will always be non-deterministic ...NETWORK_MAP, Math: { random: { ["__$$_PROXY_APPLY" /* APPLY */]: true } }, Date: { now: { ["__$$_PROXY_APPLY" /* APPLY */]: true }, // Dates that receive no arguments are nondeterministic since they care about "now" and will evaluate to a new value for each invocation ["__$$_PROXY_CONSTRUCT" /* CONSTRUCT */]: (...args) => args.length === 0 && !(args[0] instanceof Date) } }; // src/interpreter/policy/trap-condition-map.ts function isTrapCondition(item, condition) { return typeof item === typeof condition || typeof item === "function"; } function isTrapConditionFunction(item) { return typeof item === "function"; } // src/interpreter/policy/is-trap-condition-met.ts function isTrapConditionMet(map, condition, item) { const atoms = item.path.split("."); return walkAtoms(map, condition, item, atoms); } function walkAtoms(map, matchCondition, item, atoms) { const [head, ...tail] = atoms; if (head == null) return false; const mapEntry = map[head]; if (mapEntry == null) return false; if (typeof mapEntry === "string") { return walkAtoms(map, matchCondition, item, [mapEntry, ...tail]); } if (isTrapCondition(mapEntry, matchCondition)) { return handleTrapCondition(mapEntry, matchCondition, item); } else { const trapMapMatch = mapEntry[item.kind]; if (trapMapMatch != null) { return handleTrapCondition(trapMapMatch, matchCondition, item); } else { return walkAtoms(mapEntry, matchCondition, item, tail); } } } function handleTrapCondition(trapCondition, matchCondition, item) { if (isTrapConditionFunction(trapCondition)) { const castItem = item; return castItem.argArray != null && trapCondition(...castItem.argArray) === matchCondition; } else { return trapCondition === matchCondition; } } // src/interpreter/policy/nondeterministic/is-nondeterministic.ts function isNonDeterministic(item) { return isTrapConditionMet(NONDETERMINISTIC_MAP, true, item); } // src/interpreter/error/policy-error/policy-error.ts var PolicyError = class extends EvaluationError { /** * The kind of policy violation encountered */ violation; constructor({ violation, node, environment, message }) { super({ node, environment, message: `[${violation}]: ${message}` }); this.violation = violation; } }; // src/interpreter/error/policy-error/non-deterministic-error/non-deterministic-error.ts var NonDeterministicError = class extends PolicyError { /** * The kind of operation that was attempted to be performed but was in violation of the policy */ operation; constructor({ operation, node, environment, message = `The operation: '${operation}' is nondeterministic. That is in violation of the policy` }) { super({ violation: "deterministic", message, node, environment }); this.operation = operation; } }; // src/interpreter/policy/io/io-map.ts var IO_MAP = { "node:fs": "fs", fs: { readFile: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, readFileSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, readdir: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, readdirSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, read: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, readSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, exists: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, existsSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, access: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, accessSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, close: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, closeSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, createReadStream: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, stat: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, statSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, watch: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, watchFile: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, unwatchFile: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, realpath: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, realpathSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, fstat: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, fstatSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "read" }, createWriteStream: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, copyFile: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, copyFileSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, unlink: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, unlinkSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, rmdir: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, rmdirSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, symlink: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, symlinkSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, truncate: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, truncateSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, utimes: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, utimesSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, appendFile: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, appendFileSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, write: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, writeSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, writeFile: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, writeFileSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, chmod: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, chmodSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, chown: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, chownSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, mkdir: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, mkdirSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, rename: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, renameSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, futimes: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, futimesSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, link: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, linkSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, mkdtemp: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, open: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, openSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, fchmod: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, fchmodSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, fchown: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, fchownSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, ftruncate: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, ftruncateSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, fsync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, fsyncSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, fdatasync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, fdatasyncSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, lchmod: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" }, lchmodSync: { ["__$$_PROXY_APPLY" /* APPLY */]: "write" } } }; // src/interpreter/policy/io/is-io-read.ts function isIoRead(item) { return isTrapConditionMet(IO_MAP, "read", item); } // src/interpreter/error/policy-error/io-error/io-error.ts var IoError = class extends PolicyError { /** * The kind of IO operation that was violated */ kind; constructor({ node, environment, kind, message = `${kind} operations are in violation of the policy` }) { super({ violation: "io", message, environment, node }); this.kind = kind; } }; // src/interpreter/policy/io/is-io-write.ts function isIoWrite(item) { return isTrapConditionMet(IO_MAP, "write", item); } // src/interpreter/policy/network/is-network-operation.ts function isNetworkOperation(item) { return isTrapConditionMet(NETWORK_MAP, true, item); } // src/interpreter/error/policy-error/network-error/network-error.ts var NetworkError = class extends PolicyError { /** * The kind of operation that was attempted to be performed but was in violation of the policy */ operation; constructor({ operation, node, environment, message = `The operation: '${operation}' is performing network activity. That is in violation of the policy` }) { super({ violation: "deterministic", message, node, environment }); this.operation = operation; } }; // src/interpreter/policy/process/process-map.ts var PROCESS_MAP = { "node:process": "process", process: { exit: { ["__$$_PROXY_APPLY" /* APPLY */]: "exit" } }, // Everything inside child_process is just one big violation of this policy "node:child_process": "child_process", child_process: { ["__$$_PROXY_APPLY" /* APPLY */]: "spawnChild" }, "node:cluster": "cluster", cluster: { Worker: { ["__$$_PROXY_CONSTRUCT" /* CONSTRUCT */]: "spawnChild" } } }; // src/interpreter/policy/process/is-process-exit-operation.ts function isProcessExitOperation(item) { return isTrapConditionMet(PROCESS_MAP, "exit", item); } // src/interpreter/error/policy-error/process-error/process-error.ts var ProcessError = class extends PolicyError { /** * The kind of process operation that was violated */ kind; constructor({ kind, node, environment, message = `${kind} operations are in violation of the policy` }) { super({ violation: "process", message, node, environment }); this.kind = kind; } }; // src/interpreter/policy/process/is-process-spawn-child-operation.ts function isProcessSpawnChildOperation(item) { return isTrapConditionMet(PROCESS_MAP, "spawnChild", item); } // src/interpreter/policy/console/console-map.ts var CONSOLE_MAP = { "node:console": "console", console: { ["__$$_PROXY_APPLY" /* APPLY */]: true } }; // src/interpreter/policy/console/is-console-operation.ts function isConsoleOperation(item) { return isTrapConditionMet(CONSOLE_MAP, true, item); } // src/interpreter/environment/create-sanitized-environment.ts function createSanitizedEnvironment({ policy, env }) { const hook = (item) => { if (!policy.console && isConsoleOperation(item)) { return false; } if (!policy.io.read && isIoRead(item)) { return new EvaluationErrorIntent((node, options) => new IoError({ ...options, node, kind: "read" })); } if (!policy.io.write && isIoWrite(item)) { return new EvaluationErrorIntent((node, options) => new IoError({ ...options, node, kind: "write" })); } if (!policy.process.exit && isProcessExitOperation(item)) { return new EvaluationErrorIntent((node, options) => new ProcessError({ ...options, node, kind: "exit" })); } if (!policy.process.exit && isProcessSpawnChildOperation(item)) { return new EvaluationErrorIntent((node, options) => new ProcessError({ ...options, node, kind: "spawnChild" })); } if (!policy.network && isNetworkOperation(item)) { return new EvaluationErrorIntent((node, options) => new NetworkError({ ...options, node, operation: stringifyPolicyTrapKindOnPath(item.kind, item.path) })); } if (policy.deterministic && isNonDeterministic(item)) { return new EvaluationErrorIntent((node, options) => new NonDeterministicError({ ...options, node, operation: stringifyPolicyTrapKindOnPath(item.kind, item.path) })); } return true; }; const descriptors = Object.entries(Object.getOwnPropertyDescriptors(env)); const gettersAndSetters = Object.assign({}, ...descriptors.filter(([, descriptor]) => !("value" in descriptor)).map(([name, descriptor]) => ({ [name]: descriptor }))); const values = Object.assign( {}, ...descriptors.filter(([, descriptor]) => "value" in descriptor).map(([name, descriptor]) => ({ [name]: name === "require" ? new Proxy(descriptor.value, { /** * A trap for a function call. Used to create new proxies for methods on the retrieved module objects */ apply(target, thisArg, argArray = []) { const [moduleName] = argArray; if (moduleName != null) { return createPolicyProxy({ policy, item: Reflect.apply(target, thisArg, argArray), scope: moduleName, hook }); } else { return Reflect.apply(target, thisArg, argArray); } } }) : createPolicyProxy({ policy, item: descriptor.value, scope: name, hook }) })) ); return Object.defineProperties(values, { ...gettersAndSetters }); } // src/interpreter/lexical-environment/lexical-environment.ts function getRelevantDictFromLexicalEnvironment(env, path4) { const [firstBinding] = path4.split("."); if (firstBinding == null) return void 0; if (import_object_path.default.has(env.env, firstBinding)) return env.env; if (env.parentEnv != null) return getRelevantDictFromLexicalEnvironment(env.parentEnv, path4); return void 0; } function getPresetForLexicalEnvironment(env) { if (env.preset != null) return env.preset; else if (env.parentEnv != null) return getPresetForLexicalEnvironment(env.parentEnv); else return "NONE"; } function findLexicalEnvironmentInSameContext(from, node, typescript) { const startingNodeContext = getStatementContext(from.startingNode, typescript); const nodeContext = getStatementContext(node, typescript); if (startingNodeContext?.pos === nodeContext?.pos) { return from; } if (from.parentEnv == null) { return void 0; } return findLexicalEnvironmentInSameContext(from.parentEnv, node, typescript); } function getFromLexicalEnvironment(node, env, path4) { const [firstBinding] = path4.split("."); if (firstBinding == null) return void 0; if (import_object_path.default.has(env.env, firstBinding)) { const literal = import_object_path.default.get(env.env, path4); switch (path4) { // If we're in a Node environment, the "__dirname" and "__filename" meta-properties should report the current directory or file of the SourceFile and not the parent process case "__dirname": case "__filename": { const preset = getPresetForLexicalEnvironment(env); return (preset === "NODE" || preset === "NODE_CJS") && typeof literal === "function" && node != null ? { literal: literal(node.getSourceFile().fileName) } : { literal }; } case "import.meta": { const preset = getPresetForLexicalEnvironment(env); return (preset === "NODE_ESM" || preset === "BROWSER" || preset === "ECMA") && typeof literal === "object" && literal != null && typeof literal.url === "function" && node != null ? { literal: { url: literal.url(node.getSourceFile().fileName) } } : { literal }; } default: return { literal }; } } if (env.parentEnv != null) return getFromLexicalEnvironment(node, env.parentEnv, path4); return void 0; } function pathInLexicalEnvironmentEquals(node, env, equals, ...matchPaths) { return matchPaths.some((path4) => { const match = getFromLexicalEnvironment(node, env, path4); return match == null ? false : match.literal === equals; }); } function isInternalSymbol(value) { switch (value) { case RETURN_SYMBOL: case BREAK_SYMBOL: case CONTINUE_SYMBOL: case THIS_SYMBOL: case SUPER_SYMBOL: return true; default: return false; } } function setInLexicalEnvironment({ environment, path: path4, value, reporting, node, newBinding = false }) { const [firstBinding] = path4.split("."); if (firstBinding == null) return void 0; if (import_object_path.default.has(environment.env, firstBinding) || newBinding || environment.parentEnv == null) { if (import_object_path.default.has(environment.env, path4) && import_object_path.default.get(environment.env, path4) === value) return; import_object_path.default.set(environment.env, path4, value); if (reporting.reportBindings != null && !isInternalSymbol(path4)) { reporting.reportBindings({ path: path4, value, node }); } } else { let currentParentEnv = environment.parentEnv; while (currentParentEnv != null) { if (import_object_path.default.has(currentParentEnv.env, firstBinding)) { if (import_object_path.default.has(currentParentEnv.env, path4) && import_object_path.default.get(currentParentEnv.env, path4) === value) return; import_object_path.default.set(currentParentEnv.env, path4, value); if (reporting.reportBindings != null && !isInternalSymbol(path4)) { reporting.reportBindings({ path: path4, value, node }); } return; } else { if (currentParentEnv.parentEnv == null) { import_object_path.default.set(currentParentEnv.env, path4, value); if (reporting.reportBindings != null && !isInternalSymbol(path4)) { reporting.reportBindings({ path: path4, value, node }); } } else { currentParentEnv = currentParentEnv.parentEnv; } } } } } function createLexicalEnvironment({ inputEnvironment: { extra, preset }, startingNode, policy }) { let env; switch (preset) { case "NONE": env = mergeDescriptors(extra); break; case "ECMA": env = mergeDescriptors(ECMA_GLOBALS(), extra); break; case "NODE": case "NODE_CJS": env = mergeDescriptors(NODE_CJS_GLOBALS(), extra); break; case "NODE_ESM": env = mergeDescriptors(NODE_ESM_GLOBALS(), extra); break; case "BROWSER": env = mergeDescriptors(BROWSER_GLOBALS(), extra); break; default: env = {}; break; } return { parentEnv: void 0, preset, startingNode, env: createSanitizedEnvironment({ policy, env }) }; } // src/interpreter/util/node/is-boolean-literal.ts function isBooleanLiteral(node, typescript) { return node.kind === typescript.SyntaxKind.TrueKeyword || node.kind === typescript.SyntaxKind.FalseKeyword; } // src/interpreter/util/node/is-null-literal.ts function isNullLiteral(node, typescript) { return node.kind === typescript.SyntaxKind.NullKeyword; } // src/interpreter/evaluator/simple/evaluate-simple-literal.ts function evaluateSimpleLiteral(node, typescript) { if (typescript.isStringLiteralLike(node)) return { success: true, value: node.text }; else if (isBooleanLiteral(node, typescript)) return { success: true, value: node.kind === typescript.SyntaxKind.TrueKeyword }; else if (typescript.isRegularExpressionLiteral(node)) return { success: true, value: new Function(`return ${node.text}`)() }; else if (typescript.isNumericLiteral(node)) return { success: true, value: Number(node.text) }; else if (typescript.isBigIntLiteral?.(node)) return { success: true, value: BigInt(node.text) }; else if (typescript.isIdentifier(node) && node.text === "Infinity") return { success: true, value: Infinity }; else if (typescript.isIdentifier(node) && node.text === "NaN") return { success: true, value: NaN }; else if (typescript.isIdentifier(node) && node.text === "null") return { success: true, value: null }; else if (typescript.isIdentifier(node) && node.text === "undefined") return { success: true, value: void 0 }; else if (isNullLiteral(node, typescript)) return { success: true, value: null }; else return { success: false }; } // src/interpreter/error/policy-error/max-ops-exceeded-error/max-ops-exceeded-error.ts var MaxOpsExceededError = class extends PolicyError { /** * The amount of operations performed before creating this error instance */ ops; constructor({ ops, node, environment, message = `Maximum ops exceeded: ${ops}` }) { super({ violation: "maxOps", message, node, environment }); this.ops = ops; } }; // src/interpreter/evaluator/evaluate-variable-declaration.ts function evaluateVariableDeclaration(options, initializer) { const { node, environment, evaluate: evaluate2, stack, typescript, throwError, getCurrentError } = options; const initializerResult = initializer ?? (node.initializer == null ? ( // A VariableDeclaration with no initializer is implicitly bound to 'undefined' void 0 ) : evaluate2.expression(node.initializer, options)); if (getCurrentError() != null) { return; } if (initializerResult == null && !typescript.isIdentifier(node.name)) { return throwError(new EvaluationError({ node, environment })); } evaluate2.nodeWithArgument(node.name, initializerResult, options); if (getCurrentError() != null) { return; } stack.push(initializerResult); return; } // src/interpreter/util/node/is-this-expression.ts function isThisExpression(node, typescript) { return node.kind === typescript.SyntaxKind.ThisKeyword; } // src/interpreter/util/node/is-super-expression.ts function isSuperExpression(node, typescript) { return node.kind === typescript.SyntaxKind.SuperKeyword; } // src/interpreter/lexical-environment/get-dot-path-from-node.ts function getDotPathFromNode(options) { const { node, evaluate: evaluate2, typescript } = options; if (typescript.isIdentifier(node)) { return node.text; } else if (typescript.isPrivateIdentifier?.(node)) { return node.text; } else if (isThisExpression(node, typescript)) { return THIS_SYMBOL; } else if (isSuperExpression(node, typescript)) { return SUPER_SYMBOL; } else if (typescript.isParenthesizedExpression(node)) { return getDotPathFromNode({ ...options, node: node.expression }); } else if (typescript.isTypeAssertionExpression?.(node) || !("isTypeAssertionExpression" in typescript) && typescript.isTypeAssertion(node)) { return getDotPathFromNode({ ...options, node: node.expression }); } else if (typescript.isPropertyAccessExpression(node)) { let leftHand = getDotPathFromNode({ ...options, node: node.expression }); if (leftHand == null) leftHand = evaluate2.expression(node.expression, options); let rightHand = getDotPathFromNode({ ...options, node: node.name }); if (rightHand == null) rightHand = evaluate2.expression(node.name, options); if (leftHand == null || rightHand == null) return void 0; return `${leftHand}.${rightHand}`; } else if (typescript.isElementAccessExpression(node)) { let leftHand = getDotPathFromNode({ ...options, node: node.expression }); if (leftHand == null) leftHand = evaluate2.expression(node.expression, options); const rightHand = evaluate2.expression(node.argumentExpression, options); if (leftHand == null || rightHand == null) return void 0; return `${leftHand}.${rightHand}`; } else if (typescript.isFunctionDeclaration(node)) { if (node.name == null) return void 0; return node.name.text; } return void 0; } // src/interpreter/error/undefined-left-value-error/undefined-left-value-error.ts var UndefinedLeftValueError = class extends EvaluationError { constructor({ node, environment, message = `'No leftValue could be determined'` }) { super({ message, environment, node }); } }; // src/interpreter/util/node/get-inner-node.ts function getInnerNode(node, typescript) { if (typescript.isParenthesizedExpression(node)) return getInnerNode(node.expression, typescript); else if (typescript.isAsExpression(node)) return getInnerNode(node.expression, typescript); else if (typescript.isTypeAssertionExpression?.(node) || !("isTypeAssertionExpression" in typescript) && typescript.isTypeAssertion(node)) { return getInnerNode(node.expression, typescript); } else { return node; } } // src/interpreter/util/node/is-node.ts function isTypescriptNode(node) { return node != null && typeof node === "object" && "kind" in node && "flags" in node && "pos" in node && "end" in node; } // src/interpreter/evaluator/evaluate-binary-expression.ts function evaluateBinaryExpression(options) { const { node, environment, evaluate: evaluate2, logger, throwError, typeChecker, typescript, getCurrentError } = options; const leftValue = evaluate2.expression(node.left, options); if (getCurrentError() != null) { return; } const rightValue = evaluate2.expression(node.right, options); if (getCurrentError() != null) { return; } const leftIdentifier = getDotPathFromNode({ ...options, node: node.left }); const operator = node.operatorToken.kind; switch (operator) { case typescript.SyntaxKind.AmpersandToken: { return leftValue & rightValue; } case typescript.SyntaxKind.AmpersandAmpersandToken: { return leftValue && rightValue; } case typescript.SyntaxKind.AmpersandEqualsToken: case typescript.SyntaxKind.CaretEqualsToken: case typescript.SyntaxKind.BarEqualsToken: case typescript.SyntaxKind.MinusEqualsToken: case typescript.SyntaxKind.PlusEqualsToken: case typescript.SyntaxKind.PercentEqualsToken: case typescript.SyntaxKind.SlashEqualsToken: case typescript.SyntaxKind.AsteriskEqualsToken: case typescript.SyntaxKind.AsteriskAsteriskEqualsToken: case typescript.SyntaxKind.LessThanLessThanEqualsToken: case typescript.SyntaxKind.GreaterThanGreaterThanEqualsToken: case typescript.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: case typescript.SyntaxKind.QuestionQuestionEqualsToken: case typescript.SyntaxKind.BarBarEqualsToken: case typescript.SyntaxKind.AmpersandAmpersandEqualsToken: { let computedValue = leftValue; switch (operator) { case typescript.SyntaxKind.AmpersandEqualsToken: computedValue &= rightValue; break; case typescript.SyntaxKind.CaretEqualsToken: computedValue ^= rightValue; break; case typescript.SyntaxKind.BarEqualsToken: computedValue |= rightValue; break; case typescript.SyntaxKind.AsteriskEqualsToken: computedValue *= rightValue; break; case typescript.SyntaxKind.AsteriskAsteriskEqualsToken: computedValue **= rightValue; break; case typescript.SyntaxKind.LessThanLessThanEqualsToken: computedValue <<= rightValue; break; case typescript.SyntaxKind.GreaterThanGreaterThanEqualsToken: computedValue >>= rightValue; break; case typescript.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: computedValue >>>= rightValue; break; case typescript.SyntaxKind.MinusEqualsToken: computedValue -= rightValue; break; case typescript.SyntaxKind.PlusEqualsToken: computedValue += rightValue; break; case typescript.SyntaxKind.PercentEqualsToken: computedValue %= rightValue; break; case typescript.SyntaxKind.SlashEqualsToken: computedValue /= rightValue; break; case typescript.SyntaxKind.QuestionQuestionEqualsToken: computedValue = leftValue ?? rightValue; break; case typescript.SyntaxKind.BarBarEqualsToken: if (!leftValue) { computedValue = rightValue; } break; case typescript.SyntaxKind.AmpersandAmpersandEqualsToken: if (leftValue) { computedValue = rightValue; } break; } if (leftIdentifier != null) { setInLexicalEnvironment({ ...options, path: leftIdentifier, value: computedValue }); } return computedValue; } case typescript.SyntaxKind.AsteriskToken: { return leftValue * rightValue; } case typescript.SyntaxKind.AsteriskAsteriskToken: { return leftValue ** rightValue; } case typescript.SyntaxKind.BarToken: { return leftValue | rightValue; } case typescript.SyntaxKind.BarBarToken: { return leftValue || rightValue; } case typescript.SyntaxKind.CaretToken: { return leftValue ^ rightValue; } case typescript.SyntaxKind.CommaToken: { return rightValue; } case typescript.SyntaxKind.MinusToken: return leftValue - rightValue; case typescript.SyntaxKind.PlusToken: logger.logResult(leftValue + rightValue, "BinaryExpression (PlusToken)"); return leftValue + rightValue; case typescript.SyntaxKind.PercentToken: return leftValue % rightValue; case typescript.SyntaxKind.SlashToken: return leftValue / rightValue; case typescript.SyntaxKind.EqualsToken: { if (leftIdentifier != null) { const innerLeftIdentifier = getInnerNode(node.left, typescript); const leftIdentifierSymbol = typeChecker?.getSymbolAtLocation(innerLeftIdentifier); let leftIdentifierValueDeclaration = leftIdentifierSymbol?.valueDeclaration; if (leftIdentifierValueDeclaration == null && typeChecker == null && typescript.isIdentifier(innerLeftIdentifier)) { const result = findNearestParentNodeWithName(innerLeftIdentifier.parent, innerLeftIdentifier.text, options); if (isTypescriptNode(result)) { leftIdentifierValueDeclaration = result; } } const bestLexicalEnvironment = leftIdentifierValueDeclaration == null ? environment : findLexicalEnvironmentInSameContext(environment, leftIdentifierValueDeclaration, typescript) ?? environment; setInLexicalEnvironment({ ...options, environment: bestLexicalEnvironment, path: leftIdentifier, value: rightValue }); logger.logBinding(leftIdentifier, rightValue, "Assignment"); } else { return throwError(new UndefinedLeftValueError({ node: node.left, environment })); } return rightValue; } case typescript.SyntaxKind.EqualsEqualsToken: { return leftValue == rightValue; } case typescript.SyntaxKind.EqualsEqualsEqualsToken: { return leftValue === rightValue; } case typescript.SyntaxKind.ExclamationEqualsToken: { return leftValue != rightValue; } case typescript.SyntaxKind.ExclamationEqualsEqualsToken: { return leftValue !== rightValue; } case typescript.SyntaxKind.GreaterThanToken: return leftValue > rightValue; case typescript.SyntaxKind.GreaterThanEqualsToken: return leftValue >= rightValue; case typescript.SyntaxKind.LessThanToken: return leftValue < rightValue; case typescript.SyntaxKind.LessThanEqualsToken: return leftValue <= rightValue; case typescript.SyntaxKind.InKeyword: { return leftValue in rightValue; } // Nullish coalescing (A ?? B) case typescript.SyntaxKind.QuestionQuestionToken: return leftValue ?? rightValue; case typescript.SyntaxKind.InstanceOfKeyword: { return leftValue instanceof rightValue; } } return throwError(new UnexpectedNodeError({ node: node.operatorToken, typescript, environment })); } // src/interpreter/literal/literal.ts var LAZY_CALL_FLAG = "___lazyCallFlag"; function isLazyCall(literal) { return literal != null && typeof literal === "object" && LAZY_CALL_FLAG in literal; } function stringifyLiteral(literal) { if (literal === void 0) return "undefined"; else if (literal === null) return "null"; else if (typeof literal === "string") return `"${literal}"`; return literal.toString(); } // src/interpreter/error/not-callable-error/not-callable-error.ts var NotCallableError = class extends EvaluationError { /** * The non-callable value */ value; constructor({ value, node, environment, message = `${stringifyLiteral(value)} is not a function'` }) { super({ message, environment, node }); this.value = value; } }; // src/interpreter/util/expression/expression-contains-super-keyword.ts function expressionContainsSuperKeyword(expression, typescript) { if (isSuperExpression(expression, typescript)) return true; else if (typescript.isPropertyAccessExpression(expression)) { return expressionContainsSuperKeyword(expression.expression, typescript) || expressionContainsSuperKeyword(expression.name, typescript); } else if (typescript.isElementAccessExpression(expression)) { return expressionContainsSuperKeyword(expression.expression, typescript) || expressionContainsSuperKeyword(expression.argumentExpression, typescript); } else if (typescript.isParenthesizedExpression(expression)) return expressionContainsSuperKeyword(expression.expression, typescript); else if (typescript.isAsExpression(expression)) return expressionContainsSuperKeyword(expression.expression, typescript); else if (typescript.isTypeAssertionExpression?.(expression) || !("isTypeAssertionExpression" in typescript) && typescript.isTypeAssertion(expression)) { return expressionContainsSuperKeyword(expression.expression, typescript); } else { return false; } } // src/interpreter/evaluator/evaluate-call-expression.ts function evaluateCallExpression(options) { const { node, environment, evaluate: evaluate2, throwError, typescript, logger, getCurrentError } = options; const evaluatedArgs = []; for (let i = 0; i < node.arguments.length; i++) { const argument = node.arguments[i]; if (argument == null) continue; evaluatedArgs[i] = evaluate2.expression(argument, options); if (getCurrentError() != null) { return; } } const expressionResult = evaluate2.expression(node.expression, options); if (getCurrentError() != null) { return; } if (isLazyCall(expressionResult)) { const currentThisBinding = expressionContainsSuperKeyword(node.expression, typescript) ? getFromLexicalEnvironment(node, environment, THIS_SYMBOL) : void 0; const value = expressionResult.invoke(currentThisBinding != null ? currentThisBinding.literal : void 0, ...evaluatedArgs); if (getCurrentError() != null) { return; } logger.logResult(value, "CallExpression"); return value; } else { if (node.questionDotToken == null && typeof expressionResult !== "function") { return throwError(new NotCallableError({ value: expressionResult, node: node.expression, environment })); } const value = typeof expressionResult !== "function" ? void 0 : maybeThrow(node, options, expressionResult(...evaluatedArgs)); if (getCurrentError() != null) { return; } logger.logResult(value, "CallExpression"); return value; } } // src/interpreter/evaluator/evaluate-parenthesized-expression.ts function evaluateParenthesizedExpression({ node, evaluate: evaluate2, ...options }) { return evaluate2.expression(node.expression, options); } // src/interpreter/lexical-environment/clone-lexical-environment.ts function cloneLexicalEnvironment(environment, startingNode) { return { parentEnv: environment, startingNode, env: {} }; } // src/interpreter/util/modifier/has-modifier.ts function hasModifier(node, modifier) { const modifiers = Array.isArray(node) ? node : "modifiers" in node && Array.isArray(node.modifiers) ? node.modifiers : void 0; return Boolean(modifiers?.some((m) => m.kind === modifier)); } // src/interpreter/evaluator/evaluate-parameter-declarations.ts function evaluateParameterDeclarations(options, boundArguments, context) { const { node, evaluate: evaluate2, environment, typescript, getCurrentError } = options; const parameters = node.filter((param) => !(typescript.isIdentifier(param.name) && param.name.text === "this")); for (let i = 0; i < parameters.length; i++) { const parameter = parameters[i]; if (parameter.dotDotDotToken != null) { evaluate2.nodeWithArgument(parameter, boundArguments.slice(i), options); if (getCurrentError() != null) { return; } break; } else { evaluate2.nodeWithArgument(parameter, boundArguments[i], options); if (getCurrentError() != null) { return; } if (context != null && typescript.isIdentifier(parameter.name) && (hasModifier(parameter, typescript.SyntaxKind.PublicKeyword) || hasModifier(parameter, typescript.SyntaxKind.ProtectedKeyword) || hasModifier(parameter, typescript.SyntaxKind.PrivateKeyword))) { const value = getFromLexicalEnvironment(parameter, environment, parameter.name.text); if (value != null) { context[parameter.name.text] = value.literal; } } } } } // src/interpreter/evaluator/evaluate-arrow-function-expression.ts function evaluateArrowFunctionExpression(options) { const { node, environment, evaluate: evaluate2, stack, typescript, getCurrentError } = options; const arrowFunctionExpression = hasModifier(node, typescript.SyntaxKind.AsyncKeyword) ? async (...args) => { const localLexicalEnvironment = cloneLexicalEnvironment(environment, node); const nextOptions = { ...options, environment: localLexicalEnvironment }; setInLexicalEnvironment({ ...nextOptions, path: RETURN_SYMBOL, value: false, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: "arguments", value: arguments, newBinding: true }); evaluateParameterDeclarations( { ...options, node: node.parameters, environment: localLexicalEnvironment }, args ); if (getCurrentError() != null) { return; } if (typescript.isBlock(node.body)) { evaluate2.statement(node.body, nextOptions); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, localLexicalEnvironment, true, RETURN_SYMBOL)) { return stack.pop(); } else return void 0; } else { return evaluate2.expression(node.body, nextOptions); } } : (...args) => { const localLexicalEnvironment = cloneLexicalEnvironment(environment, node); const nextOptions = { ...options, environment: localLexicalEnvironment }; setInLexicalEnvironment({ ...nextOptions, path: RETURN_SYMBOL, value: false, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: "arguments", value: arguments, newBinding: true }); evaluateParameterDeclarations( { ...options, node: node.parameters, environment: localLexicalEnvironment }, args ); if (getCurrentError() != null) { return; } if (typescript.isBlock(node.body)) { evaluate2.statement(node.body, nextOptions); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, localLexicalEnvironment, true, RETURN_SYMBOL)) { return stack.pop(); } else return void 0; } else { return evaluate2.expression(node.body, nextOptions); } }; arrowFunctionExpression.toString = () => `[Function: anonymous]`; Object.setPrototypeOf(arrowFunctionExpression, getFromLexicalEnvironment(node, environment, "Function").literal); return arrowFunctionExpression; } // src/interpreter/evaluator/evaluate-string-literal.ts function evaluateStringLiteral({ node }) { return node.text; } // src/interpreter/evaluator/evaluate-numeric-literal.ts function evaluateNumericLiteral({ node }) { return Number(node.text); } // src/interpreter/evaluator/evaluate-boolean-literal.ts function evaluateBooleanLiteral({ node, typescript }) { return node.kind === typescript.SyntaxKind.TrueKeyword; } // src/interpreter/evaluator/evaluate-regular-expression-literal.ts function evaluateRegularExpressionLiteral({ node, environment }) { const functionCtor = getFromLexicalEnvironment(node, environment, "Function").literal; return new functionCtor(`return ${node.text}`)(); } // src/interpreter/evaluator/evaluate-object-literal-expression.ts function evaluateObjectLiteralExpression(options) { const { node, evaluate: evaluate2, environment, getCurrentError } = options; const objectCtor = getFromLexicalEnvironment(node, environment, "Object").literal; const value = objectCtor.create(objectCtor.prototype); setInLexicalEnvironment({ ...options, path: THIS_SYMBOL, value, newBinding: true }); for (const property of node.properties) { evaluate2.nodeWithArgument(property, value, options); if (getCurrentError() != null) { return; } } return value; } // src/interpreter/util/iterable/is-iterable.ts function isIterable(item) { return item != null && item[Symbol.iterator] != null; } // src/interpreter/evaluator/evaluate-array-literal-expression.ts function evaluateArrayLiteralExpression(options) { const { node, environment, evaluate: evaluate2, typescript, getCurrentError } = options; const arrayCtor = getFromLexicalEnvironment(node, environment, "Array").literal; const value = arrayCtor.of(); for (const element of node.elements) { const nextValue = evaluate2.expression(element, options); if (getCurrentError() != null) { return; } if (typescript.isSpreadElement(element) && isIterable(nextValue)) { value.push(...nextValue); } else { value.push(nextValue); } } return value; } // src/interpreter/error/undefined-identifier-error/undefined-identifier-error.ts var UndefinedIdentifierError = class extends EvaluationError { constructor({ node, environment, message = `'${node.text}' is not defined'` }) { super({ message, environment, node }); } }; // src/interpreter/evaluator/evaluate-identifier.ts function evaluateIdentifier(options) { const { node, environment, typeChecker, evaluate: evaluate2, stack, logger, reporting, typescript, throwError, getCurrentError } = options; const environmentMatch = getFromLexicalEnvironment(node, environment, node.text); if (environmentMatch != null) { logger.logBinding(node.text, environmentMatch.literal, "Lexical Environment match"); return environmentMatch.literal; } const symbol = typescript.isShorthandPropertyAssignment(node.parent) ? typeChecker?.getShorthandAssignmentValueSymbol(node.parent) : typeChecker?.getSymbolAtLocation(node); let valueDeclaration = symbol == null ? void 0 : symbol.valueDeclaration; if (symbol != null && valueDeclaration == null) { try { const aliasedSymbol = typeChecker?.getAliasedSymbol(symbol); valueDeclaration = aliasedSymbol?.valueDeclaration; } catch { } } if (valueDeclaration == null) { const result = findNearestParentNodeWithName(node.parent, node.text, options); if (getCurrentError() != null) { return; } if (isTypescriptNode(result) && !typescript.isIdentifier(result)) { valueDeclaration = result; } else if (result != null) { setInLexicalEnvironment({ ...options, path: node.text, value: result }); logger.logBinding(node.text, result, `Discovered declaration value`); return result; } } if (valueDeclaration != null) { if (valueDeclaration.getSourceFile().isDeclarationFile) { const implementation = getImplementationForDeclarationWithinDeclarationFile({ ...options, node: valueDeclaration }); if (getCurrentError() != null) { return; } setInLexicalEnvironment({ environment, path: node.text, value: implementation, reporting, node: valueDeclaration }); logger.logBinding( node.text, implementation, `Discovered declaration value${valueDeclaration.getSourceFile() === node.getSourceFile() ? "" : ` (imported into '${node.getSourceFile().fileName}' from '${valueDeclaration.getSourceFile().fileName}')`}` ); return implementation; } if (typescript.isVariableDeclaration(valueDeclaration) && valueDeclaration.getSourceFile().fileName === node.getSourceFile().fileName && valueDeclaration.pos > node.pos) { if (typescript.isVariableDeclarationList(valueDeclaration.parent) && isVarDeclaration(valueDeclaration.parent, typescript)) { const returnValue = void 0; setInLexicalEnvironment({ ...options, path: node.text, value: returnValue, newBinding: true, node: valueDeclaration }); logger.logBinding(node.text, returnValue, "Hoisted var declaration"); return returnValue; } else { return throwError(new UndefinedIdentifierError({ node, environment })); } } evaluate2.declaration(valueDeclaration, options); if (getCurrentError() != null) { return; } const stackValue = stack.pop(); setInLexicalEnvironment({ ...options, path: node.text, value: stackValue, node: valueDeclaration }); logger.logBinding( node.text, stackValue, `Discovered declaration value${valueDeclaration.getSourceFile() === node.getSourceFile() ? "" : ` (imported into '${node.getSourceFile().fileName}' from '${valueDeclaration.getSourceFile().fileName}')`}` ); return stackValue; } return throwError(new UndefinedIdentifierError({ node, environment })); } // src/interpreter/evaluator/evaluate-block.ts function evaluateBlock(options) { const { node, environment, typescript, evaluate: evaluate2, getCurrentError } = options; const localLexicalEnvironment = cloneLexicalEnvironment(environment, node); for (let i = 0; i < node.statements.length; i++) { const statement = node.statements[i]; if (statement == null) continue; if (typescript.isConstructorDeclaration(node.parent) && i === 0 && typescript.isExpressionStatement(statement) && typescript.isCallExpression(statement.expression) && isSuperExpression(statement.expression.expression, typescript)) { continue; } evaluate2.statement(statement, { ...options, environment: localLexicalEnvironment }); if (getCurrentError() != null) break; if (pathInLexicalEnvironmentEquals(node, localLexicalEnvironment, true, BREAK_SYMBOL, CONTINUE_SYMBOL, RETURN_SYMBOL)) { break; } } } // src/interpreter/evaluator/evaluate-return-statement.ts function evaluateReturnStatement({ node, evaluate: evaluate2, stack, ...options }) { const { getCurrentError } = options; setInLexicalEnvironment({ ...options, environment: options.environment, path: RETURN_SYMBOL, value: true, node }); if (node.expression == null) { stack.push(void 0); } else { const result = evaluate2.expression(node.expression, options); if (getCurrentError() != null) { return; } stack.push(result); } } // src/interpreter/evaluator/evaluate-variable-declaration-list.ts function evaluateVariableDeclarationList({ node, evaluate: evaluate2, ...options }) { for (const declaration of node.declarations) { evaluate2.declaration(declaration, options); if (options.getCurrentError() != null) { return; } } } // src/interpreter/evaluator/evaluate-variable-statement.ts function evaluateVariableStatement({ node, ...rest }) { evaluateVariableDeclarationList({ node: node.declarationList, ...rest }); } // src/interpreter/evaluator/evaluate-prefix-unary-expression.ts function evaluatePrefixUnaryExpression(options) { const { node, environment, evaluate: evaluate2, reporting, typescript, throwError, getCurrentError } = options; const operandValue = evaluate2.expression(node.operand, options); if (getCurrentError() != null) { return; } switch (node.operator) { case typescript.SyntaxKind.PlusToken: { return +operandValue; } case typescript.SyntaxKind.MinusToken: { return -operandValue; } case typescript.SyntaxKind.TildeToken: { return ~operandValue; } case typescript.SyntaxKind.ExclamationToken: { return !operandValue; } case typescript.SyntaxKind.PlusPlusToken: { if (!typescript.isIdentifier(node.operand) && !typescript.isPrivateIdentifier?.(node.operand)) { return throwError(new UnexpectedNodeError({ node: node.operand, environment, typescript })); } const dict = getRelevantDictFromLexicalEnvironment(environment, node.operand.text); const value = ++dict[node.operand.text]; if (reporting.reportBindings != null) { reporting.reportBindings({ path: node.operand.text, value, node }); } return value; } case typescript.SyntaxKind.MinusMinusToken: { if (!typescript.isIdentifier(node.operand) && !typescript.isPrivateIdentifier?.(node.operand)) { return throwError(new UnexpectedNodeError({ node: node.operand, environment, typescript })); } const dict = getRelevantDictFromLexicalEnvironment(environment, node.operand.text); const value = --dict[node.operand.text]; if (reporting.reportBindings != null) { reporting.reportBindings({ path: node.operand.text, value, node }); } return value; } } } // src/interpreter/evaluator/evaluate-property-access-expression.ts function evaluatePropertyAccessExpression(options) { const { evaluate: evaluate2, node, statementTraversalStack, environment, typescript, getCurrentError } = options; const expressionResult = evaluate2.expression(node.expression, options); if (expressionResult == null || getCurrentError() != null) { return; } const match = node.questionDotToken != null && expressionResult == null ? ( // If optional chaining are being used and the expressionResult is undefined or null, assign undefined to 'match' void 0 ) : expressionResult[node.name.text]; if (typeof match === "function" && statementTraversalStack.includes(typescript.SyntaxKind.CallExpression)) { return { [LAZY_CALL_FLAG]: 0 /* CALL */, invoke: (overriddenThis, ...args) => maybeThrow( node, options, overriddenThis != null && !isBindCallApply(match, environment) ? ( // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type expressionResult[node.name.text].call(overriddenThis, ...args) ) : expressionResult[node.name.text](...args) ) }; } else return match; } // src/interpreter/evaluator/evaluate-element-access-expression.ts function evaluateElementAccessExpression(options) { const { node, environment, evaluate: evaluate2, statementTraversalStack, typescript, getCurrentError } = options; const expressionResult = evaluate2.expression(node.expression, options); if (getCurrentError() != null) { return; } const argumentExpressionResult = evaluate2.expression(node.argumentExpression, options); if (getCurrentError() != null) { return; } const match = node.questionDotToken != null && expressionResult == null ? ( // If optional chaining are being used and the expressionResult is undefined or null, assign undefined to 'match' void 0 ) : expressionResult[argumentExpressionResult]; if (typeof match === "function" && statementTraversalStack.includes(typescript.SyntaxKind.CallExpression)) { return { [LAZY_CALL_FLAG]: 0 /* CALL */, invoke: (overriddenThis, ...args) => maybeThrow( node, options, overriddenThis != null && !isBindCallApply(match, environment) ? ( // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type expressionResult[argumentExpressionResult].call(overriddenThis, ...args) ) : expressionResult[argumentExpressionResult](...args) ) }; } else return match; } // src/interpreter/evaluator/evaluate-computed-property-name.ts function evaluateComputedPropertyName({ node, evaluate: evaluate2, ...options }) { return evaluate2.expression(node.expression, options); } // src/interpreter/evaluator/evaluate-function-declaration.ts function evaluateFunctionDeclaration(options) { const { node, environment, evaluate: evaluate2, stack, typescript, getCurrentError } = options; const nameResult = node.name == null ? void 0 : node.name.text; const _functionDeclaration = hasModifier(node, typescript.SyntaxKind.AsyncKeyword) ? async function functionDeclaration(...args) { const localLexicalEnvironment = cloneLexicalEnvironment(environment, node); const nextOptions = { ...options, environment: localLexicalEnvironment }; setInLexicalEnvironment({ ...nextOptions, path: RETURN_SYMBOL, value: false, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: "arguments", value: arguments, newBinding: true }); if (this != null) { setInLexicalEnvironment({ ...nextOptions, path: THIS_SYMBOL, value: this, newBinding: true }); } evaluateParameterDeclarations( { ...options, node: node.parameters, environment: localLexicalEnvironment }, args ); if (getCurrentError() != null) { return; } const sourceFile = node.getSourceFile(); if (nameResult != null && sourceFile.isDeclarationFile) { const implementation = getImplementationForDeclarationWithinDeclarationFile(options); return implementation(...args); } if (node.body == null) return; evaluate2.statement(node.body, nextOptions); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, localLexicalEnvironment, true, RETURN_SYMBOL)) { return stack.pop(); } else { return void 0; } } : function functionDeclaration(...args) { const localLexicalEnvironment = cloneLexicalEnvironment(environment, node); const nextOptions = { ...options, environment: localLexicalEnvironment }; setInLexicalEnvironment({ ...nextOptions, path: RETURN_SYMBOL, value: false, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: "arguments", value: arguments, newBinding: true }); if (this != null) { setInLexicalEnvironment({ ...nextOptions, path: THIS_SYMBOL, value: this, newBinding: true }); } evaluateParameterDeclarations( { ...nextOptions, node: node.parameters }, args ); if (getCurrentError() != null) { return; } const sourceFile = node.getSourceFile(); if (nameResult != null && sourceFile.isDeclarationFile) { const implementation = getImplementationForDeclarationWithinDeclarationFile(options); return implementation(...args); } if (node.body == null) return; evaluate2.statement(node.body, nextOptions); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, localLexicalEnvironment, true, RETURN_SYMBOL)) { return stack.pop(); } else return void 0; }; if (nameResult != null) { setInLexicalEnvironment({ ...options, path: nameResult, value: _functionDeclaration.bind(_functionDeclaration) }); } _functionDeclaration.toString = () => `[Function${nameResult == null ? "" : `: ${nameResult}`}]`; Object.setPrototypeOf(_functionDeclaration, getFromLexicalEnvironment(node, environment, "Function").literal); stack.push(_functionDeclaration); } // src/interpreter/evaluator/evaluate-if-statement.ts function evaluateIfStatement({ node, evaluate: evaluate2, ...options }) { const { getCurrentError } = options; const expressionValue = evaluate2.expression(node.expression, options); if (getCurrentError() != null) { return; } if (expressionValue) { evaluate2.statement(node.thenStatement, options); if (getCurrentError() != null) { return; } } else if (node.elseStatement != null) { return evaluate2.statement(node.elseStatement, options); } return; } // src/interpreter/evaluator/evaluate-expression-statement.ts function evaluateExpressionStatement({ node, evaluate: evaluate2, stack, ...options }) { const result = evaluate2.expression(node.expression, options); if (options.getCurrentError() != null) { return; } stack.push(result); } // src/interpreter/evaluator/evaluate-template-expression.ts function evaluateTemplateExpression({ node, evaluate: evaluate2, ...options }) { let str = ""; str += node.head.text; for (const span of node.templateSpans) { const expression = evaluate2.expression(span.expression, options); if (options.getCurrentError() != null) { return; } str += expression; str += span.literal.text; } return str; } // src/interpreter/evaluator/evaluate-type-assertion-expression.ts function evaluateTypeAssertion({ node, evaluate: evaluate2, ...options }) { return evaluate2.expression(node.expression, options); } // src/interpreter/evaluator/evaluate-postfix-unary-expression.ts function evaluatePostfixUnaryExpression(options) { const { evaluate: evaluate2, node, environment, typescript, throwError, reporting } = options; evaluate2.expression(node.operand, options); switch (node.operator) { case typescript.SyntaxKind.PlusPlusToken: { if (!typescript.isIdentifier(node.operand) && !typescript.isPrivateIdentifier?.(node.operand)) { return throwError(new UnexpectedNodeError({ node: node.operand, environment, typescript })); } const value = getRelevantDictFromLexicalEnvironment(environment, node.operand.text)[node.operand.text]++; if (reporting.reportBindings != null) { reporting.reportBindings({ path: node.operand.text, value, node }); } return value; } case typescript.SyntaxKind.MinusMinusToken: { if (!typescript.isIdentifier(node.operand) && !typescript.isPrivateIdentifier?.(node.operand)) { return throwError(new UnexpectedNodeError({ node: node.operand, environment, typescript })); } const value = getRelevantDictFromLexicalEnvironment(environment, node.operand.text)[node.operand.text]--; if (reporting.reportBindings != null) { reporting.reportBindings({ path: node.operand.text, value, node }); } return value; } } } // src/interpreter/evaluator/evaluate-new-expression.ts function evaluateNewExpression({ node, evaluate: evaluate2, ...options }) { const { getCurrentError } = options; const evaluatedArgs = []; if (node.arguments != null) { for (let i = 0; i < node.arguments.length; i++) { evaluatedArgs[i] = evaluate2.expression(node.arguments[i], options); if (getCurrentError() != null) { return; } } } const expressionResult = evaluate2.expression(node.expression, options); if (getCurrentError() != null) { return; } if (typeof expressionResult === "function") { setInLexicalEnvironment({ ...options, node, path: "[[NewTarget]]", value: expressionResult, newBinding: true }); } return maybeThrow(node, options, new expressionResult(...evaluatedArgs)); } // src/interpreter/evaluator/evaluate-non-null-expression.ts function evaluateNonNullExpression({ node, evaluate: evaluate2, ...options }) { return evaluate2.expression(node.expression, options); } // src/interpreter/evaluator/evaluate-as-expression.ts function evaluateAsExpression({ node, evaluate: evaluate2, ...options }) { return evaluate2.expression(node.expression, options); } // src/interpreter/evaluator/evaluate-switch-statement.ts function evaluateSwitchStatement({ node, evaluate: evaluate2, ...options }) { const expressionResult = evaluate2.expression(node.expression, options); if (options.getCurrentError() != null) { return; } evaluate2.nodeWithArgument(node.caseBlock, expressionResult, options); } // src/interpreter/error/async-iterator-not-supported-error/async-iterator-not-supported-error.ts var AsyncIteratorNotSupportedError = class extends EvaluationError { constructor({ message = `It is not possible to evaluate an async iterator'`, typescript, environment }) { super({ message, environment, node: typescript.factory?.createEmptyStatement() ?? typescript.createEmptyStatement() }); } }; // src/interpreter/evaluator/evaluate-for-of-statement.ts function evaluateForOfStatement(options) { const { node, environment, evaluate: evaluate2, logger, typescript, throwError, getCurrentError } = options; const expressionResult = evaluate2.expression(node.expression, options); if (getCurrentError() != null) { return; } if (!typescript.isVariableDeclarationList(node.initializer)) { return throwError(new UnexpectedNodeError({ node: node.initializer, environment, typescript })); } else if (node.initializer.declarations.length > 1) { return throwError(new UnexpectedNodeError({ node: node.initializer.declarations[1], environment, typescript })); } if (node.awaitModifier != null) { return throwError(new AsyncIteratorNotSupportedError({ typescript, environment })); } else { for (const literal of expressionResult) { const localEnvironment = cloneLexicalEnvironment(environment, node); const nextOptions = { ...options, environment: localEnvironment }; setInLexicalEnvironment({ ...nextOptions, path: BREAK_SYMBOL, value: false, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: CONTINUE_SYMBOL, value: false, newBinding: true }); evaluate2.nodeWithArgument(node.initializer.declarations[0], literal, nextOptions); if (getCurrentError() != null) { return; } evaluate2.statement(node.statement, nextOptions); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, BREAK_SYMBOL)) { logger.logBreak(node, typescript); break; } else if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, CONTINUE_SYMBOL)) { logger.logContinue(node, typescript); continue; } else if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, RETURN_SYMBOL)) { logger.logReturn(node, typescript); return; } } } return; } // src/interpreter/evaluator/evaluate-this-expression.ts function evaluateThisExpression({ node, environment }) { const match = getFromLexicalEnvironment(node, environment, THIS_SYMBOL); return match == null ? void 0 : match.literal; } // src/interpreter/evaluator/evaluate-break-statement.ts function evaluateBreakStatement(options) { setInLexicalEnvironment({ ...options, path: BREAK_SYMBOL, value: true }); } // src/interpreter/evaluator/evaluate-continue-statement.ts function evaluateContinueStatement(options) { setInLexicalEnvironment({ ...options, path: CONTINUE_SYMBOL, value: true }); } // src/interpreter/evaluator/evaluate-for-statement.ts function evaluateForStatement({ environment, evaluate: evaluate2, typescript, ...options }) { const { node, getCurrentError } = options; const forEnvironment = cloneLexicalEnvironment(environment, node); const forOptions = { ...options, environment: forEnvironment }; if (node.initializer !== void 0) { if (typescript.isVariableDeclarationList(node.initializer)) { for (const declaration of node.initializer.declarations) { evaluate2.declaration(declaration, forOptions); if (getCurrentError() != null) { return; } } } else { evaluate2.expression(node.initializer, forOptions); if (getCurrentError() != null) { return; } } } while (true) { const iterationEnvironment = cloneLexicalEnvironment(forEnvironment, node); const iterationOptions = { ...options, environment: iterationEnvironment }; setInLexicalEnvironment({ ...iterationOptions, path: BREAK_SYMBOL, value: false, newBinding: true }); setInLexicalEnvironment({ ...iterationOptions, path: CONTINUE_SYMBOL, value: false, newBinding: true }); const conditionResult = node.condition == null ? true : evaluate2.expression(node.condition, forOptions); if (!conditionResult || getCurrentError() != null) return; evaluate2.statement(node.statement, iterationOptions); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, iterationEnvironment, true, BREAK_SYMBOL)) { break; } else if (pathInLexicalEnvironmentEquals(node, iterationEnvironment, true, RETURN_SYMBOL)) { return; } if (node.incrementor != null) { evaluate2.expression(node.incrementor, forOptions); if (getCurrentError() != null) { return; } } else if (pathInLexicalEnvironmentEquals(node, iterationEnvironment, true, CONTINUE_SYMBOL)) { continue; } } } // src/interpreter/evaluator/evaluate-while-statement.ts function evaluateWhileStatement(options) { const { node, environment, evaluate: evaluate2, logger, typescript, getCurrentError } = options; let condition = evaluate2.expression(node.expression, options); if (getCurrentError() != null) { return; } while (condition) { const iterationEnvironment = cloneLexicalEnvironment(environment, node); const iterationOptions = { ...options, environment: iterationEnvironment }; setInLexicalEnvironment({ ...iterationOptions, path: BREAK_SYMBOL, value: false, newBinding: true }); setInLexicalEnvironment({ ...iterationOptions, path: CONTINUE_SYMBOL, value: false, newBinding: true }); evaluate2.statement(node.statement, iterationOptions); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, iterationEnvironment, true, BREAK_SYMBOL)) { logger.logBreak(node, typescript); break; } else if (pathInLexicalEnvironmentEquals(node, iterationEnvironment, true, RETURN_SYMBOL)) { logger.logReturn(node, typescript); return; } condition = evaluate2.expression(node.expression, options); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, iterationEnvironment, true, CONTINUE_SYMBOL)) { logger.logContinue(node, typescript); continue; } } } // src/interpreter/evaluator/evaluate-for-in-statement.ts function evaluateForInStatement(options) { const { node, environment, evaluate: evaluate2, logger, typescript, throwError, getCurrentError } = options; const expressionResult = evaluate2.expression(node.expression, options); if (getCurrentError() != null) { return; } if (!typescript.isVariableDeclarationList(node.initializer)) { return throwError(new UnexpectedNodeError({ node: node.initializer, environment, typescript })); } else if (node.initializer.declarations.length > 1) { return throwError(new UnexpectedNodeError({ node: node.initializer.declarations[1], environment, typescript })); } for (const literal in expressionResult) { const localEnvironment = cloneLexicalEnvironment(environment, node); const nextOptions = { ...options, environment: localEnvironment }; setInLexicalEnvironment({ ...nextOptions, path: BREAK_SYMBOL, value: false, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: CONTINUE_SYMBOL, value: false, newBinding: true }); evaluate2.nodeWithArgument(node.initializer.declarations[0], literal, nextOptions); if (getCurrentError() != null) { return; } evaluate2.statement(node.statement, nextOptions); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, BREAK_SYMBOL)) { logger.logBreak(node, typescript); break; } else if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, CONTINUE_SYMBOL)) { logger.logContinue(node, typescript); continue; } else if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, RETURN_SYMBOL)) { logger.logReturn(node, typescript); return; } } return; } // src/interpreter/evaluator/evaluate-function-expression.ts function evaluateFunctionExpression(options) { const { node, environment, evaluate: evaluate2, stack, typescript, getCurrentError } = options; const nameResult = node.name == null ? void 0 : node.name.text; const _functionExpression = hasModifier(node, typescript.SyntaxKind.AsyncKeyword) ? async function functionExpression(...args) { const localLexicalEnvironment = cloneLexicalEnvironment(environment, node); const nextOptions = { ...options, environment: localLexicalEnvironment }; setInLexicalEnvironment({ ...nextOptions, path: RETURN_SYMBOL, value: false, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: "arguments", value: arguments, newBinding: true }); if (this != null) { setInLexicalEnvironment({ ...nextOptions, path: THIS_SYMBOL, value: this, newBinding: true }); } evaluateParameterDeclarations( { ...nextOptions, node: node.parameters }, args ); if (node.body == null || getCurrentError() != null) return; evaluate2.statement(node.body, nextOptions); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, localLexicalEnvironment, true, RETURN_SYMBOL)) { return stack.pop(); } else return void 0; } : function functionExpression(...args) { const localLexicalEnvironment = cloneLexicalEnvironment(environment, node); const nextOptions = { ...options, environment: localLexicalEnvironment }; setInLexicalEnvironment({ ...nextOptions, path: RETURN_SYMBOL, value: false, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: "arguments", value: arguments, newBinding: true }); if (this != null) { setInLexicalEnvironment({ ...nextOptions, path: THIS_SYMBOL, value: this, newBinding: true }); } evaluateParameterDeclarations( { ...nextOptions, node: node.parameters }, args ); if (node.body == null || getCurrentError() != null) return; evaluate2.statement(node.body, nextOptions); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, localLexicalEnvironment, true, RETURN_SYMBOL)) { return stack.pop(); } else return void 0; }; if (nameResult != null) { setInLexicalEnvironment({ ...options, path: nameResult, value: _functionExpression.bind(_functionExpression) }); } _functionExpression.toString = () => `[Function${nameResult == null ? "" : `: ${nameResult}`}]`; Object.setPrototypeOf(_functionExpression, getFromLexicalEnvironment(node, environment, "Function").literal); return _functionExpression; } // src/interpreter/error/missing-catch-or-finally-after-try-error/missing-catch-or-finally-after-try-error.ts var MissingCatchOrFinallyAfterTryError = class extends EvaluationError { constructor({ node, environment, message = `Missing catch or finally after try` }) { super({ node, environment, message }); } }; // src/interpreter/evaluator/evaluate-try-statement.ts function evaluateTryStatement(options) { const { node, evaluate: evaluate2, environment, throwError } = options; let error; const executeTry = () => { try { return evaluate2.statement(node.tryBlock, { ...options, throwError: (ex) => { error = ex; return ex; }, getCurrentError: () => error }); } catch (ex) { error = ex; } }; const executeCatch = (ex) => { evaluate2.nodeWithArgument(node.catchClause, ex, options); }; const executeFinally = () => { let finallyError; evaluate2.statement(node.finallyBlock, { ...options, throwError: (ex) => { finallyError = ex; options.throwError(ex); return ex; }, getCurrentError: () => finallyError }); }; if (node.catchClause == null && node.finallyBlock == null) { return throwError(new MissingCatchOrFinallyAfterTryError({ node, environment })); } else if (node.catchClause != null && node.finallyBlock == null) { executeTry(); if (error != null) { executeCatch(error); } } else if (node.catchClause != null && node.finallyBlock != null) { executeTry(); if (error != null) { executeCatch(error); } executeFinally(); } else if (node.catchClause == null && node.finallyBlock != null) { executeTry(); if (error != null) { throwError(error); } executeFinally(); } return; } // src/interpreter/util/class/generate-class-declaration.ts function generateClassDeclaration({ name, extendedType, ctor = () => { } }) { if (extendedType == null) { return new Function( "ctor", `return class ${name ?? ""} {constructor () {const ctorReturnValue = ctor.call(this, ...arguments); if (ctorReturnValue != null) return ctorReturnValue;}}` )(ctor); } else { return new Function( "extendedType", "ctor", `return class ${name ?? ""} extends extendedType {constructor () {super(...arguments); const ctorReturnValue = ctor.call(this, ...arguments); if (ctorReturnValue != null) return ctorReturnValue;}}` )(extendedType, ctor); } } // src/interpreter/util/node/modifier-util.ts function canHaveDecorators(node, typescript) { if ("canHaveDecorators" in typescript) { return typescript.canHaveDecorators(node); } else { return true; } } function getDecorators(node, typescript) { if ("getDecorators" in typescript) { return typescript.getDecorators(node); } else { const legacyDecorators = "decorators" in node && Array.isArray(node.decorators) ? node.decorators : void 0; const decoratorModifierLikes = node.modifiers?.filter((modifier) => "expression" in modifier); return [...legacyDecorators ?? [], ...decoratorModifierLikes ?? []]; } } // src/interpreter/evaluator/evaluate-class-declaration.ts function evaluateClassDeclaration(options) { const { node, evaluate: evaluate2, stack, logger, typescript, getCurrentError } = options; let extendedType; const ctorMember = node.members.find(typescript.isConstructorDeclaration); const otherMembers = node.members.filter((member) => !typescript.isConstructorDeclaration(member)); let ctor; if (ctorMember != null) { evaluate2.declaration(ctorMember, options); if (getCurrentError() != null) { return; } ctor = stack.pop(); } if (node.heritageClauses != null) { const extendsClause = node.heritageClauses.find((clause) => clause.token === typescript.SyntaxKind.ExtendsKeyword); if (extendsClause != null) { const [firstExtendedType] = extendsClause.types; if (firstExtendedType != null) { extendedType = evaluate2.expression(firstExtendedType.expression, options); if (getCurrentError() != null) { return; } } } } const name = node.name == null ? void 0 : node.name.text; let classDeclaration = generateClassDeclaration({ name, extendedType, ctor }); if (canHaveDecorators(node, typescript)) { for (const decorator of getDecorators(node, typescript) ?? []) { evaluate2.nodeWithArgument(decorator, [classDeclaration], options); if (getCurrentError() != null) { return; } classDeclaration = stack.pop(); } } classDeclaration.toString = () => `[Class${name == null ? "" : `: ${name}`}]`; if (name != null) { setInLexicalEnvironment({ ...options, path: name, value: classDeclaration, newBinding: true }); } for (const member of otherMembers) { evaluate2.nodeWithArgument(member, hasModifier(member, typescript.SyntaxKind.StaticKeyword) ? classDeclaration : classDeclaration.prototype, options); if (getCurrentError() != null) { return; } } logger.logHeritage(classDeclaration); stack.push(classDeclaration); logger.logStack(stack); } // src/interpreter/evaluator/evaluate-constructor-declaration.ts function evaluateConstructorDeclaration(options) { const { node, environment, evaluate: evaluate2, stack, getCurrentError } = options; function constructor(...args) { const localLexicalEnvironment = cloneLexicalEnvironment(environment, node); const nextOptions = { ...options, environment: localLexicalEnvironment }; setInLexicalEnvironment({ ...nextOptions, path: RETURN_SYMBOL, value: false, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: "arguments", value: arguments, newBinding: true }); if (this != null) { setInLexicalEnvironment({ ...nextOptions, path: THIS_SYMBOL, value: this, newBinding: true }); } evaluateParameterDeclarations( { ...nextOptions, node: node.parameters }, args, this ); if (node.body == null || getCurrentError() != null) return; evaluate2.statement(node.body, nextOptions); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, localLexicalEnvironment, true, RETURN_SYMBOL)) { return stack.pop(); } else return void 0; } constructor.toString = () => "[Function: constructor]"; stack.push(constructor); } // src/interpreter/evaluator/evaluate-super-expression.ts function evaluateSuperExpression({ node, environment }) { const match = getFromLexicalEnvironment(node, environment, SUPER_SYMBOL); return match == null ? void 0 : match.literal; } // src/interpreter/evaluator/evaluate-spread-element.ts function evaluateSpreadElement({ node, evaluate: evaluate2, ...options }) { return evaluate2.expression(node.expression, options); } // src/interpreter/evaluator/evaluate-class-expression.ts function evaluateClassExpression(options) { const { node, evaluate: evaluate2, stack, logger, typescript, getCurrentError } = options; let extendedType; const ctorMember = node.members.find(typescript.isConstructorDeclaration); const otherMembers = node.members.filter((member) => !typescript.isConstructorDeclaration(member)); let ctor; if (ctorMember != null) { evaluate2.declaration(ctorMember, options); if (getCurrentError() != null) { return; } ctor = stack.pop(); } if (node.heritageClauses != null) { const extendsClause = node.heritageClauses.find((clause) => clause.token === typescript.SyntaxKind.ExtendsKeyword); if (extendsClause != null) { const [firstExtendedType] = extendsClause.types; if (firstExtendedType != null) { extendedType = evaluate2.expression(firstExtendedType.expression, options); if (getCurrentError() != null) { return; } } } } const name = node.name == null ? void 0 : node.name.text; let classExpression = generateClassDeclaration({ name, extendedType, ctor }); if (canHaveDecorators(node, typescript)) { for (const decorator of getDecorators(node, typescript) ?? []) { evaluate2.nodeWithArgument(decorator, [classExpression], options); if (getCurrentError() != null) { return; } classExpression = stack.pop(); } } classExpression.toString = () => `[Class${name == null ? "" : `: ${name}`}]`; if (name != null) { setInLexicalEnvironment({ ...options, path: name, value: classExpression, newBinding: true }); } for (const member of otherMembers) { evaluate2.nodeWithArgument(member, hasModifier(member, typescript.SyntaxKind.StaticKeyword) ? classExpression : classExpression.prototype, options); if (getCurrentError() != null) { return; } } logger.logHeritage(classExpression); return classExpression; } // src/interpreter/evaluator/evaluate-null-literal.ts function evaluateNullLiteral(_options) { return null; } // src/interpreter/evaluator/evaluate-void-expression.ts function evaluateVoidExpression({ node, evaluate: evaluate2, ...options }) { evaluate2.expression(node.expression, options); return void 0; } // src/interpreter/evaluator/evaluate-type-of-expression.ts function evaluateTypeOfExpression({ evaluate: evaluate2, node, ...options }) { const result = evaluate2.expression(node.expression, options); if (options.getCurrentError() != null) { return; } return typeof result; } // src/interpreter/evaluator/evaluate-big-int-literal.ts function evaluateBigIntLiteral({ node, environment }) { const _BigInt = getFromLexicalEnvironment(node, environment, "BigInt").literal; return _BigInt(node.text.endsWith("n") ? node.text.slice(0, -1) : node.text); } // src/interpreter/evaluator/evaluate-enum-declaration.ts function evaluateEnumDeclaration(options) { const { node, environment, evaluate: evaluate2, stack, getCurrentError } = options; const objectCtor = getFromLexicalEnvironment(node, environment, "Object").literal; const enumDeclaration = objectCtor.create(objectCtor.prototype); const name = node.name.text; setInLexicalEnvironment({ ...options, path: name, value: enumDeclaration, newBinding: true }); for (const member of node.members) { evaluate2.nodeWithArgument(member, enumDeclaration, options); if (getCurrentError() != null) { return; } } enumDeclaration.toString = () => `[Enum: ${name}]`; stack.push(enumDeclaration); } // src/interpreter/evaluator/evaluate-source-file-as-namespace-object.ts function evaluateSourceFileAsNamespaceObject(options) { const { node, evaluate: evaluate2, environment, typeChecker, stack, getCurrentError } = options; const objectCtor = getFromLexicalEnvironment(node, environment, "Object").literal; const namespaceObject = objectCtor.create(objectCtor.prototype); const moduleSymbol = typeChecker?.getSymbolAtLocation(node); if (moduleSymbol != null) { const exports2 = moduleSymbol.exports; if (exports2 != null) { for (const [identifier, symbol] of exports2.entries()) { const valueDeclaration = symbol.valueDeclaration; if (valueDeclaration == null) return; evaluate2.declaration(valueDeclaration, options); if (getCurrentError() != null) { return; } namespaceObject[identifier] = stack.pop(); } } } stack.push(namespaceObject); } // src/interpreter/evaluator/evaluate-module-declaration.ts function evaluateModuleDeclaration(options) { const { getCurrentError, stack } = options; const result = getImplementationForDeclarationWithinDeclarationFile(options); if (getCurrentError() != null) { return; } stack.push(result); } // src/interpreter/evaluator/evaluate-import-declaration.ts function evaluateImportDeclaration({ node, evaluate: evaluate2, ...options }) { if (node.importClause == null) return; evaluate2.declaration(node.importClause, options); } // src/interpreter/evaluator/evaluate-throw-statement.ts function evaluateThrowStatement({ node, evaluate: evaluate2, ...options }) { const { getCurrentError, throwError } = options; const result = evaluate2.expression(node.expression, options); if (getCurrentError() != null) { return; } return throwError(result); } // src/interpreter/evaluator/evaluate-import-equals-declaration.ts function evaluateImportEqualsDeclaration(_options) { } // src/interpreter/error/policy-error/max-op-duration-exceeded-error/max-op-duration-exceeded-error.ts var MaxOpDurationExceededError = class extends PolicyError { /** * The total duration of an operation that was being performed before exceeding the limit */ duration; constructor({ duration, environment, node, message = `Maximum operation duration exceeded: ${duration}` }) { super({ violation: "maxOpDuration", message, node, environment }); this.duration = duration; } }; // src/interpreter/evaluator/evaluate-await-expression.ts async function evaluateAwaitExpression(options) { const { node, environment, evaluate: evaluate2, policy, throwError, getCurrentError } = options; const timeout = policy.maxOpDuration === Infinity ? void 0 : setTimeout(() => { throwError(new MaxOpDurationExceededError({ duration: policy.maxOpDuration, node, environment })); }, policy.maxOpDuration); const result = evaluate2.expression(node.expression, options); if (timeout != null) clearTimeout(timeout); if (getCurrentError() != null) { return; } return result; } // src/interpreter/evaluator/evaluate-conditional-expression.ts function evaluateConditionalExpression({ node, evaluate: evaluate2, ...options }) { const { getCurrentError } = options; const conditionValue = evaluate2.expression(node.condition, options); if (getCurrentError() != null) { return; } if (conditionValue) { return evaluate2.expression(node.whenTrue, options); } return evaluate2.expression(node.whenFalse, options); } // src/interpreter/util/static/in-static-context.ts function inStaticContext(node, typescript) { let currentNode = node; while (currentNode != null && !typescript.isSourceFile(currentNode)) { if (hasModifier(currentNode, typescript.SyntaxKind.StaticKeyword)) return true; currentNode = currentNode.parent; } return false; } // src/interpreter/evaluator/evaluate-method-declaration.ts function evaluateMethodDeclaration(options, parent) { const { node, environment, evaluate: evaluate2, stack, typescript, getCurrentError } = options; const nameResult = evaluate2.nodeWithValue(node.name, options); if (getCurrentError() != null) { return; } const isStatic = inStaticContext(node, typescript); if (parent == null) { let updatedParent; if (typescript.isClassLike(node.parent)) { evaluate2.declaration(node.parent, options); if (getCurrentError() != null) { return; } updatedParent = stack.pop(); } else { updatedParent = evaluate2.expression(node.parent, options); if (getCurrentError() != null) { return; } } stack.push(isStatic ? updatedParent[nameResult] : updatedParent.prototype[nameResult]); return; } const _methodDeclaration = hasModifier(node, typescript.SyntaxKind.AsyncKeyword) ? async function methodDeclaration(...args) { const localLexicalEnvironment = cloneLexicalEnvironment(environment, node); const nextOptions = { ...options, environment: localLexicalEnvironment }; setInLexicalEnvironment({ ...nextOptions, path: RETURN_SYMBOL, value: false, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: "arguments", value: arguments, newBinding: true }); if (this != null) { setInLexicalEnvironment({ ...nextOptions, path: THIS_SYMBOL, value: this, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: SUPER_SYMBOL, value: isStatic ? Object.getPrototypeOf(this) : Object.getPrototypeOf(this.constructor).prototype, newBinding: true }); } evaluateParameterDeclarations( { ...options, node: node.parameters, environment: localLexicalEnvironment }, args ); if (node.body == null || getCurrentError() != null) return; evaluate2.statement(node.body, nextOptions); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, localLexicalEnvironment, true, RETURN_SYMBOL)) { return stack.pop(); } else return void 0; } : function methodDeclaration(...args) { const localLexicalEnvironment = cloneLexicalEnvironment(environment, node); const nextOptions = { ...options, environment: localLexicalEnvironment }; setInLexicalEnvironment({ ...nextOptions, path: RETURN_SYMBOL, value: false, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: "arguments", value: arguments, newBinding: true }); if (this != null) { setInLexicalEnvironment({ ...nextOptions, path: THIS_SYMBOL, value: this, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: SUPER_SYMBOL, value: isStatic ? Object.getPrototypeOf(this) : Object.getPrototypeOf(this.constructor).prototype, newBinding: true }); } evaluateParameterDeclarations( { ...options, node: node.parameters, environment: localLexicalEnvironment }, args ); if (node.body == null || getCurrentError() != null) return; evaluate2.statement(node.body, nextOptions); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, localLexicalEnvironment, true, RETURN_SYMBOL)) { return stack.pop(); } else return void 0; }; _methodDeclaration.toString = () => `[Method: ${nameResult}]`; Object.setPrototypeOf(_methodDeclaration, getFromLexicalEnvironment(node, environment, "Function").literal); parent[nameResult] = _methodDeclaration; if (canHaveDecorators(node, typescript)) { for (const decorator of getDecorators(node, typescript) ?? []) { evaluate2.nodeWithArgument(decorator, [parent, nameResult], options); if (getCurrentError() != null) { return; } stack.pop(); } } if (node.parameters != null) { const parameters = node.parameters.filter((param) => !(typescript.isIdentifier(param.name) && param.name.text === "this")); for (let i = 0; i < parameters.length; i++) { const parameter = parameters[i]; if (canHaveDecorators(parameter, typescript)) { for (const decorator of getDecorators(parameter, typescript) ?? []) { evaluate2.nodeWithArgument(decorator, [parent, nameResult, i], options); if (getCurrentError() != null) { return; } stack.pop(); } } } } } // src/interpreter/evaluator/evaluate-property-declaration.ts function evaluatePropertyDeclaration({ node, evaluate: evaluate2, typescript, stack, ...options }, parent) { const { getCurrentError } = options; const propertyNameResult = evaluate2.nodeWithValue(node.name, options); if (getCurrentError() != null) { return; } if (parent == null) { evaluate2.declaration(node.parent, options); if (getCurrentError() != null) { return; } const updatedParent = stack.pop(); const isStatic = inStaticContext(node, typescript); stack.push(isStatic ? updatedParent[propertyNameResult] : updatedParent.prototype[propertyNameResult]); return; } parent[propertyNameResult] = node.initializer == null ? void 0 : evaluate2.expression(node.initializer, options); if (getCurrentError() != null) { return; } if (canHaveDecorators(node, typescript)) { for (const decorator of getDecorators(node, typescript) ?? []) { evaluate2.nodeWithArgument(decorator, [parent, propertyNameResult], options); if (getCurrentError() != null) { return; } stack.pop(); } } } // src/interpreter/evaluator/evaluate-get-accessor-declaration.ts function evaluateGetAccessorDeclaration(options, parent) { const { node, environment, evaluate: evaluate2, stack, typescript, getCurrentError } = options; if (typescript.isTypeLiteralNode(node.parent) || typescript.isInterfaceDeclaration(node.parent)) { return; } const nameResult = evaluate2.nodeWithValue(node.name, options); if (getCurrentError() != null) { return; } const isStatic = inStaticContext(node, typescript); if (parent == null) { let updatedParent; if (typescript.isClassLike(node.parent)) { evaluate2.declaration(node.parent, options); if (getCurrentError() != null) { return; } updatedParent = stack.pop(); } else { updatedParent = evaluate2.expression(node.parent, options); if (getCurrentError() != null) { return; } } stack.push(isStatic ? updatedParent[nameResult] : updatedParent.prototype[nameResult]); return; } function getAccessorDeclaration() { const localLexicalEnvironment = cloneLexicalEnvironment(environment, node); const nextOptions = { ...options, environment: localLexicalEnvironment }; setInLexicalEnvironment({ ...nextOptions, path: RETURN_SYMBOL, value: false, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: "arguments", value: arguments, newBinding: true }); if (this != null) { setInLexicalEnvironment({ ...nextOptions, path: THIS_SYMBOL, value: this, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: SUPER_SYMBOL, value: isStatic ? Object.getPrototypeOf(this) : Object.getPrototypeOf(this.constructor).prototype, newBinding: true }); } if (node.body == null) return; evaluate2.statement(node.body, nextOptions); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, localLexicalEnvironment, true, RETURN_SYMBOL)) { return stack.pop(); } else return void 0; } getAccessorDeclaration.toString = () => `[Get: ${nameResult}]`; let currentPropertyDescriptor = Object.getOwnPropertyDescriptor(parent, nameResult); if (currentPropertyDescriptor == null) currentPropertyDescriptor = {}; Object.defineProperty(parent, nameResult, { ...currentPropertyDescriptor, configurable: true, get: getAccessorDeclaration }); } // src/interpreter/evaluator/evaluate-type-alias-declaration.ts function evaluateTypeAliasDeclaration(_options) { return; } // src/interpreter/evaluator/evaluate-interface-declaration.ts function evaluateInterfaceDeclaration(_options) { return; } // src/interpreter/evaluator/evaluate-import-clause.ts function evaluateImportClause({ node, evaluate: evaluate2, ...options }) { const { getCurrentError } = options; if (node.name != null) { evaluate2.declaration(node.name, options); if (getCurrentError() != null) { return; } } if (node.namedBindings != null) { if ("elements" in node.namedBindings) { for (const importSpecifier of node.namedBindings.elements) { evaluate2.declaration(importSpecifier, options); if (getCurrentError() != null) { return; } } } else { evaluate2.declaration(node.namedBindings.name, options); } } } // src/interpreter/evaluator/evaluate-import-specifier.ts function evaluateImportSpecifier({ node, evaluate: evaluate2, ...options }) { evaluate2.declaration(node.propertyName ?? node.name, options); } // src/interpreter/evaluator/evaluate-namespace-import.ts function evaluateNamespaceImport({ node, evaluate: evaluate2, ...options }) { evaluate2.declaration(node.name, options); } // src/interpreter/error/unexpected-syntax-error/unexpected-syntax-error.ts var UnexpectedSyntaxError = class extends EvaluationError { constructor({ node, environment, message = `'SyntaxError'` }) { super({ message, environment, node }); } }; // src/interpreter/evaluator/evaluate-meta-property.ts function evaluateMetaProperty({ node, typescript, throwError, environment }) { switch (node.keywordToken) { case typescript.SyntaxKind.NewKeyword: { switch (node.name.text) { case "target": return getFromLexicalEnvironment(node, environment, "[[NewTarget]]")?.literal; default: return throwError(new UnexpectedSyntaxError({ node: node.name, environment })); } } case typescript.SyntaxKind.ImportKeyword: { switch (node.name.text) { case "meta": return getFromLexicalEnvironment(node, environment, "import.meta")?.literal; default: return throwError(new UnexpectedSyntaxError({ node: node.name, environment })); } } } } // src/interpreter/evaluator/evaluate-node.ts function evaluateNode({ node, ...rest }) { if (rest.typescript.isIdentifier(node)) { return evaluateIdentifier({ node, ...rest }); } else if (rest.typescript.isPrivateIdentifier?.(node)) { return evaluateIdentifier({ node, ...rest }); } else if (rest.typescript.isStringLiteralLike(node)) { return evaluateStringLiteral({ node, ...rest }); } else if (rest.typescript.isNumericLiteral(node)) { return evaluateNumericLiteral({ node, ...rest }); } else if (isBooleanLiteral(node, rest.typescript)) { return evaluateBooleanLiteral({ node, ...rest }); } else if (rest.typescript.isForOfStatement(node)) { return evaluateForOfStatement({ node, ...rest }); } else if (rest.typescript.isForInStatement(node)) { return evaluateForInStatement({ node, ...rest }); } else if (rest.typescript.isForStatement(node)) { return evaluateForStatement({ node, ...rest }); } else if (rest.typescript.isWhileStatement(node)) { return evaluateWhileStatement({ node, ...rest }); } else if (rest.typescript.isRegularExpressionLiteral(node)) { return evaluateRegularExpressionLiteral({ node, ...rest }); } else if (rest.typescript.isObjectLiteralExpression(node)) { return evaluateObjectLiteralExpression({ node, ...rest }); } else if (rest.typescript.isAwaitExpression(node)) { return evaluateAwaitExpression({ node, ...rest }); } else if (rest.typescript.isTypeAssertionExpression?.(node) || !("isTypeAssertionExpression" in rest.typescript) && rest.typescript.isTypeAssertion(node)) { return evaluateTypeAssertion({ node, ...rest }); } else if (rest.typescript.isTemplateExpression(node)) { return evaluateTemplateExpression({ node, ...rest }); } else if (rest.typescript.isMethodDeclaration(node)) { return evaluateMethodDeclaration({ node, ...rest }); } else if (rest.typescript.isPropertyDeclaration(node)) { return evaluatePropertyDeclaration({ node, ...rest }); } else if (rest.typescript.isGetAccessorDeclaration(node)) { return evaluateGetAccessorDeclaration({ node, ...rest }); } else if (rest.typescript.isArrayLiteralExpression(node)) { return evaluateArrayLiteralExpression({ node, ...rest }); } else if (rest.typescript.isSourceFile(node)) { return evaluateSourceFileAsNamespaceObject({ node, ...rest }); } else if (rest.typescript.isModuleDeclaration(node)) { return evaluateModuleDeclaration({ node, ...rest }); } else if (rest.typescript.isPrefixUnaryExpression(node)) { return evaluatePrefixUnaryExpression({ node, ...rest }); } else if (rest.typescript.isPostfixUnaryExpression(node)) { return evaluatePostfixUnaryExpression({ node, ...rest }); } else if (rest.typescript.isVariableStatement(node)) { return evaluateVariableStatement({ node, ...rest }); } else if (rest.typescript.isComputedPropertyName(node)) { return evaluateComputedPropertyName({ node, ...rest }); } else if (rest.typescript.isVariableDeclarationList(node)) { return evaluateVariableDeclarationList({ node, ...rest }); } else if (rest.typescript.isImportDeclaration(node)) { return evaluateImportDeclaration({ node, ...rest }); } else if (rest.typescript.isImportClause(node)) { return evaluateImportClause({ node, ...rest }); } else if (rest.typescript.isImportSpecifier(node)) { return evaluateImportSpecifier({ node, ...rest }); } else if (rest.typescript.isNamespaceImport(node)) { return evaluateNamespaceImport({ node, ...rest }); } else if (rest.typescript.isImportEqualsDeclaration(node)) { return evaluateImportEqualsDeclaration({ node, ...rest }); } else if (rest.typescript.isMetaProperty(node)) { return evaluateMetaProperty({ node, ...rest }); } else if (rest.typescript.isThrowStatement(node)) { return evaluateThrowStatement({ node, ...rest }); } else if (rest.typescript.isVariableDeclaration(node)) { return evaluateVariableDeclaration({ node, ...rest }); } else if (rest.typescript.isEnumDeclaration(node)) { return evaluateEnumDeclaration({ node, ...rest }); } else if (rest.typescript.isConstructorDeclaration(node)) { return evaluateConstructorDeclaration({ node, ...rest }); } else if (rest.typescript.isBinaryExpression(node)) { return evaluateBinaryExpression({ node, ...rest }); } else if (rest.typescript.isParenthesizedExpression(node)) { return evaluateParenthesizedExpression({ node, ...rest }); } else if (rest.typescript.isExpressionStatement(node)) { return evaluateExpressionStatement({ node, ...rest }); } else if (rest.typescript.isArrowFunction(node)) { return evaluateArrowFunctionExpression({ node, ...rest }); } else if (rest.typescript.isFunctionDeclaration(node)) { return evaluateFunctionDeclaration({ node, ...rest }); } else if (rest.typescript.isFunctionExpression(node)) { return evaluateFunctionExpression({ node, ...rest }); } else if (rest.typescript.isClassDeclaration(node)) { return evaluateClassDeclaration({ node, ...rest }); } else if (rest.typescript.isIfStatement(node)) { return evaluateIfStatement({ node, ...rest }); } else if (rest.typescript.isConditionalExpression(node)) { return evaluateConditionalExpression({ node, ...rest }); } else if (rest.typescript.isPropertyAccessExpression(node)) { return evaluatePropertyAccessExpression({ node, ...rest }); } else if (rest.typescript.isElementAccessExpression(node)) { return evaluateElementAccessExpression({ node, ...rest }); } else if (rest.typescript.isCallExpression(node)) { return evaluateCallExpression({ node, ...rest }); } else if (rest.typescript.isSwitchStatement(node)) { return evaluateSwitchStatement({ node, ...rest }); } else if (rest.typescript.isNewExpression(node)) { return evaluateNewExpression({ node, ...rest }); } else if (rest.typescript.isNonNullExpression(node)) { return evaluateNonNullExpression({ node, ...rest }); } else if (rest.typescript.isAsExpression(node)) { return evaluateAsExpression({ node, ...rest }); } else if (rest.typescript.isBlock(node)) { return evaluateBlock({ node, ...rest }); } else if (rest.typescript.isClassExpression(node)) { return evaluateClassExpression({ node, ...rest }); } else if (rest.typescript.isSpreadElement(node)) { return evaluateSpreadElement({ node, ...rest }); } else if (rest.typescript.isTryStatement(node)) { return evaluateTryStatement({ node, ...rest }); } else if (rest.typescript.isReturnStatement(node)) { return evaluateReturnStatement({ node, ...rest }); } else if (isThisExpression(node, rest.typescript)) { return evaluateThisExpression({ node, ...rest }); } else if (rest.typescript.isVoidExpression(node)) { return evaluateVoidExpression({ node, ...rest }); } else if (rest.typescript.isTypeOfExpression(node)) { return evaluateTypeOfExpression({ node, ...rest }); } else if (isSuperExpression(node, rest.typescript)) { return evaluateSuperExpression({ node, ...rest }); } else if (isNullLiteral(node, rest.typescript)) { return evaluateNullLiteral({ node, ...rest }); } else if (rest.typescript.isBigIntLiteral?.(node)) { return evaluateBigIntLiteral({ node, ...rest }); } else if (rest.typescript.isBreakStatement(node)) { return evaluateBreakStatement({ node, ...rest }); } else if (rest.typescript.isContinueStatement(node)) { return evaluateContinueStatement({ node, ...rest }); } else if (rest.typescript.isTypeAliasDeclaration(node)) { return evaluateTypeAliasDeclaration({ node, ...rest }); } else if (rest.typescript.isInterfaceDeclaration(node)) { return evaluateInterfaceDeclaration({ node, ...rest }); } else if (rest.getCurrentError() != null) { return; } else { return rest.throwError(new UnexpectedNodeError({ node, environment: rest.environment, typescript: rest.typescript })); } } // src/interpreter/stack/traversal-stack/statement-traversal-stack.ts function createStatementTraversalStack() { return []; } // src/interpreter/evaluator/evaluate-statement.ts function evaluateStatement(options) { options.logger.logNode(options.node, options.typescript); options.statementTraversalStack = createStatementTraversalStack(); evaluateNode(options); } // src/interpreter/evaluator/evaluate-expression.ts function evaluateExpression(options) { const { getCurrentError } = options; options.logger.logNode(options.node, options.typescript); const value = evaluateNode(options); if (getCurrentError() != null) { return; } if (options.reporting.reportIntermediateResults != null) { options.reporting.reportIntermediateResults({ node: options.node, value }); } return value; } // src/interpreter/evaluator/evaluate-declaration.ts function evaluateDeclaration(options) { options.logger.logNode(options.node, options.typescript); evaluateNode(options); } // src/interpreter/evaluator/evaluate-binding-name.ts function evaluateBindingName({ node, evaluate: evaluate2, typescript, logger, ...options }, rightHandValue) { if (typescript.isIdentifier(node) || typescript.isPrivateIdentifier?.(node)) { setInLexicalEnvironment({ ...options, node, path: node.text, value: rightHandValue, newBinding: true }); logger.logBinding(node.text, rightHandValue, "evaluateBindingName"); } else { evaluate2.nodeWithArgument(node, rightHandValue, options); } } // src/interpreter/evaluator/evaluate-set-accessor-declaration.ts function evaluateSetAccessorDeclaration(options, parent) { const { node, environment, evaluate: evaluate2, typescript, getCurrentError } = options; const nameResult = evaluate2.nodeWithValue(node.name, options); if (getCurrentError() != null) { return; } const isStatic = inStaticContext(node, typescript); function setAccessorDeclaration(...args) { const localLexicalEnvironment = cloneLexicalEnvironment(environment, node); const nextOptions = { ...options, environment: localLexicalEnvironment }; setInLexicalEnvironment({ ...nextOptions, path: RETURN_SYMBOL, value: false, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: "arguments", value: arguments, newBinding: true }); if (this != null) { setInLexicalEnvironment({ ...nextOptions, path: THIS_SYMBOL, value: this, newBinding: true }); setInLexicalEnvironment({ ...nextOptions, path: SUPER_SYMBOL, value: isStatic ? Object.getPrototypeOf(this) : Object.getPrototypeOf(this.constructor).prototype, newBinding: true }); } evaluateParameterDeclarations( { ...nextOptions, node: node.parameters }, args ); if (node.body == null || getCurrentError() != null) return; evaluate2.statement(node.body, nextOptions); if (getCurrentError() != null) { return; } } setAccessorDeclaration.toString = () => `[Set: ${nameResult}]`; let currentPropertyDescriptor = Object.getOwnPropertyDescriptor(parent, nameResult); if (currentPropertyDescriptor == null) currentPropertyDescriptor = {}; Object.defineProperty(parent, nameResult, { ...currentPropertyDescriptor, configurable: true, set: setAccessorDeclaration }); } // src/interpreter/evaluator/evaluate-property-assignment.ts function evaluatePropertyAssignment({ node, evaluate: evaluate2, ...options }, parent) { const initializer = evaluate2.expression(node.initializer, options); if (options.getCurrentError() != null) { return; } const propertyNameResult = evaluate2.nodeWithValue(node.name, options); if (options.getCurrentError() != null) { return; } parent[propertyNameResult] = initializer; } // src/interpreter/evaluator/evaluate-parameter-declaration.ts function evaluateParameterDeclaration({ node, evaluate: evaluate2, logger, ...options }, boundArgument) { const boundValue = boundArgument != null || node.initializer === void 0 ? boundArgument : evaluate2.expression(node.initializer, options); if (options.getCurrentError() != null) { return; } logger.logBinding(node.name.getText(), boundValue, "evaluateParameterDeclaration"); evaluate2.nodeWithArgument(node.name, boundValue, options); } // src/interpreter/evaluator/evaluate-shorthand-property-assignment.ts function evaluateShorthandPropertyAssignment({ node, evaluate: evaluate2, ...options }, parent) { const { getCurrentError } = options; const identifier = node.name.text; const initializer = evaluate2.expression(node.name, options); if (getCurrentError() != null) { return; } parent[identifier] = initializer; } // src/interpreter/evaluator/evaluate-spread-assignment.ts function evaluateSpreadAssignment({ node, evaluate: evaluate2, ...options }, parent) { const entries = evaluate2.expression(node.expression, options); if (options.getCurrentError() != null) { return; } Object.assign(parent, entries); } // src/interpreter/evaluator/evaluate-array-binding-pattern.ts function evaluateArrayBindingPattern({ node, evaluate: evaluate2, ...options }, rightHandValue) { const iterator = rightHandValue[Symbol.iterator](); let elementsCursor = 0; while (elementsCursor < node.elements.length) { const { done, value } = iterator.next(); if (done === true) break; const nextElement = node.elements[elementsCursor++]; if (nextElement == null) continue; evaluate2.nodeWithArgument(nextElement, value, options); if (options.getCurrentError() != null) { return; } } } // src/interpreter/evaluator/evaluate-binding-element.ts function evaluateBindingElement(options, rightHandValue) { const { node, evaluate: evaluate2, logger, typescript, getCurrentError } = options; const bindingElementInitializer = node.initializer == null ? void 0 : evaluate2.expression(node.initializer, options); if (getCurrentError() != null) { return; } if ((typescript.isIdentifier(node.name) || typescript.isPrivateIdentifier?.(node.name)) && node.propertyName != null) { const aliasName = node.name.text; const propertyNameResult = evaluate2.nodeWithValue(node.propertyName, options); if (getCurrentError() != null) { return; } const propertyValue = typescript.isArrayBindingPattern(node.parent) ? rightHandValue : rightHandValue[propertyNameResult]; const propertyValueWithInitializerFallback = propertyValue ?? bindingElementInitializer; setInLexicalEnvironment({ ...options, path: aliasName, value: propertyValueWithInitializerFallback, newBinding: true }); } else if ((typescript.isIdentifier(node.name) || typescript.isPrivateIdentifier?.(node.name)) && node.propertyName == null) { const nameResult = node.name.text; const propertyValue = typescript.isArrayBindingPattern(node.parent) ? rightHandValue : rightHandValue[nameResult]; const propertyValueWithInitializerFallback = propertyValue ?? bindingElementInitializer; logger.logBinding(node.name.text, propertyValueWithInitializerFallback); setInLexicalEnvironment({ ...options, path: node.name.text, value: propertyValueWithInitializerFallback, newBinding: true }); } else if (!typescript.isIdentifier(node.name) && !typescript.isPrivateIdentifier?.(node.name) && node.propertyName != null) { const propertyNameResult = evaluate2.nodeWithValue(node.propertyName, options); if (getCurrentError() != null) { return; } const propertyValue = typescript.isArrayBindingPattern(node.parent) ? rightHandValue : rightHandValue[propertyNameResult]; const propertyValueWithInitializerFallback = propertyValue ?? bindingElementInitializer; evaluate2.nodeWithArgument(node.name, propertyValueWithInitializerFallback, options); if (getCurrentError() != null) { return; } } else if (!typescript.isIdentifier(node.name) && !typescript.isPrivateIdentifier?.(node.name) && node.propertyName == null) { const propertyValueWithInitializerFallback = rightHandValue ?? bindingElementInitializer; evaluate2.nodeWithArgument(node.name, propertyValueWithInitializerFallback, options); if (getCurrentError() != null) { return; } } } // src/interpreter/evaluator/evaluate-object-binding-pattern.ts function evaluateObjectBindingPattern({ node, evaluate: evaluate2, ...options }, rightHandValue) { for (const element of node.elements) { evaluate2.nodeWithArgument(element, rightHandValue, options); if (options.getCurrentError() != null) { return; } } } // src/interpreter/evaluator/evaluate-case-block.ts function evaluateCaseBlock(options, switchExpression) { const { node, evaluate: evaluate2, environment, getCurrentError } = options; const localEnvironment = cloneLexicalEnvironment(environment, node); const nextOptions = { ...options, environment: localEnvironment }; setInLexicalEnvironment({ ...nextOptions, path: BREAK_SYMBOL, value: false, newBinding: true }); for (const clause of node.clauses) { evaluate2.nodeWithArgument(clause, switchExpression, nextOptions); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, BREAK_SYMBOL, CONTINUE_SYMBOL, RETURN_SYMBOL)) { break; } } } // src/interpreter/evaluator/evaluate-case-clause.ts function evaluateCaseClause({ node, evaluate: evaluate2, ...options }, switchExpression) { const { getCurrentError } = options; const expressionResult = evaluate2.expression(node.expression, options); if (expressionResult !== switchExpression || getCurrentError() != null) return; for (const statement of node.statements) { evaluate2.statement(statement, options); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, options.environment, true, BREAK_SYMBOL, CONTINUE_SYMBOL, RETURN_SYMBOL)) { break; } } } // src/interpreter/evaluator/evaluate-default-clause.ts function evaluateDefaultClause(options) { const { node, evaluate: evaluate2, environment, getCurrentError } = options; for (const statement of node.statements) { evaluate2.statement(statement, options); if (getCurrentError() != null) { return; } if (pathInLexicalEnvironmentEquals(node, environment, true, BREAK_SYMBOL, CONTINUE_SYMBOL, RETURN_SYMBOL)) { break; } } } // src/interpreter/evaluator/evaluate-catch-clause.ts function evaluateCatchClause(options, ex) { const { node, evaluate: evaluate2, environment, getCurrentError } = options; const catchEnvironment = node.variableDeclaration == null ? environment : cloneLexicalEnvironment(environment, node); const nextOptions = { ...options, environment: catchEnvironment }; if (node.variableDeclaration != null) { evaluate2.nodeWithArgument(node.variableDeclaration, ex, nextOptions); if (getCurrentError() != null) { return; } } evaluate2.statement(node.block, nextOptions); } // src/interpreter/evaluator/evaluate-omitted-expression.ts function evaluateOmittedExpression(_options) { return void 0; } // src/interpreter/util/tslib/tslib-util.ts function __decorate(decorators, target, key, desc) { const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let d; for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function(target, key) { decorator(target, key, paramIndex); }; } // src/interpreter/evaluator/evaluate-decorator.ts function evaluateDecorator(options, [parent, propertyName, index]) { const { node, evaluate: evaluate2, environment, throwError, stack, getCurrentError } = options; const decoratorImplementation = evaluate2.expression(node.expression, options); if (getCurrentError() != null) { return; } if (typeof decoratorImplementation !== "function") { return throwError( new NotCallableError({ node, environment, value: decoratorImplementation, message: `${stringifyLiteral(decoratorImplementation)} is not a valid decorator implementation'` }) ); } stack.push(__decorate([index != null ? __param(index, decoratorImplementation) : decoratorImplementation], parent, propertyName)); return; } // src/interpreter/evaluator/evaluate-enum-member.ts function evaluateEnumMember(options, parent) { const { node, typeChecker, evaluate: evaluate2, getCurrentError } = options; let constantValue = typeChecker?.getConstantValue(node); if (constantValue == null) { if (node.initializer != null) { constantValue = evaluate2.expression(node.initializer, options); if (getCurrentError() != null) { return; } } else { const siblings = node.parent.members; const thisIndex = siblings.findIndex((member) => member === node); const beforeSiblings = siblings.slice(0, thisIndex); let traversal = 0; for (const sibling of [...beforeSiblings].reverse()) { traversal++; if (sibling.initializer != null) { const siblingConstantValue = evaluate2.expression(sibling.initializer, options); if (getCurrentError() != null) { return; } if (typeof siblingConstantValue === "number") { constantValue = siblingConstantValue + traversal; break; } } } if (constantValue == null) { constantValue = thisIndex; } } } const propertyName = evaluate2.nodeWithValue(node.name, options); if (getCurrentError() != null) { return; } if (typeof constantValue === "string") { parent[propertyName] = constantValue; } else { parent[parent[propertyName] = constantValue ?? 0] = propertyName; } } // src/interpreter/evaluator/evaluate-node-with-argument.ts function evaluateNodeWithArgument(options, arg) { options.logger.logNode(options.node, options.typescript, "nodeWithArgument"); const { node, ...rest } = options; if (rest.typescript.isGetAccessorDeclaration(node)) { evaluateGetAccessorDeclaration({ node, ...rest }, arg); } else if (rest.typescript.isSetAccessorDeclaration(node)) { evaluateSetAccessorDeclaration({ node, ...rest }, arg); } else if (rest.typescript.isPropertyAssignment(node)) { evaluatePropertyAssignment({ node, ...rest }, arg); } else if (rest.typescript.isPropertyDeclaration(node)) { evaluatePropertyDeclaration({ node, ...rest }, arg); } else if (rest.typescript.isParameter(node)) { evaluateParameterDeclaration({ node, ...rest }, arg); } else if (rest.typescript.isEnumMember(node)) { evaluateEnumMember({ node, ...rest }, arg); } else if (rest.typescript.isShorthandPropertyAssignment(node)) { evaluateShorthandPropertyAssignment({ node, ...rest }, arg); } else if (rest.typescript.isDecorator(node)) { evaluateDecorator({ node, ...rest }, arg); } else if (rest.typescript.isSpreadAssignment(node)) { evaluateSpreadAssignment({ node, ...rest }, arg); } else if (rest.typescript.isMethodDeclaration(node)) { evaluateMethodDeclaration({ node, ...rest }, arg); } else if (rest.typescript.isArrayBindingPattern(node)) { evaluateArrayBindingPattern({ node, ...rest }, arg); } else if (rest.typescript.isBindingElement(node)) { evaluateBindingElement({ node, ...rest }, arg); } else if (rest.typescript.isObjectBindingPattern(node)) { evaluateObjectBindingPattern({ node, ...rest }, arg); } else if (rest.typescript.isVariableDeclaration(node)) { evaluateVariableDeclaration({ node, ...rest }, arg); } else if (rest.typescript.isCaseBlock(node)) { evaluateCaseBlock({ node, ...rest }, arg); } else if (rest.typescript.isCaseClause(node)) { evaluateCaseClause({ node, ...rest }, arg); } else if (rest.typescript.isDefaultClause(node)) { evaluateDefaultClause({ node, ...rest }); } else if (rest.typescript.isCatchClause(node)) { evaluateCatchClause({ node, ...rest }, arg); } else if (rest.typescript.isBindingName(node)) { evaluateBindingName({ node, ...rest }, arg); } else if (rest.typescript.isOmittedExpression(node)) { evaluateOmittedExpression({ node, ...rest }); } else if (options.getCurrentError() != null) { return; } else { rest.throwError(new UnexpectedNodeError({ node, environment: rest.environment, typescript: rest.typescript })); } } // src/interpreter/evaluator/evaluate-property-name.ts function evaluatePropertyName({ node, evaluate: evaluate2, typescript, ...options }) { return typescript.isComputedPropertyName(node) ? evaluate2.expression(node.expression, options) : typescript.isIdentifier(node) || typescript.isPrivateIdentifier?.(node) ? node.text : evaluate2.expression(node, options); } // src/interpreter/evaluator/evaluate-node-with-value.ts function evaluateNodeWithValue(options) { options.logger.logNode(options.node, options.typescript, "nodeWithValue"); const { node, ...rest } = options; if (options.typescript.isPropertyName(node) || options.typescript.isPrivateIdentifier(node)) { return evaluatePropertyName({ node, ...rest }); } return options.throwError(new UnexpectedNodeError({ node, environment: options.environment, typescript: options.typescript })); } // src/interpreter/evaluator/node-evaluator/create-node-evaluator.ts function createNodeEvaluator(options) { let ops = 0; const { policy, reporting } = options; const prequalifyNextNode = (node, nextOptions) => { const { environment = options.environment, statementTraversalStack = options.statementTraversalStack, getCurrentError = options.getCurrentError, throwError = options.throwError } = nextOptions ?? {}; const currentError = getCurrentError(); if (currentError != null) { return currentError; } ops++; if (ops >= policy.maxOps) { return throwError(new MaxOpsExceededError({ ops, environment, node })); } statementTraversalStack.push(node.kind); if (reporting.reportTraversal != null) { reporting.reportTraversal({ node }); } return void 0; }; const evaluate2 = { statement: (node, nextOptions) => { const combinedNextOptions = { ...nextOptions, statementTraversalStack: createStatementTraversalStack() }; const prequalifyResult = prequalifyNextNode(node, combinedNextOptions); if (isEvaluationError(prequalifyResult)) { return; } return evaluateStatement(getEvaluatorOptions(node, combinedNextOptions)); }, declaration: (node, nextOptions) => { const prequalifyResult = prequalifyNextNode(node, nextOptions); if (isEvaluationError(prequalifyResult)) { return; } return evaluateDeclaration(getEvaluatorOptions(node, nextOptions)); }, nodeWithArgument: (node, arg, nextOptions) => { const prequalifyResult = prequalifyNextNode(node, nextOptions); if (isEvaluationError(prequalifyResult)) { return; } return evaluateNodeWithArgument(getEvaluatorOptions(node, nextOptions), arg); }, expression: (node, nextOptions) => { const prequalifyResult = prequalifyNextNode(node, nextOptions); if (isEvaluationError(prequalifyResult)) { return prequalifyResult; } return evaluateExpression(getEvaluatorOptions(node, nextOptions)); }, nodeWithValue: (node, nextOptions) => { const prequalifyResult = prequalifyNextNode(node, nextOptions); if (isEvaluationError(prequalifyResult)) { return prequalifyResult; } return evaluateNodeWithValue(getEvaluatorOptions(node, nextOptions)); } }; function getEvaluatorOptions(node, nextOptions) { return { ...options, ...nextOptions, evaluate: evaluate2, node }; } return evaluate2; } // src/interpreter/logger/log-level.ts var LogLevelKind = /* @__PURE__ */ ((LogLevelKind2) => { LogLevelKind2[LogLevelKind2["SILENT"] = 0] = "SILENT"; LogLevelKind2[LogLevelKind2["INFO"] = 1] = "INFO"; LogLevelKind2[LogLevelKind2["VERBOSE"] = 2] = "VERBOSE"; LogLevelKind2[LogLevelKind2["DEBUG"] = 3] = "DEBUG"; return LogLevelKind2; })(LogLevelKind || {}); // src/interpreter/util/syntax-kind/stringify-syntax-kind.ts function stringifySyntaxKind(kind, typescript) { if (kind === typescript.SyntaxKind.NumericLiteral) return "NumericLiteral"; return typescript.SyntaxKind[kind]; } // src/interpreter/logger/logger.ts var import_util = require("util"); var import_ansi_colors = __toESM(require("ansi-colors"), 1); var Logger = class { options; constructor(optionsOrLogLevel = {}) { const { logLevel = 0 /* SILENT */, color: { info = "white", verbose = "yellow", debug = "magenta" } = {} } = typeof optionsOrLogLevel === "object" ? optionsOrLogLevel : { logLevel: optionsOrLogLevel }; this.options = { logLevel, color: { info, verbose, debug } }; } /** * Logs info output if the log level allows it */ logInfo(message) { if (this.options.logLevel < 1 /* INFO */) return; console.log(this.formatWithColor(this.options.color.info, message)); } /** * Logs verbose output if the log level allows it */ logVerbose(message) { if (this.options.logLevel < 2 /* VERBOSE */) return; console.log(this.formatWithColor(this.options.color.verbose, message)); } /** * Logs debug output if the log level allows it */ logDebug(message) { if (this.options.logLevel < 3 /* DEBUG */) return; console.log(this.formatWithColor(this.options.color.debug, message)); } /** * Logs that a 'continue' keyword appeared within a statement */ logContinue(node, typescript) { if (this.options.logLevel < 3 /* DEBUG */) return; console.log( `${this.formatWithColor(this.options.color.debug, `continue`)} encountered within ${this.formatWithColor( this.options.color.debug, stringifySyntaxKind(node.kind, typescript) )}` ); } /** * Logs that a 'break' keyword appeared within a statement */ logBreak(node, typescript) { if (this.options.logLevel < 3 /* DEBUG */) return; console.log( `${this.formatWithColor(this.options.color.debug, `break`)} encountered within ${this.formatWithColor(this.options.color.debug, stringifySyntaxKind(node.kind, typescript))}` ); } /** * Logs that a 'return' keyword appeared within a statement */ logReturn(node, typescript) { if (this.options.logLevel < 3 /* DEBUG */) return; console.log( `${this.formatWithColor(this.options.color.debug, `return`)} encountered within ${this.formatWithColor(this.options.color.debug, stringifySyntaxKind(node.kind, typescript))}` ); } /** * Logs the given result */ logResult(result, intermediateContext) { if (this.options.logLevel < 1 /* INFO */) return; if (intermediateContext != null) { console.log( this.formatWithColor(this.options.color.info, `(intermediate value from context '${intermediateContext}'):`), this.formatWithColor(this.options.color.info, `[RESULT]:`), this.compactValue(result) ); } else { console.log(this.formatWithColor(this.options.color.info, `[RESULT]:`), result); } } /** * Logs the given evaluation */ logNode(node, typescript, context) { if (this.options.logLevel < 3 /* DEBUG */) return; let headRaw = `[${stringifySyntaxKind(node.kind, typescript)}]`.padEnd(25); if (context != null) headRaw += this.formatWithColor(this.options.color.debug, `(${context})`); const tailRaw = node.getText(); const head = this.formatWithColor(this.options.color.debug, headRaw); const tail = this.formatWithColor(this.options.color.debug, tailRaw); console.log(head); console.log(tail); } /** * Logs the given binding */ logBinding(lValue, rValue, scope) { if (this.options.logLevel < 2 /* VERBOSE */) return; console.log( `${scope == null ? "" : this.formatWithColor(this.options.color.verbose, `(${scope}): `)}${this.formatWithColor(this.options.color.verbose, `${lValue} ->`)}`, this.formatWithColor(this.options.color.verbose, this.compactValue(rValue)) ); } /** * Logs the heritage of a ClassDeclaration */ logHeritage(classDeclaration) { if (this.options.logLevel < 3 /* DEBUG */) return; const parent = Object.getPrototypeOf(classDeclaration); if (parent.toString().includes("[Class")) { console.log( `${this.formatWithColor(this.options.color.debug, classDeclaration.toString())} ${this.formatWithColor(this.options.color.debug, `extends`)} ${this.formatWithColor( this.options.color.debug, parent.toString() )}` ); } } /** * Logs the newest value has been pushed onto the Stack */ logStack(stack) { if (this.options.logLevel < 3 /* DEBUG */) return; console.log(this.formatWithColor(this.options.color.debug, `Stack value: ${stringifyLiteral(this.compactValue(stack.lastItem))}`)); } /** * Logs the entire Traversal Stack */ logStatementTraversalStack(stack, typescript) { if (this.options.logLevel < 3 /* DEBUG */) return; console.log(this.formatWithColor(this.options.color.debug, `[${stack.map((kind) => stringifySyntaxKind(kind, typescript)).join(", ")}]`)); } /** * Makes a value compact so it is easier on the eyes when printing it */ compactValue(value) { return (0, import_util.inspect)(value, { depth: 0, colors: true, compact: true, maxArrayLength: 5 }); } formatWithColor(loggerColor, message) { return import_ansi_colors.default[loggerColor](message); } }; // src/interpreter/util/expression/is-expression.ts function isExpression(node, typescript) { return typescript.isExpressionNode(node) || typescript.isIdentifier(node) || typescript.isPrivateIdentifier?.(node); } // src/interpreter/util/statement/is-statement.ts function isStatement(node, typescript) { return typescript.isStatementButNotDeclaration(node); } // src/interpreter/stack/stack.ts function createStack() { const stack = []; return { /** * Gets an iterator for the Stack */ [Symbol.iterator]() { return stack[Symbol.iterator](); }, /** * Gets the length of the Stack */ get length() { return stack.length; }, /** * Gets the last item of the Stack */ get lastItem() { return stack[stack.length - 1]; }, /** * Pushes the given StackEntries on to the Stack */ push(...values) { return stack.push(...values); }, /** * Pops the last item from the stack */ pop() { return stack.pop(); } }; } // src/interpreter/util/reporting/report-error.ts function reportError(reporting, error, node) { if (reporting.reportErrors != null && !reporting.reportedErrorSet.has(error)) { reporting.reportedErrorSet.add(error); reporting.reportErrors({ error, node: error instanceof EvaluationError ? error.node : node }); } } // src/interpreter/reporting/reported-error-set.ts function createReportedErrorSet() { return /* @__PURE__ */ new WeakSet(); } // src/interpreter/evaluate.ts function evaluate({ typeChecker, node, environment: { preset = "NODE", extra = {} } = {}, moduleOverrides = {}, typescript = TSModule, logLevel = 0 /* SILENT */, policy: { deterministic = false, network = false, console: console2 = false, maxOps = Infinity, maxOpDuration = Infinity, io = { read: true, write: false }, process: process2 = { exit: false, spawnChild: false } } = {}, reporting: reportingInput = {} }) { const simpleLiteralResult = evaluateSimpleLiteral(node, typescript); if (simpleLiteralResult.success) return simpleLiteralResult; const policy = { deterministic, maxOps, maxOpDuration, network, console: console2, io: { read: typeof io === "boolean" ? io : io.read, write: typeof io === "boolean" ? io : io.write }, process: { exit: typeof process2 === "boolean" ? process2 : process2.exit, spawnChild: typeof process2 === "boolean" ? process2 : process2.spawnChild } }; const reporting = { ...reportingInput, reportedErrorSet: createReportedErrorSet() }; let error; const logger = new Logger(logLevel); const throwError = (ex) => { reportError(reporting, ex, ex.node); error = ex; return error; }; const environment = createLexicalEnvironment({ inputEnvironment: { preset, extra }, startingNode: node, policy }); const stack = createStack(); const statementTraversalStack = createStatementTraversalStack(); const nodeEvaluatorOptions = { policy, typeChecker, typescript, logger, stack, moduleOverrides, reporting, throwError, environment, statementTraversalStack, getCurrentError: () => error }; const nodeEvaluator = createNodeEvaluator(nodeEvaluatorOptions); try { let value; if (isExpression(node, typescript)) { value = nodeEvaluator.expression(node, nodeEvaluatorOptions); } else if (isStatement(node, typescript)) { nodeEvaluator.statement(node, nodeEvaluatorOptions); value = stack.pop(); } else if (isDeclaration(node, typescript)) { nodeEvaluator.declaration(node, nodeEvaluatorOptions); value = stack.pop(); } else { throwError(new UnexpectedNodeError({ node, environment, typescript })); } if (error != null) { return { success: false, reason: error }; } else { logger.logResult(value); return { success: true, value }; } } catch (reason) { throwError(reason); return { success: false, reason }; } } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { EvaluationError, IoError, LogLevelKind, MaxOpDurationExceededError, MaxOpsExceededError, MissingCatchOrFinallyAfterTryError, ModuleNotFoundError, NetworkError, NonDeterministicError, NotCallableError, PolicyError, ProcessError, UndefinedIdentifierError, UndefinedLeftValueError, UnexpectedNodeError, UnexpectedSyntaxError, evaluate, isEvaluationError }); //# sourceMappingURL=index.cjs.map