All files / src/lib/scriptEventsHandlers untrustedHandler.ts

88.54% Statements 340/384
80% Branches 108/135
89.13% Functions 41/46
88.71% Lines 322/363

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885                9x             9x 9x         9x                   9x   9x         9x                                                                                                                                           9x       125x 2152x 2152x       2152x 360x     1792x 360x     1432x 53x     53x     1379x 103x 103x     1276x 5x 5x 5x   5x 2x   3x 3x         1271x 562x 562x       562x 562x 562x 3x   559x             709x 709x 709x 95x 95x 95x       614x                   9x             125x 2152x 2152x   2152x     2152x 2152x 2152x 2152x   2152x 2152x 1337x   1337x 1337x 11x 11x   11x 9x 9x       9x 5x   9x 9x         9x 1x 1x 1x       8x 8x 8x   9x       1326x 1326x 81x   1245x   1326x             2152x     2149x 2148x 1954x 1481x 1356x 376x   376x           95x 95x     95x 95x 95x   281x                         125x 125x 125x                   125x 125x 125x     125x 95x   95x     95x 95x   95x     125x         125x               125x 125x         125x             265x   265x   265x 265x             265x   265x           265x       125x       125x 125x   125x 2x 2x 2x   2x   125x   125x 2x 2x 2x   2x   125x   125x 2x 2x 2x   2x   125x   125x 125x   125x 125x 125x 125x 125x             125x   125x                                                   125x 48x 48x 48x 3x   45x 45x           125x 125x             125x       125x   125x                     125x           125x   125x 8x 8x 8x     117x               1489x 1488x   1485x   2x   9x   1151x   241x 35x 35x 35x     82x 14x       68x 55x 55x 1103x 1103x 1103x   55x     13x   13x 22x 9x 5x 5x 5x   9x 9x   13x 13x 13x     13x                   4484x   4484x   1538x       2067x   879x       879x 879x 341x 341x   341x 341x 629x 629x 629x   341x   538x 538x     538x 538x 538x 538x         538x   538x 536x 536x   536x   536x 1872x   1872x   1872x   1872x 17x   17x   17x 15x       15x 15x       15x 21x       15x 15x           15x 1x 1x 1x         14x 14x 14x   21x       17x 17x   1855x 1855x       536x   2x           2x                           119x       119x       119x   119x 3x 3x     116x 232x 206x   26x           116x 116x   116x 4x 4x 4x 4x       4x         112x 112x 112x   232x 116x               1755x       1755x   1755x 1755x 1755x             117x       117x   117x   117x 117x 117x             125x 117x 117x     125x 125x   125x 28x   125x   125x 125x 125x             9x 125x 125x 125x           9x         125x   125x 125x 125x   117x                                           117x   117x   113x 113x     113x               23x       22x       96x       113x   113x   12x 12x      
/* eslint-disable @typescript-eslint/ban-types */
 
/**
 * Untrusted Script Event Handler Loader (QuickJS)
 *
 * Executes handler code in isolated QuickJS environment for security.
 */
 
import {
  newQuickJSWASMModuleFromVariant,
  QuickJSContext,
  QuickJSHandle,
  QuickJSRuntime,
  shouldInterruptAfterDeadline,
} from "quickjs-emscripten-core";
import quickJSVariant from "#my-quickjs-variant";
import uuid from "uuid/v4";
import type {
  FileReaderFn,
  ScriptEventHandlerWithCleanup,
} from "lib/scriptEventsHandlers/handlerTypes";
import {
  detectModuleSystem,
  createMockRequire,
  validateHandlerMetadata,
  createHandlerBase,
  finalizeHandler,
  noReadFileFn,
  convertESMToCommonJS,
} from "./handlerCommon";
 
export const QuickJS = newQuickJSWASMModuleFromVariant(quickJSVariant);
 
const TIMEOUT_MS = 60000;
 
/**
 * Proxy factory for creating lazy proxies in the VM
 */
const PROXY_FACTORY_SRC = `
  (function(moduleName, invoker, proxyFactory) {
    const handler = {
      get(_t, prop) {        
        if (prop === Symbol.iterator) {
          const isArray = invoker(moduleName, '__IS_ARRAY__', []);
          if (isArray) {
            return function* () {
              const keys = invoker(moduleName, '__KEYS__', []);
              if (Array.isArray(keys)) {
                for (let i = 0; i < keys.length; i++) {
                  yield invoker(moduleName, String(i), []);
                }
              }
            };
          }
          return undefined;
        }
        
        const value = invoker(moduleName, String(prop), []);
        
        if (value && typeof value === 'object' && value.__PROXY_MARKER__) {
          return proxyFactory(value.__PROXY_MARKER__, invoker, proxyFactory);
        }
        
        if (typeof value === 'function') {
          return (...args) => invoker(moduleName, String(prop), ['__CALL__', ...args]);
        }
        
        return value;
      },
      set(_t, prop, value) {
        invoker(moduleName, String(prop), ['__SET__', value]);
        return true;
      },
      ownKeys(_t) {
        const keys = invoker(moduleName, '__KEYS__', []);
        return Array.isArray(keys) ? keys : [];
      },
      has(_t, prop) {
        const result = invoker(moduleName, '__HAS__', [String(prop)]);
        return !!result;
      },
      getOwnPropertyDescriptor(_t, prop) {
        const exists = invoker(moduleName, '__HAS__', [String(prop)]);
        if (exists) {
          return {
            enumerable: true,
            configurable: true,
            writable: true,
            value: this.get(_t, prop)
          };
        }
        return undefined;
      },
      apply(_t, _thisArg, argArray) {
        return invoker(moduleName, '', ['__CALL__', ...argArray]);
      }
    };
    
    const hostObjType = invoker(moduleName, '__GET_TYPE__', []);
    const isArray = invoker(moduleName, '__IS_ARRAY__', []);
    const target = (hostObjType === 'function') ? function(){} : (isArray ? [] : {});
    return new Proxy(target, handler);
  })
`;
 
/**
 * Creates invoke handler for proxy system
 */
const createOnInvokeHandler = (
  hostRegistry: Map<string, unknown>,
  createProxy: (value: unknown) => { proxyId: string; needsProxy: boolean },
): ((module: string, path: string, args: unknown[]) => unknown) => {
  return (module: string, path: string, args: unknown[]) => {
    const hostObj = hostRegistry.get(module);
    Iif (!hostObj) {
      throw new Error(`Module ${module} not found in host registry`);
    }
 
    if (path === "__GET_TYPE__") {
      return typeof hostObj;
    }
 
    if (path === "__IS_ARRAY__") {
      return Array.isArray(hostObj);
    }
 
    if (path === "__KEYS__") {
      Iif (Array.isArray(hostObj)) {
        return hostObj.map((_, i) => String(i));
      }
      return Object.keys(hostObj as object);
    }
 
    if (path === "__HAS__") {
      const [prop] = args;
      return Object.prototype.hasOwnProperty.call(hostObj, String(prop));
    }
 
    if (args.length > 0 && args[0] === "__SET__") {
      const [, value] = args;
      if (hostObj && typeof hostObj === "object") {
        const existingValue = (hostObj as Record<string, unknown>)[path];
        // Prevent replacing functions
        if (typeof existingValue === "function") {
          return undefined;
        }
        (hostObj as Record<string, unknown>)[path] = value;
        return undefined;
      }
      return undefined;
    }
 
    if (args.length > 0 && args[0] === "__CALL__") {
      const [, ...callArgs] = args;
      Iif (typeof hostObj === "function") {
        return (hostObj as Function)(...callArgs);
      }
 
      const prop = (hostObj as Record<string, unknown>)[path];
      if (typeof prop === "function") {
        if (Array.isArray(hostObj)) {
          return (prop as Function).call(hostObj, ...callArgs);
        }
        return (prop as Function).call(hostObj, ...callArgs);
      }
 
      throw new Error(`Property ${path} is not a function`);
    }
 
    // Regular property access
    if (hostObj && typeof hostObj === "object") {
      const value = (hostObj as Record<string, unknown>)[path];
      if (value !== null && value !== undefined && typeof value === "object") {
        const { proxyId, needsProxy } = createProxy(value);
        if (needsProxy) {
          return { __PROXY_MARKER__: proxyId };
        }
      }
 
      return value;
    }
 
    return undefined;
  };
};
 
/**
 * Creates host invoke function for the proxy system
 */
const createHostInvokeFn = (
  vm: QuickJSContext,
  onInvoke: (module: string, path: string, args: unknown[]) => unknown,
  jsValueToHandle: (val: unknown, useProxies: boolean) => QuickJSHandle,
  handleToJsValue: (handle: QuickJSHandle) => unknown,
  vmHandleRegistry: Map<string, QuickJSHandle>,
) => {
  return vm.newFunction("hostInvoke", (moduleH, pathH, argsH) => {
    const module = vm.getString(moduleH);
    const path = vm.getString(pathH);
 
    const argsType = vm.typeof(argsH);
    let args: unknown[];
 
    if (argsType === "object" && argsH !== vm.null) {
      const lengthProp = vm.getProp(argsH, "length");
      const length = vm.getNumber(lengthProp);
      lengthProp.dispose();
 
      args = [];
      for (let i = 0; i < length; i++) {
        const elementHandle = vm.getProp(argsH, String(i));
 
        const elementType = vm.typeof(elementHandle);
        if (elementType === "function") {
          const funcId = `arg_func_${Date.now()}_${i}_${Math.random()}`;
          vmHandleRegistry.set(funcId, elementHandle);
 
          args[i] = (...callArgs: unknown[]) => {
            const storedHandle = vmHandleRegistry.get(funcId);
            Iif (!storedHandle) {
              throw new Error(`Function handle ${funcId} not found`);
            }
 
            const argHandles = callArgs.map((arg) =>
              jsValueToHandle(arg, true),
            );
            try {
              const result = vm.callFunction(
                storedHandle,
                vm.undefined,
                ...argHandles,
              );
              if (result.error) {
                const error = vm.dump(result.error);
                result.error.dispose();
                throw new Error(
                  `Callback function failed: ${JSON.stringify(error)}`,
                );
              }
              const returnValue = vm.dump(result.value);
              result.value.dispose();
              return returnValue;
            } finally {
              argHandles.forEach((h) => h.dispose());
            }
          };
        } else {
          const elementType = vm.typeof(elementHandle);
          if (elementType === "object" && elementHandle !== vm.null) {
            args[i] = handleToJsValue(elementHandle);
          } else {
            args[i] = vm.dump(elementHandle);
          }
          elementHandle.dispose();
        }
      }
    } else E{
      args = [vm.dump(argsH)];
    }
 
    const result = onInvoke(module, path, args);
 
    // Convert result back to VM handle
    if (result === null) return vm.null;
    if (result === undefined) return vm.undefined;
    if (typeof result === "boolean") return result ? vm.true : vm.false;
    if (typeof result === "number") return vm.newNumber(result);
    if (typeof result === "string") return vm.newString(result);
    if (typeof result === "object" || typeof result === "function") {
      // Check if this is a proxy marker - if so, return it as-is so the VM can handle it
      if (
        result &&
        typeof result === "object" &&
        "__PROXY_MARKER__" in result &&
        Object.keys(result).length === 1
      ) {
        const markerObj = vm.newObject();
        const proxyIdHandle = vm.newString(
          (result as { __PROXY_MARKER__: string }).__PROXY_MARKER__,
        );
        vm.setProp(markerObj, "__PROXY_MARKER__", proxyIdHandle);
        proxyIdHandle.dispose();
        return markerObj;
      }
      return jsValueToHandle(result, false);
    }
 
    return vm.undefined;
  });
};
 
/**
 * Persistent VM wrapper maintaining QuickJS context across function calls.
 */
class PersistentVM {
  private vm: QuickJSContext;
  private runtime: QuickJSRuntime;
  private moduleExports: QuickJSHandle | null = null;
  private hostFunctionRegistry = new Map<string, unknown>();
  private vmHandleRegistry = new Map<string, QuickJSHandle>();
  private proxyFactory: QuickJSHandle;
  private hostInvokeFn: QuickJSHandle;
  private onInvokeHandler: (
    module: string,
    path: string,
    args: unknown[],
  ) => unknown;
 
