Move entire ns object to top-level

This commit is contained in:
Snarling 2022-08-09 15:41:47 -04:00
parent 589b9df2a7
commit 931ea730a5
18 changed files with 2169 additions and 2110 deletions

@ -2,6 +2,8 @@ import { getRamCost } from "./RamCostGenerator";
import type { WorkerScript } from "./WorkerScript";
import { Player } from "../Player";
import { helpers } from "./NetscriptHelpers";
import { ScriptArg } from "./ScriptArg";
import { NSEnums } from "src/ScriptEditor/NetscriptDefinitions";
type ExternalFunction = (...args: unknown[]) => unknown;
export type ExternalAPI = {
@ -13,6 +15,10 @@ type InternalFunction<F extends (...args: unknown[]) => unknown> = (ctx: Netscri
export type InternalAPI<API> = {
[Property in keyof API]: API[Property] extends ExternalFunction
? InternalFunction<API[Property]>
: API[Property] extends NSEnums
? NSEnums
: API[Property] extends ScriptArg[]
? ScriptArg[]
: API[Property] extends object
? InternalAPI<API[Property]>
: never;

@ -26,6 +26,8 @@ import { IPlayer } from "../PersonObjects/IPlayer";
import { FormulaGang } from "../Gang/formulas/formulas";
import { GangMember } from "../Gang/GangMember";
import { GangMemberTask } from "../Gang/GangMemberTask";
import { RunningScript } from "../Script/RunningScript";
import { toNative } from "../NetscriptFunctions/toNative";
//Helpers that are not specific to use in WorkerScripts/NetscriptContexts should be in src/utils/helpers instead
@ -34,6 +36,7 @@ export const helpers = {
string,
number,
scriptArgs,
argsToString,
isScriptErrorMessage,
//Error checking and generation
makeRuntimeRejectMsg,
@ -56,6 +59,7 @@ export const helpers = {
gangMember,
gangTask,
log,
getRunningScriptByArgs,
};
export type ScriptIdentifier = //This was previously in INetscriptHelper.ts, may move to its own file or a generic types file.
@ -66,12 +70,14 @@ export type ScriptIdentifier = //This was previously in INetscriptHelper.ts, ma
args: ScriptArg[];
};
/** If v is a number or string, returns the string representation. Error for other non-strings. */
function string(ctx: NetscriptContext, argName: string, v: unknown): string {
if (typeof v === "string") return v;
if (typeof v === "number") return v + ""; // cast to string;
throw makeRuntimeErrorMsg(ctx, `'${argName}' should be a string.`);
}
/** Validates v as non-NaN number, or as a string representation of a number, and returns that number. Error on NaN or non-number. */
function number(ctx: NetscriptContext, argName: string, v: unknown): number {
if (typeof v === "string") {
const x = parseFloat(v);
@ -83,11 +89,13 @@ function number(ctx: NetscriptContext, argName: string, v: unknown): number {
throw makeRuntimeErrorMsg(ctx, `'${argName}' should be a number.`);
}
/** Validates args as a ScriptArg[]. Throws an error if it is not. */
function scriptArgs(ctx: NetscriptContext, args: unknown) {
if (!isScriptArgs(args)) throw makeRuntimeErrorMsg(ctx, "'args' is not an array of script args");
return args;
}
/** Determines if the given msg string is an error created by makeRuntimeRejectMsg. */
function isScriptErrorMessage(msg: string): boolean {
if (!isString(msg)) {
return false;
@ -96,6 +104,26 @@ function isScriptErrorMessage(msg: string): boolean {
return splitMsg.length == 4;
}
/** Used to convert multiple arguments for tprint or print into a single string. */
function argsToString(args: unknown[]): string {
let out = "";
for (let arg of args) {
if (arg === null) {
out += "null";
continue;
}
if (arg === undefined) {
out += "undefined";
continue;
}
arg = toNative(arg);
out += typeof arg === "object" ? JSON.stringify(arg) : `${arg}`;
}
return out;
}
/** Creates an error message string containing hostname, scriptname, and the error message msg */
function makeRuntimeRejectMsg(workerScript: WorkerScript, msg: string): string {
for (const scriptUrl of workerScript.scriptRef.dependencies) {
msg = msg.replace(new RegExp(scriptUrl.url, "g"), scriptUrl.filename);
@ -104,6 +132,7 @@ function makeRuntimeRejectMsg(workerScript: WorkerScript, msg: string): string {
return "|DELIMITER|" + workerScript.hostname + "|DELIMITER|" + workerScript.name + "|DELIMITER|" + msg;
}
/** Creates an error message string with a stack trace. */
function makeRuntimeErrorMsg(ctx: NetscriptContext, msg: string): string {
const errstack = new Error().stack;
if (errstack === undefined) throw new Error("how did we not throw an error?");
@ -174,6 +203,7 @@ function makeRuntimeErrorMsg(ctx: NetscriptContext, msg: string): string {
return makeRuntimeRejectMsg(workerScript, rejectMsg);
}
/** Validate requested number of threads for h/g/w options */
function resolveNetscriptRequestedThreads(ctx: NetscriptContext, requestedThreads?: number): number {
const threads = ctx.workerScript.scriptRef.threads;
if (!requestedThreads) {
@ -195,6 +225,7 @@ function resolveNetscriptRequestedThreads(ctx: NetscriptContext, requestedThread
return requestedThreadsAsInt;
}
/** Validate singularity access by throwing an error if the player does not have access. */
function checkSingularityAccess(ctx: NetscriptContext): void {
if (Player.bitNodeN !== 4 && Player.sourceFileLvl(4) === 0) {
throw makeRuntimeErrorMsg(
@ -205,6 +236,7 @@ function checkSingularityAccess(ctx: NetscriptContext): void {
}
}
/** Create an error if a script is dead or if concurrent ns function calls are made */
function checkEnvFlags(ctx: NetscriptContext): void {
const ws = ctx.workerScript;
if (ws.env.stopFlag) throw new ScriptDeath(ws);
@ -503,3 +535,42 @@ function gangTask(ctx: NetscriptContext, t: unknown): GangMemberTask {
function log(ctx: NetscriptContext, message: () => string) {
ctx.workerScript.log(ctx.functionPath, message);
}
/**
* Searches for and returns the RunningScript object for the specified script.
* If the 'fn' argument is not specified, this returns the current RunningScript.
* @param {string} fn - Filename of script
* @param {string} hostname - Hostname/ip of the server on which the script resides
* @param {any[]} scriptArgs - Running script's arguments
* @returns {RunningScript}
* Running script identified by the parameters, or null if no such script
* exists, or the current running script if the first argument 'fn'
* is not specified.
*/
function getRunningScriptByArgs(
ctx: NetscriptContext,
fn: string,
hostname: string,
scriptArgs: ScriptArg[],
): RunningScript | null {
if (!Array.isArray(scriptArgs)) {
throw helpers.makeRuntimeRejectMsg(
ctx.workerScript,
`Invalid scriptArgs argument passed into getRunningScript() from ${ctx.function}(). ` +
`This is probably a bug. Please report to game developer`,
);
}
if (fn != null && typeof fn === "string") {
// Get Logs of another script
if (hostname == null) {
hostname = ctx.workerScript.hostname;
}
const server = helpers.getServer(ctx, hostname);
return findRunningScript(fn, scriptArgs, server);
}
// If no arguments are specified, return the current RunningScript
return ctx.workerScript.scriptRef;
}

File diff suppressed because it is too large Load Diff

@ -1,5 +1,4 @@
import { WorkerScript } from "../Netscript/WorkerScript";
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { Bladeburner } from "../Bladeburner/Bladeburner";
import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers";
import { Bladeburner as INetscriptBladeburner, BladeburnerCurAction } from "../ScriptEditor/NetscriptDefinitions";
@ -8,7 +7,7 @@ import { InternalAPI, NetscriptContext } from "src/Netscript/APIWrapper";
import { BlackOperation } from "../Bladeburner/BlackOperation";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript): InternalAPI<INetscriptBladeburner> {
export function NetscriptBladeburner(): InternalAPI<INetscriptBladeburner> {
const checkBladeburnerAccess = function (ctx: NetscriptContext, skipjoined = false): void {
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Must have joined bladeburner");
@ -102,7 +101,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
try {
return bladeburner.startActionNetscriptFn(player, type, name, workerScript);
return bladeburner.startActionNetscriptFn(player, type, name, ctx.workerScript);
} catch (e: unknown) {
throw helpers.makeRuntimeErrorMsg(ctx, String(e));
}
@ -200,7 +199,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
try {
return bladeburner.getActionCountRemainingNetscriptFn(type, name, workerScript);
return bladeburner.getActionCountRemainingNetscriptFn(type, name, ctx.workerScript);
} catch (e: unknown) {
throw helpers.makeRuntimeErrorMsg(ctx, String(e));
}
@ -275,7 +274,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
try {
return bladeburner.getSkillLevelNetscriptFn(skillName, workerScript);
return bladeburner.getSkillLevelNetscriptFn(skillName, ctx.workerScript);
} catch (e: unknown) {
throw helpers.makeRuntimeErrorMsg(ctx, String(e));
}
@ -289,7 +288,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
try {
return bladeburner.getSkillUpgradeCostNetscriptFn(skillName, count, workerScript);
return bladeburner.getSkillUpgradeCostNetscriptFn(skillName, count, ctx.workerScript);
} catch (e: unknown) {
throw helpers.makeRuntimeErrorMsg(ctx, String(e));
}
@ -303,7 +302,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
try {
return bladeburner.upgradeSkillNetscriptFn(skillName, count, workerScript);
return bladeburner.upgradeSkillNetscriptFn(skillName, count, ctx.workerScript);
} catch (e: unknown) {
throw helpers.makeRuntimeErrorMsg(ctx, String(e));
}
@ -317,7 +316,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
try {
return bladeburner.getTeamSizeNetscriptFn(type, name, workerScript);
return bladeburner.getTeamSizeNetscriptFn(type, name, ctx.workerScript);
} catch (e: unknown) {
throw helpers.makeRuntimeErrorMsg(ctx, String(e));
}
@ -332,7 +331,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
try {
return bladeburner.setTeamSizeNetscriptFn(type, name, size, workerScript);
return bladeburner.setTeamSizeNetscriptFn(type, name, size, ctx.workerScript);
} catch (e: unknown) {
throw helpers.makeRuntimeErrorMsg(ctx, String(e));
}
@ -394,7 +393,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
checkBladeburnerAccess(ctx, true);
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
return bladeburner.joinBladeburnerFactionNetscriptFn(workerScript);
return bladeburner.joinBladeburnerFactionNetscriptFn(ctx.workerScript);
},
joinBladeburnerDivision: (ctx: NetscriptContext) => (): boolean => {
if (player.bitNodeN === 7 || player.sourceFileLvl(7) > 0) {

@ -1,12 +1,11 @@
import { WorkerScript } from "../Netscript/WorkerScript";
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { is2DArray } from "../utils/helpers/is2DArray";
import { CodingContract } from "../CodingContracts";
import { CodingAttemptOptions, CodingContract as ICodingContract } from "../ScriptEditor/NetscriptDefinitions";
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptCodingContract(player: IPlayer, workerScript: WorkerScript): InternalAPI<ICodingContract> {
export function NetscriptCodingContract(): InternalAPI<ICodingContract> {
const getCodingContract = function (
ctx: NetscriptContext,
func: string,
@ -28,7 +27,7 @@ export function NetscriptCodingContract(player: IPlayer, workerScript: WorkerScr
(
answer: unknown,
_filename: unknown,
_hostname: unknown = workerScript.hostname,
_hostname: unknown = ctx.workerScript.hostname,
{ returnReward }: CodingAttemptOptions = { returnReward: false },
): boolean | string => {
const filename = helpers.string(ctx, "filename", _filename);
@ -78,7 +77,7 @@ export function NetscriptCodingContract(player: IPlayer, workerScript: WorkerScr
},
getContractType:
(ctx: NetscriptContext) =>
(_filename: unknown, _hostname: unknown = workerScript.hostname): string => {
(_filename: unknown, _hostname: unknown = ctx.workerScript.hostname): string => {
const filename = helpers.string(ctx, "filename", _filename);
const hostname = helpers.string(ctx, "hostname", _hostname);
const contract = getCodingContract(ctx, "getContractType", hostname, filename);
@ -86,7 +85,7 @@ export function NetscriptCodingContract(player: IPlayer, workerScript: WorkerScr
},
getData:
(ctx: NetscriptContext) =>
(_filename: unknown, _hostname: unknown = workerScript.hostname): unknown => {
(_filename: unknown, _hostname: unknown = ctx.workerScript.hostname): unknown => {
const filename = helpers.string(ctx, "filename", _filename);
const hostname = helpers.string(ctx, "hostname", _hostname);
const contract = getCodingContract(ctx, "getData", hostname, filename);
@ -109,7 +108,7 @@ export function NetscriptCodingContract(player: IPlayer, workerScript: WorkerScr
},
getDescription:
(ctx: NetscriptContext) =>
(_filename: unknown, _hostname: unknown = workerScript.hostname): string => {
(_filename: unknown, _hostname: unknown = ctx.workerScript.hostname): string => {
const filename = helpers.string(ctx, "filename", _filename);
const hostname = helpers.string(ctx, "hostname", _hostname);
const contract = getCodingContract(ctx, "getDescription", hostname, filename);
@ -117,7 +116,7 @@ export function NetscriptCodingContract(player: IPlayer, workerScript: WorkerScr
},
getNumTriesRemaining:
(ctx: NetscriptContext) =>
(_filename: unknown, _hostname: unknown = workerScript.hostname): number => {
(_filename: unknown, _hostname: unknown = ctx.workerScript.hostname): number => {
const filename = helpers.string(ctx, "filename", _filename);
const hostname = helpers.string(ctx, "hostname", _hostname);
const contract = getCodingContract(ctx, "getNumTriesRemaining", hostname, filename);

@ -1,4 +1,4 @@
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { OfficeSpace } from "../Corporation/OfficeSpace";
import { Employee } from "../Corporation/Employee";
@ -68,7 +68,7 @@ import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers";
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptCorporation(player: IPlayer): InternalAPI<NSCorporation> {
export function NetscriptCorporation(): InternalAPI<NSCorporation> {
function createCorporation(corporationName: string, selfFund = true): boolean {
if (!player.canAccessCorporation() || player.hasCorporation()) return false;
if (!corporationName) return false;

@ -1,4 +1,4 @@
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { Exploit } from "../Exploits/Exploit";
import * as bcrypt from "bcryptjs";
import { Apr1Events as devMenu } from "../ui/Apr1";
@ -16,7 +16,7 @@ export interface INetscriptExtra {
rainbow(guess: string): void;
}
export function NetscriptExtra(player: IPlayer): InternalAPI<INetscriptExtra> {
export function NetscriptExtra(): InternalAPI<INetscriptExtra> {
return {
heart: {
// Easter egg function

@ -1,41 +1,42 @@
import { toNative } from "./toNative";
import libarg from "arg";
import { ScriptArg } from "../Netscript/ScriptArg";
import { NetscriptContext } from "../Netscript/APIWrapper";
type FlagType = StringConstructor | NumberConstructor | BooleanConstructor | StringConstructor[];
type FlagsRet = { [key: string]: ScriptArg };
export function Flags(vargs: string[]): () => (data: unknown) => FlagsRet {
return (/* ctx: NetscriptContext */) =>
(schema: unknown): FlagsRet => {
schema = toNative(schema);
if (!Array.isArray(schema)) throw new Error("flags schema passed in is invalid.");
const args: {
[key: string]: FlagType;
} = {};
export function Flags(ctx: NetscriptContext | string[]): (data: unknown) => FlagsRet {
const vargs = Array.isArray(ctx) ? ctx : ctx.workerScript.args;
return (schema: unknown): FlagsRet => {
schema = toNative(schema);
if (!Array.isArray(schema)) throw new Error("flags schema passed in is invalid.");
const args: {
[key: string]: FlagType;
} = {};
for (const d of schema) {
let t: FlagType = String;
if (typeof d[1] === "number") {
t = Number;
} else if (typeof d[1] === "boolean") {
t = Boolean;
} else if (Array.isArray(d[1])) {
t = [String];
}
const numDashes = d[0].length > 1 ? 2 : 1;
args["-".repeat(numDashes) + d[0]] = t;
for (const d of schema) {
let t: FlagType = String;
if (typeof d[1] === "number") {
t = Number;
} else if (typeof d[1] === "boolean") {
t = Boolean;
} else if (Array.isArray(d[1])) {
t = [String];
}
const ret: FlagsRet = libarg(args, { argv: vargs });
for (const d of schema) {
if (!ret.hasOwnProperty("--" + d[0]) || !ret.hasOwnProperty("-" + d[0])) ret[d[0]] = d[1];
}
for (const key of Object.keys(ret)) {
if (!key.startsWith("-")) continue;
const value = ret[key];
delete ret[key];
const numDashes = key.length === 2 ? 1 : 2;
ret[key.slice(numDashes)] = value;
}
return ret;
};
const numDashes = d[0].length > 1 ? 2 : 1;
args["-".repeat(numDashes) + d[0]] = t;
}
const ret: FlagsRet = libarg(args, { argv: vargs });
for (const d of schema) {
if (!ret.hasOwnProperty("--" + d[0]) || !ret.hasOwnProperty("-" + d[0])) ret[d[0]] = d[1];
}
for (const key of Object.keys(ret)) {
if (!key.startsWith("-")) continue;
const value = ret[key];
delete ret[key];
const numDashes = key.length === 2 ? 1 : 2;
ret[key.slice(numDashes)] = value;
}
return ret;
};
}

@ -1,4 +1,4 @@
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { calculateServerGrowth } from "../Server/formulas/grow";
import {
calculateMoneyGainRate,
@ -44,7 +44,7 @@ import { repFromDonation } from "../Faction/formulas/donation";
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptFormulas(player: IPlayer): InternalAPI<IFormulas> {
export function NetscriptFormulas(): InternalAPI<IFormulas> {
const checkFormulasAccess = function (ctx: NetscriptContext): void {
if (!player.hasProgram(Programs.Formulas.name)) {
throw helpers.makeRuntimeErrorMsg(ctx, `Requires Formulas.exe to run.`);

@ -1,11 +1,10 @@
import { FactionNames } from "../Faction/data/FactionNames";
import { GangConstants } from "../Gang/data/Constants";
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { Gang } from "../Gang/Gang";
import { AllGangs } from "../Gang/AllGangs";
import { GangMemberTasks } from "../Gang/GangMemberTasks";
import { GangMemberUpgrades } from "../Gang/GangMemberUpgrades";
import { WorkerScript } from "../Netscript/WorkerScript";
import { GangMember } from "../Gang/GangMember";
import { GangMemberTask } from "../Gang/GangMemberTask";
import { helpers } from "../Netscript/NetscriptHelpers";
@ -22,7 +21,7 @@ import {
} from "../ScriptEditor/NetscriptDefinitions";
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
export function NetscriptGang(player: IPlayer, workerScript: WorkerScript): InternalAPI<IGang> {
export function NetscriptGang(): InternalAPI<IGang> {
const checkGangApiAccess = function (ctx: NetscriptContext): void {
const gang = player.gang;
if (gang === null) throw new Error("Must have joined gang");
@ -170,9 +169,9 @@ export function NetscriptGang(player: IPlayer, workerScript: WorkerScript): Inte
if (gang === null) throw new Error("Should not be called without Gang");
const recruited = gang.recruitMember(memberName);
if (recruited) {
workerScript.log("gang.recruitMember", () => `Successfully recruited Gang Member '${memberName}'`);
ctx.workerScript.log("gang.recruitMember", () => `Successfully recruited Gang Member '${memberName}'`);
} else {
workerScript.log("gang.recruitMember", () => `Failed to recruit Gang Member '${memberName}'`);
ctx.workerScript.log("gang.recruitMember", () => `Failed to recruit Gang Member '${memberName}'`);
}
return recruited;
@ -195,7 +194,7 @@ export function NetscriptGang(player: IPlayer, workerScript: WorkerScript): Inte
const gang = player.gang;
if (gang === null) throw new Error("Should not be called without Gang");
if (!gang.getAllTaskNames().includes(taskName)) {
workerScript.log(
ctx.workerScript.log(
"gang.setMemberTask",
() =>
`Failed to assign Gang Member '${memberName}' to Invalid task '${taskName}'. '${memberName}' is now Unassigned`,
@ -204,12 +203,12 @@ export function NetscriptGang(player: IPlayer, workerScript: WorkerScript): Inte
}
const success = member.assignToTask(taskName);
if (success) {
workerScript.log(
ctx.workerScript.log(
"gang.setMemberTask",
() => `Successfully assigned Gang Member '${memberName}' to '${taskName}' task`,
);
} else {
workerScript.log(
ctx.workerScript.log(
"gang.setMemberTask",
() =>
`Failed to assign Gang Member '${memberName}' to '${taskName}' task. '${memberName}' is now Unassigned`,
@ -277,9 +276,9 @@ export function NetscriptGang(player: IPlayer, workerScript: WorkerScript): Inte
if (!equipment) return false;
const res = member.buyUpgrade(equipment, player, gang);
if (res) {
workerScript.log("gang.purchaseEquipment", () => `Purchased '${equipName}' for Gang member '${memberName}'`);
ctx.workerScript.log("gang.purchaseEquipment", () => `Purchased '${equipName}' for Gang member '${memberName}'`);
} else {
workerScript.log(
ctx.workerScript.log(
"gang.purchaseEquipment",
() => `Failed to purchase '${equipName}' for Gang member '${memberName}'`,
);
@ -296,7 +295,7 @@ export function NetscriptGang(player: IPlayer, workerScript: WorkerScript): Inte
if (gang === null) throw new Error("Should not be called without Gang");
const member = getGangMember(ctx, memberName);
if (!member.canAscend()) return;
return gang.ascendMember(member, workerScript);
return gang.ascendMember(member, ctx.workerScript);
},
getAscensionResult:
(ctx: NetscriptContext) =>
@ -321,10 +320,10 @@ export function NetscriptGang(player: IPlayer, workerScript: WorkerScript): Inte
if (gang === null) throw new Error("Should not be called without Gang");
if (engage) {
gang.territoryWarfareEngaged = true;
workerScript.log("gang.setTerritoryWarfare", () => "Engaging in Gang Territory Warfare");
ctx.workerScript.log("gang.setTerritoryWarfare", () => "Engaging in Gang Territory Warfare");
} else {
gang.territoryWarfareEngaged = false;
workerScript.log("gang.setTerritoryWarfare", () => "Disengaging in Gang Territory Warfare");
ctx.workerScript.log("gang.setTerritoryWarfare", () => "Disengaging in Gang Territory Warfare");
}
},
getChanceToWinClash:

@ -4,13 +4,13 @@ import { hasAugmentationPrereqs } from "../Faction/FactionHelpers";
import { CityName } from "../Locations/data/CityNames";
import { GraftableAugmentation } from "../PersonObjects/Grafting/GraftableAugmentation";
import { getGraftingAvailableAugs, calculateGraftingTimeWithBonus } from "../PersonObjects/Grafting/GraftingHelpers";
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { Grafting as IGrafting } from "../ScriptEditor/NetscriptDefinitions";
import { Router } from "../ui/GameRoot";
import { GraftingWork } from "../Work/GraftingWork";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptGrafting(player: IPlayer): InternalAPI<IGrafting> {
export function NetscriptGrafting(): InternalAPI<IGrafting> {
const checkGraftingAPIAccess = (ctx: NetscriptContext): void => {
if (!player.canAccessGrafting()) {
throw helpers.makeRuntimeErrorMsg(

@ -1,5 +1,4 @@
import { IPlayer } from "../PersonObjects/IPlayer";
import { WorkerScript } from "../Netscript/WorkerScript";
import { Player as player } from "../Player";
import { HacknetServerConstants } from "../Hacknet/data/Constants";
import {
getCostOfNextHacknetNode,
@ -23,7 +22,7 @@ import { Hacknet as IHacknet, NodeStats } from "../ScriptEditor/NetscriptDefinit
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptHacknet(player: IPlayer, workerScript: WorkerScript): InternalAPI<IHacknet> {
export function NetscriptHacknet(): InternalAPI<IHacknet> {
// Utility function to get Hacknet Node object
const getHacknetNode = function (ctx: NetscriptContext, i: number): HacknetNode | HacknetServer {
if (i < 0 || i >= player.hacknetNodes.length) {
@ -128,7 +127,7 @@ export function NetscriptHacknet(player: IPlayer, workerScript: WorkerScript): I
}
const node = getHacknetNode(ctx, i);
if (!(node instanceof HacknetServer)) {
workerScript.log("hacknet.upgradeCache", () => "Can only be called on hacknet servers");
helpers.log(ctx, () => "Can only be called on hacknet servers");
return false;
}
const res = purchaseCacheUpgrade(player, node, n);
@ -171,7 +170,7 @@ export function NetscriptHacknet(player: IPlayer, workerScript: WorkerScript): I
}
const node = getHacknetNode(ctx, i);
if (!(node instanceof HacknetServer)) {
workerScript.log("hacknet.getCacheUpgradeCost", () => "Can only be called on hacknet servers");
helpers.log(ctx, () => "Can only be called on hacknet servers");
return -1;
}
return node.calculateCacheUpgradeCost(n);

@ -1,4 +1,4 @@
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import {
Infiltration as IInfiltration,
@ -20,7 +20,7 @@ import { checkEnum } from "../utils/helpers/checkEnum";
import { LocationName } from "../Locations/data/LocationNames";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptInfiltration(player: IPlayer): InternalAPI<IInfiltration> {
export function NetscriptInfiltration(): InternalAPI<IInfiltration> {
const getLocationsWithInfiltrations = Object.values(Locations).filter(
(location: Location) => location.infiltrationData,
);

@ -1,5 +1,4 @@
import { WorkerScript } from "../Netscript/WorkerScript";
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player} from "../Player";
import { purchaseAugmentation, joinFaction, getFactionAugmentationsFiltered } from "../Faction/FactionHelpers";
import { startWorkerScript } from "../NetscriptWorker";
import { Augmentation } from "../Augmentation/Augmentation";
@ -54,7 +53,7 @@ import { FactionWork } from "../Work/FactionWork";
import { FactionWorkType } from "../Work/data/FactionWorkType";
import { CompanyWork } from "../Work/CompanyWork";
export function NetscriptSingularity(player: IPlayer, workerScript: WorkerScript): InternalAPI<ISingularity> {
export function NetscriptSingularity(): InternalAPI<ISingularity> {
const getAugmentation = function (ctx: NetscriptContext, name: string): Augmentation {
if (!augmentationExists(name)) {
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid augmentation: '${name}'`);
@ -235,9 +234,9 @@ export function NetscriptSingularity(player: IPlayer, workerScript: WorkerScript
runAfterReset(cbScript);
}, 0);
// Prevent workerScript from "finishing execution naturally"
workerScript.running = false;
killWorkerScript(workerScript);
// Prevent ctx.workerScript from "finishing execution naturally"
ctx.workerScript.running = false;
killWorkerScript(ctx.workerScript);
},
installAugmentations: (ctx: NetscriptContext) =>
function (_cbScript: unknown = ""): boolean {
@ -255,8 +254,8 @@ export function NetscriptSingularity(player: IPlayer, workerScript: WorkerScript
runAfterReset(cbScript);
}, 0);
workerScript.running = false; // Prevent workerScript from "finishing execution naturally"
killWorkerScript(workerScript);
ctx.workerScript.running = false; // Prevent ctx.workerScript from "finishing execution naturally"
killWorkerScript(ctx.workerScript);
return true;
},
@ -1179,7 +1178,7 @@ export function NetscriptSingularity(player: IPlayer, workerScript: WorkerScript
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid crime: '${crimeRoughName}'`);
}
helpers.log(ctx, () => `Attempting to commit ${crime.name}...`);
const crimeTime = crime.commit(player, 1, workerScript);
const crimeTime = crime.commit(player, 1, ctx.workerScript);
if (focus) {
player.startFocusing();
Router.toWork();

@ -1,4 +1,4 @@
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { findSleevePurchasableAugs } from "../PersonObjects/Sleeve/SleeveHelpers";
import { StaticAugmentations } from "../Augmentation/StaticAugmentations";
import { CityName } from "../Locations/data/CityNames";
@ -19,7 +19,7 @@ import { isSleeveFactionWork } from "../PersonObjects/Sleeve/Work/SleeveFactionW
import { isSleeveCompanyWork } from "../PersonObjects/Sleeve/Work/SleeveCompanyWork";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptSleeve(player: IPlayer): InternalAPI<ISleeve> {
export function NetscriptSleeve(): InternalAPI<ISleeve> {
const checkSleeveAPIAccess = function (ctx: NetscriptContext): void {
if (player.bitNodeN !== 10 && !player.sourceFileLvl(10)) {
throw helpers.makeRuntimeErrorMsg(

@ -1,5 +1,4 @@
import { IPlayer } from "../PersonObjects/IPlayer";
import { WorkerScript } from "../Netscript/WorkerScript";
import { Player as player } from "../Player";
import { staneksGift } from "../CotMG/Helper";
import { Fragments, FragmentById } from "../CotMG/Fragment";
@ -18,7 +17,7 @@ import { joinFaction } from "../Faction/FactionHelpers";
import { Factions } from "../Faction/Factions";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptStanek(player: IPlayer, workerScript: WorkerScript): InternalAPI<IStanek> {
export function NetscriptStanek(): InternalAPI<IStanek> {
function checkStanekAPIAccess(ctx: NetscriptContext): void {
if (!player.hasAugmentation(AugmentationNames.StaneksGift1, true)) {
throw helpers.makeRuntimeErrorMsg(ctx, "Stanek's Gift is not installed");
@ -54,7 +53,7 @@ export function NetscriptStanek(player: IPlayer, workerScript: WorkerScript): In
//Charge the fragment
const time = staneksGift.inBonus() ? 200 : 1000;
return helpers.netscriptDelay(ctx, time).then(function () {
staneksGift.charge(player, fragment, workerScript.scriptRef.threads);
staneksGift.charge(player, fragment, ctx.workerScript.scriptRef.threads);
helpers.log(ctx, () => `Charged fragment with ${ctx.workerScript.scriptRef.threads} threads.`);
return Promise.resolve();
});

@ -1,5 +1,4 @@
import { WorkerScript } from "../Netscript/WorkerScript";
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { buyStock, sellStock, shortStock, sellShort } from "../StockMarket/BuyingAndSelling";
import { StockMarket, SymbolToStockMap, placeOrder, cancelOrder, initStockMarketFn } from "../StockMarket/StockMarket";
import { getBuyTransactionCost, getSellTransactionGain } from "../StockMarket/StockMarketHelpers";
@ -17,7 +16,7 @@ import { StockOrder, TIX } from "../ScriptEditor/NetscriptDefinitions";
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptStockMarket(player: IPlayer, workerScript: WorkerScript): InternalAPI<TIX> {
export function NetscriptStockMarket(): InternalAPI<TIX> {
/**
* Checks if the player has TIX API access. Throws an error if the player does not
*/
@ -164,7 +163,7 @@ export function NetscriptStockMarket(player: IPlayer, workerScript: WorkerScript
const shares = helpers.number(ctx, "shares", _shares);
checkTixApiAccess(ctx);
const stock = getStockFromSymbol(ctx, symbol);
const res = buyStock(stock, shares, workerScript, {});
const res = buyStock(stock, shares, ctx.workerScript, {});
return res ? stock.getAskPrice() : 0;
},
sellStock:
@ -174,7 +173,7 @@ export function NetscriptStockMarket(player: IPlayer, workerScript: WorkerScript
const shares = helpers.number(ctx, "shares", _shares);
checkTixApiAccess(ctx);
const stock = getStockFromSymbol(ctx, symbol);
const res = sellStock(stock, shares, workerScript, {});
const res = sellStock(stock, shares, ctx.workerScript, {});
return res ? stock.getBidPrice() : 0;
},
@ -193,7 +192,7 @@ export function NetscriptStockMarket(player: IPlayer, workerScript: WorkerScript
}
}
const stock = getStockFromSymbol(ctx, symbol);
const res = shortStock(stock, shares, workerScript, {});
const res = shortStock(stock, shares, ctx.workerScript, {});
return res ? stock.getBidPrice() : 0;
},
@ -212,7 +211,7 @@ export function NetscriptStockMarket(player: IPlayer, workerScript: WorkerScript
}
}
const stock = getStockFromSymbol(ctx, symbol);
const res = sellShort(stock, shares, workerScript, {});
const res = sellShort(stock, shares, ctx.workerScript, {});
return res ? stock.getAskPrice() : 0;
},
@ -259,7 +258,7 @@ export function NetscriptStockMarket(player: IPlayer, workerScript: WorkerScript
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid position type: ${pos}`);
}
return placeOrder(stock, shares, price, orderType, orderPos, workerScript);
return placeOrder(stock, shares, price, orderType, orderPos, ctx.workerScript);
},
cancelOrder:
(ctx: NetscriptContext) =>
@ -315,7 +314,7 @@ export function NetscriptStockMarket(player: IPlayer, workerScript: WorkerScript
type: orderType,
pos: orderPos,
};
return cancelOrder(params, workerScript);
return cancelOrder(params, ctx.workerScript);
},
getOrders: (ctx: NetscriptContext) => (): StockOrder => {
checkTixApiAccess(ctx);

@ -309,7 +309,7 @@ export async function determineAllPossibilitiesForTabCompletion(
return "--" + f[0];
});
try {
return flagFunc()(schema);
return flagFunc(schema);
} catch (err) {
return {};
}