import { createRequire } from 'module'; const require = createRequire(import.meta.url);
let [__dirname, __filename] = typeof import.meta.url === 'string'
          ? ((url) => [url.fileURLToPath(new URL('.', import.meta.url)), url.fileURLToPath(import.meta.url)])(require('node:url'))
          : ['', ''];
import "./iterator-helpers-polyfill.js";

import {
  require_hints,
  require_parser
} from "./chunk-VD62II65.js";
import {
  require_proxy,
  require_sandbox
} from "./chunk-GSPO4CLX.js";
import {
  __commonJS,
  __name,
  __require,
  require_extras,
  require_logger,
  require_options,
  require_transform,
  require_util
} from "./chunk-LY4UAG7A.js";

// lib/approx/approx.js
var require_approx = __commonJS({
  "lib/approx/approx.js"(exports, module) {
    var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    }));
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = /* @__PURE__ */ __name(function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      }, "ownKeys");
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    var util_1 = require_util();
    var parser_1 = require_parser();
    var transform_1 = require_transform();
    var path_1 = __require("path");
    var module_1 = __importDefault(__require("module"));
    var hints_1 = require_hints();
    var proxy_1 = require_proxy();
    var logger_1 = __importStar(require_logger());
    var options_1 = require_options();
    var extras_1 = require_extras();
    var url_1 = __require("url");
    var sandbox_1 = require_sandbox();
    var util_2 = __require("util");
    Object.assign(options_1.options, JSON.parse(process.argv[2]));
    logger_1.default.level = options_1.options.loglevel;
    if (options_1.options.logfile)
      (0, logger_1.logToFile)(options_1.options.logfile);
    var LOOP_COUNT_LIMIT = 2500;
    var STACK_SIZE_LIMIT = 50;
    var objLoc = /* @__PURE__ */ new WeakMap();
    var unvisitedFunctionsAndClasses = /* @__PURE__ */ new Map();
    var baseObjects = /* @__PURE__ */ new Map();
    var hints = new hints_1.Hints();
    var constr = [];
    var dynamicClassInstanceFields = /* @__PURE__ */ new WeakMap();
    var loopCount = 0;
    var stackSize = 0;
    var instrumenting = false;
    var numStaticFunctions = 0;
    var totalCodeSize = 0;
    var staticRequires = /* @__PURE__ */ new Map();
    var NATIVE_CONSTRUCTORS = /* @__PURE__ */ new Set([
      Object,
      Boolean,
      Error,
      AggregateError,
      EvalError,
      RangeError,
      ReferenceError,
      SyntaxError,
      TypeError,
      URIError,
      Number,
      BigInt,
      Date,
      String,
      RegExp,
      Array,
      Int8Array,
      Uint8Array,
      Uint8ClampedArray,
      Int16Array,
      Uint16Array,
      Int32Array,
      Uint32Array,
      BigInt64Array,
      BigUint64Array,
      Float32Array,
      Float64Array,
      Map,
      Set,
      WeakMap,
      WeakSet,
      ArrayBuffer,
      SharedArrayBuffer,
      DataView,
      Promise,
      Proxy
    ]);
    function getLocationJSON(mod, loc) {
      return `${hints.moduleIndex.get(mod) ?? "?"}:${loc}`;
    }
    __name(getLocationJSON, "getLocationJSON");
    function getProp(prop) {
      return typeof prop === "symbol" ? String(prop) : `"${String(prop)}"`;
    }
    __name(getProp, "getProp");
    function getObjLoc(obj) {
      return objLoc.get(obj) ?? [void 0, void 0];
    }
    __name(getObjLoc, "getObjLoc");
    function locToString(obj) {
      const lt = objLoc.get(obj);
      if (lt) {
        const [loc, type] = lt;
        return `${loc}:${type}`;
      } else
        return "?";
    }
    __name(locToString, "locToString");
    var ApproxError = class extends Error {
      static {
        __name(this, "ApproxError");
      }
      constructor(msg) {
        super(msg);
      }
      toString() {
        return `ApproxError: ${this.message}`;
      }
    };
    function incrementStackSize() {
      if (stackSize++ > STACK_SIZE_LIMIT) {
        stackSize = 0;
        throw new ApproxError("Maximum stack size exceeded");
      }
    }
    __name(incrementStackSize, "incrementStackSize");
    function decrementStackSize() {
      stackSize--;
    }
    __name(decrementStackSize, "decrementStackSize");
    function handleException(ex) {
      if (ex instanceof ApproxError || ex instanceof RangeError || ex.toString().startsWith("Error: Cannot find module"))
        throw ex;
      if (logger_1.default.isDebugEnabled())
        logger_1.default.debug(`Suppressed exception: ${ex}`);
      return proxy_1.theProxy;
    }
    __name(handleException, "handleException");
    function processPendingWriteHints(fun, res) {
      const cs = dynamicClassInstanceFields.get(fun);
      if (cs) {
        for (const c of cs) {
          const val = Object.getOwnPropertyDescriptor(res, c.prop)?.value;
          const [baseLoc, baseType] = getObjLoc(res);
          const [valLoc, valType] = getObjLoc(val);
          if (baseLoc && baseType && valLoc && valType)
            hints.addWriteHint({
              type: "normal",
              loc: getLocationJSON(c.mod, c.loc),
              baseLoc,
              baseType,
              prop: c.prop,
              valLoc,
              valType
            });
        }
        dynamicClassInstanceFields.delete(fun);
      }
    }
    __name(processPendingWriteHints, "processPendingWriteHints");
    function callPre(mod, loc, base, fun, args, isNew) {
      if (fun === Function) {
        const funargs = args.slice(0, args.length - 1);
        const funbody = args[args.length - 1] ?? "";
        let error = false;
        for (const a of funargs)
          if (typeof a !== "string") {
            error = true;
            break;
          }
        if (!error) {
          const str = `function anonymous(${funargs.join(",")}){${funbody}}`;
          if (logger_1.default.isVerboseEnabled())
            logger_1.default.verbose(`Function ${mod}:${loc} (code length: ${str.length})`);
          if (logger_1.default.isDebugEnabled())
            logger_1.default.debug(str);
          const result = fun(...funargs, transform(mod, loc, String(funbody), "commonjs"));
          hints.addEvalHint({
            loc: getLocationJSON(mod, loc),
            str
          });
          objLoc.set(result, [getLocationJSON(mod, loc), "Function"]);
          return { proceed: false, result };
        }
      } else if (!isNew)
        if (fun.name === "require" && "resolve" in fun && "cache" in fun) {
          const str = typeof args[0] === "string" && args[0].startsWith("node:") ? args[0].substring(5) : args[0];
          if (module_1.default.isBuiltin(str) && !sandbox_1.WHITELISTED.has(str)) {
            if (logger_1.default.isDebugEnabled())
              logger_1.default.debug(`Intercepting require "${args[0]}"`);
            return { proceed: false, result: (0, proxy_1.stdlibProxy)(fun(args[0])) };
          }
        } else
          switch (fun) {
            case eval:
              const str = args[0];
              if (logger_1.default.isVerboseEnabled())
                logger_1.default.verbose(`Indirect eval ${mod}:${loc} (code length: ${typeof str === "string" ? str.length : "?"})`);
              if (typeof str === "string")
                hints.addEvalHint({
                  loc: getLocationJSON(mod, loc),
                  str
                });
              const result = fun(transform(mod, loc, str, "commonjs"));
              return { proceed: false, result };
            case Function.prototype.apply:
              return callPre(mod, loc, args[0], base, args[1] ?? [], false);
            case Function.prototype.call:
              return callPre(mod, loc, args[0], base, args.slice(1), false);
            case Reflect.apply:
              return callPre(mod, loc, args[1], args[0], args[2], false);
            case Reflect.construct:
              return callPre(mod, loc, args[1], args[0], args[2], true);
          }
      return { proceed: true };
    }
    __name(callPre, "callPre");
    function callPost(mod, loc, fun, args, val, base) {
      function copyFromDescriptor(to, prop, descriptor) {
        const [baseLoc, baseType] = getObjLoc(to);
        if (baseLoc && baseType) {
          if ("value" in descriptor) {
            const [valLoc, valType] = getObjLoc(descriptor.value);
            if (valLoc && valType)
              hints.addWriteHint({
                type: "normal",
                loc: getLocationJSON(mod, loc),
                baseLoc,
                baseType,
                prop,
                valLoc,
                valType
              });
          }
          if ("get" in descriptor) {
            const [valLoc, valType] = getObjLoc(descriptor.get);
            if (valLoc && valType)
              hints.addWriteHint({
                type: "get",
                loc: getLocationJSON(mod, loc),
                baseLoc,
                baseType,
                prop,
                valLoc,
                valType
              });
          }
          if ("set" in descriptor) {
            const [valLoc, valType] = getObjLoc(descriptor.set);
            if (valLoc && valType)
              hints.addWriteHint({
                type: "set",
                loc: getLocationJSON(mod, loc),
                baseLoc,
                baseType,
                prop,
                valLoc,
                valType
              });
          }
        }
      }
      __name(copyFromDescriptor, "copyFromDescriptor");
      switch (fun) {
        case Object.create: {
          objLoc.set(val, [getLocationJSON(mod, loc), "Object"]);
          break;
        }
        case Object.assign: {
          const target = args.at(0);
          for (const arg of args.slice(1, args.length))
            for (const [prop, val2] of Object.entries(Object.getOwnPropertyDescriptors(arg)))
              if (val2.enumerable)
                copyFromDescriptor(target, prop, val2);
          break;
        }
        case Object.defineProperty: {
          copyFromDescriptor(args.at(0), args.at(1), args.at(2));
          break;
        }
        case Object.defineProperties: {
          const target = args.at(0);
          for (const [prop, val2] of Object.entries(args.at(1)))
            copyFromDescriptor(target, prop, val2);
          break;
        }
        case Array.from:
        case Array.of:
        case Array.prototype.concat:
        case Array.prototype.flat:
        case Array.prototype.filter:
        case Array.prototype.slice: {
          objLoc.set(val, [getLocationJSON(mod, loc), "Array"]);
          break;
        }
        case Function.prototype.bind: {
          const [baseLoc, baseAllocType] = getObjLoc(base);
          if (!baseLoc || !baseAllocType)
            return;
          objLoc.set(val, [baseLoc, baseAllocType]);
          baseObjects.set(baseLoc, args[0]);
          break;
        }
        case Reflect.get: {
          break;
        }
        case Reflect.set: {
          break;
        }
        case Reflect.defineProperty: {
          break;
        }
      }
    }
    __name(callPost, "callPost");
    function transform(mod, loc, code, mode) {
      const name = loc ? `${mod}:eval[${loc}]` : mod;
      if (logger_1.default.isVerboseEnabled())
        logger_1.default.verbose(`Instrumenting ${name}`);
      instrumenting = true;
      try {
        const ast = (0, parser_1.parseAndDesugar)(code, name);
        if (!ast) {
          logger_1.default.warn(`Parsing failed for ${name}`);
          return "";
        }
        (0, extras_1.preprocessAst)(ast);
        const { transformed, staticRequires: sr, numStaticFunctions: nsf } = (0, transform_1.approxTransform)(ast, code, name, mode);
        if (transformed === void 0) {
          logger_1.default.warn(`Instrumentation failed for ${name}`);
          return "";
        }
        if (!loc)
          numStaticFunctions += nsf;
        for (const req of sr)
          (0, util_1.mapGetSet)(staticRequires, mod).add(req);
        return transformed;
      } catch (err) {
        logger_1.default.error(`Error: Instrumentation failed for ${name}, ${err instanceof Error ? err.stack : err}`);
        return "";
      } finally {
        instrumenting = false;
      }
    }
    __name(transform, "transform");
    function transformModule(filename, code, mode) {
      let transformed;
      if (!(typeof filename === "string" && typeof code === "string"))
        transformed = "";
      else if (!filename.startsWith(options_1.options.basedir)) {
        if (logger_1.default.isVerboseEnabled())
          logger_1.default.verbose(`Ignoring module outside basedir: ${filename}`);
        transformed = mode === "commonjs" ? `module.exports = ${transform_1.PREFIX}proxy` : "";
      } else {
        try {
          (0, transform_1.checkFile)(filename);
        } catch (err) {
          logger_1.default.error(err);
          return "";
        }
        if (options_1.options.printProgress && logger_1.default.isInfoEnabled())
          (0, logger_1.writeStdOutIfActive)(`Loading module ${filename} (${Math.ceil(code.length / 1024)}KB)`);
        totalCodeSize += code.length;
        transformed = transform(filename, void 0, code, mode);
      }
      return transformed;
    }
    __name(transformModule, "transformModule");
    var g = globalThis;
    for (const [name, val] of Object.entries({
      proxy: proxy_1.theProxy,
      builtin: Object.fromEntries(module_1.default.builtinModules.filter((m) => !sandbox_1.WHITELISTED.has(m)).map((m) => [m, (0, proxy_1.stdlibProxy)(__require(m))])),
      start(mod, modobj) {
        const i = hints.addModule(mod);
        if (logger_1.default.isDebugEnabled())
          logger_1.default.debug(`$start ${mod}: ${i}`);
        if (modobj && modobj.exports) {
          objLoc.set(modobj.exports, [`${i}:-1:-1:-1:-1`, "Object"]);
          return (0, proxy_1.makeModuleProxy)(modobj);
        }
        return void 0;
      },
      init() {
        logger_1.default.debug("$init");
        constr.push([]);
      },
      alloc(mod, loc, obj, hasInit, isClass) {
        if (typeof obj === "object" || typeof obj === "function" || Array.isArray(obj)) {
          if (logger_1.default.isDebugEnabled())
            logger_1.default.debug(`$alloc ${mod}:${loc}: ${Array.isArray(obj) ? "array" : typeof obj}`);
          const s = getLocationJSON(mod, loc);
          if (Array.isArray(obj))
            objLoc.set(obj, [s, "Array"]);
          else if (typeof obj === "object")
            objLoc.set(obj, [s, "Object"]);
          else {
            if (isClass)
              objLoc.set(obj, [s, "Class"]);
            else
              objLoc.set(obj, [s, "Function"]);
            if (obj.prototype)
              objLoc.set(obj.prototype, [s, "Prototype"]);
          }
          if (typeof obj === "function" && !hints.functions.has(s) && !unvisitedFunctionsAndClasses.has(s))
            unvisitedFunctionsAndClasses.set(s, { fun: obj, isClass });
          if (hasInit)
            for (const c of constr.pop()) {
              let type;
              let valLoc, valType;
              let baseLoc = s, baseType;
              if (typeof obj === "function") {
                baseType = c.isStatic ? "Class" : "Prototype";
                const desc = Object.getOwnPropertyDescriptor(c.isStatic ? obj : obj.prototype, c.prop);
                switch (c.kind) {
                  case "field":
                    if (!c.isStatic) {
                      (0, util_1.mapArrayAdd)(obj, c, dynamicClassInstanceFields);
                      continue;
                    }
                    type = "normal";
                    [valLoc, valType] = getObjLoc(desc?.value);
                    break;
                  case "method":
                    type = "normal";
                    valLoc = getLocationJSON(c.mod, c.loc);
                    valType = "Function";
                    const v = desc?.value;
                    if (v)
                      objLoc.set(v, [valLoc, valType]);
                    break;
                  case "get":
                  case "set":
                    type = c.kind;
                    valLoc = getLocationJSON(c.mod, c.loc);
                    valType = "Function";
                    const a = desc?.[c.kind];
                    if (a)
                      objLoc.set(a, [valLoc, valType]);
                    break;
                }
              } else {
                baseType = "Object";
                const desc = Object.getOwnPropertyDescriptor(obj, c.prop);
                switch (c.kind) {
                  case "field":
                    type = "normal";
                    [valLoc, valType] = getObjLoc(desc?.value);
                    break;
                  case "method":
                    type = "normal";
                    valLoc = getLocationJSON(c.mod, c.loc);
                    valType = "Function";
                    const v = desc?.value;
                    if (v)
                      objLoc.set(v, [valLoc, valType]);
                    break;
                  case "get":
                  case "set":
                    type = c.kind;
                    valLoc = getLocationJSON(c.mod, c.loc);
                    valType = "Function";
                    const a = desc?.[c.kind];
                    if (a)
                      objLoc.set(a, [valLoc, valType]);
                    break;
                }
              }
              if (c.isDynamic && valLoc && valType)
                hints.addWriteHint({
                  type,
                  loc: getLocationJSON(c.mod, c.loc),
                  baseLoc,
                  baseType,
                  prop: c.prop,
                  valLoc,
                  valType
                });
            }
        }
        return obj;
      },
      pw(mod, loc, base, prop, val2, isDynamic) {
        if (base === void 0) {
          if (logger_1.default.isDebugEnabled())
            logger_1.default.debug(`Suppressed exception: TypeError: Cannot set properties of undefined`);
          return void 0;
        }
        if (typeof prop === "symbol" || Array.isArray(base))
          return base[prop];
        if ((0, proxy_1.isProxy)(base) || (0, proxy_1.isProxy)(val2))
          return proxy_1.theProxy;
        const p = String(prop);
        if (logger_1.default.isDebugEnabled())
          logger_1.default.debug(`$pw ${mod}:${loc}: ${locToString(base)}${isDynamic ? `[${getProp(prop)}]` : `.${String(prop)}`} = ${locToString(val2)}`);
        try {
          base[p] = val2;
        } catch (ex) {
          if (logger_1.default.isDebugEnabled())
            logger_1.default.debug(`Suppressed exception: ${ex}`);
        }
        if (typeof val2 === "function") {
          const loc2 = objLoc.get(val2);
          if (loc2) {
            const [funloc] = loc2;
            if (!baseObjects.has(funloc))
              baseObjects.set(funloc, base);
          }
        }
        const [baseLoc, baseType] = getObjLoc(base);
        const [valLoc, valType] = getObjLoc(val2);
        if (baseLoc && baseType && valLoc && valType)
          hints.addWriteHint({
            type: "normal",
            loc: getLocationJSON(mod, loc),
            baseLoc,
            baseType,
            prop: p,
            valLoc,
            valType
          });
        return val2;
      },
      dpr(mod, loc, base, prop) {
        if (base === void 0) {
          if (logger_1.default.isDebugEnabled())
            logger_1.default.debug(`Suppressed exception: TypeError: Cannot read properties of undefined`);
          return void 0;
        }
        if (Array.isArray(base))
          return base[prop];
        if ((0, proxy_1.isProxy)(base))
          return proxy_1.theProxy;
        const p = typeof prop === "symbol" ? prop : String(prop);
        let val2;
        try {
          val2 = base[p];
        } catch (ex) {
          if (logger_1.default.isDebugEnabled())
            logger_1.default.debug(`Suppressed exception: ${ex}`);
          return proxy_1.theProxy;
        }
        if ((0, proxy_1.isProxy)(val2))
          return proxy_1.theProxy;
        if (logger_1.default.isDebugEnabled())
          logger_1.default.debug(`$dpr ${mod}:${loc}: ${locToString(base)}[${getProp(prop)}] -> ${locToString(val2)}`);
        const [valLoc, valType] = getObjLoc(val2);
        if (valLoc && valType)
          hints.addReadHint({
            loc: getLocationJSON(mod, loc),
            prop: typeof p === "string" ? p : void 0,
            valLoc,
            valType
          });
        return val2;
      },
      fun(mod, loc, fun, isOptionalCall, ...args) {
        if (logger_1.default.isDebugEnabled())
          logger_1.default.debug(`$fun ${mod}:${loc}${isOptionalCall ? " optional" : ""}`);
        if (isOptionalCall && (fun === void 0 || fun === null))
          return void 0;
        if (typeof fun !== "function")
          return proxy_1.theProxy;
        try {
          incrementStackSize();
          const { proceed, result } = callPre(mod, loc, void 0, fun, args, false);
          if (proceed) {
            const res = Reflect.apply(fun, void 0, args);
            callPost(mod, loc, fun, args, res);
            return res;
          } else
            return result;
        } catch (ex) {
          return handleException(ex);
        } finally {
          decrementStackSize();
        }
      },
      method(mod, loc, base, prop, isDynamic, isOptionalMember, isOptionalCall, ...args) {
        if (logger_1.default.isDebugEnabled())
          logger_1.default.debug(`$method ${mod}:${loc}${isDynamic ? " dynamic" : ""}${isOptionalMember ? " optionalMember" : ""}${isOptionalCall ? " optionalCall" : ""}`);
        let fun;
        try {
          fun = isOptionalMember && (base === void 0 || base === null) ? void 0 : base[prop];
        } catch (ex) {
          if (logger_1.default.isDebugEnabled())
            logger_1.default.debug(`Suppressed exception: ${ex}`);
          return proxy_1.theProxy;
        }
        if (isOptionalCall && (fun === void 0 || fun === null))
          return void 0;
        if (typeof fun !== "function") {
          if (logger_1.default.isDebugEnabled())
            logger_1.default.debug(`Suppressed exception: TypeError: Must be a function`);
          return proxy_1.theProxy;
        }
        try {
          incrementStackSize();
          const { proceed, result } = callPre(mod, loc, base, fun, args, false);
          if (proceed) {
            const res = Reflect.apply(fun, base, args);
            callPost(mod, loc, fun, args, res, base);
            return res;
          } else
            return result;
        } catch (ex) {
          return handleException(ex);
        } finally {
          decrementStackSize();
        }
      },
      new(mod, loc, fun, ...args) {
        logger_1.default.debug("$new");
        if (typeof fun !== "function") {
          if (logger_1.default.isDebugEnabled())
            logger_1.default.debug(`Suppressed exception: TypeError: Must be a function`);
          return proxy_1.theProxy;
        }
        try {
          incrementStackSize();
          const { proceed, result } = callPre(mod, loc, void 0, fun, args, true);
          if (proceed) {
            const res = Reflect.construct(fun, args);
            processPendingWriteHints(fun, res);
            if (NATIVE_CONSTRUCTORS.has(fun) && (typeof res === "object" || typeof res === "function")) {
              const t = typeof res === "object" ? "Object" : typeof res === "function" ? "Function" : Array.isArray(res) ? "Array" : void 0;
              if (t)
                objLoc.set(res, [getLocationJSON(mod, loc), t]);
            }
            return res;
          } else
            return result;
        } catch (ex) {
          return handleException(ex);
        } finally {
          decrementStackSize();
        }
      },
      comp(mod, loc, prop, kind, isStatic, isDynamic) {
        if (logger_1.default.isDebugEnabled())
          logger_1.default.debug(`$comp ${mod}:${loc} ${getProp(prop)} ${kind}`);
        if (typeof prop !== "symbol")
          constr.at(constr.length - 1).push({ mod, loc, prop: String(prop), kind, isStatic, isDynamic });
        return prop;
      },
      enter(mod, loc) {
        if (logger_1.default.isDebugEnabled())
          logger_1.default.debug(`$enter ${mod}:${loc}`);
        const s = getLocationJSON(mod, loc);
        unvisitedFunctionsAndClasses.delete(s);
        hints.addFunction(s);
      },
      this(mod, loc, thiss) {
        logger_1.default.debug(`$this ${mod}:${loc}`);
        if (thiss) {
          const s = getLocationJSON(mod, loc);
          objLoc.set(thiss, [s, "Object"]);
        }
        return thiss;
      },
      catch(ex) {
        logger_1.default.debug("$catch");
        if (ex instanceof ApproxError)
          throw ex;
      },
      loop() {
        logger_1.default.debug("$loop");
        if (loopCount++ > LOOP_COUNT_LIMIT) {
          loopCount = 0;
          throw new ApproxError("Loop limit reached");
        }
      },
      eval(mod, loc, str) {
        if (logger_1.default.isDebugEnabled())
          logger_1.default.debug(`$eval ${mod}:${loc} (code length: ${typeof str === "string" ? str.length : "?"})`);
        if (typeof str === "string")
          hints.addEvalHint({
            loc: getLocationJSON(mod, loc),
            str
          });
        return transform(mod, loc, str, "commonjs");
      },
      require(mod, loc, str) {
        if (module_1.default.isBuiltin(str))
          return str;
        if (logger_1.default.isDebugEnabled())
          logger_1.default.debug(`$require ${mod}:${loc} "${str}"`);
        if (typeof str === "string")
          hints.addRequireHint({
            loc: getLocationJSON(mod, loc),
            str
          });
        return str;
      },
      freeze(obj) {
        Object.freeze(obj);
      }
    }))
      g[transform_1.PREFIX + name] = val;
    g.$log = function(msg) {
      (0, logger_1.writeStdOutIfActive)("");
      logger_1.default.info(`$log: ${(0, util_2.inspect)(msg, { depth: 1 })}`);
    };
    var realSetTimeout = setTimeout;
    async function forceExecuteUnvisitedFunctions() {
      let numForced = 0, numForcedExceptions = 0;
      for (const [loc, { fun, isClass }] of unvisitedFunctionsAndClasses) {
        const sloc = `${hints.modules[parseInt(loc)]}${loc.substring(loc.indexOf(":"))}`;
        if (options_1.options.printProgress && logger_1.default.isInfoEnabled())
          (logger_1.default.isVerboseEnabled() ? logger_1.default.verbose : logger_1.writeStdOutIfActive)(`Force-executing ${isClass ? "constructor" : "function"} ${sloc} (${unvisitedFunctionsAndClasses.size - 1} pending)`);
        try {
          const args = proxy_1.theArgumentsProxy;
          if (isClass)
            Reflect.construct(fun, args);
          else {
            const base = baseObjects.get(loc);
            let res = Reflect.apply(fun, (0, proxy_1.makeBaseProxy)(base), args);
            if (res && typeof res === "object" && (Symbol.iterator in res || Symbol.asyncIterator in res) && typeof res.next === "function")
              res.next();
            if (res instanceof Promise) {
              if (logger_1.default.isDebugEnabled())
                logger_1.default.debug("Awaiting promise");
              res = await Promise.race([res, new Promise((resolve) => realSetTimeout(resolve, 100))]);
            }
          }
          if (logger_1.default.isDebugEnabled())
            logger_1.default.debug("Function completed successfully");
        } catch (err) {
          if (logger_1.default.isVerboseEnabled())
            logger_1.default.verbose(`Function completed with exception: ${err instanceof Error && logger_1.default.isDebugEnabled() ? err.stack : err}`);
          numForcedExceptions++;
        }
        numForced++;
        unvisitedFunctionsAndClasses.delete(loc);
        baseObjects.delete(loc);
        loopCount = 0;
        if (!hints.functions.has(loc))
          logger_1.default.error(`Error: Function ${sloc} should be visited now`);
      }
      return { numForced, numForcedExceptions };
    }
    __name(forceExecuteUnvisitedFunctions, "forceExecuteUnvisitedFunctions");
    var { port1, port2 } = new MessageChannel();
    module_1.default.register("./hooks.js", {
      parentURL: (0, url_1.pathToFileURL)(__filename),
      data: {
        opts: options_1.options,
        port2
      },
      transferList: [port2]
    });
    port1.on("message", (msg) => {
      switch (msg.type) {
        case "log": {
          const { level, str } = msg;
          logger_1.default.log(level, str);
          break;
        }
        case "transform": {
          const { filename, source } = msg;
          const transformed = transformModule(filename, source, "module");
          port1.postMessage({ filename, transformed });
          break;
        }
      }
    });
    var realCompile = module_1.default.prototype._compile;
    module_1.default.prototype._compile = function(content, filename) {
      if (typeof content !== "string" || typeof filename !== "string")
        return;
      const orig = content;
      if (!instrumenting) {
        if (logger_1.default.isVerboseEnabled())
          logger_1.default.verbose(`Loading ${filename} (CJS loader)`);
        content = transformModule(filename, orig, "commonjs");
      }
      try {
        return realCompile.call(this, content, filename);
      } catch (err) {
        if (String(err).includes("SyntaxError"))
          logger_1.default.verbose(`Unable to load ${filename} (trying to load ESM module as CJS?)`);
        else
          logger_1.default.warn(`Unable to load ${filename}: ${err instanceof Error && logger_1.default.isDebugEnabled() ? err.stack : err}`);
        return realCompile.call(this, `module.exports = ${transform_1.PREFIX}proxy`, filename);
      }
    };
    process.on("uncaughtException", (err) => {
      logger_1.default.warn(`Unexpected exception (insufficient sandboxing?): ${err instanceof Error && logger_1.default.isDebugEnabled() ? err.stack : err}`);
    });
    process.on("unhandledRejection", (err) => {
      logger_1.default.verbose(`Unhandled promise rejection: ${err instanceof Error ? err.stack : err}`);
    });
    var chdir = process.chdir.bind(process);
    var send = process.send.bind(process);
    var dynamicImport = new Function("s", "return import(s)");
    process.on("message", async (msg) => {
      logger_1.default.verbose(`Starting approximate interpretation of ${msg.file}`);
      let moduleException = false;
      module.filename = __filename = msg.file;
      module.path = __dirname = (0, path_1.dirname)(msg.file);
      module.paths = [(0, path_1.resolve)(__dirname, "node_modules")];
      chdir(__dirname);
      try {
        await dynamicImport((0, url_1.pathToFileURL)(msg.file));
        if (logger_1.default.isDebugEnabled())
          logger_1.default.debug(`Module completed successfully: ${msg.file}`);
      } catch (err) {
        if (logger_1.default.isVerboseEnabled())
          logger_1.default.verbose(`Uncaught exception for ${msg.file}: ${err instanceof Error && logger_1.default.isDebugEnabled() ? err.stack : err}`);
        moduleException = true;
      }
      loopCount = 0;
      const { numForced, numForcedExceptions } = await forceExecuteUnvisitedFunctions();
      logger_1.default.verbose("Approximate interpretation completed");
      send({
        hints: hints.toJSON(),
        numForced,
        numForcedExceptions,
        moduleException,
        numStaticFunctions,
        totalCodeSize,
        staticRequires: (0, util_1.mapSetToPairArray)(staticRequires)
      });
      hints.clearHints();
      numStaticFunctions = 0;
      staticRequires.clear();
    });
    (0, sandbox_1.patchGlobalBuiltins)();
  }
});
export default require_approx();
//# sourceMappingURL=approx.js.map
