convert to ts

This commit is contained in:
Olivier Gagnon 2021-09-24 17:07:53 -04:00
parent 4f219a3214
commit 413333c919
8 changed files with 62 additions and 55 deletions

@ -2379,7 +2379,6 @@ function applyAugmentation(aug: IPlayerOwnedAugmentation, reapply = false): void
for (const mult in augObj.mults) { for (const mult in augObj.mults) {
const v = Player.getMult(mult) * augObj.mults[mult]; const v = Player.getMult(mult) * augObj.mults[mult];
Player.setMult(mult, v); Player.setMult(mult, v);
console.log(`${mult} ${v}`);
} }
// Special logic for NeuroFlux Governor // Special logic for NeuroFlux Governor

@ -2,8 +2,9 @@ import { setTimeoutRef } from "./utils/SetTimeoutRef";
import { isString } from "../utils/helpers/isString"; import { isString } from "../utils/helpers/isString";
import { AllServers } from "./Server/AllServers"; import { AllServers } from "./Server/AllServers";
import { WorkerScript } from "./Netscript/WorkerScript";
export function netscriptDelay(time, workerScript) { export function netscriptDelay(time: number, workerScript: WorkerScript): Promise<void> {
return new Promise(function (resolve) { return new Promise(function (resolve) {
workerScript.delay = setTimeoutRef(() => { workerScript.delay = setTimeoutRef(() => {
workerScript.delay = null; workerScript.delay = null;
@ -13,7 +14,7 @@ export function netscriptDelay(time, workerScript) {
}); });
} }
export function makeRuntimeRejectMsg(workerScript, msg, exp = null) { export function makeRuntimeRejectMsg(workerScript: WorkerScript, msg: string, exp: any = null) {
var lineNum = ""; var lineNum = "";
if (exp != null) { if (exp != null) {
var num = getErrorLineNumber(exp, workerScript); var num = getErrorLineNumber(exp, workerScript);
@ -21,13 +22,17 @@ export function makeRuntimeRejectMsg(workerScript, msg, exp = null) {
} }
const server = AllServers[workerScript.serverIp]; const server = AllServers[workerScript.serverIp];
if (server == null) { if (server == null) {
throw new Error(`WorkerScript constructed with invalid server ip: ${this.serverIp}`); throw new Error(`WorkerScript constructed with invalid server ip: ${workerScript.serverIp}`);
} }
return "|" + server.hostname + "|" + workerScript.name + "|" + msg + lineNum; return "|" + server.hostname + "|" + workerScript.name + "|" + msg + lineNum;
} }
export function resolveNetscriptRequestedThreads(workerScript, functionName, requestedThreads) { export function resolveNetscriptRequestedThreads(
workerScript: WorkerScript,
functionName: string,
requestedThreads: number,
) {
const threads = workerScript.scriptRef.threads; const threads = workerScript.scriptRef.threads;
if (!requestedThreads) { if (!requestedThreads) {
return isNaN(threads) || threads < 1 ? 1 : threads; return isNaN(threads) || threads < 1 ? 1 : threads;
@ -48,19 +53,22 @@ export function resolveNetscriptRequestedThreads(workerScript, functionName, req
return requestedThreadsAsInt; return requestedThreadsAsInt;
} }
export function getErrorLineNumber(exp, workerScript) { export function getErrorLineNumber(exp: any, workerScript: WorkerScript): number {
var code = workerScript.scriptRef.codeCode(); return -1;
// TODO wtf is codeCode?
//Split code up to the start of the node // var code = workerScript.scriptRef.codeCode();
try {
code = code.substring(0, exp.start); // //Split code up to the start of the node
return (code.match(/\n/g) || []).length + 1; // try {
} catch (e) { // code = code.substring(0, exp.start);
return -1; // return (code.match(/\n/g) || []).length + 1;
} // } catch (e) {
// return -1;
// }
} }
export function isScriptErrorMessage(msg) { export function isScriptErrorMessage(msg: string): boolean {
if (!isString(msg)) { if (!isString(msg)) {
return false; return false;
} }

@ -1,8 +1,10 @@
import { makeRuntimeRejectMsg } from "./NetscriptEvaluator"; import { makeRuntimeRejectMsg } from "./NetscriptEvaluator";
import { ScriptUrl } from "./Script/ScriptUrl"; import { ScriptUrl } from "./Script/ScriptUrl";
import { WorkerScript } from "./Netscript/WorkerScript";
import { Script } from "./Script/Script";
// Makes a blob that contains the code of a given script. // Makes a blob that contains the code of a given script.
function makeScriptBlob(code) { function makeScriptBlob(code: string): Blob {
return new Blob([code], { type: "text/javascript" }); return new Blob([code], { type: "text/javascript" });
} }
@ -14,10 +16,11 @@ function makeScriptBlob(code) {
// (i.e. hack, grow, etc.). // (i.e. hack, grow, etc.).
// When the promise returned by this resolves, we'll have finished // When the promise returned by this resolves, we'll have finished
// running the main function of the script. // running the main function of the script.
export async function executeJSScript(scripts = [], workerScript) { export async function executeJSScript(scripts: Script[] = [], workerScript: WorkerScript) {
let loadedModule; let loadedModule;
let urls = null; let uurls: ScriptUrl[] = [];
let script = workerScript.getScript(); let script = workerScript.getScript();
if (script === null) throw new Error("script is null");
if (shouldCompile(script, scripts)) { if (shouldCompile(script, scripts)) {
// The URL at the top is the one we want to import. It will // The URL at the top is the one we want to import. It will
// recursively import all the other modules in the urlStack. // recursively import all the other modules in the urlStack.
@ -27,31 +30,24 @@ export async function executeJSScript(scripts = [], workerScript) {
// load fully dynamic content. So we hide the import from webpack // load fully dynamic content. So we hide the import from webpack
// by placing it inside an eval call. // by placing it inside an eval call.
script.markUpdated(); script.markUpdated();
urls = _getScriptUrls(script, scripts, []); uurls = _getScriptUrls(script, scripts, []);
script.url = urls[urls.length - 1].url; script.url = uurls[uurls.length - 1].url;
script.module = new Promise((resolve) => resolve(eval("import(urls[urls.length - 1].url)"))); script.module = new Promise((resolve) => resolve(eval("import(uurls[uurls.length - 1].url)")));
script.dependencies = urls; script.dependencies = uurls;
} }
loadedModule = await script.module; loadedModule = await script.module;
let ns = workerScript.env.vars; let ns = workerScript.env.vars;
try { // TODO: putting await in a non-async function yields unhelpful
// TODO: putting await in a non-async function yields unhelpful // "SyntaxError: unexpected reserved word" with no line number information.
// "SyntaxError: unexpected reserved word" with no line number information. if (!loadedModule.main) {
if (!loadedModule.main) { throw makeRuntimeRejectMsg(
throw makeRuntimeRejectMsg( workerScript,
workerScript, `${script.filename} cannot be run because it does not have a main function.`,
`${script.filename} cannot be run because it does not have a main function.`, );
);
}
return loadedModule.main(ns);
} finally {
// Revoke the generated URLs
if (urls != null) {
for (const b in urls) URL.revokeObjectURL(b.url);
}
} }
return loadedModule.main(ns);
} }
/** Returns whether we should compile the script parameter. /** Returns whether we should compile the script parameter.
@ -59,7 +55,7 @@ export async function executeJSScript(scripts = [], workerScript) {
* @param {Script} script * @param {Script} script
* @param {Script[]} scripts * @param {Script[]} scripts
*/ */
function shouldCompile(script, scripts) { function shouldCompile(script: Script, scripts: Script[]): boolean {
if (script.module === "") return true; if (script.module === "") return true;
return script.dependencies.some((dep) => { return script.dependencies.some((dep) => {
const depScript = scripts.find((s) => s.filename == dep.filename); const depScript = scripts.find((s) => s.filename == dep.filename);
@ -93,7 +89,7 @@ function shouldCompile(script, scripts) {
* the script parameter. * the script parameter.
*/ */
// BUG: apparently seen is never consulted. Oops. // BUG: apparently seen is never consulted. Oops.
function _getScriptUrls(script, scripts, seen) { function _getScriptUrls(script: Script, scripts: Script[], seen: Script[]): ScriptUrl[] {
// Inspired by: https://stackoverflow.com/a/43834063/91401 // Inspired by: https://stackoverflow.com/a/43834063/91401
/** @type {ScriptUrl[]} */ /** @type {ScriptUrl[]} */
const urlStack = []; const urlStack = [];

@ -1 +1,2 @@
export declare function startWorkerScript(script: RunningScript, server: BaseServer): boolean; export declare function startWorkerScript(script: RunningScript, server: BaseServer): boolean;
export declare function prestigeWorkerScripts(): void;

@ -238,7 +238,7 @@ export interface IPlayer {
getIntelligenceBonus(weight: number): number; getIntelligenceBonus(weight: number): number;
getCasinoWinnings(): number; getCasinoWinnings(): number;
quitJob(company: string): void; quitJob(company: string): void;
createHacknetServer(): void; createHacknetServer(): HacknetServer;
startCreateProgramWork(router: IRouter, programName: string, time: number, reqLevel: number): void; startCreateProgramWork(router: IRouter, programName: string, time: number, reqLevel: number): void;
queueAugmentation(augmentationName: string): void; queueAugmentation(augmentationName: string): void;
receiveInvite(factionName: string): void; receiveInvite(factionName: string): void;

@ -245,7 +245,7 @@ export class PlayerObject implements IPlayer {
getIntelligenceBonus: (weight: number) => number; getIntelligenceBonus: (weight: number) => number;
getCasinoWinnings: () => number; getCasinoWinnings: () => number;
quitJob: (company: string) => void; quitJob: (company: string) => void;
createHacknetServer: () => void; createHacknetServer: () => HacknetServer;
startCreateProgramWork: (router: IRouter, programName: string, time: number, reqLevel: number) => void; startCreateProgramWork: (router: IRouter, programName: string, time: number, reqLevel: number) => void;
queueAugmentation: (augmentationName: string) => void; queueAugmentation: (augmentationName: string) => void;
receiveInvite: (factionName: string) => void; receiveInvite: (factionName: string) => void;

2
src/Prestige.d.ts vendored

@ -1,2 +0,0 @@
export declare function prestigeAugmentation(): void;
export declare function prestigeSourceFile(flume: boolean): void;

@ -14,6 +14,7 @@ import { updateHashManagerCapacity } from "./Hacknet/HacknetHelpers";
import { initMessages } from "./Message/MessageHelpers"; import { initMessages } from "./Message/MessageHelpers";
import { prestigeWorkerScripts } from "./NetscriptWorker"; import { prestigeWorkerScripts } from "./NetscriptWorker";
import { Player } from "./Player"; import { Player } from "./Player";
import { Router } from "./ui/GameRoot";
import { resetPidCounter } from "./Netscript/Pid"; import { resetPidCounter } from "./Netscript/Pid";
import { LiteratureNames } from "./Literature/data/LiteratureNames"; import { LiteratureNames } from "./Literature/data/LiteratureNames";
@ -31,7 +32,7 @@ import Decimal from "decimal.js";
const BitNode8StartingMoney = 250e6; const BitNode8StartingMoney = 250e6;
// Prestige by purchasing augmentation // Prestige by purchasing augmentation
function prestigeAugmentation() { function prestigeAugmentation(): void {
initBitNodeMultipliers(Player); initBitNodeMultipliers(Player);
const maintainMembership = Player.factions.filter(function (faction) { const maintainMembership = Player.factions.filter(function (faction) {
@ -42,7 +43,7 @@ function prestigeAugmentation() {
// Delete all Worker Scripts objects // Delete all Worker Scripts objects
prestigeWorkerScripts(); prestigeWorkerScripts();
var homeComp = Player.getHomeComputer(); const homeComp = Player.getHomeComputer();
// Delete all servers except home computer // Delete all servers except home computer
prestigeAllServers(); prestigeAllServers();
@ -70,14 +71,14 @@ function prestigeAugmentation() {
initForeignServers(Player.getHomeComputer()); initForeignServers(Player.getHomeComputer());
// Gain favor for Companies // Gain favor for Companies
for (var member in Companies) { for (const member in Companies) {
if (Companies.hasOwnProperty(member)) { if (Companies.hasOwnProperty(member)) {
Companies[member].gainFavor(); Companies[member].gainFavor();
} }
} }
// Gain favor for factions // Gain favor for factions
for (var member in Factions) { for (const member in Factions) {
if (Factions.hasOwnProperty(member)) { if (Factions.hasOwnProperty(member)) {
Factions[member].gainFavor(); Factions[member].gainFavor();
} }
@ -86,7 +87,7 @@ function prestigeAugmentation() {
// Stop a Terminal action if there is onerror // Stop a Terminal action if there is onerror
if (Engine._actionInProgress) { if (Engine._actionInProgress) {
Engine._actionInProgress = false; Engine._actionInProgress = false;
Terminal.finishAction(true); Terminal.finishAction(Router, Player, true);
} }
// Re-initialize things - This will update any changes // Re-initialize things - This will update any changes
@ -102,8 +103,9 @@ function prestigeAugmentation() {
initMessages(); initMessages();
// Gang // Gang
if (Player.inGang()) { const gang = Player.gang;
const faction = Factions[Player.gang.facName]; if (Player.inGang() && gang !== null) {
const faction = Factions[gang.facName];
if (faction instanceof Faction) { if (faction instanceof Faction) {
joinFaction(faction); joinFaction(faction);
} }
@ -131,8 +133,12 @@ function prestigeAugmentation() {
// Red Pill // Red Pill
if (augmentationExists(AugmentationNames.TheRedPill) && Augmentations[AugmentationNames.TheRedPill].owned) { if (augmentationExists(AugmentationNames.TheRedPill) && Augmentations[AugmentationNames.TheRedPill].owned) {
var WorldDaemon = AllServers[SpecialServerIps[SpecialServerNames.WorldDaemon]]; const WorldDaemonIP = SpecialServerIps[SpecialServerNames.WorldDaemon];
var DaedalusServer = AllServers[SpecialServerIps[SpecialServerNames.DaedalusServer]]; if (typeof WorldDaemonIP !== "string") throw new Error("WorldDaemonIP should be string");
const WorldDaemon = AllServers[WorldDaemonIP];
const DaedalusServerIP = SpecialServerIps[SpecialServerNames.DaedalusServer];
if (typeof DaedalusServerIP !== "string") throw new Error("DaedalusServerIP should be string");
const DaedalusServer = AllServers[DaedalusServerIP];
if (WorldDaemon && DaedalusServer) { if (WorldDaemon && DaedalusServer) {
WorldDaemon.serversOnNetwork.push(DaedalusServer.ip); WorldDaemon.serversOnNetwork.push(DaedalusServer.ip);
DaedalusServer.serversOnNetwork.push(WorldDaemon.ip); DaedalusServer.serversOnNetwork.push(WorldDaemon.ip);
@ -143,7 +149,7 @@ function prestigeAugmentation() {
} }
// Prestige by destroying Bit Node and gaining a Source File // Prestige by destroying Bit Node and gaining a Source File
function prestigeSourceFile(flume) { function prestigeSourceFile(flume: boolean): void {
initBitNodeMultipliers(Player); initBitNodeMultipliers(Player);
updateSourceFileFlags(Player); updateSourceFileFlags(Player);
@ -191,7 +197,7 @@ function prestigeSourceFile(flume) {
// Stop a Terminal action if there is one // Stop a Terminal action if there is one
if (Engine._actionInProgress) { if (Engine._actionInProgress) {
Engine._actionInProgress = false; Engine._actionInProgress = false;
Terminal.finishAction(true); Terminal.finishAction(Router, Player, true);
} }
// Delete all Augmentations // Delete all Augmentations
@ -249,7 +255,6 @@ function prestigeSourceFile(flume) {
deleteStockMarket(); deleteStockMarket();
} }
if (Player.inGang()) clearGangUI();
Player.gang = null; Player.gang = null;
Player.corporation = null; Player.corporation = null;
resetIndustryResearchTrees(); resetIndustryResearchTrees();