2023-05-26 14:07:37 +02:00
|
|
|
import React from "react";
|
2022-08-08 19:43:41 +02:00
|
|
|
import { NetscriptContext } from "./APIWrapper";
|
|
|
|
import { WorkerScript } from "./WorkerScript";
|
2023-04-28 00:21:06 +02:00
|
|
|
import { killWorkerScript } from "./killWorkerScript";
|
2022-08-10 00:08:04 +02:00
|
|
|
import { GetAllServers, GetServer } from "../Server/AllServers";
|
2022-10-10 00:42:14 +02:00
|
|
|
import { Player } from "@player";
|
2022-08-08 19:43:41 +02:00
|
|
|
import { ScriptDeath } from "./ScriptDeath";
|
2023-02-11 19:18:50 +01:00
|
|
|
import { formatExp, formatMoney, formatRam, formatThreads } from "../ui/formatNumber";
|
2022-08-08 19:43:41 +02:00
|
|
|
import { ScriptArg } from "./ScriptArg";
|
2023-12-08 02:34:49 +01:00
|
|
|
import { RunningScript as IRunningScript, Person as IPerson, Server as IServer } from "@nsdefs";
|
2022-08-08 19:43:41 +02:00
|
|
|
import { Server } from "../Server/Server";
|
|
|
|
import {
|
|
|
|
calculateHackingChance,
|
|
|
|
calculateHackingExpGain,
|
|
|
|
calculateHackingTime,
|
|
|
|
calculatePercentMoneyHacked,
|
|
|
|
} from "../Hacking";
|
|
|
|
import { netscriptCanHack } from "../Hacking/netscriptCanHack";
|
|
|
|
import { convertTimeMsToTimeElapsedString } from "../utils/StringHelperFunctions";
|
2023-06-16 23:52:42 +02:00
|
|
|
import { currentNodeMults } from "../BitNode/BitNodeMultipliers";
|
2022-08-08 19:43:41 +02:00
|
|
|
import { CONSTANTS } from "../Constants";
|
|
|
|
import { influenceStockThroughServerHack } from "../StockMarket/PlayerInfluencing";
|
2023-02-28 01:54:04 +01:00
|
|
|
import { PortNumber } from "../NetscriptPort";
|
2022-08-08 19:43:41 +02:00
|
|
|
import { FormulaGang } from "../Gang/formulas/formulas";
|
|
|
|
import { GangMember } from "../Gang/GangMember";
|
|
|
|
import { GangMemberTask } from "../Gang/GangMemberTask";
|
2022-08-09 21:41:47 +02:00
|
|
|
import { RunningScript } from "../Script/RunningScript";
|
|
|
|
import { toNative } from "../NetscriptFunctions/toNative";
|
2022-08-10 00:08:04 +02:00
|
|
|
import { ScriptIdentifier } from "./ScriptIdentifier";
|
2023-04-28 00:21:06 +02:00
|
|
|
import { findRunningScripts, findRunningScriptByPid } from "../Script/ScriptHelpers";
|
2023-05-05 09:55:59 +02:00
|
|
|
import { arrayToString } from "../utils/helpers/ArrayHelpers";
|
2022-08-10 00:08:04 +02:00
|
|
|
import { HacknetServer } from "../Hacknet/HacknetServer";
|
|
|
|
import { BaseServer } from "../Server/BaseServer";
|
2022-09-05 15:55:57 +02:00
|
|
|
import { dialogBoxCreate } from "../ui/React/DialogBox";
|
2022-12-30 02:28:53 +01:00
|
|
|
import { RamCostConstants } from "./RamCostGenerator";
|
2024-02-10 13:24:11 +01:00
|
|
|
import { isPositiveInteger, PositiveInteger, Unknownify, isPositiveNumber, PositiveNumber } from "../types";
|
2023-03-08 01:31:54 +01:00
|
|
|
import { Engine } from "../engine";
|
2023-04-28 00:21:06 +02:00
|
|
|
import { resolveFilePath, FilePath } from "../Paths/FilePath";
|
|
|
|
import { hasScriptExtension, ScriptFilePath } from "../Paths/ScriptFilePath";
|
2023-05-26 14:07:37 +02:00
|
|
|
import { CustomBoundary } from "../ui/Components/CustomBoundary";
|
2024-02-10 10:13:42 +01:00
|
|
|
import { ServerConstants } from "../Server/data/Constants";
|
2022-08-08 19:43:41 +02:00
|
|
|
|
|
|
|
export const helpers = {
|
|
|
|
string,
|
|
|
|
number,
|
2023-02-14 07:32:01 +01:00
|
|
|
positiveInteger,
|
2022-08-08 19:43:41 +02:00
|
|
|
scriptArgs,
|
2023-03-21 23:54:49 +01:00
|
|
|
runOptions,
|
2023-09-27 07:31:47 +02:00
|
|
|
spawnOptions,
|
2022-08-09 21:41:47 +02:00
|
|
|
argsToString,
|
2022-08-28 11:33:38 +02:00
|
|
|
makeBasicErrorMsg,
|
2022-08-08 19:43:41 +02:00
|
|
|
makeRuntimeErrorMsg,
|
2023-12-08 02:34:49 +01:00
|
|
|
validateHGWOptions,
|
2022-08-08 19:43:41 +02:00
|
|
|
checkEnvFlags,
|
|
|
|
checkSingularityAccess,
|
|
|
|
netscriptDelay,
|
|
|
|
updateDynamicRam,
|
|
|
|
getServer,
|
|
|
|
scriptIdentifier,
|
|
|
|
hack,
|
2023-02-28 01:54:04 +01:00
|
|
|
portNumber,
|
2022-11-09 13:26:26 +01:00
|
|
|
person,
|
2022-08-08 19:43:41 +02:00
|
|
|
server,
|
|
|
|
gang,
|
|
|
|
gangMember,
|
|
|
|
gangTask,
|
2022-08-08 21:51:50 +02:00
|
|
|
log,
|
2023-04-28 00:21:06 +02:00
|
|
|
filePath,
|
|
|
|
scriptPath,
|
2022-08-10 00:08:04 +02:00
|
|
|
getRunningScript,
|
2023-04-28 00:21:06 +02:00
|
|
|
getRunningScriptsByArgs,
|
2022-08-10 00:08:04 +02:00
|
|
|
getCannotFindRunningScriptErrorMessage,
|
|
|
|
createPublicRunningScript,
|
|
|
|
failOnHacknetServer,
|
2022-08-08 19:43:41 +02:00
|
|
|
};
|
|
|
|
|
2023-09-27 07:31:47 +02:00
|
|
|
/** RunOptions with non-optional, type-validated members, for passing between internal functions. */
|
2023-03-21 23:54:49 +01:00
|
|
|
export interface CompleteRunOptions {
|
|
|
|
threads: PositiveInteger;
|
|
|
|
temporary: boolean;
|
2023-03-22 15:09:12 +01:00
|
|
|
ramOverride?: number;
|
2023-04-28 00:21:06 +02:00
|
|
|
preventDuplicates: boolean;
|
2023-03-21 23:54:49 +01:00
|
|
|
}
|
2023-09-27 07:31:47 +02:00
|
|
|
/** SpawnOptions with non-optional, type-validated members, for passing between internal functions. */
|
|
|
|
export interface CompleteSpawnOptions extends CompleteRunOptions {
|
|
|
|
spawnDelay: PositiveInteger;
|
|
|
|
}
|
2023-12-08 02:34:49 +01:00
|
|
|
/** HGWOptions with non-optional, type-validated members, for passing between internal functions. */
|
|
|
|
export interface CompleteHGWOptions {
|
2024-02-10 13:24:11 +01:00
|
|
|
threads: PositiveNumber;
|
2023-12-08 02:34:49 +01:00
|
|
|
stock: boolean;
|
|
|
|
additionalMsec: number;
|
|
|
|
}
|
2023-03-21 23:54:49 +01:00
|
|
|
|
2022-10-25 03:54:54 +02:00
|
|
|
export function assertString(ctx: NetscriptContext, argName: string, v: unknown): asserts v is string {
|
|
|
|
if (typeof v !== "string")
|
|
|
|
throw makeRuntimeErrorMsg(ctx, `${argName} expected to be a string. ${debugType(v)}`, "TYPE");
|
|
|
|
}
|
|
|
|
|
2022-08-30 00:07:17 +02:00
|
|
|
const userFriendlyString = (v: unknown): string => {
|
|
|
|
const clip = (s: string): string => {
|
|
|
|
if (s.length > 15) return s.slice(0, 12) + "...";
|
|
|
|
return s;
|
|
|
|
};
|
|
|
|
if (typeof v === "number") return String(v);
|
|
|
|
if (typeof v === "string") {
|
|
|
|
if (v === "") return "empty string";
|
|
|
|
return `'${clip(v)}'`;
|
|
|
|
}
|
|
|
|
const json = JSON.stringify(v);
|
|
|
|
if (!json) return "???";
|
|
|
|
return `'${clip(json)}'`;
|
|
|
|
};
|
|
|
|
|
|
|
|
const debugType = (v: unknown): string => {
|
|
|
|
if (v === null) return `Is null.`;
|
|
|
|
if (v === undefined) return "Is undefined.";
|
|
|
|
if (typeof v === "function") return "Is a function.";
|
|
|
|
return `Is of type '${typeof v}', value: ${userFriendlyString(v)}`;
|
|
|
|
};
|
|
|
|
|
2022-08-10 00:08:04 +02:00
|
|
|
/** Convert a provided value v for argument argName to string. If it wasn't originally a string or number, throw. */
|
2022-08-08 19:43:41 +02:00
|
|
|
function string(ctx: NetscriptContext, argName: string, v: unknown): string {
|
2022-10-25 03:54:54 +02:00
|
|
|
if (typeof v === "number") v = v + ""; // cast to string;
|
|
|
|
assertString(ctx, argName, v);
|
|
|
|
return v;
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
|
|
|
|
2022-08-10 00:08:04 +02:00
|
|
|
/** Convert provided value v for argument argName to number. Throw if could not convert to a non-NaN number. */
|
2022-08-08 19:43:41 +02:00
|
|
|
function number(ctx: NetscriptContext, argName: string, v: unknown): number {
|
|
|
|
if (typeof v === "string") {
|
|
|
|
const x = parseFloat(v);
|
|
|
|
if (!isNaN(x)) return x; // otherwise it wasn't even a string representing a number.
|
|
|
|
} else if (typeof v === "number") {
|
|
|
|
if (isNaN(v)) throw makeRuntimeErrorMsg(ctx, `'${argName}' is NaN.`);
|
|
|
|
return v;
|
|
|
|
}
|
2022-09-05 20:12:48 +02:00
|
|
|
throw makeRuntimeErrorMsg(ctx, `'${argName}' should be a number. ${debugType(v)}`, "TYPE");
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
|
|
|
|
2023-02-14 07:32:01 +01:00
|
|
|
/** Convert provided value v for argument argName to a positive integer, throwing if it looks like something else. */
|
2023-03-06 04:39:42 +01:00
|
|
|
function positiveInteger(ctx: NetscriptContext, argName: string, v: unknown): PositiveInteger {
|
2023-02-14 07:32:01 +01:00
|
|
|
const n = number(ctx, argName, v);
|
2023-03-06 17:45:09 +01:00
|
|
|
if (!isPositiveInteger(n)) {
|
2023-02-14 07:32:01 +01:00
|
|
|
throw makeRuntimeErrorMsg(ctx, `${argName} should be a positive integer, was ${n}`, "TYPE");
|
|
|
|
}
|
2023-03-06 17:45:09 +01:00
|
|
|
return n;
|
2023-02-14 07:32:01 +01:00
|
|
|
}
|
2024-02-10 13:24:11 +01:00
|
|
|
/** Convert provided value v for argument argName to a positive number, throwing if it looks like something else. */
|
|
|
|
function positiveNumber(ctx: NetscriptContext, argName: string, v: unknown): PositiveNumber {
|
|
|
|
const n = number(ctx, argName, v);
|
|
|
|
if (!isPositiveNumber(n)) {
|
|
|
|
throw makeRuntimeErrorMsg(ctx, `${argName} should be a positive number, was ${n}`, "TYPE");
|
|
|
|
}
|
|
|
|
return n;
|
|
|
|
}
|
2022-08-10 00:08:04 +02:00
|
|
|
/** Returns args back if it is a ScriptArg[]. Throws an error if it is not. */
|
2022-08-08 19:43:41 +02:00
|
|
|
function scriptArgs(ctx: NetscriptContext, args: unknown) {
|
2022-09-05 20:12:48 +02:00
|
|
|
if (!isScriptArgs(args)) throw makeRuntimeErrorMsg(ctx, "'args' is not an array of script args", "TYPE");
|
2022-08-08 19:43:41 +02:00
|
|
|
return args;
|
|
|
|
}
|
|
|
|
|
2023-03-22 15:09:12 +01:00
|
|
|
function runOptions(ctx: NetscriptContext, threadOrOption: unknown): CompleteRunOptions {
|
2023-03-23 17:01:20 +01:00
|
|
|
const result: CompleteRunOptions = {
|
|
|
|
threads: 1 as PositiveInteger,
|
|
|
|
temporary: false,
|
2023-04-28 00:21:06 +02:00
|
|
|
preventDuplicates: false,
|
2023-03-23 17:01:20 +01:00
|
|
|
};
|
|
|
|
function checkThreads(threads: unknown, argName: string) {
|
|
|
|
if (threads !== null && threads !== undefined) {
|
|
|
|
result.threads = positiveInteger(ctx, argName, threads);
|
|
|
|
}
|
|
|
|
}
|
2023-03-22 15:09:12 +01:00
|
|
|
if (typeof threadOrOption !== "object" || threadOrOption === null) {
|
2023-03-23 17:01:20 +01:00
|
|
|
checkThreads(threadOrOption, "threads");
|
|
|
|
return result;
|
2023-03-21 23:54:49 +01:00
|
|
|
}
|
2023-03-22 15:09:12 +01:00
|
|
|
// Safe assertion since threadOrOption type has been narrowed to a non-null object
|
|
|
|
const options = threadOrOption as Unknownify<CompleteRunOptions>;
|
2023-03-23 17:01:20 +01:00
|
|
|
checkThreads(options.threads, "RunOptions.threads");
|
|
|
|
result.temporary = !!options.temporary;
|
2023-04-28 00:21:06 +02:00
|
|
|
result.preventDuplicates = !!options.preventDuplicates;
|
2023-03-23 17:01:20 +01:00
|
|
|
if (options.ramOverride !== undefined && options.ramOverride !== null) {
|
|
|
|
result.ramOverride = number(ctx, "RunOptions.ramOverride", options.ramOverride);
|
|
|
|
if (result.ramOverride < RamCostConstants.Base) {
|
|
|
|
throw makeRuntimeErrorMsg(
|
|
|
|
ctx,
|
|
|
|
`RunOptions.ramOverride must be >= baseCost (${RamCostConstants.Base}), was ${result.ramOverride}`,
|
|
|
|
);
|
|
|
|
}
|
2023-03-22 15:09:12 +01:00
|
|
|
}
|
2023-03-23 17:01:20 +01:00
|
|
|
return result;
|
2023-03-21 23:54:49 +01:00
|
|
|
}
|
|
|
|
|
2023-09-27 07:31:47 +02:00
|
|
|
function spawnOptions(ctx: NetscriptContext, threadOrOption: unknown): CompleteSpawnOptions {
|
|
|
|
const result: CompleteSpawnOptions = { spawnDelay: 10000 as PositiveInteger, ...runOptions(ctx, threadOrOption) };
|
|
|
|
if (typeof threadOrOption !== "object" || !threadOrOption) return result;
|
|
|
|
// Safe assertion since threadOrOption type has been narrowed to a non-null object
|
|
|
|
const { spawnDelay } = threadOrOption as Unknownify<CompleteSpawnOptions>;
|
|
|
|
if (spawnDelay !== undefined) result.spawnDelay = positiveInteger(ctx, "spawnDelayMsec", spawnDelay);
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2022-08-10 00:08:04 +02:00
|
|
|
/** Convert multiple arguments for tprint or print into a single string. */
|
2022-08-09 21:41:47 +02:00
|
|
|
function argsToString(args: unknown[]): string {
|
2023-09-12 07:07:41 +02:00
|
|
|
// Reduce array of args into a single output string
|
|
|
|
return args.reduce((out, arg) => {
|
2022-08-09 21:41:47 +02:00
|
|
|
if (arg === null) {
|
2023-09-12 07:07:41 +02:00
|
|
|
return (out += "null");
|
2022-08-09 21:41:47 +02:00
|
|
|
}
|
|
|
|
if (arg === undefined) {
|
2023-09-12 07:07:41 +02:00
|
|
|
return (out += "undefined");
|
|
|
|
}
|
|
|
|
const nativeArg = toNative(arg);
|
|
|
|
|
|
|
|
// Handle Map formatting, since it does not JSON stringify or toString in a helpful way
|
|
|
|
// output is "< Map: key1 => value1; key2 => value2 >"
|
|
|
|
if (nativeArg instanceof Map && [...nativeArg].length) {
|
|
|
|
const formattedMap = [...nativeArg]
|
|
|
|
.map((m) => {
|
|
|
|
return `${m[0]} => ${m[1]}`;
|
|
|
|
})
|
|
|
|
.join("; ");
|
|
|
|
return (out += `< Map: ${formattedMap} >`);
|
|
|
|
}
|
|
|
|
// Handle Set formatting, since it does not JSON stringify or toString in a helpful way
|
|
|
|
if (nativeArg instanceof Set) {
|
|
|
|
return (out += `< Set: ${[...nativeArg].join("; ")} >`);
|
|
|
|
}
|
|
|
|
if (typeof nativeArg === "object") {
|
|
|
|
return (out += JSON.stringify(nativeArg));
|
2022-08-09 21:41:47 +02:00
|
|
|
}
|
|
|
|
|
2023-09-12 07:07:41 +02:00
|
|
|
return (out += `${nativeArg}`);
|
|
|
|
}, "") as string;
|
2022-08-09 21:41:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/** Creates an error message string containing hostname, scriptname, and the error message msg */
|
2022-09-05 15:55:57 +02:00
|
|
|
function makeBasicErrorMsg(ws: WorkerScript | ScriptDeath, msg: string, type = "RUNTIME"): string {
|
|
|
|
if (ws instanceof WorkerScript) {
|
2023-04-07 06:33:51 +02:00
|
|
|
for (const [scriptUrl, script] of ws.scriptRef.dependencies) {
|
|
|
|
msg = msg.replace(new RegExp(scriptUrl, "g"), script.filename);
|
2022-09-05 15:55:57 +02:00
|
|
|
}
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
2022-09-05 15:55:57 +02:00
|
|
|
return `${type} ERROR\n${ws.name}@${ws.hostname} (PID - ${ws.pid})\n\n${msg}`;
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
|
|
|
|
2022-08-09 21:41:47 +02:00
|
|
|
/** Creates an error message string with a stack trace. */
|
2023-12-08 02:34:49 +01:00
|
|
|
export function makeRuntimeErrorMsg(ctx: NetscriptContext, msg: string, type = "RUNTIME"): string {
|
2022-08-08 19:43:41 +02:00
|
|
|
const errstack = new Error().stack;
|
|
|
|
if (errstack === undefined) throw new Error("how did we not throw an error?");
|
|
|
|
const stack = errstack.split("\n").slice(1);
|
2022-08-28 11:33:38 +02:00
|
|
|
const ws = ctx.workerScript;
|
|
|
|
const caller = ctx.functionPath;
|
2022-08-08 19:43:41 +02:00
|
|
|
const userstack = [];
|
|
|
|
for (const stackline of stack) {
|
2023-04-07 06:33:51 +02:00
|
|
|
const filename = (() => {
|
2023-04-08 03:08:39 +02:00
|
|
|
// Check urls for dependencies
|
2023-04-07 06:33:51 +02:00
|
|
|
for (const [url, script] of ws.scriptRef.dependencies) if (stackline.includes(url)) return script.filename;
|
|
|
|
// Check for filenames directly if no URL found
|
|
|
|
if (stackline.includes(ws.scriptRef.filename)) return ws.scriptRef.filename;
|
|
|
|
for (const script of ws.scriptRef.dependencies.values()) {
|
|
|
|
if (stackline.includes(script.filename)) return script.filename;
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
2023-04-07 06:33:51 +02:00
|
|
|
})();
|
2022-08-08 19:43:41 +02:00
|
|
|
if (!filename) continue;
|
|
|
|
|
|
|
|
let call = { line: "-1", func: "unknown" };
|
|
|
|
const chromeCall = parseChromeStackline(stackline);
|
|
|
|
if (chromeCall) {
|
|
|
|
call = chromeCall;
|
|
|
|
}
|
|
|
|
|
|
|
|
const firefoxCall = parseFirefoxStackline(stackline);
|
|
|
|
if (firefoxCall) {
|
|
|
|
call = firefoxCall;
|
|
|
|
}
|
|
|
|
|
|
|
|
userstack.push(`${filename}:L${call.line}@${call.func}`);
|
|
|
|
}
|
|
|
|
|
2022-08-28 11:33:38 +02:00
|
|
|
log(ctx, () => msg);
|
2022-09-05 14:56:39 +02:00
|
|
|
let rejectMsg = `${caller}: ${msg}`;
|
2022-08-29 08:41:17 +02:00
|
|
|
if (userstack.length !== 0) rejectMsg += `\n\nStack:\n${userstack.join("\n")}`;
|
2022-09-05 20:12:48 +02:00
|
|
|
return makeBasicErrorMsg(ws, rejectMsg, type);
|
2023-05-05 09:55:59 +02:00
|
|
|
|
|
|
|
interface ILine {
|
|
|
|
line: string;
|
|
|
|
func: string;
|
|
|
|
}
|
|
|
|
function parseChromeStackline(line: string): ILine | null {
|
|
|
|
const lineMatch = line.match(/.*:(\d+):\d+.*/);
|
|
|
|
const funcMatch = line.match(/.*at (.+) \(.*/);
|
|
|
|
if (lineMatch && funcMatch) return { line: lineMatch[1], func: funcMatch[1] };
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
function parseFirefoxStackline(line: string): ILine | null {
|
|
|
|
const lineMatch = line.match(/.*:(\d+):\d+$/);
|
|
|
|
const lio = line.lastIndexOf("@");
|
|
|
|
if (lineMatch && lio !== -1) return { line: lineMatch[1], func: line.slice(0, lio) };
|
|
|
|
return null;
|
|
|
|
}
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
|
|
|
|
2023-12-08 02:34:49 +01:00
|
|
|
function validateHGWOptions(ctx: NetscriptContext, opts: unknown): CompleteHGWOptions {
|
|
|
|
const result: CompleteHGWOptions = {
|
2023-12-16 10:38:39 +01:00
|
|
|
threads: ctx.workerScript.scriptRef.threads,
|
2023-12-08 02:34:49 +01:00
|
|
|
stock: false,
|
|
|
|
additionalMsec: 0,
|
|
|
|
};
|
|
|
|
if (opts == null) {
|
|
|
|
return result;
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
2023-12-08 02:34:49 +01:00
|
|
|
if (typeof opts !== "object") {
|
|
|
|
throw makeRuntimeErrorMsg(ctx, `BasicHGWOptions must be an object if specified, was ${opts}`);
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
2023-12-08 02:34:49 +01:00
|
|
|
// Safe assertion since threadOrOption type has been narrowed to a non-null object
|
|
|
|
const options = opts as Unknownify<CompleteHGWOptions>;
|
|
|
|
result.stock = !!options.stock;
|
|
|
|
result.additionalMsec = number(ctx, "opts.additionalMsec", options.additionalMsec ?? 0);
|
|
|
|
if (result.additionalMsec < 0) {
|
|
|
|
throw makeRuntimeErrorMsg(ctx, `additionalMsec must be non-negative, got ${options.additionalMsec}`);
|
|
|
|
}
|
|
|
|
if (result.additionalMsec > 1e9) {
|
|
|
|
throw makeRuntimeErrorMsg(ctx, `additionalMsec too large (>1e9), got ${options.additionalMsec}`);
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
2023-12-08 02:34:49 +01:00
|
|
|
const requestedThreads = options.threads;
|
|
|
|
const threads = ctx.workerScript.scriptRef.threads;
|
|
|
|
if (!requestedThreads) {
|
|
|
|
result.threads = (isNaN(threads) || threads < 1 ? 1 : threads) as PositiveInteger;
|
|
|
|
} else {
|
2024-02-10 13:24:11 +01:00
|
|
|
const positiveThreads = positiveNumber(ctx, "opts.threads", requestedThreads);
|
2023-12-08 02:34:49 +01:00
|
|
|
if (positiveThreads > threads) {
|
|
|
|
throw makeRuntimeErrorMsg(
|
|
|
|
ctx,
|
|
|
|
`Too many threads requested by ${ctx.function}. Requested: ${positiveThreads}. Has: ${threads}.`,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
result.threads = positiveThreads;
|
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
|
|
|
|
2022-08-09 21:41:47 +02:00
|
|
|
/** Validate singularity access by throwing an error if the player does not have access. */
|
2022-08-08 19:43:41 +02:00
|
|
|
function checkSingularityAccess(ctx: NetscriptContext): void {
|
|
|
|
if (Player.bitNodeN !== 4 && Player.sourceFileLvl(4) === 0) {
|
|
|
|
throw makeRuntimeErrorMsg(
|
|
|
|
ctx,
|
|
|
|
`This singularity function requires Source-File 4 to run. A power up you obtain later in the game.
|
|
|
|
It will be very obvious when and how you can obtain it.`,
|
2022-09-05 20:12:48 +02:00
|
|
|
"API ACCESS",
|
2022-08-08 19:43:41 +02:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-09 21:41:47 +02:00
|
|
|
/** Create an error if a script is dead or if concurrent ns function calls are made */
|
2022-08-08 19:43:41 +02:00
|
|
|
function checkEnvFlags(ctx: NetscriptContext): void {
|
|
|
|
const ws = ctx.workerScript;
|
2022-08-28 11:33:38 +02:00
|
|
|
if (ws.env.stopFlag) {
|
|
|
|
log(ctx, () => "Failed to run due to script being killed.");
|
|
|
|
throw new ScriptDeath(ws);
|
|
|
|
}
|
2022-08-08 19:43:41 +02:00
|
|
|
if (ws.env.runningFn && ctx.function !== "asleep") {
|
2022-08-29 08:41:17 +02:00
|
|
|
log(ctx, () => "Failed to run due to failed concurrency check.");
|
2023-04-28 00:21:06 +02:00
|
|
|
const err = makeRuntimeErrorMsg(
|
2022-08-29 08:41:17 +02:00
|
|
|
ctx,
|
2022-08-08 19:43:41 +02:00
|
|
|
`Concurrent calls to Netscript functions are not allowed!
|
|
|
|
Did you forget to await hack(), grow(), or some other
|
|
|
|
promise-returning function?
|
|
|
|
Currently running: ${ws.env.runningFn} tried to run: ${ctx.function}`,
|
2022-09-05 20:12:48 +02:00
|
|
|
"CONCURRENCY",
|
2022-08-08 19:43:41 +02:00
|
|
|
);
|
2023-04-28 00:21:06 +02:00
|
|
|
killWorkerScript(ws);
|
|
|
|
throw err;
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-10 00:08:04 +02:00
|
|
|
/** Set a timeout for performing a task, mark the script as busy in the meantime. */
|
2022-08-08 19:43:41 +02:00
|
|
|
function netscriptDelay(ctx: NetscriptContext, time: number): Promise<void> {
|
|
|
|
const ws = ctx.workerScript;
|
|
|
|
return new Promise(function (resolve, reject) {
|
|
|
|
ws.delay = window.setTimeout(() => {
|
|
|
|
ws.delay = null;
|
|
|
|
ws.delayReject = undefined;
|
|
|
|
ws.env.runningFn = "";
|
|
|
|
if (ws.env.stopFlag) reject(new ScriptDeath(ws));
|
|
|
|
else resolve();
|
|
|
|
}, time);
|
|
|
|
ws.delayReject = reject;
|
|
|
|
ws.env.runningFn = ctx.function;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-08-10 00:08:04 +02:00
|
|
|
/** Adds to dynamic ram cost when calling new ns functions from a script */
|
2022-08-08 19:43:41 +02:00
|
|
|
function updateDynamicRam(ctx: NetscriptContext, ramCost: number): void {
|
|
|
|
const ws = ctx.workerScript;
|
|
|
|
const fnName = ctx.function;
|
|
|
|
if (ws.dynamicLoadedFns[fnName]) return;
|
|
|
|
ws.dynamicLoadedFns[fnName] = true;
|
|
|
|
|
2022-12-30 02:28:53 +01:00
|
|
|
ws.dynamicRamUsage = Math.min(ws.dynamicRamUsage + ramCost, RamCostConstants.Max);
|
2023-09-22 03:44:32 +02:00
|
|
|
// This constant is just a handful of ULPs, and gives protection against
|
|
|
|
// rounding issues without exposing rounding exploits in ramUsage.
|
|
|
|
if (ws.dynamicRamUsage > 1.00000000000001 * ws.scriptRef.ramUsage) {
|
2022-08-28 11:33:38 +02:00
|
|
|
log(ctx, () => "Insufficient static ram available.");
|
2023-04-28 00:21:06 +02:00
|
|
|
const err = makeRuntimeErrorMsg(
|
2022-08-29 08:41:17 +02:00
|
|
|
ctx,
|
2023-03-22 15:09:12 +01:00
|
|
|
`Dynamic RAM usage calculated to be greater than RAM allocation.
|
2022-08-08 19:43:41 +02:00
|
|
|
This is probably because you somehow circumvented the static RAM calculation.
|
|
|
|
|
2023-03-06 04:39:42 +01:00
|
|
|
Threads: ${ws.scriptRef.threads}
|
2023-02-11 19:18:50 +01:00
|
|
|
Dynamic RAM Usage: ${formatRam(ws.dynamicRamUsage)} per thread
|
2023-03-22 15:09:12 +01:00
|
|
|
RAM Allocation: ${formatRam(ws.scriptRef.ramUsage)} per thread
|
2022-08-08 19:43:41 +02:00
|
|
|
|
|
|
|
One of these could be the reason:
|
|
|
|
* Using eval() to get a reference to a ns function
|
2022-08-29 08:41:17 +02:00
|
|
|
\u00a0\u00a0const myScan = eval('ns.scan');
|
2022-08-08 19:43:41 +02:00
|
|
|
|
|
|
|
* Using map access to do the same
|
2022-08-29 08:41:17 +02:00
|
|
|
\u00a0\u00a0const myScan = ns['scan'];
|
2022-08-08 19:43:41 +02:00
|
|
|
|
2023-03-22 15:09:12 +01:00
|
|
|
* Using RunOptions.ramOverride to set a smaller allocation than needed
|
|
|
|
|
2022-08-08 19:43:41 +02:00
|
|
|
Sorry :(`,
|
2022-09-05 20:12:48 +02:00
|
|
|
"RAM USAGE",
|
2022-08-08 19:43:41 +02:00
|
|
|
);
|
2023-04-28 00:21:06 +02:00
|
|
|
killWorkerScript(ws);
|
|
|
|
throw err;
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function scriptIdentifier(
|
|
|
|
ctx: NetscriptContext,
|
|
|
|
scriptID: unknown,
|
|
|
|
_hostname: unknown,
|
|
|
|
_args: unknown,
|
|
|
|
): ScriptIdentifier {
|
|
|
|
const ws = ctx.workerScript;
|
|
|
|
// Provide the pid for the current script if no identifier provided
|
|
|
|
if (scriptID === undefined) return ws.pid;
|
|
|
|
if (typeof scriptID === "number") return scriptID;
|
|
|
|
if (typeof scriptID === "string") {
|
|
|
|
const hostname = _hostname === undefined ? ctx.workerScript.hostname : string(ctx, "hostname", _hostname);
|
|
|
|
const args = _args === undefined ? [] : scriptArgs(ctx, _args);
|
|
|
|
return {
|
|
|
|
scriptname: scriptID,
|
|
|
|
hostname,
|
|
|
|
args,
|
|
|
|
};
|
|
|
|
}
|
2022-09-05 20:12:48 +02:00
|
|
|
throw makeRuntimeErrorMsg(ctx, "An unknown type of input was provided as a script identifier.", "TYPE");
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Gets the Server for a specific hostname/ip, throwing an error
|
|
|
|
* if the server doesn't exist.
|
|
|
|
* @param {NetscriptContext} ctx - Context from which getServer is being called. For logging purposes.
|
|
|
|
* @param {string} hostname - Hostname of the server
|
|
|
|
* @returns {BaseServer} The specified server as a BaseServer
|
|
|
|
*/
|
|
|
|
function getServer(ctx: NetscriptContext, hostname: string) {
|
|
|
|
const server = GetServer(hostname);
|
2023-10-23 10:37:19 +02:00
|
|
|
if (server == null || (server.serversOnNetwork.length == 0 && server.hostname != "home")) {
|
2022-08-08 19:43:41 +02:00
|
|
|
const str = hostname === "" ? "'' (empty string)" : "'" + hostname + "'";
|
|
|
|
throw makeRuntimeErrorMsg(ctx, `Invalid hostname: ${str}`);
|
|
|
|
}
|
|
|
|
return server;
|
|
|
|
}
|
|
|
|
|
|
|
|
function isScriptArgs(args: unknown): args is ScriptArg[] {
|
|
|
|
const isScriptArg = (arg: unknown) => typeof arg === "string" || typeof arg === "number" || typeof arg === "boolean";
|
|
|
|
return Array.isArray(args) && args.every(isScriptArg);
|
|
|
|
}
|
|
|
|
|
2023-12-08 02:34:49 +01:00
|
|
|
function hack(ctx: NetscriptContext, hostname: string, manual: boolean, opts: unknown): Promise<number> {
|
2022-08-08 19:43:41 +02:00
|
|
|
const ws = ctx.workerScript;
|
2023-12-08 02:34:49 +01:00
|
|
|
const { threads, stock, additionalMsec } = validateHGWOptions(ctx, opts);
|
2022-08-08 19:43:41 +02:00
|
|
|
const server = getServer(ctx, hostname);
|
|
|
|
if (!(server instanceof Server)) {
|
|
|
|
throw makeRuntimeErrorMsg(ctx, "Cannot be executed on this server.");
|
|
|
|
}
|
|
|
|
|
|
|
|
// Calculate the hacking time
|
2023-01-11 03:18:33 +01:00
|
|
|
// This is in seconds
|
|
|
|
const hackingTime = calculateHackingTime(server, Player) + additionalMsec / 1000.0;
|
2022-08-08 19:43:41 +02:00
|
|
|
|
|
|
|
// No root access or skill level too low
|
2022-09-06 15:07:12 +02:00
|
|
|
const canHack = netscriptCanHack(server);
|
2022-08-08 19:43:41 +02:00
|
|
|
if (!canHack.res) {
|
|
|
|
throw makeRuntimeErrorMsg(ctx, canHack.msg || "");
|
|
|
|
}
|
|
|
|
|
2022-08-08 21:51:50 +02:00
|
|
|
log(
|
|
|
|
ctx,
|
2022-08-08 19:43:41 +02:00
|
|
|
() =>
|
|
|
|
`Executing on '${server.hostname}' in ${convertTimeMsToTimeElapsedString(
|
|
|
|
hackingTime * 1000,
|
|
|
|
true,
|
2023-02-11 19:18:50 +01:00
|
|
|
)} (t=${formatThreads(threads)})`,
|
2022-08-08 19:43:41 +02:00
|
|
|
);
|
|
|
|
|
|
|
|
return helpers.netscriptDelay(ctx, hackingTime * 1000).then(function () {
|
|
|
|
const hackChance = calculateHackingChance(server, Player);
|
|
|
|
const rand = Math.random();
|
|
|
|
let expGainedOnSuccess = calculateHackingExpGain(server, Player) * threads;
|
|
|
|
const expGainedOnFailure = expGainedOnSuccess / 4;
|
|
|
|
if (rand < hackChance) {
|
|
|
|
// Success!
|
|
|
|
const percentHacked = calculatePercentMoneyHacked(server, Player);
|
|
|
|
let maxThreadNeeded = Math.ceil(1 / percentHacked);
|
|
|
|
if (isNaN(maxThreadNeeded)) {
|
|
|
|
// Server has a 'max money' of 0 (probably). We'll set this to an arbitrarily large value
|
|
|
|
maxThreadNeeded = 1e6;
|
|
|
|
}
|
|
|
|
|
2023-06-28 22:21:15 +02:00
|
|
|
let moneyDrained = server.moneyAvailable * percentHacked * threads;
|
2022-08-08 19:43:41 +02:00
|
|
|
|
|
|
|
// Over-the-top safety checks
|
|
|
|
if (moneyDrained <= 0) {
|
|
|
|
moneyDrained = 0;
|
|
|
|
expGainedOnSuccess = expGainedOnFailure;
|
|
|
|
}
|
|
|
|
if (moneyDrained > server.moneyAvailable) {
|
|
|
|
moneyDrained = server.moneyAvailable;
|
|
|
|
}
|
|
|
|
server.moneyAvailable -= moneyDrained;
|
|
|
|
if (server.moneyAvailable < 0) {
|
|
|
|
server.moneyAvailable = 0;
|
|
|
|
}
|
|
|
|
|
2023-06-16 23:52:42 +02:00
|
|
|
let moneyGained = moneyDrained * currentNodeMults.ScriptHackMoneyGain;
|
2022-08-08 19:43:41 +02:00
|
|
|
if (manual) {
|
2023-06-16 23:52:42 +02:00
|
|
|
moneyGained = moneyDrained * currentNodeMults.ManualHackMoney;
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
Player.gainMoney(moneyGained, "hacking");
|
|
|
|
ws.scriptRef.onlineMoneyMade += moneyGained;
|
|
|
|
Player.scriptProdSinceLastAug += moneyGained;
|
|
|
|
ws.scriptRef.recordHack(server.hostname, moneyGained, threads);
|
|
|
|
Player.gainHackingExp(expGainedOnSuccess);
|
|
|
|
if (manual) Player.gainIntelligenceExp(0.005);
|
|
|
|
ws.scriptRef.onlineExpGained += expGainedOnSuccess;
|
2022-08-08 21:51:50 +02:00
|
|
|
log(
|
|
|
|
ctx,
|
2022-08-08 19:43:41 +02:00
|
|
|
() =>
|
2023-02-11 19:18:50 +01:00
|
|
|
`Successfully hacked '${server.hostname}' for ${formatMoney(moneyGained)} and ${formatExp(
|
|
|
|
expGainedOnSuccess,
|
|
|
|
)} exp (t=${formatThreads(threads)})`,
|
2022-08-08 19:43:41 +02:00
|
|
|
);
|
2024-02-10 10:13:42 +01:00
|
|
|
server.fortify(ServerConstants.ServerFortifyAmount * Math.min(threads, maxThreadNeeded));
|
2022-08-08 19:43:41 +02:00
|
|
|
if (stock) {
|
|
|
|
influenceStockThroughServerHack(server, moneyDrained);
|
|
|
|
}
|
|
|
|
if (manual) {
|
|
|
|
server.backdoorInstalled = true;
|
2023-03-08 01:31:54 +01:00
|
|
|
// Manunally check for faction invites
|
|
|
|
Engine.Counters.checkFactionInvitations = 0;
|
|
|
|
Engine.checkCounters();
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
2022-08-29 08:41:17 +02:00
|
|
|
return moneyGained;
|
2022-08-08 19:43:41 +02:00
|
|
|
} else {
|
|
|
|
// Player only gains 25% exp for failure?
|
|
|
|
Player.gainHackingExp(expGainedOnFailure);
|
|
|
|
ws.scriptRef.onlineExpGained += expGainedOnFailure;
|
2022-08-08 21:51:50 +02:00
|
|
|
log(
|
|
|
|
ctx,
|
2022-08-08 19:43:41 +02:00
|
|
|
() =>
|
2023-02-11 19:18:50 +01:00
|
|
|
`Failed to hack '${server.hostname}'. Gained ${formatExp(expGainedOnFailure)} exp (t=${formatThreads(
|
|
|
|
threads,
|
|
|
|
)})`,
|
2022-08-08 19:43:41 +02:00
|
|
|
);
|
2022-08-29 08:41:17 +02:00
|
|
|
return 0;
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-02-28 01:54:04 +01:00
|
|
|
function portNumber(ctx: NetscriptContext, _n: unknown): PortNumber {
|
|
|
|
const n = positiveInteger(ctx, "portNumber", _n);
|
|
|
|
if (n > CONSTANTS.NumNetscriptPorts) {
|
2022-08-08 19:43:41 +02:00
|
|
|
throw makeRuntimeErrorMsg(
|
|
|
|
ctx,
|
2023-02-28 01:54:04 +01:00
|
|
|
`Trying to use an invalid port: ${n}. Must be less or equal to ${CONSTANTS.NumNetscriptPorts}.`,
|
2022-08-08 19:43:41 +02:00
|
|
|
);
|
|
|
|
}
|
2023-02-28 01:54:04 +01:00
|
|
|
return n as PortNumber;
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
|
|
|
|
2022-11-09 13:26:26 +01:00
|
|
|
function person(ctx: NetscriptContext, p: unknown): IPerson {
|
|
|
|
const fakePerson = {
|
2022-08-08 19:43:41 +02:00
|
|
|
hp: undefined,
|
2022-11-09 13:26:26 +01:00
|
|
|
exp: undefined,
|
2022-08-08 19:43:41 +02:00
|
|
|
mults: undefined,
|
|
|
|
city: undefined,
|
|
|
|
};
|
2023-03-07 12:33:24 +01:00
|
|
|
const error = missingKey(fakePerson, p);
|
|
|
|
if (error) throw makeRuntimeErrorMsg(ctx, `person should be a Person.\n${error}`, "TYPE");
|
2022-11-09 13:26:26 +01:00
|
|
|
return p as IPerson;
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
|
|
|
|
2023-04-11 21:12:55 +02:00
|
|
|
function server(ctx: NetscriptContext, s: unknown): IServer {
|
2022-08-23 22:01:34 +02:00
|
|
|
const fakeServer = {
|
|
|
|
hostname: undefined,
|
|
|
|
ip: undefined,
|
2023-04-11 21:12:55 +02:00
|
|
|
sshPortOpen: undefined,
|
|
|
|
ftpPortOpen: undefined,
|
|
|
|
smtpPortOpen: undefined,
|
|
|
|
httpPortOpen: undefined,
|
|
|
|
sqlPortOpen: undefined,
|
|
|
|
hasAdminRights: undefined,
|
|
|
|
cpuCores: undefined,
|
2022-08-23 22:01:34 +02:00
|
|
|
isConnectedTo: undefined,
|
2023-04-11 21:12:55 +02:00
|
|
|
ramUsed: undefined,
|
2022-08-23 22:01:34 +02:00
|
|
|
maxRam: undefined,
|
|
|
|
organizationName: undefined,
|
|
|
|
purchasedByPlayer: undefined,
|
|
|
|
};
|
2023-03-07 12:33:24 +01:00
|
|
|
const error = missingKey(fakeServer, s);
|
2023-04-11 21:12:55 +02:00
|
|
|
if (error) throw makeRuntimeErrorMsg(ctx, `server should be a Server.\n${error}`, "TYPE");
|
|
|
|
return s as IServer;
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
|
|
|
|
2023-03-07 12:33:24 +01:00
|
|
|
function missingKey(expect: object, actual: unknown): string | false {
|
|
|
|
if (typeof actual !== "object" || actual === null) {
|
|
|
|
return `Expected to be an object, was ${actual === null ? "null" : typeof actual}.`;
|
|
|
|
}
|
|
|
|
for (const key in expect) {
|
|
|
|
if (!(key in actual)) return `Property ${key} was expected but not present.`;
|
|
|
|
}
|
|
|
|
return false;
|
2022-08-08 19:43:41 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
function gang(ctx: NetscriptContext, g: unknown): FormulaGang {
|
2023-03-07 12:33:24 +01:00
|
|
|
const error = missingKey({ respect: 0, territory: 0, wantedLevel: 0 }, g);
|
|
|
|
if (error) throw makeRuntimeErrorMsg(ctx, `gang should be a Gang.\n${error}`, "TYPE");
|
2022-08-08 19:43:41 +02:00
|
|
|
return g as FormulaGang;
|
|
|
|
}
|
|
|
|
|
|
|
|
function gangMember(ctx: NetscriptContext, m: unknown): GangMember {
|
2023-03-07 12:33:24 +01:00
|
|
|
const error = missingKey(new GangMember(), m);
|
|
|
|
if (error) throw makeRuntimeErrorMsg(ctx, `member should be a GangMember.\n${error}`, "TYPE");
|
2022-08-08 19:43:41 +02:00
|
|
|
return m as GangMember;
|
|
|
|
}
|
|
|
|
|
|
|
|
function gangTask(ctx: NetscriptContext, t: unknown): GangMemberTask {
|
2023-03-07 12:33:24 +01:00
|
|
|
const error = missingKey(new GangMemberTask("", "", false, false, { hackWeight: 100 }), t);
|
|
|
|
if (error) throw makeRuntimeErrorMsg(ctx, `task should be a GangMemberTask.\n${error}`, "TYPE");
|
2022-08-08 19:43:41 +02:00
|
|
|
return t as GangMemberTask;
|
|
|
|
}
|
2022-08-08 22:13:04 +02:00
|
|
|
|
2022-08-08 21:51:50 +02:00
|
|
|
function log(ctx: NetscriptContext, message: () => string) {
|
|
|
|
ctx.workerScript.log(ctx.functionPath, message);
|
|
|
|
}
|
2022-08-09 21:41:47 +02:00
|
|
|
|
2023-04-28 00:21:06 +02:00
|
|
|
export function filePath(ctx: NetscriptContext, argName: string, filename: unknown): FilePath {
|
|
|
|
assertString(ctx, argName, filename);
|
|
|
|
const path = resolveFilePath(filename, ctx.workerScript.name);
|
|
|
|
if (path) return path;
|
|
|
|
throw makeRuntimeErrorMsg(ctx, `Invalid ${argName}, was not a valid path: ${filename}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function scriptPath(ctx: NetscriptContext, argName: string, filename: unknown): ScriptFilePath {
|
|
|
|
const path = filePath(ctx, argName, filename);
|
|
|
|
if (hasScriptExtension(path)) return path;
|
|
|
|
throw makeRuntimeErrorMsg(ctx, `Invalid ${argName}, must be a script: ${filename}`);
|
|
|
|
}
|
|
|
|
|
2022-08-09 21:41:47 +02:00
|
|
|
/**
|
2023-04-28 00:21:06 +02:00
|
|
|
* Searches for and returns the RunningScript objects for the specified script.
|
2022-08-09 21:41:47 +02:00
|
|
|
* If the 'fn' argument is not specified, this returns the current RunningScript.
|
2023-03-22 15:09:12 +01:00
|
|
|
* @param fn - Filename of script
|
|
|
|
* @param hostname - Hostname/ip of the server on which the script resides
|
|
|
|
* @param scriptArgs - Running script's arguments
|
2023-04-28 00:21:06 +02:00
|
|
|
* @returns Running scripts identified by the parameters, or empty if no such script
|
|
|
|
* exists, or only the current running script if the first argument 'fn'
|
2023-03-22 15:09:12 +01:00
|
|
|
* is not specified.
|
2022-08-09 21:41:47 +02:00
|
|
|
*/
|
2023-04-28 00:21:06 +02:00
|
|
|
export function getRunningScriptsByArgs(
|
2022-08-09 21:41:47 +02:00
|
|
|
ctx: NetscriptContext,
|
|
|
|
fn: string,
|
|
|
|
hostname: string,
|
|
|
|
scriptArgs: ScriptArg[],
|
2023-04-28 00:21:06 +02:00
|
|
|
): Map<number, RunningScript> | null {
|
2022-08-09 21:41:47 +02:00
|
|
|
if (!Array.isArray(scriptArgs)) {
|
2022-08-29 08:41:17 +02:00
|
|
|
throw helpers.makeRuntimeErrorMsg(
|
|
|
|
ctx,
|
|
|
|
"Invalid scriptArgs argument passed into getRunningScriptByArgs().\n" +
|
|
|
|
"This is probably a bug. Please report to game developer",
|
2022-08-09 21:41:47 +02:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-04-28 00:21:06 +02:00
|
|
|
const path = scriptPath(ctx, "filename", fn);
|
|
|
|
// Lookup server to scope search
|
|
|
|
if (hostname == null) {
|
|
|
|
hostname = ctx.workerScript.hostname;
|
2022-08-09 21:41:47 +02:00
|
|
|
}
|
2023-04-28 00:21:06 +02:00
|
|
|
const server = helpers.getServer(ctx, hostname);
|
2022-08-09 21:41:47 +02:00
|
|
|
|
2023-04-28 00:21:06 +02:00
|
|
|
return findRunningScripts(path, scriptArgs, server);
|
2022-08-09 21:41:47 +02:00
|
|
|
}
|
2022-08-10 00:08:04 +02:00
|
|
|
|
|
|
|
function getRunningScriptByPid(pid: number): RunningScript | null {
|
|
|
|
for (const server of GetAllServers()) {
|
|
|
|
const runningScript = findRunningScriptByPid(pid, server);
|
|
|
|
if (runningScript) return runningScript;
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
function getRunningScript(ctx: NetscriptContext, ident: ScriptIdentifier): RunningScript | null {
|
|
|
|
if (typeof ident === "number") {
|
|
|
|
return getRunningScriptByPid(ident);
|
|
|
|
} else {
|
2023-04-28 00:21:06 +02:00
|
|
|
const scripts = getRunningScriptsByArgs(ctx, ident.scriptname, ident.hostname, ident.args);
|
|
|
|
if (scripts === null) return null;
|
|
|
|
return scripts.values().next().value;
|
2022-08-10 00:08:04 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Helper function for getting the error log message when the user specifies
|
|
|
|
* a nonexistent running script
|
2023-03-22 15:09:12 +01:00
|
|
|
* @param ident - Identifier (pid or identifier object) of script.
|
|
|
|
* @returns Error message to print to logs
|
2022-08-10 00:08:04 +02:00
|
|
|
*/
|
|
|
|
function getCannotFindRunningScriptErrorMessage(ident: ScriptIdentifier): string {
|
|
|
|
if (typeof ident === "number") return `Cannot find running script with pid: ${ident}`;
|
|
|
|
|
|
|
|
return `Cannot find running script ${ident.scriptname} on server ${ident.hostname} with args: ${arrayToString(
|
|
|
|
ident.args,
|
|
|
|
)}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Sanitizes a `RunningScript` to remove sensitive information, making it suitable for
|
|
|
|
* return through an NS function.
|
|
|
|
* @see NS.getRecentScripts
|
|
|
|
* @see NS.getRunningScript
|
|
|
|
* @param runningScript Existing, internal RunningScript
|
|
|
|
* @returns A sanitized, NS-facing copy of the RunningScript
|
|
|
|
*/
|
|
|
|
function createPublicRunningScript(runningScript: RunningScript): IRunningScript {
|
2023-05-26 14:07:37 +02:00
|
|
|
const logProps = runningScript.tailProps;
|
2022-08-10 00:08:04 +02:00
|
|
|
return {
|
|
|
|
args: runningScript.args.slice(),
|
|
|
|
filename: runningScript.filename,
|
2023-01-06 02:30:34 +01:00
|
|
|
logs: runningScript.logs.map((x) => "" + x),
|
2022-08-10 00:08:04 +02:00
|
|
|
offlineExpGained: runningScript.offlineExpGained,
|
|
|
|
offlineMoneyMade: runningScript.offlineMoneyMade,
|
|
|
|
offlineRunningTime: runningScript.offlineRunningTime,
|
|
|
|
onlineExpGained: runningScript.onlineExpGained,
|
|
|
|
onlineMoneyMade: runningScript.onlineMoneyMade,
|
|
|
|
onlineRunningTime: runningScript.onlineRunningTime,
|
|
|
|
pid: runningScript.pid,
|
|
|
|
ramUsage: runningScript.ramUsage,
|
|
|
|
server: runningScript.server,
|
2023-05-26 14:07:37 +02:00
|
|
|
tailProperties:
|
|
|
|
!logProps || !logProps.isVisible()
|
|
|
|
? null
|
|
|
|
: {
|
|
|
|
x: logProps.x,
|
|
|
|
y: logProps.y,
|
|
|
|
width: logProps.width,
|
|
|
|
height: logProps.height,
|
|
|
|
},
|
|
|
|
title: runningScript.title,
|
2022-08-10 00:08:04 +02:00
|
|
|
threads: runningScript.threads,
|
2023-03-21 23:54:49 +01:00
|
|
|
temporary: runningScript.temporary,
|
2022-08-10 00:08:04 +02:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Used to fail a function if the function's target is a Hacknet Server.
|
|
|
|
* This is used for functions that should run on normal Servers, but not Hacknet Servers
|
|
|
|
* @param {Server} server - Target server
|
|
|
|
* @param {string} callingFn - Name of calling function. For logging purposes
|
|
|
|
* @returns {boolean} True if the server is a Hacknet Server, false otherwise
|
|
|
|
*/
|
2022-09-05 16:35:12 +02:00
|
|
|
function failOnHacknetServer(ctx: NetscriptContext, server: BaseServer): boolean {
|
2022-08-10 00:08:04 +02:00
|
|
|
if (server instanceof HacknetServer) {
|
2022-09-05 16:35:12 +02:00
|
|
|
log(ctx, () => `Does not work on Hacknet Servers`);
|
2022-08-10 00:08:04 +02:00
|
|
|
return true;
|
|
|
|
} else {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
2022-09-05 15:55:57 +02:00
|
|
|
|
|
|
|
/** Generate an error dialog when workerscript is known */
|
|
|
|
export function handleUnknownError(e: unknown, ws: WorkerScript | ScriptDeath | null = null, initialText = "") {
|
|
|
|
if (e instanceof ScriptDeath) {
|
|
|
|
//No dialog for an empty ScriptDeath
|
|
|
|
if (e.errorMessage === "") return;
|
|
|
|
if (!ws) {
|
|
|
|
ws = e;
|
|
|
|
e = ws.errorMessage;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (ws && typeof e === "string") {
|
|
|
|
const headerText = makeBasicErrorMsg(ws, "", "");
|
|
|
|
if (!e.includes(headerText)) e = makeBasicErrorMsg(ws, e);
|
|
|
|
} else if (e instanceof SyntaxError) {
|
|
|
|
const msg = `${e.message} (sorry we can't be more helpful)`;
|
|
|
|
e = ws ? makeBasicErrorMsg(ws, msg, "SYNTAX") : `SYNTAX ERROR:\n\n${msg}`;
|
|
|
|
} else if (e instanceof Error) {
|
2022-11-10 16:08:59 +01:00
|
|
|
// Ignore any cancellation errors from Monaco that get here
|
|
|
|
if (e.name === "Canceled" && e.message === "Canceled") return;
|
2022-09-05 15:55:57 +02:00
|
|
|
const msg = `${e.message}${e.stack ? `\nstack:\n${e.stack.toString()}` : ""}`;
|
|
|
|
e = ws ? makeBasicErrorMsg(ws, msg) : `RUNTIME ERROR:\n\n${msg}`;
|
|
|
|
}
|
|
|
|
if (typeof e !== "string") {
|
2022-10-19 22:32:39 +02:00
|
|
|
console.error("Unexpected error:", e);
|
|
|
|
const msg = `Unexpected type of error thrown. This error was likely thrown manually within a script.
|
|
|
|
Error has been logged to the console.\n\nType of error: ${typeof e}\nValue of error: ${e}`;
|
|
|
|
e = ws ? makeBasicErrorMsg(ws, msg, "UNKNOWN") : msg;
|
2022-09-05 15:55:57 +02:00
|
|
|
}
|
|
|
|
dialogBoxCreate(initialText + e);
|
|
|
|
}
|
2023-05-26 14:07:37 +02:00
|
|
|
|
|
|
|
// Incrementing value for custom element keys
|
|
|
|
let customElementKey = 0;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Wrap a user-provided React Element (or maybe invalid junk) in an Error-catching component,
|
|
|
|
* so the game won't crash and the user gets sensible messages.
|
|
|
|
*/
|
|
|
|
export function wrapUserNode(value: unknown) {
|
2023-06-27 04:29:44 +02:00
|
|
|
return <CustomBoundary key={`PlayerContent${customElementKey++}`}>{value}</CustomBoundary>;
|
2023-05-26 14:07:37 +02:00
|
|
|
}
|