API: Fix removed functions (#720)

This commit is contained in:
Snarling 2023-08-07 02:38:38 -04:00 committed by GitHub
parent d637828759
commit 4ca598defb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 99 additions and 84 deletions

@ -46,7 +46,9 @@ class NSProxyHandler<API extends GenericAPI<API>> {
getOwnPropertyDescriptor(__target: unknown, key: keyof API & string): PropertyDescriptor | undefined { getOwnPropertyDescriptor(__target: unknown, key: keyof API & string): PropertyDescriptor | undefined {
if (!this.has(__target, key)) return undefined; if (!this.has(__target, key)) return undefined;
return { value: this.get(__target, key, this), configurable: true, enumerable: true, writable: false }; if (Object.hasOwn(this.memoed, key)) return Object.getOwnPropertyDescriptor(this.memoed, key);
this.get(__target, key, this);
return Object.getOwnPropertyDescriptor(this.memoed, key);
} }
defineProperty(__target: unknown, __key: unknown, __attrs: unknown): boolean { defineProperty(__target: unknown, __key: unknown, __attrs: unknown): boolean {
@ -62,8 +64,9 @@ class NSProxyHandler<API extends GenericAPI<API>> {
const ours = this.memoed[key]; const ours = this.memoed[key];
if (ours) return ours; if (ours) return ours;
const field = this.ns[key]; const descriptor = Object.getOwnPropertyDescriptor(this.ns, key);
if (!field) return field; if (!descriptor) return descriptor;
const field = descriptor.value;
if (typeof field === "function") { if (typeof field === "function") {
const arrayPath = [...this.tree, key]; const arrayPath = [...this.tree, key];
@ -75,10 +78,11 @@ class NSProxyHandler<API extends GenericAPI<API>> {
const wrappedFunction = function (...args: unknown[]): unknown { const wrappedFunction = function (...args: unknown[]): unknown {
// What remains *must* be called every time. // What remains *must* be called every time.
helpers.checkEnvFlags(ctx); helpers.checkEnvFlags(ctx);
helpers.updateDynamicRam(ctx, getRamCost(...arrayPath)); helpers.updateDynamicRam(ctx, getRamCost(arrayPath));
return func(...args); return func(...args);
}; };
return ((this.memoed[key] as APIFn) = wrappedFunction); Object.defineProperty(this.memoed, key, { ...descriptor, value: wrappedFunction });
return wrappedFunction;
} }
if (typeof field === "object") { if (typeof field === "object") {
return ((this.memoed[key] as GenericAPI<API[keyof API]>) = NSProxy( return ((this.memoed[key] as GenericAPI<API[keyof API]>) = NSProxy(
@ -105,12 +109,26 @@ export function NSProxy<API extends GenericAPI<API>>(
} }
/** Specify when a function was removed from the game, and its replacement function. */ /** Specify when a function was removed from the game, and its replacement function. */
export function removedFunction(version: string, replacement: string, replaceMsg?: boolean) { interface RemovedFunctionInfo {
return (ctx: NetscriptContext) => () => { /** The version in which the function was removed */
version: string;
/** The replacement function to use, or the entire replacement message if replaceMsg is true. */
replacement: string;
/** If set, replacement is treated as a full replacement message. */
replaceMsg?: true;
}
export function setRemovedFunctions(api: object, infos: Record<string, RemovedFunctionInfo>) {
for (const [key, { version, replacement, replaceMsg }] of Object.entries(infos)) {
Object.defineProperty(api, key, {
value: (ctx: NetscriptContext) => () => {
throw helpers.makeRuntimeErrorMsg( throw helpers.makeRuntimeErrorMsg(
ctx, ctx,
`Function removed in ${version}. ${replaceMsg ? replacement : `Please use ${replacement} instead.`}`, `Function removed in ${version}. ${replaceMsg ? replacement : `Please use ${replacement} instead.`}`,
"REMOVED FUNCTION", "REMOVED FUNCTION",
); );
}; },
configurable: true,
enumerable: false,
});
}
} }

@ -615,32 +615,27 @@ export const RamCosts: RamCostTree<NSFull> = {
}, },
} as const; } as const;
export function getRamCost(...args: string[]): number { type RamTreeGeneric = { [key: string]: number | (() => number) | RamTreeGeneric | undefined };
if (args.length === 0) {
throw new Error(`No arguments passed to getRamCost()`); export function getRamCost(tree: string[], throwOnUndefined = false): number {
if (tree.length === 0) throw new Error(`No arguments passed to getRamCost()`);
let obj: RamTreeGeneric = RamCosts;
for (const branch of tree) {
const next = obj[branch];
if (next === undefined) {
// If no ram cost is defined (e.g. for removed functions), the cost is 0.
const errorText = `No ram cost is defined for (ns.${tree.join(".")})`;
if (throwOnUndefined) throw errorText;
return 0;
}
if (next && typeof next === "object") {
obj = next;
continue;
} }
let curr = RamCosts[args[0] as keyof typeof RamCosts]; return typeof next === "function" ? next() : next;
for (let i = 1; i < args.length; ++i) {
if (curr == null) {
throw new Error(`Invalid function passed to getRamCost: ${args.join(".")}`);
} }
throw new Error(`Tried to get ram cost for ns.${tree.join(".")} but the value was an invalid type`);
const currType = typeof curr;
if (currType === "function" || currType === "number") {
break;
}
curr = curr[args[i] as keyof typeof curr];
}
if (typeof curr === "number") {
return curr;
}
if (typeof curr === "function") {
return curr();
}
throw new Error(`Invalid function passed to getRamCost: ${args.join(".")}`);
} }

@ -86,7 +86,7 @@ import { Flags } from "./NetscriptFunctions/Flags";
import { calculateIntelligenceBonus } from "./PersonObjects/formulas/intelligence"; import { calculateIntelligenceBonus } from "./PersonObjects/formulas/intelligence";
import { CalculateShareMult, StartSharing } from "./NetworkShare/Share"; import { CalculateShareMult, StartSharing } from "./NetworkShare/Share";
import { recentScripts } from "./Netscript/RecentScripts"; import { recentScripts } from "./Netscript/RecentScripts";
import { InternalAPI, removedFunction, NSProxy } from "./Netscript/APIWrapper"; import { InternalAPI, setRemovedFunctions, NSProxy } from "./Netscript/APIWrapper";
import { INetscriptExtra } from "./NetscriptFunctions/Extra"; import { INetscriptExtra } from "./NetscriptFunctions/Extra";
import { ScriptDeath } from "./Netscript/ScriptDeath"; import { ScriptDeath } from "./Netscript/ScriptDeath";
import { getBitNodeMultipliers } from "./BitNode/BitNode"; import { getBitNodeMultipliers } from "./BitNode/BitNode";
@ -1764,7 +1764,7 @@ export const ns: InternalAPI<NSFull> = {
}), }),
getFunctionRamCost: (ctx) => (_name) => { getFunctionRamCost: (ctx) => (_name) => {
const name = helpers.string(ctx, "name", _name); const name = helpers.string(ctx, "name", _name);
return getRamCost(...name.split(".")); return getRamCost(name.split("."), true);
}, },
tprintRaw: () => (value) => { tprintRaw: () => (value) => {
Terminal.printRaw(wrapUserNode(value)); Terminal.printRaw(wrapUserNode(value));
@ -1775,9 +1775,10 @@ export const ns: InternalAPI<NSFull> = {
flags: Flags, flags: Flags,
...NetscriptExtra(), ...NetscriptExtra(),
}; };
// Object.assign to bypass ts for removedFunctions which have no documentation or ramcost
Object.assign(ns, { // Removed functions
getServerRam: removedFunction("v2.2.0", "getServerMaxRam and getServerUsedRam"), setRemovedFunctions(ns, {
getServerRam: { version: "2.2.0", replacement: "getServerMaxRam and getServerUsedRam" },
}); });
export function NetscriptFunctions(ws: WorkerScript): NSFull { export function NetscriptFunctions(ws: WorkerScript): NSFull {

@ -57,7 +57,7 @@ import * as corpConstants from "../Corporation/data/Constants";
import { ResearchMap } from "../Corporation/ResearchMap"; import { ResearchMap } from "../Corporation/ResearchMap";
import { Factions } from "../Faction/Factions"; import { Factions } from "../Faction/Factions";
import { currentNodeMults } from "../BitNode/BitNodeMultipliers"; import { currentNodeMults } from "../BitNode/BitNodeMultipliers";
import { InternalAPI, NetscriptContext, removedFunction } from "../Netscript/APIWrapper"; import { InternalAPI, NetscriptContext, setRemovedFunctions } from "../Netscript/APIWrapper";
import { helpers } from "../Netscript/NetscriptHelpers"; import { helpers } from "../Netscript/NetscriptHelpers";
import { getEnumHelper } from "../utils/EnumHelper"; import { getEnumHelper } from "../utils/EnumHelper";
import { MaterialInfo } from "../Corporation/MaterialInfo"; import { MaterialInfo } from "../Corporation/MaterialInfo";
@ -841,22 +841,26 @@ export function NetscriptCorporation(): InternalAPI<NSCorporation> {
}, },
}; };
// TODO 3.0: Remove these removedFunctions warnings. // Removed functions
Object.assign(corpFunctions, { setRemovedFunctions(corpFunctions, {
assignJob: removedFunction( assignJob: {
"v2.2.0", version: "2.2.0",
"Removed due to employees no longer being objects. Use ns.corporation.setAutoJobAssignment instead.", replacement: "Removed due to employees no longer being objects. Use ns.corporation.setAutoJobAssignment instead.",
true, replaceMsg: true,
), },
getEmployee: removedFunction("v2.2.0", "Removed due to employees no longer being individual objects.", true), getEmployee: {
getExpandCityCost: removedFunction("v2.2.0", "corporation.getConstants().officeInitialCost"), version: "2.2.0",
getExpandIndustryCost: removedFunction("v2.2.0", "corporation.getIndustryData"), replacement: "Removed due to employees no longer being individual objects.",
getIndustryTypes: removedFunction("v2.2.0", "corporation.getConstants().industryNames"), replaceMsg: true,
getMaterialNames: removedFunction("v2.2.0", "corporation.getConstants().materialNames"), },
getPurchaseWarehouseCost: removedFunction("v2.2.0", "corporation.getConstants().warehouseInitialCost"), getExpandCityCost: { version: "2.2.0", replacement: "corporation.getConstants().officeInitialCost" },
getResearchNames: removedFunction("v2.2.0", "corporation.getConstants().researchNames"), getExpandIndustryCost: { version: "2.2.0", replacement: "corporation.getIndustryData" },
getUnlockables: removedFunction("v2.2.0", "corporation.getConstants().unlockNames"), getIndustryTypes: { version: "2.2.0", replacement: "corporation.getConstants().industryNames" },
getUpgradeNames: removedFunction("v2.2.0", "corporation.getConstants().upgradeNames"), getMaterialNames: { version: "2.2.0", replacement: "corporation.getConstants().materialNames" },
getPurchaseWarehouseCost: { version: "2.2.0", replacement: "corporation.getConstants().warehouseInitialCost" },
getResearchNames: { version: "2.2.0", replacement: "corporation.getConstants().researchNames" },
getUnlockables: { version: "2.2.0", replacement: "corporation.getConstants().unlockNames" },
getUpgradeNames: { version: "2.2.0", replacement: "corporation.getConstants().upgradeNames" },
}); });
return corpFunctions; return corpFunctions;
} }

@ -46,7 +46,7 @@ import {
} from "../Gang/formulas/formulas"; } from "../Gang/formulas/formulas";
import { favorToRep as calculateFavorToRep, repToFavor as calculateRepToFavor } from "../Faction/formulas/favor"; import { favorToRep as calculateFavorToRep, repToFavor as calculateRepToFavor } from "../Faction/formulas/favor";
import { repFromDonation } from "../Faction/formulas/donation"; import { repFromDonation } from "../Faction/formulas/donation";
import { InternalAPI, NetscriptContext, removedFunction } from "../Netscript/APIWrapper"; import { InternalAPI, NetscriptContext, setRemovedFunctions } from "../Netscript/APIWrapper";
import { helpers } from "../Netscript/NetscriptHelpers"; import { helpers } from "../Netscript/NetscriptHelpers";
import { calculateCrimeWorkStats } from "../Work/Formulas"; import { calculateCrimeWorkStats } from "../Work/Formulas";
import { calculateCompanyWorkStats } from "../Work/Formulas"; import { calculateCompanyWorkStats } from "../Work/Formulas";
@ -427,10 +427,10 @@ export function NetscriptFormulas(): InternalAPI<IFormulas> {
}, },
}, },
}; };
// Removed undocumented functions added using Object.assign because typescript.
// TODO: Remove these at 3.0 // Removed functions
Object.assign(formulasFunctions.work, { setRemovedFunctions(formulasFunctions.work, {
classGains: removedFunction("2.2.0", "formulas.work.universityGains or formulas.work.gymGains"), classGains: { version: "2.2.0", replacement: "formulas.work.universityGains or formulas.work.gymGains" },
}); });
return formulasFunctions; return formulasFunctions;
} }

