Skip to content

Example for using "export default async function" #224

@Attacler

Description

@Attacler

Hi there,

I have been going trough the docs and trough issues to get some code to work.
The code below is the closest that i could get:

import { getQuickJS } from "quickjs-emscripten";

/**
 * Executes JavaScript code in a QuickJS VM with provided input as globals.
 * @param code The JavaScript code to execute.
 * @param input An object whose properties will be set as global variables.
 * @returns The result of the code execution, or an error message.
 */
export async function executeCodeWithInput(
  code: string,
  input: Record<string, any>
): Promise<any> {
  const QuickJS = await getQuickJS();
  const vm = QuickJS.newContext();

  // Inject input object properties as globals
  for (const [key, value] of Object.entries(input)) {
    let jsValue;
    if (typeof value === "string") {
      jsValue = vm.newString(value);
    } else if (typeof value === "number") {
      jsValue = vm.newNumber(value);
    } else {
      jsValue = vm.newString(JSON.stringify(value));
    }
    vm.setProp(vm.global, key, jsValue);
    jsValue.dispose();
  }

  // Evaluate the code as a module to support 'export default'
  const moduleEval = vm.evalCode(
    `(async () => {\n  let module = {}\n  ${code}\n  return module.default;\n})()`
  );
  let output;
  if (moduleEval.error) {
    output = { error: vm.dump(moduleEval.error) };
    moduleEval.error.dispose();
  } else {
    const fn = vm.dump(moduleEval.value);
    if (typeof fn === "function") {
      try {
        const result = await fn();
        output = { value: result };
      } catch (err) {
        output = { error: String(err) };
      }
    } else {
      output = { value: fn };
    }
    moduleEval.value.dispose();
  }

  vm.dispose();
  return output;
}

To trigger it i am using:
executeCodeWithInput("export default async function () { return 'bar'; }",{}).then(console.log)

But it always gives back:

{
    "error": {
        "name": "SyntaxError",
        "message": "unsupported keyword: export",
        "stack": "    at eval.js:3\n",
        "fileName": "eval.js",
        "lineNumber": 3
    }
}

I tried other methods (also looked at the automated tests) but it will scream about lifetimes instead of executing the code.
How can i do what i want to do?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions