bitburner-src/src/NetscriptEvaluator.ts

67 lines
2.0 KiB
TypeScript
Raw Normal View History

2021-09-25 20:42:57 +02:00
import { isString } from "./utils/helpers/isString";
2021-10-07 22:56:01 +02:00
import { GetServer } from "./Server/AllServers";
2021-09-24 23:07:53 +02:00
import { WorkerScript } from "./Netscript/WorkerScript";
import { BlobsMap } from "./NetscriptJSEvaluator";
2021-09-24 23:07:53 +02:00
export function netscriptDelay(time: number, workerScript: WorkerScript): Promise<void> {
2021-09-05 01:09:30 +02:00
return new Promise(function (resolve) {
workerScript.delay = window.setTimeout(() => {
2021-09-05 01:09:30 +02:00
workerScript.delay = null;
resolve();
}, time);
workerScript.delayResolve = resolve;
});
2017-06-05 06:48:37 +02:00
}
2021-09-25 08:36:49 +02:00
export function makeRuntimeRejectMsg(workerScript: WorkerScript, msg: string): string {
2021-12-14 04:26:22 +01:00
if ((msg as any) instanceof WorkerScript) {
console.error("HERE");
}
2021-10-07 23:55:49 +02:00
const server = GetServer(workerScript.hostname);
2021-09-05 01:09:30 +02:00
if (server == null) {
2021-10-07 23:55:49 +02:00
throw new Error(`WorkerScript constructed with invalid server ip: ${workerScript.hostname}`);
2021-09-05 01:09:30 +02:00
}
for (const url in BlobsMap) {
msg = msg.replace(new RegExp(url, "g"), BlobsMap[url]);
}
2021-10-22 21:21:10 +02:00
return "|DELIMITER|" + server.hostname + "|DELIMITER|" + workerScript.name + "|DELIMITER|" + msg;
}
2021-09-24 23:07:53 +02:00
export function resolveNetscriptRequestedThreads(
workerScript: WorkerScript,
functionName: string,
requestedThreads: number,
2021-09-25 08:36:49 +02:00
): number {
2021-09-05 01:09:30 +02:00
const threads = workerScript.scriptRef.threads;
if (!requestedThreads) {
return isNaN(threads) || threads < 1 ? 1 : threads;
}
const requestedThreadsAsInt = requestedThreads | 0;
if (isNaN(requestedThreads) || requestedThreadsAsInt < 1) {
throw makeRuntimeRejectMsg(
workerScript,
`Invalid thread count passed to ${functionName}: ${requestedThreads}. Threads must be a positive number.`,
);
}
if (requestedThreads > threads) {
throw makeRuntimeRejectMsg(
workerScript,
`Too many threads requested by ${functionName}. Requested: ${requestedThreads}. Has: ${threads}.`,
);
}
return requestedThreadsAsInt;
}
2021-09-24 23:07:53 +02:00
export function isScriptErrorMessage(msg: string): boolean {
2021-09-05 01:09:30 +02:00
if (!isString(msg)) {
return false;
}
2021-10-22 21:21:10 +02:00
const splitMsg = msg.split("|DELIMITER|");
2021-09-05 01:09:30 +02:00
if (splitMsg.length != 4) {
return false;
}
return true;
}