-
-
Notifications
You must be signed in to change notification settings - Fork 263
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
rpc: remove usage of vm module, embed filename using sourceURL
- Loading branch information
Showing
1 changed file
with
9 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |