NETSCRIPT: Faster API wrapping on script launch. (#229)

* ns API is wrapped once
* when a new workerscript is created, each layer of ns is stamped with a private workerscript field that allows the functions to work.
* Test has been refactored to account for new method of wrapping
* BREAKING: ns functions need access to `this` value of their parent ns layer (or any ns layer)
* Enums are passed directly to player (no cloning) but are frozen.
This commit is contained in:
Snarling
2022-11-28 09:11:55 -05:00
committed by GitHub
parent 675c2a0456
commit 6af36e3b29
4 changed files with 85 additions and 45 deletions
+3 -3
View File
@@ -11,7 +11,7 @@ import { generateNextPid } from "./Netscript/Pid";
import { CONSTANTS } from "./Constants";
import { Interpreter } from "./ThirdParty/JSInterpreter";
import { NetscriptFunctions } from "./NetscriptFunctions";
import { NetscriptFunctions, wrappedNS } from "./NetscriptFunctions";
import { compile, Node } from "./NetscriptJSEvaluator";
import { IPort } from "./NetscriptPort";
import { RunningScript } from "./Script/RunningScript";
@@ -81,14 +81,14 @@ async function startNetscript1Script(workerScript: WorkerScript): Promise<void>
//TODO: Make NS1 wrapping type safe instead of using BasicObject
type BasicObject = Record<string, any>;
function wrapNS1Layer(int: Interpreter, intLayer: unknown, nsLayer = workerScript.env.vars as BasicObject) {
function wrapNS1Layer(int: Interpreter, intLayer: unknown, nsLayer = wrappedNS as BasicObject) {
for (const [name, entry] of Object.entries(nsLayer)) {
if (typeof entry === "function") {
const wrapper = async (...args: unknown[]) => {
try {
// Sent a resolver function as an extra arg. See createAsyncFunction JSInterpreter.js:3209
const callback = args.pop() as (value: unknown) => void;
const result = await entry(...args.map((arg) => int.pseudoToNative(arg)));
const result = await entry.bind(workerScript.env.vars)(...args.map((arg) => int.pseudoToNative(arg)));
return callback(int.nativeToPseudo(result));
} catch (e: unknown) {
errorToThrow = e;