  constructor(vm: QuickJSContext, runtime: QuickJSRuntime) {
    this.vm = vm;
    this.runtime = runtime;
    this.setupGlobalEnvironment();
 
    // Setup proxy system
    const createProxyHelper = (value: unknown) => {
      const proxyId = `proxy_${uuid()}`;
      const needsProxy =
        value !== null &&
        value !== undefined &&
        (typeof value === "object" || typeof value === "function");
      if (needsProxy) {
        this.hostFunctionRegistry.set(proxyId, value);
      }
      return { proxyId, needsProxy };
    };
 
    this.onInvokeHandler = createOnInvokeHandler(
      this.hostFunctionRegistry,
      createProxyHelper,
    );
 
    this.hostInvokeFn = createHostInvokeFn(
      this.vm,
      this.onInvokeHandler,
      this.jsValueToHandle.bind(this),
      this.handleToJsValue.bind(this),
      this.vmHandleRegistry,
    );
 
    const factoryEval = this.vm.evalCode(PROXY_FACTORY_SRC);
    Iif (factoryEval.error) {
      const err = this.vm.dump(factoryEval.error);
      factoryEval.error.dispose();
      throw new Error("Failed to install proxy factory: " + String(err));
    }
    this.proxyFactory = factoryEval.value;
  }
 
  /**
   * Creates a lazy proxy for objects and arrays
   */
  private createLazyProxy(hostObj: unknown): QuickJSHandle {
    const proxyId = `proxy_${uuid()}`;
 
    this.hostFunctionRegistry.set(proxyId, hostObj);
 
    const proxyIdHandle = this.vm.newString(proxyId);
    const proxyResult = this.vm.callFunction(
      this.proxyFactory,
      this.vm.undefined,
      proxyIdHandle,
      this.hostInvokeFn,
      this.proxyFactory,
    );
    proxyIdHandle.dispose();
 
    Iif (proxyResult.error) {
      const err = this.vm.dump(proxyResult.error);
      proxyResult.error.dispose();
      throw new Error("Failed to create proxy: " + String(err));
    }
 
    return proxyResult.value;
  }
 
  private setupGlobalEnvironment() {
    this.runtime.setInterruptHandler(
      shouldInterruptAfterDeadline(Date.now() + TIMEOUT_MS),
    );
 
    const consoleObj = this.vm.newObject();
    this.vm.setProp(this.vm.global, "console", consoleObj);
 
    const logFn = this.vm.newFunction("log", (...args) => {
      if (process.env.NODE_ENV !== "production") {
        const jsArgs = args.map((arg) => this.vm.dump(arg));
        console.log(...jsArgs);
      }
      return this.vm.undefined;
    });
    this.vm.setProp(consoleObj, "log", logFn);
 
    const warnFn = this.vm.newFunction("warn", (...args) => {
      if (process.env.NODE_ENV !== "production") {
        const jsArgs = args.map((arg) => this.vm.dump(arg));
        console.warn(...jsArgs);
      }
      return this.vm.undefined;
    });
    this.vm.setProp(consoleObj, "warn", warnFn);
 
    const errorFn = this.vm.newFunction("error", (...args) => {
      if (process.env.NODE_ENV !== "production") {
        const jsArgs = args.map((arg) => this.vm.dump(arg));
        console.error(...jsArgs);
      }
      return this.vm.undefined;
    });
    this.vm.setProp(consoleObj, "error", errorFn);
 
    const moduleObj = this.vm.newObject();
    this.vm.setProp(this.vm.global, "module", moduleObj);
 
    logFn.dispose();
    warnFn.dispose();
    errorFn.dispose();
    consoleObj.dispose();
    moduleObj.dispose();
  }
 