@ -40,7 +40,7 @@ import { Server } from "../Server/Server";
import { netscriptCanHack } from "../Hacking/netscriptCanHack"; import { netscriptCanHack } from "../Hacking/netscriptCanHack";
import { FactionInfos } from "../Faction/FactionInfo"; import { FactionInfos } from "../Faction/FactionInfo";
import { donate, repNeededToDonate } from "../Faction/formulas/donation"; import { donate, repNeededToDonate } from "../Faction/formulas/donation";
import { InternalAPI, removedFunction } from "../Netscript/APIWrapper"; import { InternalAPI, setRemovedFunctions } from "../Netscript/APIWrapper";
import { enterBitNode } from "../RedPill"; import { enterBitNode } from "../RedPill";
import { ClassWork } from "../Work/ClassWork"; import { ClassWork } from "../Work/ClassWork";
import { CreateProgramWork, isCreateProgramWork } from "../Work/CreateProgramWork"; import { CreateProgramWork, isCreateProgramWork } from "../Work/CreateProgramWork";
@ -1204,11 +1204,13 @@ export function NetscriptSingularity(): InternalAPI<ISingularity> {
return canGetBonus(); return canGetBonus();
}, },
}; };
Object.assign(singularityAPI, {
getAugmentationCost: removedFunction( // Removed functions
"v2.2.0", setRemovedFunctions(singularityAPI, {
"singularity.getAugmentationPrice and singularity.getAugmentationRepReq", getAugmentationCost: {
), version: "2.2.0",
replacement: "singularity.getAugmentationPrice and singularity.getAugmentationRepReq",
},
}); });
return singularityAPI; return singularityAPI;
} }

@ -5,7 +5,7 @@ import { Player } from "@player";
import { Augmentations } from "../Augmentation/Augmentations"; import { Augmentations } from "../Augmentation/Augmentations";
import { findCrime } from "../Crime/CrimeHelpers"; import { findCrime } from "../Crime/CrimeHelpers";
import { getEnumHelper } from "../utils/EnumHelper"; import { getEnumHelper } from "../utils/EnumHelper";
import { InternalAPI, NetscriptContext, removedFunction } from "../Netscript/APIWrapper"; import { InternalAPI, NetscriptContext, setRemovedFunctions } from "../Netscript/APIWrapper";
import { isSleeveBladeburnerWork } from "../PersonObjects/Sleeve/Work/SleeveBladeburnerWork"; import { isSleeveBladeburnerWork } from "../PersonObjects/Sleeve/Work/SleeveBladeburnerWork";
import { isSleeveFactionWork } from "../PersonObjects/Sleeve/Work/SleeveFactionWork"; import { isSleeveFactionWork } from "../PersonObjects/Sleeve/Work/SleeveFactionWork";
import { isSleeveCompanyWork } from "../PersonObjects/Sleeve/Work/SleeveCompanyWork"; import { isSleeveCompanyWork } from "../PersonObjects/Sleeve/Work/SleeveCompanyWork";
@ -262,11 +262,11 @@ export function NetscriptSleeve(): InternalAPI<NetscriptSleeve> {
return Player.sleeves[sleeveNumber].bladeburner(action, contract); return Player.sleeves[sleeveNumber].bladeburner(action, contract);
}, },
}; };
// Removed undocumented functions added using Object.assign because typescript.
// TODO: Remove these at 3.0 // Removed functions
Object.assign(sleeveFunctions, { setRemovedFunctions(sleeveFunctions, {
getSleeveStats: removedFunction("v2.2.0", "sleeve.getSleeve"), getSleeveStats: { version: "2.2.0", replacement: "sleeve.getSleeve" },
getInformation: removedFunction("v2.2.0", "sleeve.getSleeve"), getInformation: { version: "2.2.0", replacement: "sleeve.getSleeve" },
}); });
return sleeveFunctions; return sleeveFunctions;
} }

@ -7,7 +7,7 @@ import { Script } from "../../../src/Script/Script";
import { WorkerScript } from "../../../src/Netscript/WorkerScript"; import { WorkerScript } from "../../../src/Netscript/WorkerScript";
import { calculateRamUsage } from "../../../src/Script/RamCalculations"; import { calculateRamUsage } from "../../../src/Script/RamCalculations";
import { ns } from "../../../src/NetscriptFunctions"; import { ns } from "../../../src/NetscriptFunctions";
import { InternalAPI, NetscriptContext } from "src/Netscript/APIWrapper"; import { InternalAPI } from "src/Netscript/APIWrapper";
import { Singularity } from "@nsdefs"; import { Singularity } from "@nsdefs";
type PotentiallyAsyncFunction = (arg?: unknown) => { catch?: PotentiallyAsyncFunction }; type PotentiallyAsyncFunction = (arg?: unknown) => { catch?: PotentiallyAsyncFunction };
@ -22,9 +22,6 @@ function grabCost<API>(ramEntry: RamCostTree<API>[keyof API]) {
if (typeof ramEntry === "number") return ramEntry; if (typeof ramEntry === "number") return ramEntry;
throw new Error("Invalid ramcost: " + ramEntry); throw new Error("Invalid ramcost: " + ramEntry);
} }
function isRemovedFunction(ctx: NetscriptContext, fn: (ctx: NetscriptContext) => (...__: unknown[]) => unknown) {
return /REMOVED FUNCTION/.test(fn(ctx) + "");
}
describe("Netscript RAM Calculation/Generation Tests", function () { describe("Netscript RAM Calculation/Generation Tests", function () {
Player.sourceFiles.set(4, 3); Player.sourceFiles.set(4, 3);
@ -74,7 +71,7 @@ describe("Netscript RAM Calculation/Generation Tests", function () {
const fnName = fnPath[fnPath.length - 1]; const fnName = fnPath[fnPath.length - 1];
//check imported getRamCost fn vs. expected ram from test //check imported getRamCost fn vs. expected ram from test
expect(getRamCost(...fnPath)).toEqual(expectedRamCost); expect(getRamCost(fnPath, true)).toEqual(expectedRamCost);
// Static ram check // Static ram check
const staticCost = calculateRamUsage(code, new Map()).cost; const staticCost = calculateRamUsage(code, new Map()).cost;
@ -118,8 +115,6 @@ describe("Netscript RAM Calculation/Generation Tests", function () {
for (const [key, val] of Object.entries(internalLayer) as [keyof API, InternalAPI<API>[keyof API]][]) { for (const [key, val] of Object.entries(internalLayer) as [keyof API, InternalAPI<API>[keyof API]][]) {
const newPath = [...path, key as string]; const newPath = [...path, key as string];
if (typeof val === "function") { if (typeof val === "function") {
// Removed functions have no ram cost and should be skipped.
if (isRemovedFunction({ workerScript }, val)) return;
const fn = getFunction(externalLayer[key]); const fn = getFunction(externalLayer[key]);
const fnName = newPath.join("."); const fnName = newPath.join(".");
if (!(key in ramLayer)) { if (!(key in ramLayer)) {
@ -150,7 +145,7 @@ describe("Netscript RAM Calculation/Generation Tests", function () {
const singObjects = ( const singObjects = (
Object.entries(ns.singularity) as [keyof Singularity, InternalAPI<Singularity>[keyof Singularity]][] Object.entries(ns.singularity) as [keyof Singularity, InternalAPI<Singularity>[keyof Singularity]][]
) )
.filter(([__, v]) => typeof v === "function" && !isRemovedFunction({ workerScript }, v)) .filter(([__, v]) => typeof v === "function")
.map(([name]) => { .map(([name]) => {
return { return {
name, name,