bitburner-src/src/NetscriptFunctions.ts

1829 lines
68 KiB
TypeScript
Raw Normal View History

2022-04-17 02:29:20 +02:00
import $ from "jquery";
2021-09-05 01:09:30 +02:00
import { vsprintf, sprintf } from "sprintf-js";
import { currentNodeMults } from "./BitNode/BitNodeMultipliers";
import { CONSTANTS } from "./Constants";
import {
2021-09-05 01:09:30 +02:00
calculateHackingChance,
calculateHackingExpGain,
calculatePercentMoneyHacked,
calculateHackingTime,
calculateGrowTime,
calculateWeakenTime,
} from "./Hacking";
2022-08-08 19:43:41 +02:00
import { netscriptCanGrow, netscriptCanWeaken } from "./Hacking/netscriptCanHack";
import { Terminal } from "./Terminal";
import { Player } from "@player";
import {
CityName,
CompletedProgramName,
CrimeType,
FactionWorkType,
GymType,
JobName,
LiteratureName,
LocationName,
ToastVariant,
UniversityClassType,
} from "@enums";
2021-10-02 04:53:23 +02:00
import { PromptEvent } from "./ui/React/PromptManager";
2022-08-10 00:08:04 +02:00
import { GetServer, DeleteServer, AddToAllServers, createUniqueRandomIp } from "./Server/AllServers";
import {
2021-09-05 01:09:30 +02:00
getServerOnNetwork,
numCycleForGrowth,
2022-04-13 15:54:48 +02:00
numCycleForGrowthCorrected,
2021-09-05 01:09:30 +02:00
processSingleServerGrowth,
2022-10-09 07:25:31 +02:00
safelyCreateUniqueServer,
} from "./Server/ServerHelpers";
2022-10-09 08:32:13 +02:00
import {
getPurchasedServerUpgradeCost,
getPurchaseServerCost,
getPurchaseServerLimit,
getPurchaseServerMaxRam,
renamePurchasedServer,
upgradePurchasedServer,
} from "./Server/ServerPurchases";
2021-09-25 03:49:49 +02:00
import { Server } from "./Server/Server";
2022-08-08 19:43:41 +02:00
import { influenceStockThroughServerGrow } from "./StockMarket/PlayerInfluencing";
2022-09-02 19:19:00 +02:00
import { runScriptFromScript } from "./NetscriptWorker";
import { killWorkerScript, killWorkerScriptByPid } from "./Netscript/killWorkerScript";
import { workerScripts } from "./Netscript/WorkerScripts";
2021-09-25 03:49:49 +02:00
import { WorkerScript } from "./Netscript/WorkerScript";
2023-05-26 14:07:37 +02:00
import { helpers, assertObjectType, wrapUserNode } from "./Netscript/NetscriptHelpers";
import {
formatExp,
formatNumberNoSuffix,
formatMoney,
formatPercent,
formatRam,
formatSecurity,
formatThreads,
formatNumber,
} from "./ui/formatNumber";
import { convertTimeMsToTimeElapsedString } from "./utils/StringHelperFunctions";
2023-05-26 14:07:37 +02:00
import { LogBoxEvents, LogBoxCloserEvents } from "./ui/React/LogBoxManager";
import { arrayToString } from "./utils/helpers/ArrayHelpers";
import { NetscriptGang } from "./NetscriptFunctions/Gang";
import { NetscriptSleeve } from "./NetscriptFunctions/Sleeve";
2022-05-25 02:16:39 +02:00
import { NetscriptExtra } from "./NetscriptFunctions/Extra";
import { NetscriptHacknet } from "./NetscriptFunctions/Hacknet";
2021-11-14 04:44:17 +01:00
import { NetscriptStanek } from "./NetscriptFunctions/Stanek";
import { NetscriptInfiltration } from "./NetscriptFunctions/Infiltration";
2021-12-29 08:04:24 +01:00
import { NetscriptUserInterface } from "./NetscriptFunctions/UserInterface";
import { NetscriptBladeburner } from "./NetscriptFunctions/Bladeburner";
import { NetscriptCodingContract } from "./NetscriptFunctions/CodingContract";
import { NetscriptCorporation } from "./NetscriptFunctions/Corporation";
import { NetscriptFormulas } from "./NetscriptFunctions/Formulas";
2021-10-30 22:03:34 +02:00
import { NetscriptStockMarket } from "./NetscriptFunctions/StockMarket";
2022-03-23 18:35:15 +01:00
import { NetscriptGrafting } from "./NetscriptFunctions/Grafting";
import { NS, RecentScript, BasicHGWOptions, ProcessInfo, NSEnums } from "@nsdefs";
2021-11-14 04:44:17 +01:00
import { NetscriptSingularity } from "./NetscriptFunctions/Singularity";
2021-09-25 23:21:50 +02:00
2021-10-13 02:02:37 +02:00
import { dialogBoxCreate } from "./ui/React/DialogBox";
import { SnackbarEvents } from "./ui/React/Snackbar";
import { matchScriptPathExact } from "./utils/helpers/scriptKey";
2021-10-15 18:47:43 +02:00
import { Flags } from "./NetscriptFunctions/Flags";
2022-01-18 20:02:12 +01:00
import { calculateIntelligenceBonus } from "./PersonObjects/formulas/intelligence";
import { CalculateShareMult, StartSharing } from "./NetworkShare/Share";
2022-01-19 08:04:48 +01:00
import { recentScripts } from "./Netscript/RecentScripts";
import { InternalAPI, removedFunction, NSProxy } from "./Netscript/APIWrapper";
2022-08-10 01:02:33 +02:00
import { INetscriptExtra } from "./NetscriptFunctions/Extra";
2022-09-01 14:23:31 +02:00
import { ScriptDeath } from "./Netscript/ScriptDeath";
2022-10-13 06:51:53 +02:00
import { getBitNodeMultipliers } from "./BitNode/BitNode";
import { assert, arrayAssert, stringAssert, objectAssert } from "./utils/helpers/typeAssertion";
import { cloneDeep, escapeRegExp } from "lodash";
import numeral from "numeral";
import { clearPort, peekPort, portHandle, readPort, tryWritePort, writePort } from "./NetscriptPort";
import { FilePath, resolveFilePath } from "./Paths/FilePath";
import { hasScriptExtension } from "./Paths/ScriptFilePath";
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
import { hasTextExtension } from "./Paths/TextFilePath";
import { ContentFilePath } from "./Paths/ContentFile";
import { hasContractExtension } from "./Paths/ContractFilePath";
2023-05-26 13:46:08 +02:00
import { getRamCost } from "./Netscript/RamCostGenerator";
import { getEnumHelper } from "./utils/EnumHelper";
2022-10-03 18:12:16 +02:00
export const enums: NSEnums = {
CityName,
CrimeType,
FactionWorkType,
GymType,
JobName,
LocationName,
ToastVariant,
UniversityClassType,
WIP: Crimes streamlining. (#138) * streamline crimes * Crimes object is now indexed by CrimeType enum instead of an entirely new set of keys that aren't used for anything else. This eliminated a lot of instances of iterating to find the right crime for a given CrimeType. * Removed unused `None` CrimeType which allowed typing Crimes as a Record<CrimeType, Crime>. * Added slums tooltip text as a crime property, to allow streamlining slums. * Refactor slums location - removed repetitive code, rerenders 1/sec to update chances * Fix bugged descriptive text when sleeve is committing a crime (was "is attempting to DRUGS", now uses correct text e.g. "to deal drugs"). * Remove unused and now unneeded NewCrimeType enum. Values were identical to existing CrimeType values after removing unused None. * Add CrimeType enum in NetscriptDefinition.d.ts * Also update broken ToastVariant type. Better support for enums in player scripts. * Still todo is modifying some NS functions to expect CrimeType as input (rough crime names will continue to work to avoid breaking scripts) * Expect enum use for crime functions Affected functions: * ns.singularity.commitCrime * ns.singularity.getCrimeChance * ns.singularity.getCrimeStats * ns.sleeve.setToCommitCrime * formulas.work.crimeGains (param type only) - Affected functions still will fall back to rough names, except formulas.work.crimeGains which already only accepted the enum members. - Some documentation changes: * examples updated to use uppercase expected form. * Note on sleeve.setToCommitCrime that it only accepts exact matches removed. It already, and still does, accept any rough crime name (but the enum is expected input). * note about needing to use isBusy to schedule crimes remove - crimes autoloop now. * Since expected string inputs are documented directly on the type, removed list of crimes from sleeve.setToCommitCrimes
2022-10-21 17:57:37 +02:00
};
for (const val of Object.values(enums)) Object.freeze(val);
Object.freeze(enums);
export type NSFull = Readonly<Omit<NS & INetscriptExtra, "pid" | "args" | "enums">>;
2022-08-10 01:02:33 +02:00
2022-12-13 15:08:23 +01:00
export const ns: InternalAPI<NSFull> = {
2022-08-09 21:41:47 +02:00
singularity: NetscriptSingularity(),
gang: NetscriptGang(),
bladeburner: NetscriptBladeburner(),
codingcontract: NetscriptCodingContract(),
sleeve: NetscriptSleeve(),
corporation: NetscriptCorporation(),
stanek: NetscriptStanek(),
infiltration: NetscriptInfiltration(),
ui: NetscriptUserInterface(),
formulas: NetscriptFormulas(),
stock: NetscriptStockMarket(),
grafting: NetscriptGrafting(),
hacknet: NetscriptHacknet(),
sprintf: () => sprintf,
vsprintf: () => vsprintf,
scan: (ctx) => (_hostname) => {
const hostname = _hostname ? helpers.string(ctx, "hostname", _hostname) : ctx.workerScript.hostname;
const server = helpers.getServer(ctx, hostname);
const out: string[] = [];
for (let i = 0; i < server.serversOnNetwork.length; i++) {
const s = getServerOnNetwork(server, i);
if (s === null) continue;
const entry = s.hostname;
if (entry === null) continue;
out.push(entry);
}
helpers.log(ctx, () => `returned ${server.serversOnNetwork.length} connections for ${server.hostname}`);
return out;
},
NETSCRIPT: ns.sleeve.getSleeve added. getPlayer and getSleeve can both be used for formulas. (#200) * BREAKING CHANGE: Removed getSleeveStats and getSleeveInformation because this info is provided by getSleeve in a more usable form. * BREAKING CHANGE: Removed tor, inBladeburner, and hasCorporation fields from ns.getPlayer. Functionality still exists via added functions ns.hasTorRouter, ns.corporation.hasCorporation, and ns.bladeburner.inBladeburner. * Separated ns definitions for Person, Sleeve, and Player interfaces with both Player and Sleeve just extending Person. Added getSleeve, which provides a Sleeve object similar to getPlayer. * Renamed the sleeve ns layer's interface as sleeve lowercase because of name conflict. todo: May move all the ns layers interface names to lowercase for consistency * Added ns.formulas.work.crimeSuccessChance and reworked to allow both sleeve and player calculations. * Removed internal Person.getIntelligenceBonus function which was just a wrapper for calculateIntelligenceBonus. Any use of the former in formulas creates a conflict where ns-provided Person objects throw an error. * Renamed helpers.player to helpers.person for netscript person validation. Reduced number of fields validated due to Person being a smaller interface. * Fixed bug in bladeburner where Player multipliers and int were being used no matter which person was performing the task * Fixed leak of Player.jobs at ns.getPlayer * Person / Player / Sleeve classes now implement the netscript equivalent interfaces. Netscript helper for person no longer asserts that it's a real Person class member, only that it's a Person interface. Functions that use netscript persons have been changed to expect just a person interface to prevent needing this incorrect type assertion.
2022-11-09 13:26:26 +01:00
hasTorRouter: () => () => Player.hasTorRouter(),
2022-08-09 21:41:47 +02:00
hack:
(ctx) =>
(_hostname, opts = {}) => {
2022-08-09 21:41:47 +02:00
const hostname = helpers.string(ctx, "hostname", _hostname);
// TODO 2.2: better type safety rework for functions using assertObjectType, then remove function.
const optsValidator: BasicHGWOptions = {};
assertObjectType(ctx, "opts", opts, optsValidator);
return helpers.hack(ctx, hostname, false, opts);
},
hackAnalyzeThreads: (ctx) => (_hostname, _hackAmount) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const hackAmount = helpers.number(ctx, "hackAmount", _hackAmount);
// Check argument validity
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return -1;
}
if (isNaN(hackAmount)) {
throw helpers.makeRuntimeErrorMsg(
ctx,
`Invalid hackAmount argument passed into hackAnalyzeThreads: ${hackAmount}. Must be numeric.`,
);
}
if (hackAmount < 0 || hackAmount > server.moneyAvailable) {
return -1;
} else if (hackAmount === 0) {
return 0;
}
2021-09-05 01:09:30 +02:00
const percentHacked = calculatePercentMoneyHacked(server, Player);
2022-05-25 02:16:39 +02:00
if (percentHacked === 0 || server.moneyAvailable === 0) {
return -1; // To prevent returning infinity below
}
return hackAmount / (server.moneyAvailable * percentHacked);
},
hackAnalyze: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
2021-09-02 06:36:33 +02:00
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 0;
}
return calculatePercentMoneyHacked(server, Player);
},
hackAnalyzeSecurity: (ctx) => (_threads, _hostname?) => {
let threads = helpers.number(ctx, "threads", _threads);
if (_hostname) {
const hostname = helpers.string(ctx, "hostname", _hostname);
2022-08-09 21:41:47 +02:00
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 0;
}
2021-09-02 06:36:33 +02:00
const percentHacked = calculatePercentMoneyHacked(server, Player);
2022-04-12 17:42:49 +02:00
if (percentHacked > 0) {
// thread count is limited to the maximum number of threads needed
threads = Math.min(threads, Math.ceil(1 / percentHacked));
2022-08-09 21:41:47 +02:00
}
}
2022-04-12 17:42:49 +02:00
return CONSTANTS.ServerFortifyAmount * threads;
},
hackAnalyzeChance: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
2021-09-02 06:36:33 +02:00
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 0;
}
2021-09-05 01:09:30 +02:00
return calculateHackingChance(server, Player);
},
2022-08-09 21:41:47 +02:00
sleep:
(ctx) =>
2022-10-12 15:54:13 +02:00
(_time = 0) => {
2022-08-09 21:41:47 +02:00
const time = helpers.number(ctx, "time", _time);
helpers.log(ctx, () => `Sleeping for ${time} milliseconds`);
return helpers.netscriptDelay(ctx, time).then(function () {
return Promise.resolve(true);
});
},
2022-10-12 15:54:13 +02:00
asleep:
(ctx) =>
(_time = 0) => {
2022-08-09 21:41:47 +02:00
const time = helpers.number(ctx, "time", _time);
helpers.log(ctx, () => `Sleeping for ${time} milliseconds`);
return new Promise((resolve) => setTimeout(() => resolve(true), time));
},
grow:
(ctx) =>
2022-10-12 15:54:13 +02:00
(_hostname, opts = {}) => {
2022-08-09 21:41:47 +02:00
const hostname = helpers.string(ctx, "hostname", _hostname);
const optsValidator: BasicHGWOptions = {};
assertObjectType(ctx, "opts", opts, optsValidator);
const threads = helpers.resolveNetscriptRequestedThreads(ctx, opts.threads);
const additionalMsec = helpers.number(ctx, "opts.additionalMsec", opts.additionalMsec ?? 0);
if (additionalMsec < 0) {
throw helpers.makeRuntimeErrorMsg(ctx, `additionalMsec must be non-negative, got ${additionalMsec}`);
}
2022-05-25 02:16:39 +02:00
2022-08-09 21:41:47 +02:00
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return Promise.resolve(0);
}
2021-09-05 01:09:30 +02:00
2022-08-09 21:41:47 +02:00
const host = GetServer(ctx.workerScript.hostname);
if (host === null) {
throw new Error("Workerscript host is null");
}
2021-09-05 01:09:30 +02:00
2022-08-09 21:41:47 +02:00
// No root access or skill level too low
const canHack = netscriptCanGrow(server);
if (!canHack.res) {
throw helpers.makeRuntimeErrorMsg(ctx, canHack.msg || "");
}
const growTime = calculateGrowTime(server, Player) + additionalMsec / 1000.0;
2022-08-09 21:41:47 +02:00
helpers.log(
ctx,
() =>
`Executing on '${server.hostname}' in ${convertTimeMsToTimeElapsedString(
growTime * 1000,
true,
)} (t=${formatThreads(threads)}).`,
2022-08-09 21:41:47 +02:00
);
return helpers.netscriptDelay(ctx, growTime * 1000).then(function () {
const moneyBefore = server.moneyAvailable <= 0 ? 1 : server.moneyAvailable;
2022-09-18 03:09:15 +02:00
processSingleServerGrowth(server, threads, host.cpuCores);
2022-08-09 21:41:47 +02:00
const moneyAfter = server.moneyAvailable;
ctx.workerScript.scriptRef.recordGrow(server.hostname, threads);
const expGain = calculateHackingExpGain(server, Player) * threads;
const logGrowPercent = moneyAfter / moneyBefore - 1;
2022-08-08 21:51:50 +02:00
helpers.log(
ctx,
() =>
`Available money on '${server.hostname}' grown by ${formatPercent(logGrowPercent, 6)}. Gained ${formatExp(
expGain,
)} hacking exp (t=${formatThreads(threads)}).`,
2021-09-05 01:09:30 +02:00
);
2022-08-09 21:41:47 +02:00
ctx.workerScript.scriptRef.onlineExpGained += expGain;
Player.gainHackingExp(expGain);
if (opts.stock) {
2022-08-09 21:41:47 +02:00
influenceStockThroughServerGrow(server, moneyAfter - moneyBefore);
}
return Promise.resolve(moneyAfter / moneyBefore);
});
},
growthAnalyze:
(ctx) =>
(_host, _multiplier, _cores = 1) => {
const host = helpers.string(ctx, "hostname", _host);
const mult = helpers.number(ctx, "multiplier", _multiplier);
2022-08-09 21:41:47 +02:00
const cores = helpers.number(ctx, "cores", _cores);
// Check argument validity
const server = helpers.getServer(ctx, host);
2022-08-09 21:41:47 +02:00
if (!(server instanceof Server)) {
// Todo 2.3: Make this throw instead of returning 0?
helpers.log(ctx, () => `${host} is not a hackable server. Returning 0.`);
2022-08-09 21:41:47 +02:00
return 0;
}
if (mult < 1 || !isFinite(mult)) {
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid argument: multiplier must be finite and >= 1, is ${mult}.`);
}
// TODO 2.3: Add assertion function for positive integer, there are a lot of places everywhere that can use this
if (!Number.isInteger(cores) || cores < 1) {
throw helpers.makeRuntimeErrorMsg(ctx, `Cores should be a positive integer. Cores provided: ${cores}`);
2022-08-09 21:41:47 +02:00
}
2022-05-25 02:16:39 +02:00
return numCycleForGrowth(server, mult, cores);
2022-08-09 21:41:47 +02:00
},
growthAnalyzeSecurity:
(ctx) =>
(_threads, _hostname?, _cores = 1) => {
2022-08-09 21:41:47 +02:00
let threads = helpers.number(ctx, "threads", _threads);
if (_hostname) {
2022-09-29 06:02:33 +02:00
const cores = helpers.number(ctx, "cores", _cores);
2022-08-09 21:41:47 +02:00
const hostname = helpers.string(ctx, "hostname", _hostname);
2022-08-08 19:43:41 +02:00
const server = helpers.getServer(ctx, hostname);
2022-08-09 21:41:47 +02:00
2022-04-13 09:16:59 +02:00
if (!(server instanceof Server)) {
2022-08-08 21:51:50 +02:00
helpers.log(ctx, () => "Cannot be executed on this server.");
2022-04-13 09:16:59 +02:00
return 0;
}
2022-08-09 21:41:47 +02:00
const maxThreadsNeeded = Math.ceil(
2022-09-18 03:09:15 +02:00
numCycleForGrowthCorrected(server, server.moneyMax, server.moneyAvailable, cores),
2022-08-09 21:41:47 +02:00
);
2022-04-13 09:16:59 +02:00
2022-08-09 21:41:47 +02:00
threads = Math.min(threads, maxThreadsNeeded);
}
2021-09-05 01:09:30 +02:00
2022-08-09 21:41:47 +02:00
return 2 * CONSTANTS.ServerFortifyAmount * threads;
},
weaken:
(ctx) =>
async (_hostname, opts = {}) => {
2022-08-09 21:41:47 +02:00
const hostname = helpers.string(ctx, "hostname", _hostname);
const optsValidator: BasicHGWOptions = {};
assertObjectType(ctx, "opts", opts, optsValidator);
const threads = helpers.resolveNetscriptRequestedThreads(ctx, opts.threads);
const additionalMsec = helpers.number(ctx, "opts.additionalMsec", opts.additionalMsec ?? 0);
if (additionalMsec < 0) {
throw helpers.makeRuntimeErrorMsg(ctx, `additionalMsec must be non-negative, got ${additionalMsec}`);
}
2022-08-09 21:41:47 +02:00
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return Promise.resolve(0);
}
2021-09-05 01:09:30 +02:00
2022-08-09 21:41:47 +02:00
// No root access or skill level too low
const canHack = netscriptCanWeaken(server);
if (!canHack.res) {
throw helpers.makeRuntimeErrorMsg(ctx, canHack.msg || "");
}
2022-05-25 02:16:39 +02:00
const weakenTime = calculateWeakenTime(server, Player) + additionalMsec / 1000.0;
2022-08-09 21:41:47 +02:00
helpers.log(
ctx,
() =>
`Executing on '${server.hostname}' in ${convertTimeMsToTimeElapsedString(
weakenTime * 1000,
true,
)} (t=${formatThreads(threads)})`,
2022-08-09 21:41:47 +02:00
);
return helpers.netscriptDelay(ctx, weakenTime * 1000).then(function () {
const host = GetServer(ctx.workerScript.hostname);
if (host === null) {
helpers.log(ctx, () => "Server is null, did it die?");
return Promise.resolve(0);
2022-05-25 02:16:39 +02:00
}
2022-08-09 21:41:47 +02:00
const coreBonus = 1 + (host.cpuCores - 1) / 16;
const weakenAmt = CONSTANTS.ServerWeakenAmount * threads * coreBonus;
server.weaken(weakenAmt);
2022-08-09 21:41:47 +02:00
ctx.workerScript.scriptRef.recordWeaken(server.hostname, threads);
const expGain = calculateHackingExpGain(server, Player) * threads;
2022-08-08 21:51:50 +02:00
helpers.log(
ctx,
() =>
`'${server.hostname}' security level weakened to ${server.hackDifficulty}. Gained ${formatExp(
expGain,
)} hacking exp (t=${formatThreads(threads)})`,
2021-09-05 01:09:30 +02:00
);
2022-08-09 21:41:47 +02:00
ctx.workerScript.scriptRef.onlineExpGained += expGain;
Player.gainHackingExp(expGain);
// Account for hidden multiplier in Server.weaken()
return Promise.resolve(weakenAmt * currentNodeMults.ServerWeakenRate);
2022-01-18 20:02:12 +01:00
});
},
2022-08-09 21:41:47 +02:00
weakenAnalyze:
(ctx) =>
(_threads, _cores = 1) => {
2022-08-09 21:41:47 +02:00
const threads = helpers.number(ctx, "threads", _threads);
const cores = helpers.number(ctx, "cores", _cores);
const coreBonus = 1 + (cores - 1) / 16;
return CONSTANTS.ServerWeakenAmount * threads * coreBonus * currentNodeMults.ServerWeakenRate;
2022-01-18 20:02:12 +01:00
},
2022-10-12 15:54:13 +02:00
share: (ctx) => () => {
2022-08-09 21:41:47 +02:00
helpers.log(ctx, () => "Sharing this computer.");
const end = StartSharing(
ctx.workerScript.scriptRef.threads * calculateIntelligenceBonus(Player.skills.intelligence, 2),
);
return helpers.netscriptDelay(ctx, 10000).finally(function () {
helpers.log(ctx, () => "Finished sharing this computer.");
end();
});
},
getSharePower: () => () => {
2022-08-09 21:41:47 +02:00
return CalculateShareMult();
},
print:
(ctx) =>
(...args) => {
2022-08-09 21:41:47 +02:00
if (args.length === 0) {
throw helpers.makeRuntimeErrorMsg(ctx, "Takes at least 1 argument.");
}
2022-08-10 00:08:04 +02:00
ctx.workerScript.print(helpers.argsToString(args));
2022-08-09 21:41:47 +02:00
},
printf:
(ctx) =>
(_format, ...args) => {
2022-08-09 21:41:47 +02:00
const format = helpers.string(ctx, "format", _format);
if (typeof format !== "string") {
throw helpers.makeRuntimeErrorMsg(ctx, "First argument must be string for the format.");
}
ctx.workerScript.print(vsprintf(format, args));
},
tprint:
(ctx) =>
(...args) => {
2022-08-09 21:41:47 +02:00
if (args.length === 0) {
throw helpers.makeRuntimeErrorMsg(ctx, "Takes at least 1 argument.");
}
2022-08-10 00:08:04 +02:00
const str = helpers.argsToString(args);
2022-08-09 21:41:47 +02:00
if (str.startsWith("ERROR") || str.startsWith("FAIL")) {
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
Terminal.error(`${ctx.workerScript.name}: ${str}`);
2022-08-09 21:41:47 +02:00
return;
}
if (str.startsWith("SUCCESS")) {
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
Terminal.success(`${ctx.workerScript.name}: ${str}`);
2022-08-09 21:41:47 +02:00
return;
}
if (str.startsWith("WARN")) {
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
Terminal.warn(`${ctx.workerScript.name}: ${str}`);
2022-08-09 21:41:47 +02:00
return;
}
if (str.startsWith("INFO")) {
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
Terminal.info(`${ctx.workerScript.name}: ${str}`);
2022-08-09 21:41:47 +02:00
return;
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
Terminal.print(`${ctx.workerScript.name}: ${str}`);
2022-08-09 21:41:47 +02:00
},
tprintf:
(ctx) =>
(_format, ...args) => {
2022-08-09 21:41:47 +02:00
const format = helpers.string(ctx, "format", _format);
const str = vsprintf(format, args);
if (str.startsWith("ERROR") || str.startsWith("FAIL")) {
Terminal.error(`${str}`);
return;
}
if (str.startsWith("SUCCESS")) {
Terminal.success(`${str}`);
return;
}
if (str.startsWith("WARN")) {
Terminal.warn(`${str}`);
return;
}
if (str.startsWith("INFO")) {
Terminal.info(`${str}`);
return;
}
Terminal.print(`${str}`);
},
clearLog: (ctx) => () => {
2022-08-09 21:41:47 +02:00
ctx.workerScript.scriptRef.clearLog();
},
disableLog: (ctx) => (_fn) => {
const fn = helpers.string(ctx, "fn", _fn);
if (fn === "ALL") {
for (const fn of Object.keys(possibleLogs)) {
2022-08-09 21:41:47 +02:00
ctx.workerScript.disableLogs[fn] = true;
}
helpers.log(ctx, () => `Disabled logging for all functions`);
} else if (possibleLogs[fn] === undefined) {
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid argument: ${fn}.`);
} else {
ctx.workerScript.disableLogs[fn] = true;
helpers.log(ctx, () => `Disabled logging for ${fn}`);
}
},
enableLog: (ctx) => (_fn) => {
const fn = helpers.string(ctx, "fn", _fn);
if (fn === "ALL") {
for (const fn of Object.keys(possibleLogs)) {
delete ctx.workerScript.disableLogs[fn];
}
helpers.log(ctx, () => `Enabled logging for all functions`);
} else if (possibleLogs[fn] === undefined) {
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid argument: ${fn}.`);
}
delete ctx.workerScript.disableLogs[fn];
helpers.log(ctx, () => `Enabled logging for ${fn}`);
},
isLogEnabled: (ctx) => (_fn) => {
const fn = helpers.string(ctx, "fn", _fn);
if (possibleLogs[fn] === undefined) {
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid argument: ${fn}.`);
}
return !ctx.workerScript.disableLogs[fn];
},
2022-08-09 21:41:47 +02:00
getScriptLogs:
(ctx) =>
(scriptID, hostname, ...scriptArgs) => {
2022-08-09 21:41:47 +02:00
const ident = helpers.scriptIdentifier(ctx, scriptID, hostname, scriptArgs);
2022-08-10 00:08:04 +02:00
const runningScriptObj = helpers.getRunningScript(ctx, ident);
2022-08-09 21:41:47 +02:00
if (runningScriptObj == null) {
2022-08-10 00:08:04 +02:00
helpers.log(ctx, () => helpers.getCannotFindRunningScriptErrorMessage(ident));
return [] as string[];
2022-08-09 21:41:47 +02:00
}
2022-05-25 02:16:39 +02:00
return runningScriptObj.logs.map((x) => "" + x);
2022-08-09 21:41:47 +02:00
},
tail:
(ctx) =>
(scriptID, hostname, ...scriptArgs) => {
2022-08-09 21:41:47 +02:00
const ident = helpers.scriptIdentifier(ctx, scriptID, hostname, scriptArgs);
2022-08-10 00:08:04 +02:00
const runningScriptObj = helpers.getRunningScript(ctx, ident);
2022-08-09 21:41:47 +02:00
if (runningScriptObj == null) {
2022-08-10 00:08:04 +02:00
helpers.log(ctx, () => helpers.getCannotFindRunningScriptErrorMessage(ident));
2022-08-09 21:41:47 +02:00
return;
}
2022-08-09 21:41:47 +02:00
LogBoxEvents.emit(runningScriptObj);
},
moveTail:
(ctx) =>
(_x, _y, _pid = ctx.workerScript.scriptRef.pid) => {
const x = helpers.number(ctx, "x", _x);
const y = helpers.number(ctx, "y", _y);
const pid = helpers.number(ctx, "pid", _pid);
2023-05-26 14:07:37 +02:00
const runningScriptObj = helpers.getRunningScript(ctx, pid);
if (runningScriptObj == null) {
helpers.log(ctx, () => helpers.getCannotFindRunningScriptErrorMessage(pid));
return;
}
runningScriptObj.tailProps?.setPosition(x, y);
},
resizeTail:
(ctx) =>
(_w, _h, _pid = ctx.workerScript.scriptRef.pid) => {
const w = helpers.number(ctx, "w", _w);
const h = helpers.number(ctx, "h", _h);
const pid = helpers.number(ctx, "pid", _pid);
2023-05-26 14:07:37 +02:00
const runningScriptObj = helpers.getRunningScript(ctx, pid);
if (runningScriptObj == null) {
helpers.log(ctx, () => helpers.getCannotFindRunningScriptErrorMessage(pid));
return;
}
runningScriptObj.tailProps?.setSize(w, h);
},
2022-08-09 21:41:47 +02:00
closeTail:
(ctx) =>
(_pid = ctx.workerScript.scriptRef.pid) => {
2022-08-09 21:41:47 +02:00
const pid = helpers.number(ctx, "pid", _pid);
//Emit an event to tell the game to close the tail window if it exists
LogBoxCloserEvents.emit(pid);
},
2023-05-26 14:07:37 +02:00
setTitle:
(ctx) =>
(title, _pid = ctx.workerScript.scriptRef.pid) => {
const pid = helpers.number(ctx, "pid", _pid);
const runningScriptObj = helpers.getRunningScript(ctx, pid);
if (runningScriptObj == null) {
helpers.log(ctx, () => helpers.getCannotFindRunningScriptErrorMessage(pid));
return;
}
runningScriptObj.title = typeof title === "string" ? title : wrapUserNode(title);
runningScriptObj.tailProps?.rerender();
},
nuke: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
2022-08-09 21:41:47 +02:00
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return false;
}
if (server.hasAdminRights) {
helpers.log(ctx, () => `Already have root access to '${server.hostname}'.`);
2022-08-09 21:41:47 +02:00
return true;
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
if (!Player.hasProgram(CompletedProgramName.nuke)) {
throw helpers.makeRuntimeErrorMsg(ctx, "You do not have the NUKE.exe virus!");
}
if (server.openPortCount < server.numOpenPortsRequired) {
throw helpers.makeRuntimeErrorMsg(ctx, "Not enough ports opened to use NUKE.exe virus.");
}
server.hasAdminRights = true;
helpers.log(ctx, () => `Executed NUKE.exe virus on '${server.hostname}' to gain root access.`);
return true;
},
brutessh: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return false;
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
if (!Player.hasProgram(CompletedProgramName.bruteSsh)) {
throw helpers.makeRuntimeErrorMsg(ctx, "You do not have the BruteSSH.exe program!");
}
if (!server.sshPortOpen) {
helpers.log(ctx, () => `Executed BruteSSH.exe on '${server.hostname}' to open SSH port (22).`);
server.sshPortOpen = true;
++server.openPortCount;
} else {
helpers.log(ctx, () => `SSH Port (22) already opened on '${server.hostname}'.`);
}
return true;
},
ftpcrack: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return false;
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
if (!Player.hasProgram(CompletedProgramName.ftpCrack)) {
throw helpers.makeRuntimeErrorMsg(ctx, "You do not have the FTPCrack.exe program!");
}
if (!server.ftpPortOpen) {
helpers.log(ctx, () => `Executed FTPCrack.exe on '${server.hostname}' to open FTP port (21).`);
server.ftpPortOpen = true;
++server.openPortCount;
} else {
helpers.log(ctx, () => `FTP Port (21) already opened on '${server.hostname}'.`);
}
return true;
},
relaysmtp: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return false;
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
if (!Player.hasProgram(CompletedProgramName.relaySmtp)) {
throw helpers.makeRuntimeErrorMsg(ctx, "You do not have the relaySMTP.exe program!");
}
if (!server.smtpPortOpen) {
helpers.log(ctx, () => `Executed relaySMTP.exe on '${server.hostname}' to open SMTP port (25).`);
server.smtpPortOpen = true;
++server.openPortCount;
} else {
helpers.log(ctx, () => `SMTP Port (25) already opened on '${server.hostname}'.`);
}
return true;
},
httpworm: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return false;
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
if (!Player.hasProgram(CompletedProgramName.httpWorm)) {
throw helpers.makeRuntimeErrorMsg(ctx, "You do not have the HTTPWorm.exe program!");
}
if (!server.httpPortOpen) {
helpers.log(ctx, () => `Executed HTTPWorm.exe on '${server.hostname}' to open HTTP port (80).`);
server.httpPortOpen = true;
++server.openPortCount;
} else {
helpers.log(ctx, () => `HTTP Port (80) already opened on '${server.hostname}'.`);
}
return true;
},
sqlinject: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return false;
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
if (!Player.hasProgram(CompletedProgramName.sqlInject)) {
throw helpers.makeRuntimeErrorMsg(ctx, "You do not have the SQLInject.exe program!");
}
if (!server.sqlPortOpen) {
helpers.log(ctx, () => `Executed SQLInject.exe on '${server.hostname}' to open SQL port (1433).`);
server.sqlPortOpen = true;
++server.openPortCount;
} else {
helpers.log(ctx, () => `SQL Port (1433) already opened on '${server.hostname}'.`);
}
return true;
},
2022-08-09 21:41:47 +02:00
run:
(ctx) =>
(_scriptname, _thread_or_opt = 1, ..._args) => {
const path = helpers.scriptPath(ctx, "scriptname", _scriptname);
const runOpts = helpers.runOptions(ctx, _thread_or_opt);
2022-08-09 21:41:47 +02:00
const args = helpers.scriptArgs(ctx, _args);
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
const scriptServer = ctx.workerScript.getServer();
2022-08-09 21:41:47 +02:00
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
return runScriptFromScript("run", scriptServer, path, args, ctx.workerScript, runOpts);
2022-08-09 21:41:47 +02:00
},
exec:
(ctx) =>
(_scriptname, _hostname, _thread_or_opt = 1, ..._args) => {
const path = helpers.scriptPath(ctx, "scriptname", _scriptname);
2022-08-09 21:41:47 +02:00
const hostname = helpers.string(ctx, "hostname", _hostname);
const runOpts = helpers.runOptions(ctx, _thread_or_opt);
2022-08-09 21:41:47 +02:00
const args = helpers.scriptArgs(ctx, _args);
const server = helpers.getServer(ctx, hostname);
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
return runScriptFromScript("exec", server, path, args, ctx.workerScript, runOpts);
2022-08-09 21:41:47 +02:00
},
spawn:
(ctx) =>
(_scriptname, _thread_or_opt = 1, ..._args) => {
const path = helpers.scriptPath(ctx, "scriptname", _scriptname);
const runOpts = helpers.runOptions(ctx, _thread_or_opt);
2022-08-09 21:41:47 +02:00
const args = helpers.scriptArgs(ctx, _args);
const spawnDelay = 10;
setTimeout(() => {
const scriptServer = GetServer(ctx.workerScript.hostname);
if (scriptServer == null) {
throw helpers.makeRuntimeErrorMsg(ctx, "Could not find server. This is a bug. Report to dev");
2022-05-25 02:16:39 +02:00
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
return runScriptFromScript("spawn", scriptServer, path, args, ctx.workerScript, runOpts);
2022-08-09 21:41:47 +02:00
}, spawnDelay * 1e3);
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
helpers.log(ctx, () => `Will execute '${path}' in ${spawnDelay} seconds`);
2022-08-09 21:41:47 +02:00
if (killWorkerScript(ctx.workerScript)) {
helpers.log(ctx, () => "Exiting...");
}
},
kill:
(ctx) =>
(scriptID, hostname = ctx.workerScript.hostname, ...scriptArgs) => {
2022-08-09 21:41:47 +02:00
const ident = helpers.scriptIdentifier(ctx, scriptID, hostname, scriptArgs);
let res;
const killByPid = typeof ident === "number";
if (killByPid) {
// Kill by pid
res = killWorkerScriptByPid(ident);
2022-08-09 21:41:47 +02:00
} else {
// Kill by filename/hostname
if (scriptID === undefined) {
2022-08-09 21:41:47 +02:00
throw helpers.makeRuntimeErrorMsg(ctx, "Usage: kill(scriptname, server, [arg1], [arg2]...)");
2022-05-25 02:16:39 +02:00
}
2021-08-19 22:37:59 +02:00
const byPid = helpers.getRunningScriptsByArgs(ctx, ident.scriptname, ident.hostname, ident.args);
if (byPid === null) {
2022-08-10 00:08:04 +02:00
helpers.log(ctx, () => helpers.getCannotFindRunningScriptErrorMessage(ident));
2022-05-25 02:16:39 +02:00
return false;
2021-09-05 01:09:30 +02:00
}
2022-05-25 02:16:39 +02:00
res = true;
for (const pid of byPid.keys()) {
res &&= killWorkerScriptByPid(pid);
}
2022-08-09 21:41:47 +02:00
}
2022-05-25 02:16:39 +02:00
2022-08-09 21:41:47 +02:00
if (res) {
if (killByPid) {
helpers.log(ctx, () => `Killing script with PID ${ident}`);
} else {
helpers.log(ctx, () => `Killing '${scriptID}' on '${hostname}' with args: ${arrayToString(scriptArgs)}.`);
2021-09-05 01:09:30 +02:00
}
2022-08-09 21:41:47 +02:00
return true;
2021-09-05 01:09:30 +02:00
} else {
2022-08-09 21:41:47 +02:00
if (killByPid) {
helpers.log(ctx, () => `No script with PID ${ident}`);
} else {
helpers.log(
ctx,
() => `Internal error killing '${scriptID}' on '${hostname}' with args: ${arrayToString(scriptArgs)}`,
2022-05-25 02:16:39 +02:00
);
2021-09-05 01:09:30 +02:00
}
2022-08-09 21:41:47 +02:00
return false;
}
},
killall:
(ctx) =>
(_hostname = ctx.workerScript.hostname, _safetyguard = true) => {
2022-08-09 21:41:47 +02:00
const hostname = helpers.string(ctx, "hostname", _hostname);
const safetyguard = !!_safetyguard;
const server = helpers.getServer(ctx, hostname);
2022-08-09 21:41:47 +02:00
let scriptsKilled = 0;
2022-07-20 01:04:06 +02:00
for (const byPid of server.runningScriptMap.values()) {
for (const pid of byPid.keys()) {
if (safetyguard && pid == ctx.workerScript.pid) continue;
killWorkerScriptByPid(pid);
++scriptsKilled;
}
2022-08-09 21:41:47 +02:00
}
helpers.log(ctx, () => `Killing all scripts on '${server.hostname}'.`);
2022-08-09 21:41:47 +02:00
return scriptsKilled > 0;
},
exit: (ctx) => () => {
2022-09-01 14:23:31 +02:00
helpers.log(ctx, () => "Exiting...");
2022-09-01 14:37:59 +02:00
killWorkerScript(ctx.workerScript);
2022-09-01 14:23:31 +02:00
throw new ScriptDeath(ctx.workerScript);
2022-08-09 21:41:47 +02:00
},
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
scp: (ctx) => (_files, _destination, _source) => {
const destination = helpers.string(ctx, "destination", _destination);
const source = helpers.string(ctx, "source", _source ?? ctx.workerScript.hostname);
const destServer = helpers.getServer(ctx, destination);
const sourceServer = helpers.getServer(ctx, source);
const files = Array.isArray(_files) ? _files : [_files];
const lits: FilePath[] = [];
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
const contentFiles: ContentFilePath[] = [];
//First loop through filenames to find all errors before moving anything.
for (const file of files) {
const path = helpers.filePath(ctx, "files", file);
if (hasScriptExtension(path) || hasTextExtension(path)) {
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
contentFiles.push(path);
continue;
}
if (!path.endsWith(".lit")) {
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
throw helpers.makeRuntimeErrorMsg(ctx, "Only works for scripts, .lit and .txt files.");
}
lits.push(path);
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
}
2018-09-23 02:25:48 +02:00
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
let noFailures = true;
// --- Scripts and Text Files---
for (const contentFilePath of contentFiles) {
const sourceContentFile = sourceServer.getContentFile(contentFilePath);
if (!sourceContentFile) {
helpers.log(ctx, () => `File '${contentFilePath}' does not exist.`);
noFailures = false;
continue;
}
// Overwrite script if it already exists
const result = destServer.writeToContentFile(contentFilePath, sourceContentFile.content);
helpers.log(ctx, () => `Copied file ${contentFilePath} from ${sourceServer.hostname} to ${destServer.hostname}`);
if (result.overwritten) {
helpers.log(ctx, () => `Warning: ${contentFilePath} was overwritten on ${destServer.hostname}`);
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
}
// --- Literature Files ---
for (const litFilePath of lits) {
const sourceMessage = sourceServer.messages.find((message) => message === litFilePath);
if (!sourceMessage) {
helpers.log(ctx, () => `File '${litFilePath}' does not exist.`);
noFailures = false;
continue;
}
2022-05-25 02:16:39 +02:00
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
const destMessage = destServer.messages.find((message) => message === litFilePath);
if (destMessage) {
helpers.log(ctx, () => `File '${litFilePath}' was already on '${destServer.hostname}'.`);
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
continue;
2022-08-09 21:41:47 +02:00
}
2022-05-25 02:16:39 +02:00
// It exists in sourceServer.messages, so it's a valid name.
destServer.messages.push(litFilePath as LiteratureName);
helpers.log(ctx, () => `File '${litFilePath}' copied over to '${destServer.hostname}'.`);
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
continue;
}
return noFailures;
},
2023-03-07 14:04:08 +01:00
ls: (ctx) => (_hostname, _substring) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const substring = helpers.string(ctx, "substring", _substring ?? "");
const server = helpers.getServer(ctx, hostname);
2023-03-07 14:04:08 +01:00
const allFilenames = [
...server.contracts.map((contract) => contract.fn),
...server.messages,
...server.programs,
...server.scripts.keys(),
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
...server.textFiles.keys(),
2023-03-07 14:04:08 +01:00
];
2023-03-07 14:04:08 +01:00
if (!substring) return allFilenames.sort();
return allFilenames.filter((filename) => ("/" + filename).includes(substring)).sort();
2023-03-07 14:04:08 +01:00
},
getRecentScripts: () => (): RecentScript[] => {
2022-08-09 21:41:47 +02:00
return recentScripts.map((rs) => ({
timeOfDeath: rs.timeOfDeath,
2022-08-10 00:08:04 +02:00
...helpers.createPublicRunningScript(rs.runningScript),
2022-08-09 21:41:47 +02:00
}));
},
ps:
(ctx) =>
(_hostname = ctx.workerScript.hostname) => {
2022-08-09 21:41:47 +02:00
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
const processes: ProcessInfo[] = [];
for (const byPid of server.runningScriptMap.values()) {
for (const script of byPid.values()) {
processes.push({
filename: script.filename,
threads: script.threads,
args: script.args.slice(),
pid: script.pid,
temporary: script.temporary,
});
}
2021-09-05 01:09:30 +02:00
}
2022-08-09 21:41:47 +02:00
return processes;
},
hasRootAccess: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
return server.hasAdminRights;
},
getHostname: (ctx) => () => ctx.workerScript.hostname,
getHackingLevel: (ctx) => () => {
2022-08-09 21:41:47 +02:00
Player.updateSkillLevels();
helpers.log(ctx, () => `returned ${Player.skills.hacking}`);
return Player.skills.hacking;
},
getHackingMultipliers: () => () => {
2022-08-09 21:41:47 +02:00
return {
chance: Player.mults.hacking_chance,
speed: Player.mults.hacking_speed,
money: Player.mults.hacking_money,
growth: Player.mults.hacking_grow,
};
},
getHacknetMultipliers: () => () => {
2022-08-09 21:41:47 +02:00
return {
production: Player.mults.hacknet_node_money,
purchaseCost: Player.mults.hacknet_node_purchase_cost,
ramCost: Player.mults.hacknet_node_ram_cost,
coreCost: Player.mults.hacknet_node_core_cost,
levelCost: Player.mults.hacknet_node_level_cost,
};
},
2022-10-13 06:51:53 +02:00
getBitNodeMultipliers:
(ctx) =>
(_n = Player.bitNodeN, _lvl = Player.sourceFileLvl(Player.bitNodeN) + 1) => {
2022-10-13 06:51:53 +02:00
if (Player.sourceFileLvl(5) <= 0 && Player.bitNodeN !== 5)
throw helpers.makeRuntimeErrorMsg(ctx, "Requires Source-File 5 to run.");
const n = Math.round(helpers.number(ctx, "n", _n));
const lvl = Math.round(helpers.number(ctx, "lvl", _lvl));
if (n < 1 || n > 13) throw new Error("n must be between 1 and 13");
if (lvl < 1) throw new Error("lvl must be >= 1");
return Object.assign({}, getBitNodeMultipliers(n, lvl));
},
getServer: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname ?? ctx.workerScript.hostname);
const server = helpers.getServer(ctx, hostname);
return {
hostname: server.hostname,
ip: server.ip,
sshPortOpen: server.sshPortOpen,
ftpPortOpen: server.ftpPortOpen,
smtpPortOpen: server.smtpPortOpen,
httpPortOpen: server.httpPortOpen,
sqlPortOpen: server.sqlPortOpen,
hasAdminRights: server.hasAdminRights,
cpuCores: server.cpuCores,
isConnectedTo: server.isConnectedTo,
ramUsed: server.ramUsed,
maxRam: server.maxRam,
organizationName: server.organizationName,
purchasedByPlayer: server.purchasedByPlayer,
backdoorInstalled: server.backdoorInstalled,
baseDifficulty: server.baseDifficulty,
hackDifficulty: server.hackDifficulty,
minDifficulty: server.minDifficulty,
moneyAvailable: server.moneyAvailable,
moneyMax: server.moneyMax,
numOpenPortsRequired: server.numOpenPortsRequired,
openPortCount: server.openPortCount,
requiredHackingSkill: server.requiredHackingSkill,
serverGrowth: server.serverGrowth,
};
},
getServerMoneyAvailable: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 0;
}
if (helpers.failOnHacknetServer(ctx, server)) {
return 0;
}
if (server.hostname == "home") {
// Return player's money
helpers.log(ctx, () => `returned player's money: ${formatMoney(Player.money)}`);
return Player.money;
}
helpers.log(ctx, () => `returned ${formatMoney(server.moneyAvailable)} for '${server.hostname}'`);
return server.moneyAvailable;
},
getServerSecurityLevel: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 1;
}
if (helpers.failOnHacknetServer(ctx, server)) {
return 1;
}
helpers.log(ctx, () => `returned ${formatSecurity(server.hackDifficulty)} for '${server.hostname}'`);
return server.hackDifficulty;
},
getServerBaseSecurityLevel: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 1;
}
if (helpers.failOnHacknetServer(ctx, server)) {
return 1;
}
helpers.log(ctx, () => `returned ${formatSecurity(server.baseDifficulty)} for '${server.hostname}'`);
return server.baseDifficulty;
},
getServerMinSecurityLevel: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 1;
}
if (helpers.failOnHacknetServer(ctx, server)) {
return 1;
}
helpers.log(ctx, () => `returned ${formatSecurity(server.minDifficulty)} for ${server.hostname}`);
return server.minDifficulty;
},
getServerRequiredHackingLevel: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 1;
}
if (helpers.failOnHacknetServer(ctx, server)) {
return 1;
}
helpers.log(ctx, () => `returned ${formatNumberNoSuffix(server.requiredHackingSkill, 0)} for '${server.hostname}'`);
return server.requiredHackingSkill;
},
getServerMaxMoney: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 0;
}
if (helpers.failOnHacknetServer(ctx, server)) {
return 0;
}
helpers.log(ctx, () => `returned ${formatMoney(server.moneyMax)} for '${server.hostname}'`);
return server.moneyMax;
},
getServerGrowth: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 1;
}
if (helpers.failOnHacknetServer(ctx, server)) {
return 1;
}
helpers.log(ctx, () => `returned ${server.serverGrowth} for '${server.hostname}'`);
return server.serverGrowth;
},
getServerNumPortsRequired: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 5;
}
if (helpers.failOnHacknetServer(ctx, server)) {
return 5;
}
helpers.log(ctx, () => `returned ${server.numOpenPortsRequired} for '${server.hostname}'`);
return server.numOpenPortsRequired;
},
getServerMaxRam: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
helpers.log(ctx, () => `returned ${formatRam(server.maxRam)}`);
return server.maxRam;
},
getServerUsedRam: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
helpers.log(ctx, () => `returned ${formatRam(server.ramUsed)}`);
return server.ramUsed;
},
serverExists: (ctx) => (_hostname) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
return GetServer(hostname) !== null;
},
fileExists: (ctx) => (_filename, _hostname) => {
const filename = helpers.string(ctx, "filename", _filename);
const hostname = helpers.string(ctx, "hostname", _hostname ?? ctx.workerScript.hostname);
const server = helpers.getServer(ctx, hostname);
const path = resolveFilePath(filename, ctx.workerScript.name);
if (!path) return false;
if (hasScriptExtension(path)) return server.scripts.has(path);
if (hasTextExtension(path)) return server.textFiles.has(path);
if (path.endsWith(".lit") || path.endsWith(".msg")) return server.messages.includes(path as any);
if (hasContractExtension(path)) return !!server.contracts.find(({ fn }) => fn === path);
const lowerPath = path.toLowerCase();
return server.programs.map((programName) => programName.toLowerCase()).includes(lowerPath);
},
2022-08-09 21:41:47 +02:00
isRunning:
(ctx) =>
(fn, hostname, ...scriptArgs) => {
2022-08-09 21:41:47 +02:00
const ident = helpers.scriptIdentifier(ctx, fn, hostname, scriptArgs);
2022-08-10 00:08:04 +02:00
return helpers.getRunningScript(ctx, ident) !== null;
2022-08-09 21:41:47 +02:00
},
getPurchasedServerLimit: () => () => {
2022-08-09 21:41:47 +02:00
return getPurchaseServerLimit();
},
getPurchasedServerMaxRam: () => () => {
2022-08-09 21:41:47 +02:00
return getPurchaseServerMaxRam();
},
getPurchasedServerCost: (ctx) => (_ram) => {
const ram = helpers.number(ctx, "ram", _ram);
2022-08-09 21:41:47 +02:00
const cost = getPurchaseServerCost(ram);
if (cost === Infinity) {
helpers.log(ctx, () => `Invalid argument: ram='${ram}'`);
return Infinity;
}
2022-05-25 02:16:39 +02:00
return cost;
},
purchaseServer: (ctx) => (_name, _ram) => {
const name = helpers.string(ctx, "name", _name);
const ram = helpers.number(ctx, "ram", _ram);
let hostnameStr = String(name);
hostnameStr = hostnameStr.replace(/\s+/g, "");
if (hostnameStr == "") {
helpers.log(ctx, () => `Invalid argument: hostname='${hostnameStr}'`);
return "";
}
2022-08-09 21:41:47 +02:00
if (Player.purchasedServers.length >= getPurchaseServerLimit()) {
2022-08-09 21:41:47 +02:00
helpers.log(
ctx,
() =>
`You have reached the maximum limit of ${getPurchaseServerLimit()} servers. You cannot purchase any more.`,
2022-08-09 21:41:47 +02:00
);
return "";
}
2022-10-09 08:32:13 +02:00
const cost = getPurchaseServerCost(ram);
if (cost === Infinity) {
if (ram > getPurchaseServerMaxRam()) {
helpers.log(ctx, () => `Invalid argument: ram='${ram}' must not be greater than getPurchaseServerMaxRam`);
} else {
helpers.log(ctx, () => `Invalid argument: ram='${ram}' must be a positive power of 2`);
2022-10-09 08:32:13 +02:00
}
return "";
}
if (Player.money < cost) {
helpers.log(ctx, () => `Not enough money to purchase server. Need ${formatMoney(cost)}`);
return "";
}
const newServ = safelyCreateUniqueServer({
ip: createUniqueRandomIp(),
hostname: hostnameStr,
organizationName: "",
isConnectedTo: false,
adminRights: true,
purchasedByPlayer: true,
maxRam: ram,
});
AddToAllServers(newServ);
Player.purchasedServers.push(newServ.hostname);
const homeComputer = Player.getHomeComputer();
homeComputer.serversOnNetwork.push(newServ.hostname);
newServ.serversOnNetwork.push(homeComputer.hostname);
Player.loseMoney(cost, "servers");
helpers.log(ctx, () => `Purchased new server with hostname '${newServ.hostname}' for ${formatMoney(cost)}`);
return newServ.hostname;
},
getPurchasedServerUpgradeCost: (ctx) => (_hostname, _ram) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const ram = helpers.number(ctx, "ram", _ram);
try {
return getPurchasedServerUpgradeCost(hostname, ram);
} catch (err) {
helpers.log(ctx, () => String(err));
return -1;
}
},
upgradePurchasedServer: (ctx) => (_hostname, _ram) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const ram = helpers.number(ctx, "ram", _ram);
try {
upgradePurchasedServer(hostname, ram);
return true;
} catch (err) {
helpers.log(ctx, () => String(err));
2022-10-09 08:32:13 +02:00
return false;
}
},
renamePurchasedServer: (ctx) => (_hostname, _newName) => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const newName = helpers.string(ctx, "newName", _newName);
try {
renamePurchasedServer(hostname, newName);
return true;
} catch (err) {
helpers.log(ctx, () => String(err));
return false;
}
},
2022-10-09 08:32:13 +02:00
deleteServer: (ctx) => (_name) => {
const name = helpers.string(ctx, "name", _name);
let hostnameStr = String(name);
hostnameStr = hostnameStr.replace(/\s\s+/g, "");
const server = GetServer(hostnameStr);
if (!(server instanceof Server)) {
helpers.log(ctx, () => `Invalid argument: hostname='${hostnameStr}'`);
return false;
}
2022-05-25 02:16:39 +02:00
if (!server.purchasedByPlayer || server.hostname === "home") {
helpers.log(ctx, () => "Cannot delete non-purchased server.");
return false;
}
const hostname = server.hostname;
// Can't delete server you're currently connected to
if (server.isConnectedTo) {
helpers.log(ctx, () => "You are currently connected to the server you are trying to delete.");
return false;
}
// A server cannot delete itself
if (hostname === ctx.workerScript.hostname) {
helpers.log(ctx, () => "Cannot delete the server this script is running on.");
return false;
}
// Delete all scripts running on server
if (server.runningScriptMap.size > 0) {
helpers.log(ctx, () => `Cannot delete server '${hostname}' because it still has scripts running.`);
return false;
}
// Delete from player's purchasedServers array
let found = false;
for (let i = 0; i < Player.purchasedServers.length; ++i) {
if (hostname == Player.purchasedServers[i]) {
found = true;
Player.purchasedServers.splice(i, 1);
break;
2022-08-09 21:41:47 +02:00
}
}
if (!found) {
helpers.log(
ctx,
() => `Could not identify server ${hostname} as a purchased server. This is a bug. Report to dev.`,
);
return false;
}
// Delete from all servers
DeleteServer(hostname);
// Delete from home computer
found = false;
const homeComputer = Player.getHomeComputer();
for (let i = 0; i < homeComputer.serversOnNetwork.length; ++i) {
if (hostname == homeComputer.serversOnNetwork[i]) {
homeComputer.serversOnNetwork.splice(i, 1);
helpers.log(ctx, () => `Deleted server '${hostnameStr}`);
return true;
2022-08-09 21:41:47 +02:00
}
}
// Wasn't found on home computer
helpers.log(ctx, () => `Could not find server ${hostname} as a purchased server. This is a bug. Report to dev.`);
return false;
},
2022-08-09 21:41:47 +02:00
getPurchasedServers: () => (): string[] => {
const res: string[] = [];
Player.purchasedServers.forEach(function (hostname) {
res.push(hostname);
});
return res;
},
writePort: (ctx) => (_portNumber, data) => {
const portNumber = helpers.portNumber(ctx, _portNumber);
if (typeof data !== "string" && typeof data !== "number") {
throw helpers.makeRuntimeErrorMsg(
ctx,
`Trying to write invalid data to a port: only strings and numbers are valid.`,
);
}
return writePort(portNumber, data);
},
write: (ctx) => (_filename, _data, _mode) => {
const filepath = helpers.filePath(ctx, "filename", _filename);
const data = helpers.string(ctx, "data", _data ?? "");
const mode = helpers.string(ctx, "mode", _mode ?? "a");
const server = helpers.getServer(ctx, ctx.workerScript.hostname);
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
if (hasScriptExtension(filepath)) {
if (mode === "w") {
server.writeToScriptFile(filepath, data);
return;
2022-08-09 21:41:47 +02:00
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
const existingScript = server.scripts.get(filepath);
const existingCode = existingScript ? existingScript.code : "";
server.writeToScriptFile(filepath, existingCode + data);
return;
}
if (!hasTextExtension(filepath)) {
throw helpers.makeRuntimeErrorMsg(ctx, `File path should be a text file or script. ${filepath} is invalid.`);
}
if (mode === "w") {
server.writeToTextFile(filepath, data);
2022-08-24 04:06:05 +02:00
return;
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
const existingTextFile = server.textFiles.get(filepath);
const existingText = existingTextFile?.text ?? "";
server.writeToTextFile(filepath, mode === "w" ? data : existingText + data);
},
tryWritePort: (ctx) => (_portNumber, data) => {
const portNumber = helpers.portNumber(ctx, _portNumber);
if (typeof data !== "string" && typeof data !== "number") {
throw helpers.makeRuntimeErrorMsg(
ctx,
`Trying to write invalid data to a port: only strings and numbers are valid.`,
);
}
return tryWritePort(portNumber, data);
},
readPort: (ctx) => (_portNumber) => {
const portNumber = helpers.portNumber(ctx, _portNumber);
return readPort(portNumber);
},
read: (ctx) => (_filename) => {
const path = helpers.filePath(ctx, "filename", _filename);
if (!hasScriptExtension(path) && !hasTextExtension(path)) return "";
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
const server = ctx.workerScript.getServer();
return server.getContentFile(path)?.content ?? "";
},
peek: (ctx) => (_portNumber) => {
const portNumber = helpers.portNumber(ctx, _portNumber);
return peekPort(portNumber);
},
clear: (ctx) => (_file) => {
const path = helpers.filePath(ctx, "file", _file);
if (!hasScriptExtension(path) && !hasTextExtension(path)) {
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid file path or extension: ${_file}`);
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
const server = ctx.workerScript.getServer();
const file = server.getContentFile(path);
if (!file) throw helpers.makeRuntimeErrorMsg(ctx, `${path} does not exist on ${server.hostname}`);
// The content setter handles invalidating script modules where applicable.
file.content = "";
},
clearPort: (ctx) => (_portNumber) => {
const portNumber = helpers.portNumber(ctx, _portNumber);
return clearPort(portNumber);
},
getPortHandle: (ctx) => (_portNumber) => {
const portNumber = helpers.portNumber(ctx, _portNumber);
return portHandle(portNumber);
},
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
rm: (ctx) => (_fn, _hostname) => {
const filepath = helpers.filePath(ctx, "fn", _fn);
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
const hostname = helpers.string(ctx, "hostname", _hostname ?? ctx.workerScript.hostname);
const s = helpers.getServer(ctx, hostname);
if (!filepath) {
helpers.log(ctx, () => `Error while parsing filepath ${filepath}`);
return false;
}
2022-08-09 21:41:47 +02:00
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
const status = s.removeFile(filepath);
if (!status.res) {
helpers.log(ctx, () => status.msg + "");
}
2022-05-25 02:16:39 +02:00
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
return status.res;
},
scriptRunning: (ctx) => (_scriptname, _hostname) => {
const scriptname = helpers.scriptPath(ctx, "scriptname", _scriptname);
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
return server.isRunning(scriptname);
},
scriptKill: (ctx) => (_scriptname, _hostname) => {
const path = helpers.scriptPath(ctx, "scriptname", _scriptname);
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
let suc = false;
const pattern = matchScriptPathExact(escapeRegExp(path));
for (const [key, byPid] of server.runningScriptMap) {
if (!pattern.test(key)) continue;
suc = true;
for (const pid of byPid.keys()) {
killWorkerScriptByPid(pid);
2022-08-09 21:41:47 +02:00
}
}
return suc;
},
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
getScriptName: (ctx) => () => ctx.workerScript.name,
getScriptRam: (ctx) => (_scriptname, _hostname) => {
const path = helpers.scriptPath(ctx, "scriptname", _scriptname);
const hostname = helpers.string(ctx, "hostname", _hostname ?? ctx.workerScript.hostname);
const server = helpers.getServer(ctx, hostname);
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
const script = server.scripts.get(path);
if (!script) return 0;
const ramUsage = script.getRamUsage(server.scripts);
if (!ramUsage) {
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
helpers.log(ctx, () => `Could not calculate ram usage for ${path} on ${hostname}.`);
return 0;
}
return ramUsage;
},
2022-08-09 21:41:47 +02:00
getRunningScript:
(ctx) =>
(fn, hostname, ...args) => {
2022-08-09 21:41:47 +02:00
const ident = helpers.scriptIdentifier(ctx, fn, hostname, args);
2022-08-10 00:08:04 +02:00
const runningScript = helpers.getRunningScript(ctx, ident);
2022-08-09 21:41:47 +02:00
if (runningScript === null) return null;
2022-08-10 00:08:04 +02:00
return helpers.createPublicRunningScript(runningScript);
2022-08-09 21:41:47 +02:00
},
getHackTime:
(ctx) =>
(_hostname = ctx.workerScript.hostname) => {
2022-08-09 21:41:47 +02:00
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "invalid for this kind of server");
return Infinity;
}
if (helpers.failOnHacknetServer(ctx, server)) {
2022-08-09 21:41:47 +02:00
return Infinity;
}
2021-09-05 01:09:30 +02:00
2022-08-09 21:41:47 +02:00
return calculateHackingTime(server, Player) * 1000;
},
getGrowTime:
(ctx) =>
(_hostname = ctx.workerScript.hostname) => {
2022-08-09 21:41:47 +02:00
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "invalid for this kind of server");
return Infinity;
}
if (helpers.failOnHacknetServer(ctx, server)) {
2022-08-09 21:41:47 +02:00
return Infinity;
}
2022-08-09 21:41:47 +02:00
return calculateGrowTime(server, Player) * 1000;
},
getWeakenTime:
(ctx) =>
(_hostname = ctx.workerScript.hostname) => {
2022-08-09 21:41:47 +02:00
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "invalid for this kind of server");
return Infinity;
}
if (helpers.failOnHacknetServer(ctx, server)) {
2022-08-09 21:41:47 +02:00
return Infinity;
2022-07-20 01:04:06 +02:00
}
2022-08-09 21:41:47 +02:00
return calculateWeakenTime(server, Player) * 1000;
2022-07-20 01:04:06 +02:00
},
getTotalScriptIncome: () => () => {
2022-08-09 21:41:47 +02:00
// First element is total income of all currently running scripts
let total = 0;
for (const script of workerScripts.values()) {
total += script.scriptRef.onlineMoneyMade / script.scriptRef.onlineRunningTime;
}
2022-05-25 02:16:39 +02:00
2022-08-09 21:41:47 +02:00
return [total, Player.scriptProdSinceLastAug / (Player.playtimeSinceLastAug / 1000)];
},
getScriptIncome:
(ctx) =>
(fn, hostname, ...args) => {
2022-08-09 21:41:47 +02:00
const ident = helpers.scriptIdentifier(ctx, fn, hostname, args);
2022-08-10 00:08:04 +02:00
const runningScript = helpers.getRunningScript(ctx, ident);
2022-08-09 21:41:47 +02:00
if (runningScript == null) {
2022-08-10 00:08:04 +02:00
helpers.log(ctx, () => helpers.getCannotFindRunningScriptErrorMessage(ident));
2022-08-09 21:41:47 +02:00
return -1;
}
return runningScript.onlineMoneyMade / runningScript.onlineRunningTime;
},
getTotalScriptExpGain: () => () => {
2022-08-09 21:41:47 +02:00
let total = 0;
for (const ws of workerScripts.values()) {
total += ws.scriptRef.onlineExpGained / ws.scriptRef.onlineRunningTime;
}
return total;
},
getScriptExpGain:
(ctx) =>
(fn, hostname, ...args) => {
2022-08-09 21:41:47 +02:00
const ident = helpers.scriptIdentifier(ctx, fn, hostname, args);
2022-08-10 00:08:04 +02:00
const runningScript = helpers.getRunningScript(ctx, ident);
2022-08-09 21:41:47 +02:00
if (runningScript == null) {
2022-08-10 00:08:04 +02:00
helpers.log(ctx, () => helpers.getCannotFindRunningScriptErrorMessage(ident));
2022-08-09 21:41:47 +02:00
return -1;
}
return runningScript.onlineExpGained / runningScript.onlineRunningTime;
},
formatNumber:
(ctx) =>
(_n, _fractionalDigits = 3, _suffixStart = 1000, isInteger) => {
const n = helpers.number(ctx, "n", _n);
const fractionalDigits = helpers.number(ctx, "fractionalDigits", _fractionalDigits);
const suffixStart = helpers.number(ctx, "suffixStart", _suffixStart);
return formatNumber(n, fractionalDigits, suffixStart, !!isInteger);
},
formatRam:
(ctx) =>
(_n, _fractionalDigits = 2) => {
const n = helpers.number(ctx, "n", _n);
const fractionalDigits = helpers.number(ctx, "fractionalDigits", _fractionalDigits);
return formatRam(n, fractionalDigits);
},
formatPercent:
(ctx) =>
(_n, _fractionalDigits = 2, _multStart = 1e6) => {
const n = helpers.number(ctx, "n", _n);
const fractionalDigits = helpers.number(ctx, "fractionalDigits", _fractionalDigits);
const multStart = helpers.number(ctx, "multStart", _multStart);
return formatPercent(n, fractionalDigits, multStart);
},
// Todo: Remove function for real though in 2.4. Until then it just directly wraps numeral.
nFormat: (ctx) => (_n, _format) => {
deprecationWarning(
"ns.nFormat",
"Use ns.formatNumber, formatRam, formatPercent, or js builtins like Intl.NumberFormat instead.",
);
const n = helpers.number(ctx, "n", _n);
const format = helpers.string(ctx, "format", _format);
return numeral(n).format(format);
},
2022-10-25 02:09:10 +02:00
tFormat: (ctx) => (_milliseconds, _milliPrecision) => {
const milliseconds = helpers.number(ctx, "milliseconds", _milliseconds);
const milliPrecision = !!_milliPrecision;
return convertTimeMsToTimeElapsedString(milliseconds, milliPrecision);
},
getTimeSinceLastAug: () => () => {
deprecationWarning("ns.getTimeSinceLastAug()", "Use ns.getResetInfo().lastAugReset instead.");
2022-08-09 21:41:47 +02:00
return Player.playtimeSinceLastAug;
},
alert: (ctx) => (_message) => {
const message = helpers.string(ctx, "message", _message);
dialogBoxCreate(message, true);
},
2022-08-09 21:41:47 +02:00
toast:
(ctx) =>
(_message, _variant = ToastVariant.SUCCESS, _duration = 2000) => {
2022-08-09 21:41:47 +02:00
const message = helpers.string(ctx, "message", _message);
const variant = getEnumHelper("ToastVariant").nsGetMember(ctx, _variant);
const duration = _duration === null ? null : helpers.number(ctx, "duration", _duration);
SnackbarEvents.emit(message, variant as ToastVariant, duration);
2022-08-09 21:41:47 +02:00
},
prompt: (ctx) => (_txt, _options) => {
const options: { type?: string; choices?: string[] } = {};
_options ??= options;
const txt = helpers.string(ctx, "txt", _txt);
assert(_options, objectAssert, (type) =>
2022-10-14 17:08:24 +02:00
helpers.makeRuntimeErrorMsg(ctx, `Invalid type for options: ${type}. Should be object.`, "TYPE"),
);
if (_options.type !== undefined) {
assert(_options.type, stringAssert, (type) =>
2022-10-14 17:08:24 +02:00
helpers.makeRuntimeErrorMsg(ctx, `Invalid type for options.type: ${type}. Should be string.`, "TYPE"),
);
options.type = _options.type;
const validTypes = ["boolean", "text", "select"];
if (!["boolean", "text", "select"].includes(options.type)) {
throw helpers.makeRuntimeErrorMsg(
ctx,
`Invalid value for options.type: ${options.type}. Must be one of ${validTypes.join(", ")}.`,
);
2022-08-09 21:41:47 +02:00
}
if (options.type === "select") {
assert(_options.choices, arrayAssert, (type) =>
helpers.makeRuntimeErrorMsg(
ctx,
`Invalid type for options.choices: ${type}. If options.type is "select", options.choices must be an array.`,
"TYPE",
),
);
options.choices = _options.choices.map((choice, i) => helpers.string(ctx, `options.choices[${i}]`, choice));
}
}
return new Promise(function (resolve) {
PromptEvent.emit({
txt: txt,
options,
resolve: resolve,
});
});
},
wget: (ctx) => (_url, _target, _hostname) => {
const url = helpers.string(ctx, "url", _url);
2023-04-28 17:14:29 +02:00
const target = helpers.filePath(ctx, "target", _target);
const hostname = _hostname ? helpers.string(ctx, "hostname", _hostname) : ctx.workerScript.hostname;
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
const server = helpers.getServer(ctx, hostname);
if (!target || (!hasTextExtension(target) && !hasScriptExtension(target))) {
helpers.log(ctx, () => `Invalid target file: '${target}'. Must be a script or text file.`);
return Promise.resolve(false);
}
return new Promise(function (resolve) {
$.get(
url,
function (data) {
2023-04-28 17:49:05 +02:00
const res = server.writeToContentFile(target, data);
if (res.overwritten) {
helpers.log(ctx, () => `Successfully retrieved content and overwrote '${target}' on '${hostname}'`);
2022-08-09 21:41:47 +02:00
return resolve(true);
}
helpers.log(ctx, () => `Successfully retrieved content to new file '${target}' on '${hostname}'`);
return resolve(true);
},
"text",
).fail(function (e) {
helpers.log(ctx, () => JSON.stringify(e));
return resolve(false);
2022-08-09 21:41:47 +02:00
});
});
},
getFavorToDonate: () => () => {
return Math.floor(CONSTANTS.BaseFavorToDonate * currentNodeMults.RepToDonateToFaction);
2022-08-09 21:41:47 +02:00
},
getPlayer: () => () => {
2022-08-09 21:41:47 +02:00
const data = {
// Person
NETSCRIPT: ns.sleeve.getSleeve added. getPlayer and getSleeve can both be used for formulas. (#200) * BREAKING CHANGE: Removed getSleeveStats and getSleeveInformation because this info is provided by getSleeve in a more usable form. * BREAKING CHANGE: Removed tor, inBladeburner, and hasCorporation fields from ns.getPlayer. Functionality still exists via added functions ns.hasTorRouter, ns.corporation.hasCorporation, and ns.bladeburner.inBladeburner. * Separated ns definitions for Person, Sleeve, and Player interfaces with both Player and Sleeve just extending Person. Added getSleeve, which provides a Sleeve object similar to getPlayer. * Renamed the sleeve ns layer's interface as sleeve lowercase because of name conflict. todo: May move all the ns layers interface names to lowercase for consistency * Added ns.formulas.work.crimeSuccessChance and reworked to allow both sleeve and player calculations. * Removed internal Person.getIntelligenceBonus function which was just a wrapper for calculateIntelligenceBonus. Any use of the former in formulas creates a conflict where ns-provided Person objects throw an error. * Renamed helpers.player to helpers.person for netscript person validation. Reduced number of fields validated due to Person being a smaller interface. * Fixed bug in bladeburner where Player multipliers and int were being used no matter which person was performing the task * Fixed leak of Player.jobs at ns.getPlayer * Person / Player / Sleeve classes now implement the netscript equivalent interfaces. Netscript helper for person no longer asserts that it's a real Person class member, only that it's a Person interface. Functions that use netscript persons have been changed to expect just a person interface to prevent needing this incorrect type assertion.
2022-11-09 13:26:26 +01:00
hp: cloneDeep(Player.hp),
skills: cloneDeep(Player.skills),
exp: cloneDeep(Player.exp),
mults: cloneDeep(Player.mults),
city: Player.city,
// Player-specific
2022-08-09 21:41:47 +02:00
numPeopleKilled: Player.numPeopleKilled,
money: Player.money,
location: Player.location,
totalPlaytime: Player.totalPlaytime,
NETSCRIPT: ns.sleeve.getSleeve added. getPlayer and getSleeve can both be used for formulas. (#200) * BREAKING CHANGE: Removed getSleeveStats and getSleeveInformation because this info is provided by getSleeve in a more usable form. * BREAKING CHANGE: Removed tor, inBladeburner, and hasCorporation fields from ns.getPlayer. Functionality still exists via added functions ns.hasTorRouter, ns.corporation.hasCorporation, and ns.bladeburner.inBladeburner. * Separated ns definitions for Person, Sleeve, and Player interfaces with both Player and Sleeve just extending Person. Added getSleeve, which provides a Sleeve object similar to getPlayer. * Renamed the sleeve ns layer's interface as sleeve lowercase because of name conflict. todo: May move all the ns layers interface names to lowercase for consistency * Added ns.formulas.work.crimeSuccessChance and reworked to allow both sleeve and player calculations. * Removed internal Person.getIntelligenceBonus function which was just a wrapper for calculateIntelligenceBonus. Any use of the former in formulas creates a conflict where ns-provided Person objects throw an error. * Renamed helpers.player to helpers.person for netscript person validation. Reduced number of fields validated due to Person being a smaller interface. * Fixed bug in bladeburner where Player multipliers and int were being used no matter which person was performing the task * Fixed leak of Player.jobs at ns.getPlayer * Person / Player / Sleeve classes now implement the netscript equivalent interfaces. Netscript helper for person no longer asserts that it's a real Person class member, only that it's a Person interface. Functions that use netscript persons have been changed to expect just a person interface to prevent needing this incorrect type assertion.
2022-11-09 13:26:26 +01:00
jobs: cloneDeep(Player.jobs),
2022-08-09 21:41:47 +02:00
factions: Player.factions.slice(),
entropy: Player.entropy,
};
setDeprecatedProperties(data, {
playtimeSinceLastAug: {
identifier: "ns.getPlayer().playtimeSinceLastAug",
message: "Use ns.getResetInfo().lastAugReset instead. This is a static timestamp instead of an elapsed time.",
value: Player.playtimeSinceLastAug,
},
playtimeSinceLastBitnode: {
identifier: "ns.getPlayer().playtimeSinceLastBitnode",
message: "Use ns.getResetInfo().lastNodeReset instead. This is a static timestamp instead of an elapsed time.",
value: Player.playtimeSinceLastBitnode,
},
bitNodeN: {
identifier: "ns.getPlayer().bitNodeN",
2023-05-16 05:12:17 +02:00
message: "Use ns.getResetInfo().currentNode instead",
value: Player.bitNodeN,
},
});
2022-08-09 21:41:47 +02:00
return data;
},
2022-10-13 07:07:10 +02:00
getMoneySources: () => () => ({
2022-10-13 06:55:57 +02:00
sinceInstall: Object.assign({}, Player.moneySourceA),
sinceStart: Object.assign({}, Player.moneySourceB),
}),
atExit: (ctx) => (f) => {
if (typeof f !== "function") {
throw helpers.makeRuntimeErrorMsg(ctx, "argument should be function");
}
ctx.workerScript.atExit = () => {
f();
}; // Wrap the user function to prevent WorkerScript leaking as 'this'
},
mv: (ctx) => (_host, _source, _destination) => {
const hostname = helpers.string(ctx, "host", _host);
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
const server = helpers.getServer(ctx, hostname);
const sourcePath = helpers.filePath(ctx, "source", _source);
const destinationPath = helpers.filePath(ctx, "destination", _destination);
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
if (
(!hasTextExtension(sourcePath) && !hasScriptExtension(sourcePath)) ||
(!hasTextExtension(destinationPath) && !hasScriptExtension(destinationPath))
) {
throw helpers.makeRuntimeErrorMsg(ctx, `'mv' can only be used on scripts and text files (.txt)`);
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
}
if (sourcePath === destinationPath) {
helpers.log(ctx, () => "WARNING: Did nothing, source and destination paths were the same.");
return;
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
const sourceContentFile = server.getContentFile(sourcePath);
if (!sourceContentFile) {
throw helpers.makeRuntimeErrorMsg(ctx, `Source text file ${sourcePath} does not exist on ${hostname}`);
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
const success = sourceContentFile.deleteFromServer(server);
if (success) {
const { overwritten } = server.writeToContentFile(destinationPath, sourceContentFile.content);
if (overwritten) helpers.log(ctx, () => `WARNING: Overwriting file ${destinationPath} on ${hostname}`);
helpers.log(ctx, () => `Moved ${sourcePath} to ${destinationPath} on ${hostname}`);
return;
}
FILES: Path rework & typesafety (#479) * Added new types for various file paths, all in the Paths folder. * TypeSafety and other helper functions related to these types * Added basic globbing support with * and ?. Currently only implemented for Script/Text, on nano and download terminal commands * Enforcing the new types throughout the codebase, plus whatever rewrites happened along the way * Server.textFiles is now a map * TextFile no longer uses a fn property, now it is filename * Added a shared ContentFile interface for shared functionality between TextFile and Script. * related to ContentFile change above, the player is now allowed to move a text file to a script file and vice versa. * File paths no longer conditionally start with slashes, and all directory names other than root have ending slashes. The player is still able to provide paths starting with / but this now indicates that the player is specifying an absolute path instead of one relative to root. * Singularized the MessageFilename and LiteratureName enums * Because they now only accept correct types, server.writeToXFile functions now always succeed (the only reasons they could fail before were invalid filepath). * Fix several issues with tab completion, which included pretty much a complete rewrite * Changed the autocomplete display options so there's less chance it clips outside the display area. * Turned CompletedProgramName into an enum. * Got rid of programsMetadata, and programs and DarkWebItems are now initialized immediately instead of relying on initializers called from the engine. * For any executable (program, cct, or script file) pathing can be used directly to execute without using the run command (previously the command had to start with ./ and it wasn't actually using pathing).
2023-04-24 16:26:57 +02:00
helpers.log(ctx, () => `ERROR: Failed. Was unable to remove file ${sourcePath} from its original location.`);
},
getResetInfo: () => () => ({
lastAugReset: Player.lastAugReset,
lastNodeReset: Player.lastNodeReset,
currentNode: Player.bitNodeN,
ownedAugs: new Map(Player.augmentations.map((aug) => [aug.name, aug.level])),
ownedSF: new Map(Player.sourceFiles),
}),
2023-05-26 13:46:08 +02:00
getFunctionRamCost: (ctx) => (_name) => {
const name = helpers.string(ctx, "name", _name);
return getRamCost(...name.split("."));
},
tprintRaw: () => (value) => {
Terminal.printRaw(wrapUserNode(value));
},
printRaw: (ctx) => (value) => {
ctx.workerScript.print(wrapUserNode(value));
},
2022-08-09 21:41:47 +02:00
flags: Flags,
...NetscriptExtra(),
};
2023-01-02 19:18:02 +01:00
// Object.assign to bypass ts for removedFunctions which have no documentation or ramcost
Object.assign(ns, {
getServerRam: removedFunction("v2.2.0", "getServerMaxRam and getServerUsedRam"),
});
export function NetscriptFunctions(ws: WorkerScript): NSFull {
return NSProxy(ws, ns, [], { args: ws.args.slice(), pid: ws.pid, enums });
}
2022-08-29 08:41:17 +02:00
const possibleLogs = Object.fromEntries([...getFunctionNames(ns, "")].map((a) => [a, true]));
/** Provides an array of all function names on a nested object */
function getFunctionNames(obj: object, prefix: string): string[] {
const functionNames: string[] = [];
for (const [key, value] of Object.entries(obj)) {
if (key === "args") {
continue;
} else if (typeof value == "function") {
functionNames.push(prefix + key);
} else if (typeof value == "object") {
functionNames.push(...getFunctionNames(value, key + "."));
}
}
return functionNames;
}
const deprecatedWarningsGiven = new Set();
function setDeprecatedProperties(
obj: object,
properties: Record<string, { identifier: string; message: string; value: any }>,
) {
for (const [name, info] of Object.entries(properties)) {
Object.defineProperty(obj, name, {
get: () => {
deprecationWarning(info.identifier, info.message);
return info.value;
},
set: (value: any) => (info.value = value),
enumerable: true,
});
}
}
function deprecationWarning(identifier: string, message: string) {
if (!deprecatedWarningsGiven.has(identifier)) {
deprecatedWarningsGiven.add(identifier);
Terminal.warn(`Accessed deprecated function or property: ${identifier}`);
Terminal.warn(`This is no longer supported usage and will be removed in a later version.`);
Terminal.warn(message);
Terminal.info(`This message can also appear for object properties when the object's values are iterated.`);
Terminal.info(`This message will only be shown once per game session for each deprecated item accessed.`);
}
}