  /**
   * Sets up mock require for file reading and plugin API
   */
  setupMockRequire(readFile: FileReaderFn) {
    const mockRequire = createMockRequire(readFile);
 
    this.runtime.setModuleLoader((moduleName) => {
      const mockModule = mockRequire[moduleName];
 
      let namedExports = "";
      Iif (mockModule && typeof mockModule === "object") {
        const exportStatements = Object.keys(mockModule)
          .filter(
            (key) =>
              key !== "default" &&
              typeof (mockModule as Record<string, unknown>)[key] !==
                "undefined",
          )
          .map((key) => `export const ${key} = _module?.${key};`)
          .join("\n        ");
        namedExports = exportStatements;
      }
 
      const escapedModuleName = moduleName.replace(/["\\]/g, (m) => `\\${m}`);
 
      return `
        const _module = require("${escapedModuleName}");
        export default _module.default || _module;
        ${namedExports}
      `;
    });
 
    const requireFn = this.vm.newFunction("require", (moduleNameHandle) => {
      const moduleName = this.vm.dump(moduleNameHandle) as string;
      const module = mockRequire[moduleName];
      if (!module) {
        throw new Error(`Module '${moduleName}' not found`);
      }
      if (module && typeof module === "object" && this.proxyFactory) {
        return this.createLazyProxy(module);
      } else E{
        return this.jsValueToHandle(module, false);
      }
    });
 
    this.vm.setProp(this.vm.global, "require", requireFn);
    requireFn.dispose();
  }
 
  /**
   * Executes code and stores module exports
   */
  executeCode(code: string, filename: string): void {
    this.runtime.setInterruptHandler(
      shouldInterruptAfterDeadline(Date.now() + TIMEOUT_MS),
    );
 
    const moduleType = detectModuleSystem(code);
 
    Iif (moduleType === "module") {
      const result = this.vm.evalCode(code, filename, { type: "module" });
 
      Iif (result.error) {
        const error = this.vm.dump(result.error);
        result.error.dispose();
        throw new Error(`VM execution failed: ${JSON.stringify(error)}`);
      }
 
      this.moduleExports = result.value;
    } else {
      const wrappedCode = `
        const module = { exports: {} };
        const exports = module.exports;
        ${code}
        module.exports;
      `;
      const result = this.vm.evalCode(wrappedCode, filename);
 
      if (result.error) {
        const error = this.vm.dump(result.error);
        result.error.dispose();
        throw new Error(`VM execution failed: ${JSON.stringify(error)}`);
      }
 
      this.moduleExports = result.value;
    }
  }
 
  /**
   * Converts JS value to VM handle with selective proxy optimization
   */
  private jsValueToHandle(value: unknown, useProxies: boolean): QuickJSHandle {
    if (value === null) return this.vm.null;
    if (value === undefined) return this.vm.undefined;
 
    switch (typeof value) {
      case "boolean":
        return value ? this.vm.true : this.vm.false;
      case "number":
        return this.vm.newNumber(value);
      case "string":
        return this.vm.newString(value);
      case "function":
        return this.vm.newFunction(value.name || "anonymous", (...vmArgs) => {
          const jsArgs = vmArgs.map((arg) => this.handleToJsValue(arg));
          const result = (value as Function)(...jsArgs);
          return this.jsValueToHandle(result, useProxies);
        });
      case "object":
        if (useProxies) {
          return this.createLazyProxy(value);
        }
 
        // Handle arrays
        if (Array.isArray(value)) {
          const arr = this.vm.newArray();
          value.forEach((item, index) => {
            const itemHandle = this.jsValueToHandle(item, useProxies);
            this.vm.setProp(arr, String(index), itemHandle);
            itemHandle.dispose();
          });
          return arr;
        }
 
        const obj = this.vm.newObject();
 
        for (const [key, val] of Object.entries(value)) {
          if (typeof val === "function") {
            const fn = this.vm.newFunction(key, (...vmArgs) => {
              const jsArgs = vmArgs.map((arg) => this.handleToJsValue(arg));
              const result = (val as Function)(...jsArgs);
              return this.jsValueToHandle(result, useProxies);
            });
            this.vm.setProp(obj, key, fn);
            fn.dispose();
          } else {
            const valHandle = this.jsValueToHandle(val, useProxies);
            this.vm.setProp(obj, key, valHandle);
            valHandle.dispose();
          }
        }
        return obj;
      default:
        return this.vm.undefined;
    }
  }
 
  /**
   * Converts VM handle to JS value with function pass-through handling
   */
  private handleToJsValue(handle: QuickJSHandle): unknown {
    const type = this.vm.typeof(handle);
 
    switch (type) {
      case "undefined":
        return undefined;
      case "boolean":
      case "number":
      case "string":
        return this.vm.dump(handle);
      case "object": {
        Iif (handle === this.vm.null) {
          return null;
        }
 
        const isArrayResult = this.vm.getProp(handle, "length");
        if (isArrayResult && this.vm.typeof(isArrayResult) === "number") {
          const length = this.vm.dump(isArrayResult) as number;
          isArrayResult.dispose();
 
          const result: unknown[] = [];
          for (let i = 0; i < length; i++) {
            const itemHandle = this.vm.getProp(handle, String(i));
            result[i] = this.handleToJsValue(itemHandle);
            itemHandle.dispose();
          }
          return result;
        }
        if (isArrayResult) {
          isArrayResult.dispose();
        }
 
        const keysResult = this.vm.evalCode("Object.keys");
        if (!keysResult.error) {
          const keysFn = keysResult.value;
          const objKeysResult = this.vm.callFunction(
            keysFn,
            this.vm.undefined,
            handle,
          );
          keysFn.dispose();
 
          if (!objKeysResult.error) {
            const keys = this.vm.dump(objKeysResult.value) as string[];
            objKeysResult.value.dispose();
 
            const result: Record<string, unknown> = {};
 
            for (const key of keys) {
              Iif (key === "toString") continue;
 
              const propHandle = this.vm.getProp(handle, key);
 
              const propType = this.vm.typeof(propHandle);
 
              if (propType === "function") {
                const funcId = `func_${uuid()}`;
 
                this.vmHandleRegistry.set(funcId, propHandle);
 
                const persistentFn = (...args: unknown[]) => {
                  this.runtime.setInterruptHandler(
                    shouldInterruptAfterDeadline(Date.now() + TIMEOUT_MS),
                  );
 
                  const storedHandle = this.vmHandleRegistry.get(funcId);
                  Iif (!storedHandle) {
                    throw new Error(`Function handle ${funcId} not found`);
                  }
 
                  const argHandles = args.map((arg) =>
                    this.jsValueToHandle(arg, true),
                  );
                  let result;
 
                  try {
                    result = this.vm.callFunction(
                      storedHandle,
                      this.vm.undefined,
                      ...argHandles,
                    );
 
                    if (result.error) {
                      const error = this.vm.dump(result.error);
                      result.error.dispose();
                      throw new Error(
                        `VM function call failed: ${JSON.stringify(error)}`,
                      );
                    }
 
                    const returnValue = this.handleToJsValue(result.value);
                    result.value.dispose();
                    return returnValue;
                  } finally {
                    argHandles.forEach((h) => h.dispose());
                  }
                };
 
                this.hostFunctionRegistry.set(funcId, persistentFn);
                result[key] = persistentFn;
              } else {
                result[key] = this.handleToJsValue(propHandle);
                propHandle.dispose();
              }
            }
 
            return result;
          } else {
            objKeysResult.error.dispose();
          }
        } else E{
          keysResult.error.dispose();
        }
 
        return this.vm.dump(handle);
      }
      case "function": {
        throw new Error("Function handles are not supported here");
      }
      default:
        return this.vm.dump(handle);
    }
  }
 
  /**
   * Calls a function on the module exports
   */
  callModuleFunction(functionName: string, args: unknown[]): unknown {
    Iif (!this.moduleExports) {
      throw new Error("No module exports available");
    }
 
    this.runtime.setInterruptHandler(
      shouldInterruptAfterDeadline(Date.now() + TIMEOUT_MS),
    );
 
    const fnHandle = this.vm.getProp(this.moduleExports, functionName);
 
    if (this.vm.typeof(fnHandle) === "undefined") {
      fnHandle.dispose();
      throw new Error(`Function ${functionName} not found in module exports`);
    }
 
    const argHandles = args.map((arg) => {
      if (arg && typeof arg === "object") {
        return this.createLazyProxy(arg);
      } else {
        return this.jsValueToHandle(arg, false);
      }
    });
 
    let result;
 
    try {
      result = this.vm.callFunction(fnHandle, this.vm.undefined, ...argHandles);
 
      if (result.error) {
        const error = this.vm.dump(result.error);
        result.error.dispose();
        if ("message" in error && typeof error.message === "string") {
          Iif (error.message === "interrupted") {
            error.message = `Plugin ${functionName}() timed out after ${TIMEOUT_MS}ms`;
          }
        }
        throw new Error(
          `Module function call failed: ${JSON.stringify(error)}`,
        );
      }
 
      const returnValue = this.handleToJsValue(result.value);
      result.value.dispose();
      return returnValue;
    } finally {
      argHandles.forEach((h) => h.dispose());
      fnHandle.dispose();
    }
  }
 
  /**
   * Gets a property from module exports
   */
  getModuleProperty(propertyName: string): unknown {
    Iif (!this.moduleExports) {
      return undefined;
    }
 
    const propHandle = this.vm.getProp(this.moduleExports, propertyName);
 
    const value = this.handleToJsValue(propHandle);
    propHandle.dispose();
    return value;
  }
 
  /**
   * Checks if module exports has a property
   */
  hasModuleProperty(propertyName: string): boolean {
    Iif (!this.moduleExports) {
      return false;
    }
 
    const propHandle = this.vm.getProp(this.moduleExports, propertyName);
 
    const propType = this.vm.typeof(propHandle);
    const hasProperty =
      propHandle !== this.vm.undefined && propType !== "undefined";
    propHandle.dispose();
    return hasProperty;
  }
 
  /**
   * Cleans up VM resources
   */
  dispose(): void {
    if (this.moduleExports) {
      this.moduleExports.dispose();
      this.moduleExports = null;
    }
 
    this.proxyFactory.dispose();
    this.hostInvokeFn.dispose();
 
    for (const handle of this.vmHandleRegistry.values()) {
      handle.dispose();
    }
    this.vmHandleRegistry.clear();
 
    this.vm.dispose();
    this.runtime.dispose();
    this.hostFunctionRegistry.clear();
  }
}
 
/**
 * Creates a new persistent VM instance
 */
const createPersistentVM = async (): Promise<PersistentVM> => {
  const runtime = (await QuickJS).newRuntime();
  const vm = runtime.newContext();
  return new PersistentVM(vm, runtime);
};
 
/**
 * Loads script event handlers in isolated QuickJS environment for security.
 */
export const loadScriptEventHandlerFromUntrustedString = async (
  code: string,
  filename: string,
  readFile: FileReaderFn = noReadFileFn,
): Promise<ScriptEventHandlerWithCleanup> => {
  const persistentVM = await createPersistentVM();
 
  try {
    persistentVM.setupMockRequire(readFile);
    persistentVM.executeCode(convertESMToCommonJS(code), filename);
 
    const metadata = {
      id: persistentVM.getModuleProperty("id"),
      name: persistentVM.getModuleProperty("name"),
      description: persistentVM.getModuleProperty("description"),
      fields: persistentVM.getModuleProperty("fields"),
      groups: persistentVM.getModuleProperty("groups"),
      subGroups: persistentVM.getModuleProperty("subGroups"),
      weight: persistentVM.getModuleProperty("weight"),
      deprecated: persistentVM.getModuleProperty("deprecated"),
      editableSymbol: persistentVM.getModuleProperty("editableSymbol"),
      allowChildrenBeforeInitFade: persistentVM.getModuleProperty(
        "allowChildrenBeforeInitFade",
      ),
      waitUntilAfterInitFade: persistentVM.getModuleProperty(
        "waitUntilAfterInitFade",
      ),
      helper: persistentVM.getModuleProperty("helper"),
      presets: persistentVM.getModuleProperty("presets"),
      userPresetsGroups: persistentVM.getModuleProperty("userPresetsGroups"),
      userPresetsIgnore: persistentVM.getModuleProperty("userPresetsIgnore"),
    };
 
    const hasAutoLabel = persistentVM.hasModuleProperty("autoLabel");
 
    validateHandlerMetadata(metadata, filename);
 
    const baseHandler = createHandlerBase(metadata, hasAutoLabel, () =>
      persistentVM.dispose(),
    );
 
    const handler: ScriptEventHandlerWithCleanup = {
      ...baseHandler,
      hasAutoLabel,
      autoLabel: hasAutoLabel
        ? (
            fetchArg: (key: string) => string,
            input: Record<string, unknown>,
          ) => {
            const result = persistentVM.callModuleFunction("autoLabel", [
              fetchArg,
              input,
            ]);
            return result as string;
          }
        : undefined,
      compile: (input: unknown, helpers: unknown) => {
        persistentVM.callModuleFunction("compile", [input, helpers]);
      },
    };
 
    finalizeHandler(handler);
 
    return handler;
  } catch (error) {
    persistentVM.dispose();
    throw error;
  }
};