Skip to content

Commit

Permalink
rpc: remove usage of vm module, embed filename using sourceURL
Browse files Browse the repository at this point in the history
  • Loading branch information
koush committed Aug 3, 2024
1 parent a2bbb67 commit be21702
Showing 1 changed file with 9 additions and 14 deletions.
23 changes: 9 additions & 14 deletions server/src/rpc-peer-eval.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,22 @@
import type { CompileFunctionOptions } from 'vm';
import { RpcPeer } from "./rpc";
import type { RpcPeer } from "./rpc";

type CompileFunction = (code: string, params?: ReadonlyArray<string>, options?: CompileFunctionOptions) => Function;
export interface CompileFunctionOptions {
filename?: string;
}

function compileFunction(code: string, params?: ReadonlyArray<string>, options?: CompileFunctionOptions): any {
params = params || [];
const f = `(function(${params.join(',')}) {;${code};})`;
if (options?.filename)
code = `${code}\n//# sourceURL=${options.filename}\n`;
const f = `(function(${params.join(',')}) {;${code}\n;})`;
return eval(f);
}

export function evalLocal<T>(peer: RpcPeer, script: string, filename?: string, coercedParams?: { [name: string]: any }): T {
const params = Object.assign({}, peer.params, coercedParams);
let compile: CompileFunction;
try {
// prevent bundlers from trying to include non-existent vm module.
compile = module[`require`]('vm').compileFunction;
}
catch (e) {
compile = compileFunction;
}
const f = compile(script, Object.keys(params), {
const f = compileFunction(script, Object.keys(params), {
filename,
});
const value = f(...Object.values(params));
return value;
}
}

0 comments on commit be21702

Please sign in to comment.