This commit is contained in:
Olivier Gagnon 2021-09-25 01:26:03 -04:00
parent 5c6c472b64
commit b0f20c8c8f
33 changed files with 3609 additions and 1217 deletions

@ -23,7 +23,7 @@ function createWindow() {
win.webContents.on("new-window", function (e, url) { win.webContents.on("new-window", function (e, url) {
// make sure local urls stay in electron perimeter // make sure local urls stay in electron perimeter
if ("file://" === url.substr(0, "file://".length)) { if (url.substr(0, "file://".length) === "file://") {
return; return;
} }

File diff suppressed because one or more lines are too long

@ -2,25 +2,25 @@ const numSpaces = 4;
const maxLineLength = 160; const maxLineLength = 160;
module.exports = { module.exports = {
env: { "env": {
es6: true, "es6": true,
node: true, "node": true
}, },
extends: "eslint:recommended", "extends": "eslint:recommended",
parserOptions: { "parserOptions": {
ecmaFeatures: { "ecmaFeatures": {
experimentalObjectRestSpread: true, "experimentalObjectRestSpread": true
}, },
ecmaVersion: 8, "ecmaVersion": 8,
sourceType: "module", "sourceType": "module"
}, },
rules: { "rules": {
"accessor-pairs": [ "accessor-pairs": [
"error", "error",
{ {
getWithoutSet: false, "getWithoutSet": false,
setWithoutGet: true, "setWithoutGet": true
}, }
], ],
"array-bracket-newline": ["error"], "array-bracket-newline": ["error"],
"array-bracket-spacing": ["error"], "array-bracket-spacing": ["error"],
@ -33,35 +33,50 @@ module.exports = {
"block-spacing": ["error"], "block-spacing": ["error"],
"brace-style": ["error"], "brace-style": ["error"],
"callback-return": ["error"], "callback-return": ["error"],
camelcase: ["error"], "camelcase": ["error"],
"capitalized-comments": ["error"], "capitalized-comments": ["error"],
"class-methods-use-this": ["error"], "class-methods-use-this": ["error"],
"comma-dangle": ["error"], "comma-dangle": ["error"],
"comma-spacing": ["error"], "comma-spacing": ["error"],
"comma-style": ["error", "last"], "comma-style": [
complexity: ["error"], "error",
"computed-property-spacing": ["error", "never"], "last"
],
"complexity": ["error"],
"computed-property-spacing": [
"error",
"never"
],
"consistent-return": ["error"], "consistent-return": ["error"],
"consistent-this": ["error"], "consistent-this": ["error"],
"constructor-super": ["error"], "constructor-super": ["error"],
curly: ["error"], "curly": ["error"],
"default-case": ["error"], "default-case": ["error"],
"dot-location": ["error", "property"], "dot-location": [
"error",
"property"
],
"dot-notation": ["error"], "dot-notation": ["error"],
"eol-last": ["error"], "eol-last": ["error"],
eqeqeq: ["error"], "eqeqeq": ["error"],
"for-direction": ["error"], "for-direction": ["error"],
"func-call-spacing": ["error"], "func-call-spacing": ["error"],
"func-name-matching": ["error"], "func-name-matching": ["error"],
"func-names": ["error", "never"], "func-names": [
"error",
"never"
],
"func-style": ["error"], "func-style": ["error"],
"function-paren-newline": ["error"], "function-paren-newline": ["error"],
"generator-star-spacing": ["error", "before"], "generator-star-spacing": [
"error",
"before"
],
"getter-return": [ "getter-return": [
"error", "error",
{ {
allowImplicit: false, "allowImplicit": false
}, }
], ],
"global-require": ["error"], "global-require": ["error"],
"guard-for-in": ["error"], "guard-for-in": ["error"],
@ -69,37 +84,52 @@ module.exports = {
"id-blacklist": ["error"], "id-blacklist": ["error"],
"id-length": ["error"], "id-length": ["error"],
"id-match": ["error"], "id-match": ["error"],
"implicit-arrow-linebreak": ["error", "beside"], "implicit-arrow-linebreak": [
indent: [ "error",
"beside"
],
"indent": [
"error", "error",
numSpaces, numSpaces,
{ {
SwitchCase: 1, "SwitchCase": 1
}, }
], ],
"init-declarations": ["error"], "init-declarations": ["error"],
"jsx-quotes": ["error"], "jsx-quotes": ["error"],
"key-spacing": ["error"], "key-spacing": ["error"],
"keyword-spacing": ["error"], "keyword-spacing": ["error"],
"line-comment-position": ["error"], "line-comment-position": ["error"],
"linebreak-style": ["error", "windows"], "linebreak-style": [
"error",
"windows"
],
"lines-around-comment": ["error"], "lines-around-comment": ["error"],
"lines-between-class-members": ["error"], "lines-between-class-members": ["error"],
"max-depth": ["error"], "max-depth": ["error"],
"max-len": ["error", maxLineLength], "max-len": [
"error",
maxLineLength
],
"max-lines": [ "max-lines": [
"error", "error",
{ {
skipBlankLines: true, "skipBlankLines": true,
skipComments: true, "skipComments": true
}, }
], ],
"max-nested-callbacks": ["error"], "max-nested-callbacks": ["error"],
"max-params": ["error"], "max-params": ["error"],
"max-statements": ["error"], "max-statements": ["error"],
"max-statements-per-line": ["error"], "max-statements-per-line": ["error"],
"multiline-comment-style": ["off", "starred-block"], "multiline-comment-style": [
"multiline-ternary": ["error", "never"], "off",
"starred-block"
],
"multiline-ternary": [
"error",
"never"
],
"new-cap": ["error"], "new-cap": ["error"],
"new-parens": ["error"], "new-parens": ["error"],
// TODO: configure this... // TODO: configure this...
@ -115,15 +145,18 @@ module.exports = {
"no-catch-shadow": ["error"], "no-catch-shadow": ["error"],
"no-class-assign": ["error"], "no-class-assign": ["error"],
"no-compare-neg-zero": ["error"], "no-compare-neg-zero": ["error"],
"no-cond-assign": ["error", "except-parens"], "no-cond-assign": [
"error",
"except-parens"
],
"no-confusing-arrow": ["error"], "no-confusing-arrow": ["error"],
"no-console": ["error"], "no-console": ["error"],
"no-const-assign": ["error"], "no-const-assign": ["error"],
"no-constant-condition": [ "no-constant-condition": [
"error", "error",
{ {
checkLoops: false, "checkLoops": false
}, }
], ],
"no-continue": ["off"], "no-continue": ["off"],
"no-control-regex": ["error"], "no-control-regex": ["error"],
@ -137,15 +170,15 @@ module.exports = {
"no-duplicate-imports": [ "no-duplicate-imports": [
"error", "error",
{ {
includeExports: true, "includeExports": true
}, }
], ],
"no-else-return": ["error"], "no-else-return": ["error"],
"no-empty": [ "no-empty": [
"error", "error",
{ {
allowEmptyCatch: false, "allowEmptyCatch": false
}, }
], ],
"no-empty-character-class": ["error"], "no-empty-character-class": ["error"],
"no-empty-function": ["error"], "no-empty-function": ["error"],
@ -161,8 +194,8 @@ module.exports = {
"error", "error",
"all", "all",
{ {
conditionalAssign: false, "conditionalAssign": false
}, }
], ],
"no-extra-semi": ["error"], "no-extra-semi": ["error"],
"no-fallthrough": ["error"], "no-fallthrough": ["error"],
@ -173,17 +206,20 @@ module.exports = {
"no-implicit-globals": ["error"], "no-implicit-globals": ["error"],
"no-implied-eval": ["error"], "no-implied-eval": ["error"],
"no-inline-comments": ["error"], "no-inline-comments": ["error"],
"no-inner-declarations": ["error", "both"], "no-inner-declarations": [
"error",
"both"
],
"no-invalid-regexp": ["error"], "no-invalid-regexp": ["error"],
"no-invalid-this": ["error"], "no-invalid-this": ["error"],
"no-irregular-whitespace": [ "no-irregular-whitespace": [
"error", "error",
{ {
skipComments: false, "skipComments": false,
skipRegExps: false, "skipRegExps": false,
skipStrings: false, "skipStrings": false,
skipTemplates: false, "skipTemplates": false
}, }
], ],
"no-iterator": ["error"], "no-iterator": ["error"],
"no-label-var": ["error"], "no-label-var": ["error"],
@ -194,9 +230,13 @@ module.exports = {
"no-magic-numbers": [ "no-magic-numbers": [
"error", "error",
{ {
ignore: [-1, 0, 1], "ignore": [
ignoreArrayIndexes: true, -1,
}, 0,
1
],
"ignoreArrayIndexes": true
}
], ],
"no-mixed-operators": ["error"], "no-mixed-operators": ["error"],
"no-mixed-requires": ["error"], "no-mixed-requires": ["error"],
@ -207,8 +247,8 @@ module.exports = {
"no-multiple-empty-lines": [ "no-multiple-empty-lines": [
"error", "error",
{ {
max: 1, "max": 1
}, }
], ],
"no-native-reassign": ["error"], "no-native-reassign": ["error"],
"no-negated-condition": ["error"], "no-negated-condition": ["error"],
@ -228,8 +268,8 @@ module.exports = {
"no-plusplus": [ "no-plusplus": [
"error", "error",
{ {
allowForLoopAfterthoughts: true, "allowForLoopAfterthoughts": true
}, }
], ],
"no-process-env": ["error"], "no-process-env": ["error"],
"no-process-exit": ["error"], "no-process-exit": ["error"],
@ -243,10 +283,10 @@ module.exports = {
"no-restricted-properties": [ "no-restricted-properties": [
"error", "error",
{ {
message: "'log' is too general, use an appropriate level when logging.", "message": "'log' is too general, use an appropriate level when logging.",
object: "console", "object": "console",
property: "log", "property": "log"
}, }
], ],
"no-restricted-syntax": ["error"], "no-restricted-syntax": ["error"],
"no-return-assign": ["error"], "no-return-assign": ["error"],
@ -255,8 +295,8 @@ module.exports = {
"no-self-assign": [ "no-self-assign": [
"error", "error",
{ {
props: false, "props": false
}, }
], ],
"no-self-compare": ["error"], "no-self-compare": ["error"],
"no-sequences": ["error"], "no-sequences": ["error"],
@ -293,10 +333,10 @@ module.exports = {
"no-useless-rename": [ "no-useless-rename": [
"error", "error",
{ {
ignoreDestructuring: false, "ignoreDestructuring": false,
ignoreExport: false, "ignoreExport": false,
ignoreImport: false, "ignoreImport": false
}, }
], ],
"no-useless-return": ["error"], "no-useless-return": ["error"],
"no-var": ["error"], "no-var": ["error"],
@ -304,7 +344,10 @@ module.exports = {
"no-warning-comments": ["error"], "no-warning-comments": ["error"],
"no-whitespace-before-property": ["error"], "no-whitespace-before-property": ["error"],
"no-with": ["error"], "no-with": ["error"],
"nonblock-statement-body-position": ["error", "below"], "nonblock-statement-body-position": [
"error",
"below"
],
"object-curly-newline": ["error"], "object-curly-newline": ["error"],
"object-curly-spacing": ["error"], "object-curly-spacing": ["error"],
"object-property-newline": ["error"], "object-property-newline": ["error"],
@ -312,7 +355,10 @@ module.exports = {
"one-var": ["off"], "one-var": ["off"],
"one-var-declaration-per-line": ["error"], "one-var-declaration-per-line": ["error"],
"operator-assignment": ["error"], "operator-assignment": ["error"],
"operator-linebreak": ["error", "none"], "operator-linebreak": [
"error",
"none"
],
"padded-blocks": ["off"], "padded-blocks": ["off"],
"padding-line-between-statements": ["error"], "padding-line-between-statements": ["error"],
"prefer-arrow-callback": ["error"], "prefer-arrow-callback": ["error"],
@ -325,15 +371,24 @@ module.exports = {
"prefer-spread": ["error"], "prefer-spread": ["error"],
"prefer-template": ["error"], "prefer-template": ["error"],
"quote-props": ["error"], "quote-props": ["error"],
quotes: ["error"], "quotes": ["error"],
radix: ["error", "as-needed"], "radix": [
"error",
"as-needed"
],
"require-await": ["error"], "require-await": ["error"],
"require-jsdoc": ["off"], "require-jsdoc": ["off"],
"require-yield": ["error"], "require-yield": ["error"],
"rest-spread-spacing": ["error", "never"], "rest-spread-spacing": [
semi: ["error"], "error",
"never"
],
"semi": ["error"],
"semi-spacing": ["error"], "semi-spacing": ["error"],
"semi-style": ["error", "last"], "semi-style": [
"error",
"last"
],
"sort-imports": ["error"], "sort-imports": ["error"],
"sort-keys": ["error"], "sort-keys": ["error"],
"sort-vars": ["error"], "sort-vars": ["error"],
@ -343,25 +398,37 @@ module.exports = {
"space-infix-ops": ["error"], "space-infix-ops": ["error"],
"space-unary-ops": ["error"], "space-unary-ops": ["error"],
"spaced-comment": ["error"], "spaced-comment": ["error"],
strict: ["error"], "strict": ["error"],
"switch-colon-spacing": [ "switch-colon-spacing": [
"error", "error",
{ {
after: true, "after": true,
before: false, "before": false
}, }
], ],
"symbol-description": ["error"], "symbol-description": ["error"],
"template-curly-spacing": ["error"], "template-curly-spacing": ["error"],
"template-tag-spacing": ["error"], "template-tag-spacing": ["error"],
"unicode-bom": ["error", "never"], "unicode-bom": [
"error",
"never"
],
"use-isnan": ["error"], "use-isnan": ["error"],
"valid-jsdoc": ["error"], "valid-jsdoc": ["error"],
"valid-typeof": ["error"], "valid-typeof": ["error"],
"vars-on-top": ["error"], "vars-on-top": ["error"],
"wrap-iife": ["error", "any"], "wrap-iife": [
"error",
"any"
],
"wrap-regex": ["error"], "wrap-regex": ["error"],
"yield-star-spacing": ["error", "before"], "yield-star-spacing": [
yoda: ["error", "never"], "error",
}, "before"
],
"yoda": [
"error",
"never"
]
}
}; };

@ -8,18 +8,16 @@ const path = require("path");
const exec = require("child_process").exec; const exec = require("child_process").exec;
const semver = require("./semver"); const semver = require("./semver");
const getPackageJson = () => const getPackageJson = () => new Promise((resolve, reject) => {
new Promise((resolve, reject) => {
try { try {
/* eslint-disable-next-line global-require */ /* eslint-disable-next-line global-require */
resolve(require(path.resolve(process.cwd(), "package.json"))); resolve(require(path.resolve(process.cwd(), "package.json")));
} catch (error) { } catch (error) {
reject(error); reject(error);
} }
}); });
const getEngines = (data) => const getEngines = (data) => new Promise((resolve, reject) => {
new Promise((resolve, reject) => {
let versions = null; let versions = null;
if (data.engines) { if (data.engines) {
@ -31,10 +29,9 @@ const getEngines = (data) =>
} else { } else {
reject("Missing or improper 'engines' property in 'package.json'"); reject("Missing or improper 'engines' property in 'package.json'");
} }
}); });
const checkNpmVersion = (engines) => const checkNpmVersion = (engines) => new Promise((resolve, reject) => {
new Promise((resolve, reject) => {
exec("npm -v", (error, stdout, stderr) => { exec("npm -v", (error, stdout, stderr) => {
if (error) { if (error) {
reject(`Unable to find NPM version\n${stderr}`); reject(`Unable to find NPM version\n${stderr}`);
@ -46,25 +43,20 @@ const checkNpmVersion = (engines) =>
if (semver.satisfies(npmVersion, engineVersion)) { if (semver.satisfies(npmVersion, engineVersion)) {
resolve(); resolve();
} else { } else {
reject( reject(`Incorrect npm version\n'package.json' specifies "${engineVersion}", you are currently running "${npmVersion}".`);
`Incorrect npm version\n'package.json' specifies "${engineVersion}", you are currently running "${npmVersion}".`,
);
} }
}); });
}); });
const checkNodeVersion = (engines) => const checkNodeVersion = (engines) => new Promise((resolve, reject) => {
new Promise((resolve, reject) => {
const nodeVersion = process.version.substring(1); const nodeVersion = process.version.substring(1);
if (semver.satisfies(nodeVersion, engines.node)) { if (semver.satisfies(nodeVersion, engines.node)) {
resolve(engines); resolve(engines);
} else { } else {
reject( reject(`Incorrect node version\n'package.json' specifies "${engines.node}", you are currently running "${process.version}".`);
`Incorrect node version\n'package.json' specifies "${engines.node}", you are currently running "${process.version}".`,
);
} }
}); });
getPackageJson() getPackageJson()
.then(getEngines) .then(getEngines)
@ -77,5 +69,5 @@ getPackageJson()
/* eslint-disable no-console, no-process-exit */ /* eslint-disable no-console, no-process-exit */
console.error(error); console.error(error);
process.exit(1); process.exit(1);
}, }
); );

@ -444,6 +444,7 @@ function parseComparator(comp, loose) {
} }
class SemVer { class SemVer {
/** /**
* A semantic version. * A semantic version.
* @param {string} version The version. * @param {string} version The version.
@ -487,7 +488,7 @@ class SemVer {
// Numberify any prerelease numeric ids // Numberify any prerelease numeric ids
if (matches[4]) { if (matches[4]) {
this.prerelease = matches[4].split(".").map((id) => { this.prerelease = matches[4].split(".").map((id) => {
if (/^[0-9]+$/.test(id)) { if ((/^[0-9]+$/).test(id)) {
const num = Number(id); const num = Number(id);
if (num >= 0 && num < MAX_SAFE_INTEGER) { if (num >= 0 && num < MAX_SAFE_INTEGER) {
return num; return num;
@ -531,9 +532,7 @@ class SemVer {
} }
return ( return (
compareIdentifiers(this.major, other.major) || compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch)
compareIdentifiers(this.minor, other.minor) ||
compareIdentifiers(this.patch, other.patch)
); );
} }
@ -573,8 +572,7 @@ class SemVer {
} }
} }
const compare = (leftVersion, rightVersion, loose) => const compare = (leftVersion, rightVersion, loose) => new SemVer(leftVersion, loose).compare(new SemVer(rightVersion, loose));
new SemVer(leftVersion, loose).compare(new SemVer(rightVersion, loose));
const gt = (leftVersion, rightVersion, loose) => compare(leftVersion, rightVersion, loose) > 0; const gt = (leftVersion, rightVersion, loose) => compare(leftVersion, rightVersion, loose) > 0;
const lt = (leftVersion, rightVersion, loose) => compare(leftVersion, rightVersion, loose) < 0; const lt = (leftVersion, rightVersion, loose) => compare(leftVersion, rightVersion, loose) < 0;
const eq = (leftVersion, rightVersion, loose) => compare(leftVersion, rightVersion, loose) === 0; const eq = (leftVersion, rightVersion, loose) => compare(leftVersion, rightVersion, loose) === 0;

@ -2363,7 +2363,7 @@ function resetAugmentation(newAugObject: Augmentation): void {
if (!(newAugObject instanceof Augmentation)) { if (!(newAugObject instanceof Augmentation)) {
throw new Error("Invalid argument 'newAugObject' passed into resetAugmentation"); throw new Error("Invalid argument 'newAugObject' passed into resetAugmentation");
} }
var name = newAugObject.name; const name = newAugObject.name;
if (augmentationExists(name)) { if (augmentationExists(name)) {
delete Augmentations[name]; delete Augmentations[name];
} }
@ -2397,7 +2397,7 @@ function applyAugmentation(aug: IPlayerOwnedAugmentation, reapply = false): void
// Push onto Player's Augmentation list // Push onto Player's Augmentation list
if (!reapply) { if (!reapply) {
var ownedAug = new PlayerOwnedAugmentation(aug.name); const ownedAug = new PlayerOwnedAugmentation(aug.name);
Player.augmentations.push(ownedAug); Player.augmentations.push(ownedAug);
} }
} }

@ -26,7 +26,6 @@ function calculateAugmentedStats(): any {
function Improvements({ r }: { r: number }): React.ReactElement { function Improvements({ r }: { r: number }): React.ReactElement {
if (r) { if (r) {
console.log(r);
return ( return (
<> <>
<TableCell key="2"> <TableCell key="2">

@ -47,7 +47,7 @@ export function joinFaction(faction: Faction): void {
Factions[enemy].isBanned = true; Factions[enemy].isBanned = true;
} }
} }
for (var i = 0; i < Player.factionInvitations.length; ++i) { for (let i = 0; i < Player.factionInvitations.length; ++i) {
if (Player.factionInvitations[i] == faction.name || Factions[Player.factionInvitations[i]].isBanned) { if (Player.factionInvitations[i] == faction.name || Factions[Player.factionInvitations[i]].isBanned) {
Player.factionInvitations.splice(i, 1); Player.factionInvitations.splice(i, 1);
i--; i--;
@ -91,28 +91,28 @@ export function hasAugmentationPrereqs(aug: Augmentation): boolean {
export function purchaseAugmentation(aug: Augmentation, fac: Faction, sing = false): string { export function purchaseAugmentation(aug: Augmentation, fac: Faction, sing = false): string {
const factionInfo = fac.getInfo(); const factionInfo = fac.getInfo();
var hasPrereqs = hasAugmentationPrereqs(aug); const hasPrereqs = hasAugmentationPrereqs(aug);
if (!hasPrereqs) { if (!hasPrereqs) {
var txt = "You must first purchase or install " + aug.prereqs.join(",") + " before you can " + "purchase this one."; const txt = "You must first purchase or install " + aug.prereqs.join(",") + " before you can " + "purchase this one.";
if (sing) { if (sing) {
return txt; return txt;
} else { } else {
dialogBoxCreate(txt); dialogBoxCreate(txt);
} }
} else if (aug.baseCost !== 0 && Player.money.lt(aug.baseCost * factionInfo.augmentationPriceMult)) { } else if (aug.baseCost !== 0 && Player.money.lt(aug.baseCost * factionInfo.augmentationPriceMult)) {
let txt = "You don't have enough money to purchase " + aug.name; const txt = "You don't have enough money to purchase " + aug.name;
if (sing) { if (sing) {
return txt; return txt;
} }
dialogBoxCreate(txt); dialogBoxCreate(txt);
} else if (fac.playerReputation < aug.baseRepRequirement) { } else if (fac.playerReputation < aug.baseRepRequirement) {
let txt = "You don't have enough faction reputation to purchase " + aug.name; const txt = "You don't have enough faction reputation to purchase " + aug.name;
if (sing) { if (sing) {
return txt; return txt;
} }
dialogBoxCreate(txt); dialogBoxCreate(txt);
} else if (aug.baseCost === 0 || Player.money.gte(aug.baseCost * factionInfo.augmentationPriceMult)) { } else if (aug.baseCost === 0 || Player.money.gte(aug.baseCost * factionInfo.augmentationPriceMult)) {
var queuedAugmentation = new PlayerOwnedAugmentation(aug.name); const queuedAugmentation = new PlayerOwnedAugmentation(aug.name);
if (aug.name == AugmentationNames.NeuroFluxGovernor) { if (aug.name == AugmentationNames.NeuroFluxGovernor) {
queuedAugmentation.level = getNextNeurofluxLevel(); queuedAugmentation.level = getNextNeurofluxLevel();
} }
@ -122,18 +122,18 @@ export function purchaseAugmentation(aug: Augmentation, fac: Faction, sing = fal
// If you just purchased Neuroflux Governor, recalculate the cost // If you just purchased Neuroflux Governor, recalculate the cost
if (aug.name == AugmentationNames.NeuroFluxGovernor) { if (aug.name == AugmentationNames.NeuroFluxGovernor) {
var nextLevel = getNextNeurofluxLevel(); let nextLevel = getNextNeurofluxLevel();
--nextLevel; --nextLevel;
var mult = Math.pow(CONSTANTS.NeuroFluxGovernorLevelMult, nextLevel); const mult = Math.pow(CONSTANTS.NeuroFluxGovernorLevelMult, nextLevel);
aug.baseRepRequirement = 500 * mult * BitNodeMultipliers.AugmentationRepCost; aug.baseRepRequirement = 500 * mult * BitNodeMultipliers.AugmentationRepCost;
aug.baseCost = 750e3 * mult * BitNodeMultipliers.AugmentationMoneyCost; aug.baseCost = 750e3 * mult * BitNodeMultipliers.AugmentationMoneyCost;
for (var i = 0; i < Player.queuedAugmentations.length - 1; ++i) { for (let i = 0; i < Player.queuedAugmentations.length - 1; ++i) {
aug.baseCost *= CONSTANTS.MultipleAugMultiplier * [1, 0.96, 0.94, 0.93][SourceFileFlags[11]]; aug.baseCost *= CONSTANTS.MultipleAugMultiplier * [1, 0.96, 0.94, 0.93][SourceFileFlags[11]];
} }
} }
for (var name in Augmentations) { for (const name in Augmentations) {
if (Augmentations.hasOwnProperty(name)) { if (Augmentations.hasOwnProperty(name)) {
Augmentations[name].baseCost *= CONSTANTS.MultipleAugMultiplier * [1, 0.96, 0.94, 0.93][SourceFileFlags[11]]; Augmentations[name].baseCost *= CONSTANTS.MultipleAugMultiplier * [1, 0.96, 0.94, 0.93][SourceFileFlags[11]];
} }

@ -52,7 +52,6 @@ export function DonateOption(props: IProps): React.ReactElement {
const amt = numeralWrapper.parseMoney(event.target.value); const amt = numeralWrapper.parseMoney(event.target.value);
if (event.target.value === "" || isNaN(amt)) setDonateAmt(null); if (event.target.value === "" || isNaN(amt)) setDonateAmt(null);
else setDonateAmt(amt); else setDonateAmt(amt);
console.log("set");
} }
function donate(): void { function donate(): void {

@ -51,7 +51,7 @@ function Requirements(props: IReqProps): React.ReactElement {
); );
} }
let color = !props.hasRep || !props.hasCost ? "error" : "primary"; const color = !props.hasRep || !props.hasCost ? "error" : "primary";
return ( return (
<React.Fragment key="f"> <React.Fragment key="f">
<TableCell key={1}> <TableCell key={1}>

@ -7,9 +7,7 @@ interface IProps {
export function KeyHandler(props: IProps): React.ReactElement { export function KeyHandler(props: IProps): React.ReactElement {
useEffect(() => { useEffect(() => {
console.log("binding");
function press(this: Document, event: KeyboardEvent): void { function press(this: Document, event: KeyboardEvent): void {
console.log("press!");
const f = props.onKeyDown.bind(this); const f = props.onKeyDown.bind(this);
f(event); f(event);
} }

@ -20,7 +20,7 @@ function sendMessage(msg: Message, forced = false): void {
} }
function showMessage(msg: Message): void { function showMessage(msg: Message): void {
var txt = const txt =
"Message received from unknown sender: <br><br>" + "Message received from unknown sender: <br><br>" +
"<i>" + "<i>" +
msg.msg + msg.msg +
@ -33,12 +33,12 @@ function showMessage(msg: Message): void {
//Adds a message to a server //Adds a message to a server
function addMessageToServer(msg: Message, serverHostname: string): void { function addMessageToServer(msg: Message, serverHostname: string): void {
var server = GetServerByHostname(serverHostname); const server = GetServerByHostname(serverHostname);
if (server == null) { if (server == null) {
console.warn(`Could not find server ${serverHostname}`); console.warn(`Could not find server ${serverHostname}`);
return; return;
} }
for (var i = 0; i < server.messages.length; ++i) { for (let i = 0; i < server.messages.length; ++i) {
const msg = server.messages[i]; const msg = server.messages[i];
if (typeof msg === "string") continue; if (typeof msg === "string") continue;
if (msg.filename === msg.filename) { if (msg.filename === msg.filename) {
@ -107,7 +107,7 @@ function loadMessages(saveString: string): void {
Messages = JSON.parse(saveString, Reviver); Messages = JSON.parse(saveString, Reviver);
} }
let MessageFilenames = { const MessageFilenames = {
Jumper0: "j0.msg", Jumper0: "j0.msg",
Jumper1: "j1.msg", Jumper1: "j1.msg",
Jumper2: "j2.msg", Jumper2: "j2.msg",

@ -15,9 +15,9 @@ export function netscriptDelay(time: number, workerScript: WorkerScript): Promis
} }
export function makeRuntimeRejectMsg(workerScript: WorkerScript, msg: string, exp: any = null) { export function makeRuntimeRejectMsg(workerScript: WorkerScript, msg: string, exp: any = null) {
var lineNum = ""; let lineNum = "";
if (exp != null) { if (exp != null) {
var num = getErrorLineNumber(exp, workerScript); const num = getErrorLineNumber(exp, workerScript);
lineNum = " (Line " + num + ")"; lineNum = " (Line " + num + ")";
} }
const server = AllServers[workerScript.serverIp]; const server = AllServers[workerScript.serverIp];
@ -72,7 +72,7 @@ export function isScriptErrorMessage(msg: string): boolean {
if (!isString(msg)) { if (!isString(msg)) {
return false; return false;
} }
let splitMsg = msg.split("|"); const splitMsg = msg.split("|");
if (splitMsg.length != 4) { if (splitMsg.length != 4) {
return false; return false;
} }

@ -193,7 +193,7 @@ function toNative(pseudoObj: any): any {
} else { } else {
// Object. // Object.
nativeObj = {}; nativeObj = {};
for (var key in pseudoObj.properties) { for (const key in pseudoObj.properties) {
const val = pseudoObj.properties[key]; const val = pseudoObj.properties[key];
nativeObj[key] = toNative(val); nativeObj[key] = toNative(val);
} }
@ -253,7 +253,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
* @returns {Server} The specified Server * @returns {Server} The specified Server
*/ */
const safeGetServer = function (ip: any, callingFnName: any = "") { const safeGetServer = function (ip: any, callingFnName: any = "") {
var server = getServer(ip); const server = getServer(ip);
if (server == null) { if (server == null) {
throw makeRuntimeErrorMsg(callingFnName, `Invalid IP/hostname: ${ip}`); throw makeRuntimeErrorMsg(callingFnName, `Invalid IP/hostname: ${ip}`);
} }
@ -447,7 +447,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
return null; return null;
} }
let firefoxCall = parseFirefoxStackline(stackline); const firefoxCall = parseFirefoxStackline(stackline);
if (firefoxCall) { if (firefoxCall) {
call = firefoxCall; call = firefoxCall;
} }
@ -698,10 +698,10 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
if (workerScript.env.stopFlag) { if (workerScript.env.stopFlag) {
return Promise.reject(workerScript); return Promise.reject(workerScript);
} }
var hackChance = calculateHackingChance(server, Player); const hackChance = calculateHackingChance(server, Player);
var rand = Math.random(); const rand = Math.random();
var expGainedOnSuccess = calculateHackingExpGain(server, Player) * threads; let expGainedOnSuccess = calculateHackingExpGain(server, Player) * threads;
var expGainedOnFailure = expGainedOnSuccess / 4; const expGainedOnFailure = expGainedOnSuccess / 4;
if (rand < hackChance) { if (rand < hackChance) {
// Success! // Success!
const percentHacked = calculatePercentMoneyHacked(server, Player); const percentHacked = calculatePercentMoneyHacked(server, Player);
@ -918,12 +918,12 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
vsprintf: vsprintf, vsprintf: vsprintf,
scan: function (ip: any = workerScript.serverIp, hostnames: any = true): any { scan: function (ip: any = workerScript.serverIp, hostnames: any = true): any {
updateDynamicRam("scan", getRamCost("scan")); updateDynamicRam("scan", getRamCost("scan"));
var server = getServer(ip); const server = getServer(ip);
if (server == null) { if (server == null) {
throw makeRuntimeErrorMsg("scan", `Invalid IP/hostname: ${ip}.`); throw makeRuntimeErrorMsg("scan", `Invalid IP/hostname: ${ip}.`);
} }
var out = []; const out = [];
for (var i = 0; i < server.serversOnNetwork.length; i++) { for (let i = 0; i < server.serversOnNetwork.length; i++) {
var entry; var entry;
const s = getServerOnNetwork(server, i); const s = getServerOnNetwork(server, i);
if (s === null) continue; if (s === null) continue;
@ -1026,7 +1026,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
throw makeRuntimeErrorMsg("grow", canHack.msg || ""); throw makeRuntimeErrorMsg("grow", canHack.msg || "");
} }
var growTime = calculateGrowTime(server, Player); const growTime = calculateGrowTime(server, Player);
workerScript.log( workerScript.log(
"grow", "grow",
`Executing on '${server.hostname}' in ${convertTimeMsToTimeElapsedString( `Executing on '${server.hostname}' in ${convertTimeMsToTimeElapsedString(
@ -1043,7 +1043,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
processSingleServerGrowth(server, threads, Player, host.cpuCores); processSingleServerGrowth(server, threads, Player, host.cpuCores);
const moneyAfter = server.moneyAvailable; const moneyAfter = server.moneyAvailable;
workerScript.scriptRef.recordGrow(server.ip, threads); workerScript.scriptRef.recordGrow(server.ip, threads);
var expGain = calculateHackingExpGain(server, Player) * threads; const expGain = calculateHackingExpGain(server, Player) * threads;
const logGrowPercent = moneyAfter / moneyBefore - 1; const logGrowPercent = moneyAfter / moneyBefore - 1;
workerScript.log( workerScript.log(
"grow", "grow",
@ -1077,7 +1077,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
}, },
weaken: function (ip: any, { threads: requestedThreads }: any = {}): any { weaken: function (ip: any, { threads: requestedThreads }: any = {}): any {
updateDynamicRam("weaken", getRamCost("weaken")); updateDynamicRam("weaken", getRamCost("weaken"));
var threads = resolveNetscriptRequestedThreads(workerScript, "weaken", requestedThreads); const threads = resolveNetscriptRequestedThreads(workerScript, "weaken", requestedThreads);
if (ip === undefined) { if (ip === undefined) {
throw makeRuntimeErrorMsg("weaken", "Takes 1 argument."); throw makeRuntimeErrorMsg("weaken", "Takes 1 argument.");
} }
@ -1355,11 +1355,11 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
if (isNaN(threads) || threads <= 0) { if (isNaN(threads) || threads <= 0) {
throw makeRuntimeErrorMsg("run", `Invalid thread count. Must be numeric and > 0, is ${threads}`); throw makeRuntimeErrorMsg("run", `Invalid thread count. Must be numeric and > 0, is ${threads}`);
} }
var argsForNewScript = []; const argsForNewScript = [];
for (var i = 2; i < arguments.length; ++i) { for (let i = 2; i < arguments.length; ++i) {
argsForNewScript.push(arguments[i]); argsForNewScript.push(arguments[i]);
} }
var scriptServer = getServer(workerScript.serverIp); const scriptServer = getServer(workerScript.serverIp);
if (scriptServer == null) { if (scriptServer == null) {
throw makeRuntimeErrorMsg("run", "Could not find server. This is a bug. Report to dev."); throw makeRuntimeErrorMsg("run", "Could not find server. This is a bug. Report to dev.");
} }
@ -1374,11 +1374,11 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
if (isNaN(threads) || threads <= 0) { if (isNaN(threads) || threads <= 0) {
throw makeRuntimeErrorMsg("exec", `Invalid thread count. Must be numeric and > 0, is ${threads}`); throw makeRuntimeErrorMsg("exec", `Invalid thread count. Must be numeric and > 0, is ${threads}`);
} }
var argsForNewScript = []; const argsForNewScript = [];
for (var i = 3; i < arguments.length; ++i) { for (let i = 3; i < arguments.length; ++i) {
argsForNewScript.push(arguments[i]); argsForNewScript.push(arguments[i]);
} }
var server = getServer(ip); const server = getServer(ip);
if (server == null) { if (server == null) {
throw makeRuntimeErrorMsg("exec", `Invalid IP/hostname: ${ip}`); throw makeRuntimeErrorMsg("exec", `Invalid IP/hostname: ${ip}`);
} }
@ -1395,11 +1395,11 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
if (isNaN(threads) || threads <= 0) { if (isNaN(threads) || threads <= 0) {
throw makeRuntimeErrorMsg("spawn", `Invalid thread count. Must be numeric and > 0, is ${threads}`); throw makeRuntimeErrorMsg("spawn", `Invalid thread count. Must be numeric and > 0, is ${threads}`);
} }
var argsForNewScript = []; const argsForNewScript = [];
for (var i = 2; i < arguments.length; ++i) { for (let i = 2; i < arguments.length; ++i) {
argsForNewScript.push(arguments[i]); argsForNewScript.push(arguments[i]);
} }
var scriptServer = getServer(workerScript.serverIp); const scriptServer = getServer(workerScript.serverIp);
if (scriptServer == null) { if (scriptServer == null) {
throw makeRuntimeErrorMsg("spawn", "Could not find server. This is a bug. Report to dev"); throw makeRuntimeErrorMsg("spawn", "Could not find server. This is a bug. Report to dev");
} }
@ -1490,7 +1490,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
} }
if (scriptname && scriptname.constructor === Array) { if (scriptname && scriptname.constructor === Array) {
// Recursively call scp on all elements of array // Recursively call scp on all elements of array
var res = false; let res = false;
scriptname.forEach(function (script) { scriptname.forEach(function (script) {
if (NetscriptFunctions(workerScript).scp(script, ip1, ip2)) { if (NetscriptFunctions(workerScript).scp(script, ip1, ip2)) {
res = true; res = true;
@ -1509,7 +1509,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
throw makeRuntimeErrorMsg("scp", "Only works for .script, .lit, and .txt files"); throw makeRuntimeErrorMsg("scp", "Only works for .script, .lit, and .txt files");
} }
var destServer, currServ; let destServer, currServ;
if (ip2 != null) { if (ip2 != null) {
// 3 Argument version: scriptname, source, destination // 3 Argument version: scriptname, source, destination
@ -1545,7 +1545,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
// Scp for lit files // Scp for lit files
if (scriptname.endsWith(".lit")) { if (scriptname.endsWith(".lit")) {
var found = false; let found = false;
for (var i = 0; i < currServ.messages.length; ++i) { for (var i = 0; i < currServ.messages.length; ++i) {
if (!(currServ.messages[i] instanceof Message) && currServ.messages[i] == scriptname) { if (!(currServ.messages[i] instanceof Message) && currServ.messages[i] == scriptname) {
found = true; found = true;
@ -1591,7 +1591,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
return true; return true;
} }
} }
var newFile = new TextFile(txtFile.fn, txtFile.text); const newFile = new TextFile(txtFile.fn, txtFile.text);
destServer.textFiles.push(newFile); destServer.textFiles.push(newFile);
workerScript.log("scp", `File '${scriptname}' copied over to '${destServer.hostname}'.`); workerScript.log("scp", `File '${scriptname}' copied over to '${destServer.hostname}'.`);
return true; return true;
@ -1716,7 +1716,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
}, },
ps: function (ip: any = workerScript.serverIp): any { ps: function (ip: any = workerScript.serverIp): any {
updateDynamicRam("ps", getRamCost("ps")); updateDynamicRam("ps", getRamCost("ps"));
var server = getServer(ip); const server = getServer(ip);
if (server == null) { if (server == null) {
throw makeRuntimeErrorMsg("ps", `Invalid IP/hostname: ${ip}`); throw makeRuntimeErrorMsg("ps", `Invalid IP/hostname: ${ip}`);
} }
@ -1737,7 +1737,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
if (ip === undefined) { if (ip === undefined) {
throw makeRuntimeErrorMsg("hasRootAccess", "Takes 1 argument"); throw makeRuntimeErrorMsg("hasRootAccess", "Takes 1 argument");
} }
var server = getServer(ip); const server = getServer(ip);
if (server == null) { if (server == null) {
throw makeRuntimeErrorMsg("hasRootAccess", `Invalid IP/hostname: ${ip}`); throw makeRuntimeErrorMsg("hasRootAccess", `Invalid IP/hostname: ${ip}`);
} }
@ -1745,7 +1745,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
}, },
getIp: function (): any { getIp: function (): any {
updateDynamicRam("getIp", getRamCost("getIp")); updateDynamicRam("getIp", getRamCost("getIp"));
var scriptServer = getServer(workerScript.serverIp); const scriptServer = getServer(workerScript.serverIp);
if (scriptServer == null) { if (scriptServer == null) {
throw makeRuntimeErrorMsg("getIp", "Could not find server. This is a bug. Report to dev."); throw makeRuntimeErrorMsg("getIp", "Could not find server. This is a bug. Report to dev.");
} }
@ -1753,7 +1753,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
}, },
getHostname: function (): any { getHostname: function (): any {
updateDynamicRam("getHostname", getRamCost("getHostname")); updateDynamicRam("getHostname", getRamCost("getHostname"));
var scriptServer = getServer(workerScript.serverIp); const scriptServer = getServer(workerScript.serverIp);
if (scriptServer == null) { if (scriptServer == null) {
throw makeRuntimeErrorMsg("getHostname", "Could not find server. This is a bug. Report to dev."); throw makeRuntimeErrorMsg("getHostname", "Could not find server. This is a bug. Report to dev.");
} }
@ -1789,7 +1789,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
if (SourceFileFlags[5] <= 0 && Player.bitNodeN !== 5) { if (SourceFileFlags[5] <= 0 && Player.bitNodeN !== 5) {
throw makeRuntimeErrorMsg("getBitNodeMultipliers", "Requires Source-File 5 to run."); throw makeRuntimeErrorMsg("getBitNodeMultipliers", "Requires Source-File 5 to run.");
} }
let copy = Object.assign({}, BitNodeMultipliers); const copy = Object.assign({}, BitNodeMultipliers);
return copy; return copy;
}, },
getServer: function (ip: any): any { getServer: function (ip: any): any {
@ -1969,7 +1969,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
if (filename === undefined) { if (filename === undefined) {
throw makeRuntimeErrorMsg("fileExists", "Usage: fileExists(scriptname, [server])"); throw makeRuntimeErrorMsg("fileExists", "Usage: fileExists(scriptname, [server])");
} }
var server = getServer(ip); const server = getServer(ip);
if (server == null) { if (server == null) {
throw makeRuntimeErrorMsg("fileExists", `Invalid IP/hostname: ${ip}`); throw makeRuntimeErrorMsg("fileExists", `Invalid IP/hostname: ${ip}`);
} }
@ -1988,7 +1988,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
return true; return true;
} }
} }
var txtFile = getTextFile(filename, server); const txtFile = getTextFile(filename, server);
if (txtFile != null) { if (txtFile != null) {
return true; return true;
} }
@ -2034,7 +2034,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
getStockPosition: function (symbol: any): any { getStockPosition: function (symbol: any): any {
updateDynamicRam("getStockPosition", getRamCost("getStockPosition")); updateDynamicRam("getStockPosition", getRamCost("getStockPosition"));
checkTixApiAccess("getStockPosition"); checkTixApiAccess("getStockPosition");
var stock = SymbolToStockMap[symbol]; const stock = SymbolToStockMap[symbol];
if (stock == null) { if (stock == null) {
throw makeRuntimeErrorMsg("getStockPosition", `Invalid stock symbol: ${symbol}`); throw makeRuntimeErrorMsg("getStockPosition", `Invalid stock symbol: ${symbol}`);
} }
@ -2220,7 +2220,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
} else { } else {
throw makeRuntimeErrorMsg("cancelOrder", `Invalid position type: ${pos}`); throw makeRuntimeErrorMsg("cancelOrder", `Invalid position type: ${pos}`);
} }
var params = { const params = {
stock: stock, stock: stock,
shares: shares, shares: shares,
price: price, price: price,
@ -2241,7 +2241,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
const orders: any = {}; const orders: any = {};
const stockMarketOrders = StockMarket["Orders"]; const stockMarketOrders = StockMarket["Orders"];
for (let symbol in stockMarketOrders) { for (const symbol in stockMarketOrders) {
const orderBook = stockMarketOrders[symbol]; const orderBook = stockMarketOrders[symbol];
if (orderBook.constructor === Array && orderBook.length > 0) { if (orderBook.constructor === Array && orderBook.length > 0) {
orders[symbol] = []; orders[symbol] = [];
@ -2274,7 +2274,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
} }
const stock = getStockFromSymbol(symbol, "getStockForecast"); const stock = getStockFromSymbol(symbol, "getStockForecast");
var forecast = 50; let forecast = 50;
stock.b ? (forecast += stock.otlkMag) : (forecast -= stock.otlkMag); stock.b ? (forecast += stock.otlkMag) : (forecast -= stock.otlkMag);
return forecast / 100; // Convert from percentage to decimal return forecast / 100; // Convert from percentage to decimal
}, },
@ -2339,7 +2339,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
}, },
purchaseServer: function (hostname: any, ram: any): any { purchaseServer: function (hostname: any, ram: any): any {
updateDynamicRam("purchaseServer", getRamCost("purchaseServer")); updateDynamicRam("purchaseServer", getRamCost("purchaseServer"));
var hostnameStr = String(hostname); let hostnameStr = String(hostname);
hostnameStr = hostnameStr.replace(/\s+/g, ""); hostnameStr = hostnameStr.replace(/\s+/g, "");
if (hostnameStr == "") { if (hostnameStr == "") {
workerScript.log("purchaseServer", `Invalid argument: hostname='${hostnameStr}'`); workerScript.log("purchaseServer", `Invalid argument: hostname='${hostnameStr}'`);
@ -2408,7 +2408,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
return false; return false;
} }
var ip = server.ip; const ip = server.ip;
// Can't delete server you're currently connected to // Can't delete server you're currently connected to
if (server.isConnectedTo) { if (server.isConnectedTo) {
@ -2432,7 +2432,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
} }
// Delete from player's purchasedServers array // Delete from player's purchasedServers array
var found = false; let found = false;
for (var i = 0; i < Player.purchasedServers.length; ++i) { for (var i = 0; i < Player.purchasedServers.length; ++i) {
if (ip == Player.purchasedServers[i]) { if (ip == Player.purchasedServers[i]) {
found = true; found = true;
@ -2454,7 +2454,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
// Delete from home computer // Delete from home computer
found = false; found = false;
var homeComputer = Player.getHomeComputer(); const homeComputer = Player.getHomeComputer();
for (var i = 0; i < homeComputer.serversOnNetwork.length; ++i) { for (var i = 0; i < homeComputer.serversOnNetwork.length; ++i) {
if (ip == homeComputer.serversOnNetwork[i]) { if (ip == homeComputer.serversOnNetwork[i]) {
homeComputer.serversOnNetwork.splice(i, 1); homeComputer.serversOnNetwork.splice(i, 1);
@ -2471,10 +2471,10 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
}, },
getPurchasedServers: function (hostname: any = true): any { getPurchasedServers: function (hostname: any = true): any {
updateDynamicRam("getPurchasedServers", getRamCost("getPurchasedServers")); updateDynamicRam("getPurchasedServers", getRamCost("getPurchasedServers"));
var res: string[] = []; const res: string[] = [];
Player.purchasedServers.forEach(function (ip) { Player.purchasedServers.forEach(function (ip) {
if (hostname) { if (hostname) {
var server = getServer(ip); const server = getServer(ip);
if (server == null) { if (server == null) {
throw makeRuntimeErrorMsg("getPurchasedServers", "Could not find server. This is a bug. Report to dev."); throw makeRuntimeErrorMsg("getPurchasedServers", "Could not find server. This is a bug. Report to dev.");
} }
@ -2497,7 +2497,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
`Trying to write to invalid port: ${port}. Only ports 1-${CONSTANTS.NumNetscriptPorts} are valid.`, `Trying to write to invalid port: ${port}. Only ports 1-${CONSTANTS.NumNetscriptPorts} are valid.`,
); );
} }
var iport = NetscriptPorts[port - 1]; const iport = NetscriptPorts[port - 1];
if (iport == null || !(iport instanceof Object)) { if (iport == null || !(iport instanceof Object)) {
throw makeRuntimeErrorMsg("write", `Could not find port: ${port}. This is a bug. Report to dev.`); throw makeRuntimeErrorMsg("write", `Could not find port: ${port}. This is a bug. Report to dev.`);
} }
@ -2538,7 +2538,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
script.markUpdated(); script.markUpdated();
} else { } else {
// Write to text file // Write to text file
let txtFile = getTextFile(fn, server); const txtFile = getTextFile(fn, server);
if (txtFile == null) { if (txtFile == null) {
createTextFile(fn, data, server); createTextFile(fn, data, server);
return true; return true;
@ -2585,28 +2585,28 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
`Invalid port: ${port}. Only ports 1-${CONSTANTS.NumNetscriptPorts} are valid.`, `Invalid port: ${port}. Only ports 1-${CONSTANTS.NumNetscriptPorts} are valid.`,
); );
} }
var iport = NetscriptPorts[port - 1]; const iport = NetscriptPorts[port - 1];
if (iport == null || !(iport instanceof Object)) { if (iport == null || !(iport instanceof Object)) {
throw makeRuntimeErrorMsg("read", `Could not find port: ${port}. This is a bug. Report to dev.`); throw makeRuntimeErrorMsg("read", `Could not find port: ${port}. This is a bug. Report to dev.`);
} }
return iport.read(); return iport.read();
} else if (isString(port)) { } else if (isString(port)) {
// Read from script or text file // Read from script or text file
let fn = port; const fn = port;
let server = getServer(workerScript.serverIp); const server = getServer(workerScript.serverIp);
if (server == null) { if (server == null) {
throw makeRuntimeErrorMsg("read", "Error getting Server. This is a bug. Report to dev."); throw makeRuntimeErrorMsg("read", "Error getting Server. This is a bug. Report to dev.");
} }
if (isScriptFilename(fn)) { if (isScriptFilename(fn)) {
// Read from script // Read from script
let script = workerScript.getScriptOnServer(fn, server); const script = workerScript.getScriptOnServer(fn, server);
if (script == null) { if (script == null) {
return ""; return "";
} }
return script.code; return script.code;
} else { } else {
// Read from text file // Read from text file
let txtFile = getTextFile(fn, server); const txtFile = getTextFile(fn, server);
if (txtFile !== null) { if (txtFile !== null) {
return txtFile.text; return txtFile.text;
} else { } else {
@ -2656,12 +2656,12 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
return iport.clear(); return iport.clear();
} else if (isString(port)) { } else if (isString(port)) {
// Clear text file // Clear text file
var fn = port; const fn = port;
var server = getServer(workerScript.serverIp); const server = getServer(workerScript.serverIp);
if (server == null) { if (server == null) {
throw makeRuntimeErrorMsg("clear", "Error getting Server. This is a bug. Report to dev."); throw makeRuntimeErrorMsg("clear", "Error getting Server. This is a bug. Report to dev.");
} }
var txtFile = getTextFile(fn, server); const txtFile = getTextFile(fn, server);
if (txtFile != null) { if (txtFile != null) {
txtFile.write(""); txtFile.write("");
} }
@ -2708,11 +2708,11 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
}, },
scriptRunning: function (scriptname: any, ip: any): any { scriptRunning: function (scriptname: any, ip: any): any {
updateDynamicRam("scriptRunning", getRamCost("scriptRunning")); updateDynamicRam("scriptRunning", getRamCost("scriptRunning"));
var server = getServer(ip); const server = getServer(ip);
if (server == null) { if (server == null) {
throw makeRuntimeErrorMsg("scriptRunning", `Invalid IP/hostname: ${ip}`); throw makeRuntimeErrorMsg("scriptRunning", `Invalid IP/hostname: ${ip}`);
} }
for (var i = 0; i < server.runningScripts.length; ++i) { for (let i = 0; i < server.runningScripts.length; ++i) {
if (server.runningScripts[i].filename == scriptname) { if (server.runningScripts[i].filename == scriptname) {
return true; return true;
} }
@ -2721,12 +2721,12 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
}, },
scriptKill: function (scriptname: any, ip: any): any { scriptKill: function (scriptname: any, ip: any): any {
updateDynamicRam("scriptKill", getRamCost("scriptKill")); updateDynamicRam("scriptKill", getRamCost("scriptKill"));
var server = getServer(ip); const server = getServer(ip);
if (server == null) { if (server == null) {
throw makeRuntimeErrorMsg("scriptKill", `Invalid IP/hostname: ${ip}`); throw makeRuntimeErrorMsg("scriptKill", `Invalid IP/hostname: ${ip}`);
} }
var suc = false; let suc = false;
for (var i = 0; i < server.runningScripts.length; ++i) { for (let i = 0; i < server.runningScripts.length; ++i) {
if (server.runningScripts[i].filename == scriptname) { if (server.runningScripts[i].filename == scriptname) {
killWorkerScript(server.runningScripts[i], server.ip); killWorkerScript(server.runningScripts[i], server.ip);
suc = true; suc = true;
@ -2739,11 +2739,11 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
}, },
getScriptRam: function (scriptname: any, ip: any = workerScript.serverIp): any { getScriptRam: function (scriptname: any, ip: any = workerScript.serverIp): any {
updateDynamicRam("getScriptRam", getRamCost("getScriptRam")); updateDynamicRam("getScriptRam", getRamCost("getScriptRam"));
var server = getServer(ip); const server = getServer(ip);
if (server == null) { if (server == null) {
throw makeRuntimeErrorMsg("getScriptRam", `Invalid IP/hostname: ${ip}`); throw makeRuntimeErrorMsg("getScriptRam", `Invalid IP/hostname: ${ip}`);
} }
for (var i = 0; i < server.scripts.length; ++i) { for (let i = 0; i < server.scripts.length; ++i) {
if (server.scripts[i].filename == scriptname) { if (server.scripts[i].filename == scriptname) {
return server.scripts[i].ramUsage; return server.scripts[i].ramUsage;
} }
@ -2760,7 +2760,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
runningScript = getRunningScriptByPid(fn, "getRunningScript"); runningScript = getRunningScriptByPid(fn, "getRunningScript");
} else { } else {
const scriptArgs = []; const scriptArgs = [];
for (var i = 2; i < arguments.length; ++i) { for (let i = 2; i < arguments.length; ++i) {
scriptArgs.push(arguments[i]); scriptArgs.push(arguments[i]);
} }
runningScript = getRunningScript(fn, ip, "getRunningScript", scriptArgs); runningScript = getRunningScript(fn, ip, "getRunningScript", scriptArgs);
@ -2824,7 +2824,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
getScriptIncome: function (scriptname: any, ip: any): any { getScriptIncome: function (scriptname: any, ip: any): any {
updateDynamicRam("getScriptIncome", getRamCost("getScriptIncome")); updateDynamicRam("getScriptIncome", getRamCost("getScriptIncome"));
if (arguments.length === 0) { if (arguments.length === 0) {
var res = []; const res = [];
// First element is total income of all currently running scripts // First element is total income of all currently running scripts
let total = 0; let total = 0;
@ -2838,15 +2838,15 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
return res; return res;
} else { } else {
// Get income for a particular script // Get income for a particular script
var server = getServer(ip); const server = getServer(ip);
if (server == null) { if (server == null) {
throw makeRuntimeErrorMsg("getScriptIncome", `Invalid IP/hostnamed: ${ip}`); throw makeRuntimeErrorMsg("getScriptIncome", `Invalid IP/hostnamed: ${ip}`);
} }
var argsForScript = []; const argsForScript = [];
for (var i = 2; i < arguments.length; ++i) { for (let i = 2; i < arguments.length; ++i) {
argsForScript.push(arguments[i]); argsForScript.push(arguments[i]);
} }
var runningScriptObj = findRunningScript(scriptname, argsForScript, server); const runningScriptObj = findRunningScript(scriptname, argsForScript, server);
if (runningScriptObj == null) { if (runningScriptObj == null) {
workerScript.log( workerScript.log(
"getScriptIncome", "getScriptIncome",
@ -2860,22 +2860,22 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
getScriptExpGain: function (scriptname: any, ip: any): any { getScriptExpGain: function (scriptname: any, ip: any): any {
updateDynamicRam("getScriptExpGain", getRamCost("getScriptExpGain")); updateDynamicRam("getScriptExpGain", getRamCost("getScriptExpGain"));
if (arguments.length === 0) { if (arguments.length === 0) {
var total = 0; let total = 0;
for (const ws of workerScripts.values()) { for (const ws of workerScripts.values()) {
total += ws.scriptRef.onlineExpGained / ws.scriptRef.onlineRunningTime; total += ws.scriptRef.onlineExpGained / ws.scriptRef.onlineRunningTime;
} }
return total; return total;
} else { } else {
// Get income for a particular script // Get income for a particular script
var server = getServer(ip); const server = getServer(ip);
if (server == null) { if (server == null) {
throw makeRuntimeErrorMsg("getScriptExpGain", `Invalid IP/hostnamed: ${ip}`); throw makeRuntimeErrorMsg("getScriptExpGain", `Invalid IP/hostnamed: ${ip}`);
} }
var argsForScript = []; const argsForScript = [];
for (var i = 2; i < arguments.length; ++i) { for (let i = 2; i < arguments.length; ++i) {
argsForScript.push(arguments[i]); argsForScript.push(arguments[i]);
} }
var runningScriptObj = findRunningScript(scriptname, argsForScript, server); const runningScriptObj = findRunningScript(scriptname, argsForScript, server);
if (runningScriptObj == null) { if (runningScriptObj == null) {
workerScript.log( workerScript.log(
"getScriptExpGain", "getScriptExpGain",
@ -2937,7 +2937,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
workerScript.log("wget", `Invalid target file: '${target}'. Must be a script or text file.`); workerScript.log("wget", `Invalid target file: '${target}'. Must be a script or text file.`);
return Promise.resolve(false); return Promise.resolve(false);
} }
var s = safeGetServer(ip, "wget"); const s = safeGetServer(ip, "wget");
return new Promise(function (resolve) { return new Promise(function (resolve) {
$.get( $.get(
url, url,
@ -2980,11 +2980,11 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
return; return;
} }
if (Player.isWorking) { if (Player.isWorking) {
var txt = Player.singularityStopWork(); const txt = Player.singularityStopWork();
workerScript.log("universityCourse", txt); workerScript.log("universityCourse", txt);
} }
var costMult, expMult; let costMult, expMult;
switch (universityName.toLowerCase()) { switch (universityName.toLowerCase()) {
case LocationName.AevumSummitUniversity.toLowerCase(): case LocationName.AevumSummitUniversity.toLowerCase():
if (Player.city != CityName.Aevum) { if (Player.city != CityName.Aevum) {
@ -3027,7 +3027,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
return false; return false;
} }
var task; let task;
switch (className.toLowerCase()) { switch (className.toLowerCase()) {
case "Study Computer Science".toLowerCase(): case "Study Computer Science".toLowerCase():
task = CONSTANTS.ClassStudyComputerScience; task = CONSTANTS.ClassStudyComputerScience;
@ -3064,10 +3064,10 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
return; return;
} }
if (Player.isWorking) { if (Player.isWorking) {
var txt = Player.singularityStopWork(); const txt = Player.singularityStopWork();
workerScript.log("gymWorkout", txt); workerScript.log("gymWorkout", txt);
} }
var costMult, expMult; let costMult, expMult;
switch (gymName.toLowerCase()) { switch (gymName.toLowerCase()) {
case LocationName.AevumCrushFitnessGym.toLowerCase(): case LocationName.AevumCrushFitnessGym.toLowerCase():
if (Player.city != CityName.Aevum) { if (Player.city != CityName.Aevum) {
@ -3189,7 +3189,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
} }
Player.loseMoney(CONSTANTS.TorRouterCost); Player.loseMoney(CONSTANTS.TorRouterCost);
var darkweb = safetlyCreateUniqueServer({ const darkweb = safetlyCreateUniqueServer({
ip: createUniqueRandomIp(), ip: createUniqueRandomIp(),
hostname: "darkweb", hostname: "darkweb",
organizationName: "", organizationName: "",
@ -3264,7 +3264,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
throw makeRuntimeErrorMsg("connect", `Invalid hostname: '${hostname}'`); throw makeRuntimeErrorMsg("connect", `Invalid hostname: '${hostname}'`);
} }
let target = getServer(hostname); const target = getServer(hostname);
if (target == null) { if (target == null) {
throw makeRuntimeErrorMsg("connect", `Invalid hostname: '${hostname}'`); throw makeRuntimeErrorMsg("connect", `Invalid hostname: '${hostname}'`);
return; return;
@ -3503,7 +3503,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
checkSingularityAccess("stopAction", 1); checkSingularityAccess("stopAction", 1);
if (Player.isWorking) { if (Player.isWorking) {
Router.toTerminal(); Router.toTerminal();
var txt = Player.singularityStopWork(); const txt = Player.singularityStopWork();
workerScript.log("stopAction", txt); workerScript.log("stopAction", txt);
return true; return true;
} }
@ -3578,7 +3578,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
} }
if (Player.isWorking) { if (Player.isWorking) {
var txt = Player.singularityStopWork(); const txt = Player.singularityStopWork();
workerScript.log("workForCompany", txt); workerScript.log("workForCompany", txt);
} }
@ -3596,7 +3596,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
getCompany("applyToCompany", companyName); getCompany("applyToCompany", companyName);
Player.location = companyName; Player.location = companyName;
var res; let res;
switch (field.toLowerCase()) { switch (field.toLowerCase()) {
case "software": case "software":
res = Player.applyForSoftwareJob(true); res = Player.applyForSoftwareJob(true);
@ -3733,9 +3733,9 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
workerScript.log("workForFaction", txt); workerScript.log("workForFaction", txt);
} }
var fac = Factions[name]; const fac = Factions[name];
// Arrays listing factions that allow each time of work // Arrays listing factions that allow each time of work
var hackAvailable = [ const hackAvailable = [
"Illuminati", "Illuminati",
"Daedalus", "Daedalus",
"The Covenant", "The Covenant",
@ -3766,7 +3766,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
"Tian Di Hui", "Tian Di Hui",
"CyberSec", "CyberSec",
]; ];
var fdWkAvailable = [ const fdWkAvailable = [
"Illuminati", "Illuminati",
"Daedalus", "Daedalus",
"The Covenant", "The Covenant",
@ -3793,7 +3793,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
"Tetrads", "Tetrads",
"Slum Snakes", "Slum Snakes",
]; ];
var scWkAvailable = [ const scWkAvailable = [
"ECorp", "ECorp",
"MegaCorp", "MegaCorp",
"Bachman & Associates", "Bachman & Associates",
@ -3915,7 +3915,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
return; return;
} }
if (Player.isWorking) { if (Player.isWorking) {
var txt = Player.singularityStopWork(); const txt = Player.singularityStopWork();
workerScript.log("createProgram", txt); workerScript.log("createProgram", txt);
} }
@ -4001,7 +4001,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
getOwnedAugmentations: function (purchased: any = false): any { getOwnedAugmentations: function (purchased: any = false): any {
updateDynamicRam("getOwnedAugmentations", getRamCost("getOwnedAugmentations")); updateDynamicRam("getOwnedAugmentations", getRamCost("getOwnedAugmentations"));
checkSingularityAccess("getOwnedAugmentations", 3); checkSingularityAccess("getOwnedAugmentations", 3);
var res = []; const res = [];
for (var i = 0; i < Player.augmentations.length; ++i) { for (var i = 0; i < Player.augmentations.length; ++i) {
res.push(Player.augmentations[i].name); res.push(Player.augmentations[i].name);
} }
@ -4015,7 +4015,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
getOwnedSourceFiles: function (): any { getOwnedSourceFiles: function (): any {
updateDynamicRam("getOwnedSourceFiles", getRamCost("getOwnedSourceFiles")); updateDynamicRam("getOwnedSourceFiles", getRamCost("getOwnedSourceFiles"));
checkSingularityAccess("getOwnedSourceFiles", 3); checkSingularityAccess("getOwnedSourceFiles", 3);
let res = []; const res = [];
for (let i = 0; i < Player.sourceFiles.length; ++i) { for (let i = 0; i < Player.sourceFiles.length; ++i) {
res.push({ res.push({
n: Player.sourceFiles[i].n, n: Player.sourceFiles[i].n,
@ -4915,7 +4915,7 @@ function NetscriptFunctions(workerScript: WorkerScript): NS {
// Convert answer to string. If the answer is a 2D array, then we have to // Convert answer to string. If the answer is a 2D array, then we have to
// manually add brackets for the inner arrays // manually add brackets for the inner arrays
if (is2DArray(answer)) { if (is2DArray(answer)) {
let answerComponents = []; const answerComponents = [];
for (let i = 0; i < answer.length; ++i) { for (let i = 0; i < answer.length; ++i) {
answerComponents.push(["[", answer[i].toString(), "]"].join("")); answerComponents.push(["[", answer[i].toString(), "]"].join(""));
} }

@ -19,7 +19,7 @@ function makeScriptBlob(code: string): Blob {
export async function executeJSScript(scripts: Script[] = [], workerScript: WorkerScript) { export async function executeJSScript(scripts: Script[] = [], workerScript: WorkerScript) {
let loadedModule; let loadedModule;
let uurls: ScriptUrl[] = []; let uurls: ScriptUrl[] = [];
let script = workerScript.getScript(); const script = workerScript.getScript();
if (script === null) throw new Error("script is null"); 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
@ -37,7 +37,7 @@ export async function executeJSScript(scripts: Script[] = [], workerScript: Work
} }
loadedModule = await script.module; loadedModule = await script.module;
let ns = workerScript.env.vars; const ns = workerScript.env.vars;
// 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.

@ -38,7 +38,7 @@ import { simple as walksimple } from "acorn-walk";
// Netscript Ports are instantiated here // Netscript Ports are instantiated here
export const NetscriptPorts: IPort[] = []; export const NetscriptPorts: IPort[] = [];
for (var i = 0; i < CONSTANTS.NumNetscriptPorts; ++i) { for (let i = 0; i < CONSTANTS.NumNetscriptPorts; ++i) {
NetscriptPorts.push(NetscriptPort()); NetscriptPorts.push(NetscriptPort());
} }
@ -112,7 +112,7 @@ function startNetscript2Script(workerScript: WorkerScript): Promise<WorkerScript
}; };
} }
for (let prop in workerScript.env.vars) { for (const prop in workerScript.env.vars) {
if (typeof workerScript.env.vars[prop] !== "function") continue; if (typeof workerScript.env.vars[prop] !== "function") continue;
workerScript.env.vars[prop] = wrap(prop, workerScript.env.vars[prop]); workerScript.env.vars[prop] = wrap(prop, workerScript.env.vars[prop]);
} }
@ -145,9 +145,9 @@ function startNetscript1Script(workerScript: WorkerScript): Promise<WorkerScript
workerScript.running = true; workerScript.running = true;
//Process imports //Process imports
var codeWithImports, codeLineOffset; let codeWithImports, codeLineOffset;
try { try {
let importProcessingRes = processNetscript1Imports(code, workerScript); const importProcessingRes = processNetscript1Imports(code, workerScript);
codeWithImports = importProcessingRes.code; codeWithImports = importProcessingRes.code;
codeLineOffset = importProcessingRes.lineOffset; codeLineOffset = importProcessingRes.lineOffset;
} catch (e) { } catch (e) {
@ -158,11 +158,11 @@ function startNetscript1Script(workerScript: WorkerScript): Promise<WorkerScript
return Promise.resolve(workerScript); return Promise.resolve(workerScript);
} }
var interpreterInitialization = function (int: any, scope: any) { const interpreterInitialization = function (int: any, scope: any) {
//Add the Netscript environment //Add the Netscript environment
var ns = NetscriptFunctions(workerScript); const ns = NetscriptFunctions(workerScript);
for (let name in ns) { for (const name in ns) {
let entry = ns[name]; const entry = ns[name];
if (typeof entry === "function") { if (typeof entry === "function") {
//Async functions need to be wrapped. See JS-Interpreter documentation //Async functions need to be wrapped. See JS-Interpreter documentation
if ( if (
@ -173,8 +173,8 @@ function startNetscript1Script(workerScript: WorkerScript): Promise<WorkerScript
name === "prompt" || name === "prompt" ||
name === "manualHack" name === "manualHack"
) { ) {
let tempWrapper = function () { const tempWrapper = function () {
let fnArgs = []; const fnArgs = [];
//All of the Object/array elements are in JSInterpreter format, so //All of the Object/array elements are in JSInterpreter format, so
//we have to convert them back to native format to pass them to these fns //we have to convert them back to native format to pass them to these fns
@ -185,8 +185,8 @@ function startNetscript1Script(workerScript: WorkerScript): Promise<WorkerScript
fnArgs.push(arguments[i]); fnArgs.push(arguments[i]);
} }
} }
let cb = arguments[arguments.length - 1]; const cb = arguments[arguments.length - 1];
let fnPromise = entry.apply(null, fnArgs); const fnPromise = entry.apply(null, fnArgs);
fnPromise fnPromise
.then(function (res: any) { .then(function (res: any) {
cb(res); cb(res);
@ -206,8 +206,8 @@ function startNetscript1Script(workerScript: WorkerScript): Promise<WorkerScript
name === "run" || name === "run" ||
name === "exec" name === "exec"
) { ) {
let tempWrapper = function () { const tempWrapper = function () {
let fnArgs = []; const fnArgs = [];
//All of the Object/array elements are in JSInterpreter format, so //All of the Object/array elements are in JSInterpreter format, so
//we have to convert them back to native format to pass them to these fns //we have to convert them back to native format to pass them to these fns
@ -223,8 +223,8 @@ function startNetscript1Script(workerScript: WorkerScript): Promise<WorkerScript
}; };
int.setProperty(scope, name, int.createNativeFunction(tempWrapper)); int.setProperty(scope, name, int.createNativeFunction(tempWrapper));
} else { } else {
let tempWrapper = function () { const tempWrapper = function () {
let res = entry.apply(null, arguments); const res = entry.apply(null, arguments);
if (res == null) { if (res == null) {
return res; return res;
@ -247,7 +247,7 @@ function startNetscript1Script(workerScript: WorkerScript): Promise<WorkerScript
int.setProperty(scope, "args", int.nativeToPseudo(workerScript.args)); int.setProperty(scope, "args", int.nativeToPseudo(workerScript.args));
}; };
var interpreter: any; let interpreter: any;
try { try {
interpreter = new Interpreter(codeWithImports, interpreterInitialization, codeLineOffset); interpreter = new Interpreter(codeWithImports, interpreterInitialization, codeLineOffset);
} catch (e) { } catch (e) {
@ -314,7 +314,7 @@ function processNetscript1Imports(code: string, workerScript: WorkerScript): any
sourceType: "module", sourceType: "module",
}); });
var server = workerScript.getServer(); const server = workerScript.getServer();
if (server == null) { if (server == null) {
throw new Error("Failed to find underlying Server object for script"); throw new Error("Failed to find underlying Server object for script");
} }
@ -339,11 +339,11 @@ function processNetscript1Imports(code: string, workerScript: WorkerScript): any
if (scriptName.startsWith("./")) { if (scriptName.startsWith("./")) {
scriptName = scriptName.slice(2); scriptName = scriptName.slice(2);
} }
let script = getScript(scriptName); const script = getScript(scriptName);
if (script == null) { if (script == null) {
throw new Error("'Import' failed due to invalid script: " + scriptName); throw new Error("'Import' failed due to invalid script: " + scriptName);
} }
let scriptAst = parse(script.code, { const scriptAst = parse(script.code, {
ecmaVersion: 9, ecmaVersion: 9,
allowReserved: true, allowReserved: true,
sourceType: "module", sourceType: "module",
@ -351,9 +351,9 @@ function processNetscript1Imports(code: string, workerScript: WorkerScript): any
if (node.specifiers.length === 1 && node.specifiers[0].type === "ImportNamespaceSpecifier") { if (node.specifiers.length === 1 && node.specifiers[0].type === "ImportNamespaceSpecifier") {
// import * as namespace from script // import * as namespace from script
let namespace = node.specifiers[0].local.name; const namespace = node.specifiers[0].local.name;
let fnNames: string[] = []; //Names only const fnNames: string[] = []; //Names only
let fnDeclarations: any[] = []; //FunctionDeclaration Node objects const fnDeclarations: any[] = []; //FunctionDeclaration Node objects
walksimple(scriptAst, { walksimple(scriptAst, {
FunctionDeclaration: (node: any) => { FunctionDeclaration: (node: any) => {
fnNames.push(node.id.name); fnNames.push(node.id.name);
@ -382,13 +382,13 @@ function processNetscript1Imports(code: string, workerScript: WorkerScript): any
//import {...} from script //import {...} from script
//Get array of all fns to import //Get array of all fns to import
let fnsToImport: string[] = []; const fnsToImport: string[] = [];
node.specifiers.forEach((e: any) => { node.specifiers.forEach((e: any) => {
fnsToImport.push(e.local.name); fnsToImport.push(e.local.name);
}); });
//Walk through script and get FunctionDeclaration code for all specified fns //Walk through script and get FunctionDeclaration code for all specified fns
let fnDeclarations: any[] = []; const fnDeclarations: any[] = [];
walksimple(scriptAst, { walksimple(scriptAst, {
FunctionDeclaration: (node: any) => { FunctionDeclaration: (node: any) => {
if (fnsToImport.includes(node.id.name)) { if (fnsToImport.includes(node.id.name)) {
@ -412,7 +412,7 @@ function processNetscript1Imports(code: string, workerScript: WorkerScript): any
} }
//Remove ImportDeclarations from AST. These ImportDeclarations must be in top-level //Remove ImportDeclarations from AST. These ImportDeclarations must be in top-level
var linesRemoved = 0; let linesRemoved = 0;
if (ast.type !== "Program" || ast.body == null) { if (ast.type !== "Program" || ast.body == null) {
throw new Error("Code could not be properly parsed"); throw new Error("Code could not be properly parsed");
} }
@ -424,7 +424,7 @@ function processNetscript1Imports(code: string, workerScript: WorkerScript): any
} }
//Calculated line offset //Calculated line offset
var lineOffset = (generatedCode.match(/\n/g) || []).length - linesRemoved; const lineOffset = (generatedCode.match(/\n/g) || []).length - linesRemoved;
//Convert the AST back into code //Convert the AST back into code
code = generate(ast); code = generate(ast);
@ -432,7 +432,7 @@ function processNetscript1Imports(code: string, workerScript: WorkerScript): any
//Add the imported code and re-generate in ES5 (JS Interpreter for NS1 only supports ES5); //Add the imported code and re-generate in ES5 (JS Interpreter for NS1 only supports ES5);
code = generatedCode + code; code = generatedCode + code;
var res = { const res = {
code: code, code: code,
lineOffset: lineOffset, lineOffset: lineOffset,
}; };
@ -596,7 +596,7 @@ export function createAndAddWorkerScript(
* Updates the online running time stat of all running scripts * Updates the online running time stat of all running scripts
*/ */
export function updateOnlineScriptTimes(numCycles = 1) { export function updateOnlineScriptTimes(numCycles = 1) {
var time = (numCycles * CONSTANTS._idleSpeed) / 1000; //seconds const time = (numCycles * CONSTANTS._idleSpeed) / 1000; //seconds
for (const ws of workerScripts.values()) { for (const ws of workerScripts.values()) {
ws.scriptRef.onlineRunningTime += time; ws.scriptRef.onlineRunningTime += time;
} }
@ -607,7 +607,7 @@ export function updateOnlineScriptTimes(numCycles = 1) {
* into worker scripts so that they will start running * into worker scripts so that they will start running
*/ */
export function loadAllRunningScripts() { export function loadAllRunningScripts() {
let skipScriptLoad = window.location.href.toLowerCase().indexOf("?noscripts") !== -1; const skipScriptLoad = window.location.href.toLowerCase().indexOf("?noscripts") !== -1;
if (skipScriptLoad) { if (skipScriptLoad) {
console.info("Skipping the load of any scripts during startup"); console.info("Skipping the load of any scripts during startup");
} }
@ -661,7 +661,7 @@ export function runScriptFromScript(
} }
// Check if the script is already running // Check if the script is already running
let runningScriptObj = server.getRunningScript(scriptname, args); const runningScriptObj = server.getRunningScript(scriptname, args);
if (runningScriptObj != null) { if (runningScriptObj != null) {
workerScript.log(caller, `'${scriptname}' is already running on '${server.hostname}'`); workerScript.log(caller, `'${scriptname}' is already running on '${server.hostname}'`);
return 0; return 0;
@ -703,7 +703,7 @@ export function runScriptFromScript(
caller, caller,
`'${scriptname}' on '${server.hostname}' with ${threads} threads and args: ${arrayToString(args)}.`, `'${scriptname}' on '${server.hostname}' with ${threads} threads and args: ${arrayToString(args)}.`,
); );
let runningScriptObj = new RunningScript(script, args); const runningScriptObj = new RunningScript(script, args);
runningScriptObj.threads = threads; runningScriptObj.threads = threads;
return startWorkerScript(runningScriptObj, server, workerScript); return startWorkerScript(runningScriptObj, server, workerScript);

@ -62,7 +62,7 @@ import React from "react";
export function init(this: IPlayer) { export function init(this: IPlayer) {
/* Initialize Player's home computer */ /* Initialize Player's home computer */
var t_homeComp = safetlyCreateUniqueServer({ const t_homeComp = safetlyCreateUniqueServer({
adminRights: true, adminRights: true,
hostname: "home", hostname: "home",
ip: createUniqueRandomIp(), ip: createUniqueRandomIp(),
@ -79,7 +79,7 @@ export function init(this: IPlayer) {
} }
export function prestigeAugmentation(this: IPlayer) { export function prestigeAugmentation(this: IPlayer) {
var homeComp = this.getHomeComputer(); const homeComp = this.getHomeComputer();
this.currentServer = homeComp.ip; this.currentServer = homeComp.ip;
this.homeComputer = homeComp.ip; this.homeComputer = homeComp.ip;
@ -262,7 +262,7 @@ export function updateSkillLevels(this: IPlayer): void {
this.intelligence = 0; this.intelligence = 0;
} }
var ratio = this.hp / this.max_hp; const ratio = this.hp / this.max_hp;
this.max_hp = Math.floor(10 + this.defense / 10); this.max_hp = Math.floor(10 + this.defense / 10);
this.hp = Math.round(this.max_hp * ratio); this.hp = Math.round(this.max_hp * ratio);
} }
@ -313,7 +313,7 @@ export function hasProgram(this: IPlayer, programName: string): boolean {
return false; return false;
} }
for (var i = 0; i < home.programs.length; ++i) { for (let i = 0; i < home.programs.length; ++i) {
if (programName.toLowerCase() == home.programs[i].toLowerCase()) { if (programName.toLowerCase() == home.programs[i].toLowerCase()) {
return true; return true;
} }
@ -588,7 +588,7 @@ export function cancelationPenalty(this: IPlayer) {
export function work(this: IPlayer, numCycles: number): boolean { export function work(this: IPlayer, numCycles: number): boolean {
// Cap the number of cycles being processed to whatever would put you at // Cap the number of cycles being processed to whatever would put you at
// the work time limit (8 hours) // the work time limit (8 hours)
var overMax = false; let overMax = false;
if (this.timeWorked + CONSTANTS._idleSpeed * numCycles >= CONSTANTS.MillisecondsPer8Hours) { if (this.timeWorked + CONSTANTS._idleSpeed * numCycles >= CONSTANTS.MillisecondsPer8Hours) {
overMax = true; overMax = true;
numCycles = Math.round((CONSTANTS.MillisecondsPer8Hours - this.timeWorked) / CONSTANTS._idleSpeed); numCycles = Math.round((CONSTANTS.MillisecondsPer8Hours - this.timeWorked) / CONSTANTS._idleSpeed);
@ -714,7 +714,7 @@ export function startWorkPartTime(this: IPlayer, router: IRouter, companyName: s
export function workPartTime(this: IPlayer, numCycles: number): boolean { export function workPartTime(this: IPlayer, numCycles: number): boolean {
//Cap the number of cycles being processed to whatever would put you at the //Cap the number of cycles being processed to whatever would put you at the
//work time limit (8 hours) //work time limit (8 hours)
var overMax = false; let overMax = false;
if (this.timeWorked + CONSTANTS._idleSpeed * numCycles >= CONSTANTS.MillisecondsPer8Hours) { if (this.timeWorked + CONSTANTS._idleSpeed * numCycles >= CONSTANTS.MillisecondsPer8Hours) {
overMax = true; overMax = true;
numCycles = Math.round((CONSTANTS.MillisecondsPer8Hours - this.timeWorked) / CONSTANTS._idleSpeed); numCycles = Math.round((CONSTANTS.MillisecondsPer8Hours - this.timeWorked) / CONSTANTS._idleSpeed);
@ -733,7 +733,7 @@ export function workPartTime(this: IPlayer, numCycles: number): boolean {
} }
export function finishWorkPartTime(this: IPlayer, sing = false): string { export function finishWorkPartTime(this: IPlayer, sing = false): string {
var company = Companies[this.companyName]; const company = Companies[this.companyName];
company.playerReputation += this.workRepGained; company.playerReputation += this.workRepGained;
this.updateSkillLevels(); this.updateSkillLevels();
@ -764,7 +764,7 @@ export function finishWorkPartTime(this: IPlayer, sing = false): string {
this.resetWorkStatus(); this.resetWorkStatus();
if (sing) { if (sing) {
var res = const res =
"You worked for " + "You worked for " +
convertTimeMsToTimeElapsedString(this.timeWorked) + convertTimeMsToTimeElapsedString(this.timeWorked) +
" and " + " and " +
@ -802,7 +802,7 @@ export function stopFocusing(this: IPlayer): void {
/* Working for Faction */ /* Working for Faction */
export function startFactionWork(this: IPlayer, router: IRouter, faction: Faction): void { export function startFactionWork(this: IPlayer, router: IRouter, faction: Faction): void {
//Update reputation gain rate to account for faction favor //Update reputation gain rate to account for faction favor
var favorMult = 1 + faction.favor / 100; let favorMult = 1 + faction.favor / 100;
if (isNaN(favorMult)) { if (isNaN(favorMult)) {
favorMult = 1; favorMult = 1;
} }
@ -818,7 +818,7 @@ export function startFactionWork(this: IPlayer, router: IRouter, faction: Factio
router.toWork(); router.toWork();
} }
export function startFactionHackWork(this: IPlayer, router: IRouter, faction: Faction) { export function startFactionHackWork(this: IPlayer, router: IRouter, faction: Faction): void {
this.resetWorkStatus(CONSTANTS.WorkTypeFaction, faction.name, CONSTANTS.FactionWorkHacking); this.resetWorkStatus(CONSTANTS.WorkTypeFaction, faction.name, CONSTANTS.FactionWorkHacking);
this.workHackExpGainRate = 0.15 * this.hacking_exp_mult * BitNodeMultipliers.FactionWorkExpGain; this.workHackExpGainRate = 0.15 * this.hacking_exp_mult * BitNodeMultipliers.FactionWorkExpGain;
@ -833,7 +833,7 @@ export function startFactionHackWork(this: IPlayer, router: IRouter, faction: Fa
this.startFactionWork(router, faction); this.startFactionWork(router, faction);
} }
export function startFactionFieldWork(this: IPlayer, router: IRouter, faction: Faction) { export function startFactionFieldWork(this: IPlayer, router: IRouter, faction: Faction): void {
this.resetWorkStatus(CONSTANTS.WorkTypeFaction, faction.name, CONSTANTS.FactionWorkField); this.resetWorkStatus(CONSTANTS.WorkTypeFaction, faction.name, CONSTANTS.FactionWorkField);
this.workHackExpGainRate = 0.1 * this.hacking_exp_mult * BitNodeMultipliers.FactionWorkExpGain; this.workHackExpGainRate = 0.1 * this.hacking_exp_mult * BitNodeMultipliers.FactionWorkExpGain;
@ -850,7 +850,7 @@ export function startFactionFieldWork(this: IPlayer, router: IRouter, faction: F
this.startFactionWork(router, faction); this.startFactionWork(router, faction);
} }
export function startFactionSecurityWork(this: IPlayer, router: IRouter, faction: Faction) { export function startFactionSecurityWork(this: IPlayer, router: IRouter, faction: Faction): void {
this.resetWorkStatus(CONSTANTS.WorkTypeFaction, faction.name, CONSTANTS.FactionWorkSecurity); this.resetWorkStatus(CONSTANTS.WorkTypeFaction, faction.name, CONSTANTS.FactionWorkSecurity);
this.workHackExpGainRate = 0.05 * this.hacking_exp_mult * BitNodeMultipliers.FactionWorkExpGain; this.workHackExpGainRate = 0.05 * this.hacking_exp_mult * BitNodeMultipliers.FactionWorkExpGain;
@ -867,7 +867,7 @@ export function startFactionSecurityWork(this: IPlayer, router: IRouter, faction
this.startFactionWork(router, faction); this.startFactionWork(router, faction);
} }
export function workForFaction(this: IPlayer, numCycles: number) { export function workForFaction(this: IPlayer, numCycles: number): boolean {
const faction = Factions[this.currentWorkFactionName]; const faction = Factions[this.currentWorkFactionName];
//Constantly update the rep gain rate //Constantly update the rep gain rate
@ -933,7 +933,7 @@ export function finishFactionWork(this: IPlayer, cancelled: boolean, sing = fals
this.isWorking = false; this.isWorking = false;
this.resetWorkStatus(); this.resetWorkStatus();
if (sing) { if (sing) {
var res = const res =
"You worked for your faction " + "You worked for your faction " +
faction.name + faction.name +
" for a total of " + " for a total of " +
@ -1146,7 +1146,7 @@ export function getWorkRepGain(this: IPlayer): number {
return 0; return 0;
} }
var jobPerformance = companyPosition.calculateJobPerformance( let jobPerformance = companyPosition.calculateJobPerformance(
this.hacking_skill, this.hacking_skill,
this.strength, this.strength,
this.defense, this.defense,
@ -1159,7 +1159,7 @@ export function getWorkRepGain(this: IPlayer): number {
jobPerformance += this.intelligence / CONSTANTS.MaxSkillLevel; jobPerformance += this.intelligence / CONSTANTS.MaxSkillLevel;
//Update reputation gain rate to account for company favor //Update reputation gain rate to account for company favor
var favorMult = 1 + company.favor / 100; let favorMult = 1 + company.favor / 100;
if (isNaN(favorMult)) { if (isNaN(favorMult)) {
favorMult = 1; favorMult = 1;
} }
@ -1208,14 +1208,14 @@ export function startCreateProgramWork(
this.timeNeededToCompleteWork = time; this.timeNeededToCompleteWork = time;
//Check for incomplete program //Check for incomplete program
for (var i = 0; i < this.getHomeComputer().programs.length; ++i) { for (let i = 0; i < this.getHomeComputer().programs.length; ++i) {
var programFile = this.getHomeComputer().programs[i]; const programFile = this.getHomeComputer().programs[i];
if (programFile.startsWith(programName) && programFile.endsWith("%-INC")) { if (programFile.startsWith(programName) && programFile.endsWith("%-INC")) {
var res = programFile.split("-"); const res = programFile.split("-");
if (res.length != 3) { if (res.length != 3) {
break; break;
} }
var percComplete = Number(res[1].slice(0, -1)); const percComplete = Number(res[1].slice(0, -1));
if (isNaN(percComplete) || percComplete < 0 || percComplete >= 100) { if (isNaN(percComplete) || percComplete < 0 || percComplete >= 100) {
break; break;
} }
@ -1230,8 +1230,8 @@ export function startCreateProgramWork(
export function createProgramWork(this: IPlayer, numCycles: number): boolean { export function createProgramWork(this: IPlayer, numCycles: number): boolean {
//Higher hacking skill will allow you to create programs faster //Higher hacking skill will allow you to create programs faster
var reqLvl = this.createProgramReqLvl; const reqLvl = this.createProgramReqLvl;
var skillMult = (this.hacking_skill / reqLvl) * this.getIntelligenceBonus(3); //This should always be greater than 1; let skillMult = (this.hacking_skill / reqLvl) * this.getIntelligenceBonus(3); //This should always be greater than 1;
skillMult = 1 + (skillMult - 1) / 5; //The divider constant can be adjusted as necessary skillMult = 1 + (skillMult - 1) / 5; //The divider constant can be adjusted as necessary
//Skill multiplier directly applied to "time worked" //Skill multiplier directly applied to "time worked"
@ -1246,7 +1246,7 @@ export function createProgramWork(this: IPlayer, numCycles: number): boolean {
} }
export function finishCreateProgramWork(this: IPlayer, cancelled: boolean): string { export function finishCreateProgramWork(this: IPlayer, cancelled: boolean): string {
var programName = this.createProgramName; const programName = this.createProgramName;
if (cancelled === false) { if (cancelled === false) {
dialogBoxCreate( dialogBoxCreate(
"You've finished creating " + programName + "!<br>" + "The new program can be found on your home computer.", "You've finished creating " + programName + "!<br>" + "The new program can be found on your home computer.",
@ -1254,8 +1254,8 @@ export function finishCreateProgramWork(this: IPlayer, cancelled: boolean): stri
this.getHomeComputer().programs.push(programName); this.getHomeComputer().programs.push(programName);
} else { } else {
var perc = (Math.floor((this.timeWorkedCreateProgram / this.timeNeededToCompleteWork) * 10000) / 100).toString(); const perc = (Math.floor((this.timeWorkedCreateProgram / this.timeNeededToCompleteWork) * 10000) / 100).toString();
var incompleteName = programName + "-" + perc + "%-INC"; const incompleteName = programName + "-" + perc + "%-INC";
this.getHomeComputer().programs.push(incompleteName); this.getHomeComputer().programs.push(incompleteName);
} }
@ -1281,8 +1281,8 @@ export function startClass(this: IPlayer, router: IRouter, costMult: number, exp
const gameCPS = 1000 / CONSTANTS._idleSpeed; const gameCPS = 1000 / CONSTANTS._idleSpeed;
//Find cost and exp gain per game cycle //Find cost and exp gain per game cycle
var cost = 0; let cost = 0;
var hackExp = 0, let hackExp = 0,
strExp = 0, strExp = 0,
defExp = 0, defExp = 0,
dexExp = 0, dexExp = 0,
@ -1381,7 +1381,7 @@ export function finishClass(this: IPlayer, sing = false): string {
this.isWorking = false; this.isWorking = false;
if (sing) { if (sing) {
var res = const res =
"After " + "After " +
this.className + this.className +
" for " + " for " +
@ -1709,7 +1709,7 @@ export function applyForJob(this: IPlayer, entryPosType: CompanyPosition, sing =
} }
while (true) { while (true) {
let newPos = getNextCompanyPositionHelper(pos); const newPos = getNextCompanyPositionHelper(pos);
if (newPos == null) { if (newPos == null) {
break; break;
} }
@ -1737,7 +1737,7 @@ export function applyForJob(this: IPlayer, entryPosType: CompanyPosition, sing =
return false; return false;
} else if (company.hasPosition(nextPos)) { } else if (company.hasPosition(nextPos)) {
if (!sing) { if (!sing) {
var reqText = getJobRequirementText(company, nextPos); const reqText = getJobRequirementText(company, nextPos);
dialogBoxCreate("Unfortunately, you do not qualify for a promotion<br>" + reqText); dialogBoxCreate("Unfortunately, you do not qualify for a promotion<br>" + reqText);
} }
return false; return false;
@ -1766,7 +1766,7 @@ export function getNextCompanyPosition(
company: Company, company: Company,
entryPosType: CompanyPosition, entryPosType: CompanyPosition,
): CompanyPosition | null { ): CompanyPosition | null {
var currCompany = null; let currCompany = null;
if (this.companyName !== "") { if (this.companyName !== "") {
currCompany = Companies[this.companyName]; currCompany = Companies[this.companyName];
} }
@ -1818,7 +1818,7 @@ export function applyForItJob(this: IPlayer, sing = false): boolean {
} }
export function applyForSecurityEngineerJob(this: IPlayer, sing = false): boolean { export function applyForSecurityEngineerJob(this: IPlayer, sing = false): boolean {
var company = Companies[this.location]; //Company being applied to const company = Companies[this.location]; //Company being applied to
if (this.isQualified(company, CompanyPositions[posNames.SecurityEngineerCompanyPositions[0]])) { if (this.isQualified(company, CompanyPositions[posNames.SecurityEngineerCompanyPositions[0]])) {
return this.applyForJob(CompanyPositions[posNames.SecurityEngineerCompanyPositions[0]], sing); return this.applyForJob(CompanyPositions[posNames.SecurityEngineerCompanyPositions[0]], sing);
} else { } else {
@ -1830,7 +1830,7 @@ export function applyForSecurityEngineerJob(this: IPlayer, sing = false): boolea
} }
export function applyForNetworkEngineerJob(this: IPlayer, sing = false): boolean { export function applyForNetworkEngineerJob(this: IPlayer, sing = false): boolean {
var company = Companies[this.location]; //Company being applied to const company = Companies[this.location]; //Company being applied to
if (this.isQualified(company, CompanyPositions[posNames.NetworkEngineerCompanyPositions[0]])) { if (this.isQualified(company, CompanyPositions[posNames.NetworkEngineerCompanyPositions[0]])) {
const pos = CompanyPositions[posNames.NetworkEngineerCompanyPositions[0]]; const pos = CompanyPositions[posNames.NetworkEngineerCompanyPositions[0]];
return this.applyForJob(pos, sing); return this.applyForJob(pos, sing);
@ -1857,7 +1857,7 @@ export function applyForSecurityJob(this: IPlayer, sing = false): boolean {
} }
export function applyForAgentJob(this: IPlayer, sing = false): boolean { export function applyForAgentJob(this: IPlayer, sing = false): boolean {
var company = Companies[this.location]; //Company being applied to const company = Companies[this.location]; //Company being applied to
if (this.isQualified(company, CompanyPositions[posNames.AgentCompanyPositions[0]])) { if (this.isQualified(company, CompanyPositions[posNames.AgentCompanyPositions[0]])) {
const pos = CompanyPositions[posNames.AgentCompanyPositions[0]]; const pos = CompanyPositions[posNames.AgentCompanyPositions[0]];
return this.applyForJob(pos, sing); return this.applyForJob(pos, sing);
@ -1870,7 +1870,7 @@ export function applyForAgentJob(this: IPlayer, sing = false): boolean {
} }
export function applyForEmployeeJob(this: IPlayer, sing = false): boolean { export function applyForEmployeeJob(this: IPlayer, sing = false): boolean {
var company = Companies[this.location]; //Company being applied to const company = Companies[this.location]; //Company being applied to
if (this.isQualified(company, CompanyPositions[posNames.MiscCompanyPositions[1]])) { if (this.isQualified(company, CompanyPositions[posNames.MiscCompanyPositions[1]])) {
this.companyName = company.name; this.companyName = company.name;
this.jobs[company.name] = posNames.MiscCompanyPositions[1]; this.jobs[company.name] = posNames.MiscCompanyPositions[1];
@ -1889,7 +1889,7 @@ export function applyForEmployeeJob(this: IPlayer, sing = false): boolean {
} }
export function applyForPartTimeEmployeeJob(this: IPlayer, sing = false): boolean { export function applyForPartTimeEmployeeJob(this: IPlayer, sing = false): boolean {
var company = Companies[this.location]; //Company being applied to const company = Companies[this.location]; //Company being applied to
if (this.isQualified(company, CompanyPositions[posNames.PartTimeCompanyPositions[1]])) { if (this.isQualified(company, CompanyPositions[posNames.PartTimeCompanyPositions[1]])) {
this.jobs[company.name] = posNames.PartTimeCompanyPositions[1]; this.jobs[company.name] = posNames.PartTimeCompanyPositions[1];
if (!sing) { if (!sing) {
@ -1907,7 +1907,7 @@ export function applyForPartTimeEmployeeJob(this: IPlayer, sing = false): boolea
} }
export function applyForWaiterJob(this: IPlayer, sing = false): boolean { export function applyForWaiterJob(this: IPlayer, sing = false): boolean {
var company = Companies[this.location]; //Company being applied to const company = Companies[this.location]; //Company being applied to
if (this.isQualified(company, CompanyPositions[posNames.MiscCompanyPositions[0]])) { if (this.isQualified(company, CompanyPositions[posNames.MiscCompanyPositions[0]])) {
this.companyName = company.name; this.companyName = company.name;
this.jobs[company.name] = posNames.MiscCompanyPositions[0]; this.jobs[company.name] = posNames.MiscCompanyPositions[0];
@ -1924,7 +1924,7 @@ export function applyForWaiterJob(this: IPlayer, sing = false): boolean {
} }
export function applyForPartTimeWaiterJob(this: IPlayer, sing = false): boolean { export function applyForPartTimeWaiterJob(this: IPlayer, sing = false): boolean {
var company = Companies[this.location]; //Company being applied to const company = Companies[this.location]; //Company being applied to
if (this.isQualified(company, CompanyPositions[posNames.PartTimeCompanyPositions[0]])) { if (this.isQualified(company, CompanyPositions[posNames.PartTimeCompanyPositions[0]])) {
this.companyName = company.name; this.companyName = company.name;
this.jobs[company.name] = posNames.PartTimeCompanyPositions[0]; this.jobs[company.name] = posNames.PartTimeCompanyPositions[0];
@ -1942,13 +1942,13 @@ export function applyForPartTimeWaiterJob(this: IPlayer, sing = false): boolean
//Checks if the Player is qualified for a certain position //Checks if the Player is qualified for a certain position
export function isQualified(this: IPlayer, company: Company, position: CompanyPosition): boolean { export function isQualified(this: IPlayer, company: Company, position: CompanyPosition): boolean {
var offset = company.jobStatReqOffset; const offset = company.jobStatReqOffset;
var reqHacking = position.requiredHacking > 0 ? position.requiredHacking + offset : 0; const reqHacking = position.requiredHacking > 0 ? position.requiredHacking + offset : 0;
var reqStrength = position.requiredStrength > 0 ? position.requiredStrength + offset : 0; const reqStrength = position.requiredStrength > 0 ? position.requiredStrength + offset : 0;
var reqDefense = position.requiredDefense > 0 ? position.requiredDefense + offset : 0; const reqDefense = position.requiredDefense > 0 ? position.requiredDefense + offset : 0;
var reqDexterity = position.requiredDexterity > 0 ? position.requiredDexterity + offset : 0; const reqDexterity = position.requiredDexterity > 0 ? position.requiredDexterity + offset : 0;
var reqAgility = position.requiredDexterity > 0 ? position.requiredDexterity + offset : 0; const reqAgility = position.requiredDexterity > 0 ? position.requiredDexterity + offset : 0;
var reqCharisma = position.requiredCharisma > 0 ? position.requiredCharisma + offset : 0; const reqCharisma = position.requiredCharisma > 0 ? position.requiredCharisma + offset : 0;
if ( if (
this.hacking_skill >= reqHacking && this.hacking_skill >= reqHacking &&
@ -1977,7 +1977,7 @@ export function reapplyAllAugmentations(this: IPlayer, resetMultipliers = true):
} }
const augName = this.augmentations[i].name; const augName = this.augmentations[i].name;
var aug = Augmentations[augName]; const aug = Augmentations[augName];
if (aug == null) { if (aug == null) {
console.warn(`Invalid augmentation name in Player.reapplyAllAugmentations(). Aug ${augName} will be skipped`); console.warn(`Invalid augmentation name in Player.reapplyAllAugmentations(). Aug ${augName} will be skipped`);
continue; continue;
@ -2000,8 +2000,8 @@ export function reapplyAllSourceFiles(this: IPlayer): void {
//this.resetMultipliers(); //this.resetMultipliers();
for (let i = 0; i < this.sourceFiles.length; ++i) { for (let i = 0; i < this.sourceFiles.length; ++i) {
var srcFileKey = "SourceFile" + this.sourceFiles[i].n; const srcFileKey = "SourceFile" + this.sourceFiles[i].n;
var sourceFileObject = SourceFiles[srcFileKey]; const sourceFileObject = SourceFiles[srcFileKey];
if (sourceFileObject == null) { if (sourceFileObject == null) {
console.error(`Invalid source file number: ${this.sourceFiles[i].n}`); console.error(`Invalid source file number: ${this.sourceFiles[i].n}`);
continue; continue;
@ -2016,9 +2016,9 @@ export function reapplyAllSourceFiles(this: IPlayer): void {
//those requirements and will return an array of all factions that the Player should //those requirements and will return an array of all factions that the Player should
//receive an invitation to //receive an invitation to
export function checkForFactionInvitations(this: IPlayer): Faction[] { export function checkForFactionInvitations(this: IPlayer): Faction[] {
let invitedFactions: Faction[] = []; //Array which will hold all Factions the player should be invited to const invitedFactions: Faction[] = []; //Array which will hold all Factions the player should be invited to
var numAugmentations = this.augmentations.length; const numAugmentations = this.augmentations.length;
const allCompanies = Object.keys(this.jobs); const allCompanies = Object.keys(this.jobs);
const allPositions = Object.values(this.jobs); const allPositions = Object.values(this.jobs);
@ -2042,7 +2042,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Illuminati //Illuminati
var illuminatiFac = Factions["Illuminati"]; const illuminatiFac = Factions["Illuminati"];
if ( if (
!illuminatiFac.isBanned && !illuminatiFac.isBanned &&
!illuminatiFac.isMember && !illuminatiFac.isMember &&
@ -2059,7 +2059,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Daedalus //Daedalus
var daedalusFac = Factions["Daedalus"]; const daedalusFac = Factions["Daedalus"];
if ( if (
!daedalusFac.isBanned && !daedalusFac.isBanned &&
!daedalusFac.isMember && !daedalusFac.isMember &&
@ -2073,7 +2073,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//The Covenant //The Covenant
var covenantFac = Factions["The Covenant"]; const covenantFac = Factions["The Covenant"];
if ( if (
!covenantFac.isBanned && !covenantFac.isBanned &&
!covenantFac.isMember && !covenantFac.isMember &&
@ -2090,7 +2090,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//ECorp //ECorp
var ecorpFac = Factions["ECorp"]; const ecorpFac = Factions["ECorp"];
if ( if (
!ecorpFac.isBanned && !ecorpFac.isBanned &&
!ecorpFac.isMember && !ecorpFac.isMember &&
@ -2101,7 +2101,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//MegaCorp //MegaCorp
var megacorpFac = Factions["MegaCorp"]; const megacorpFac = Factions["MegaCorp"];
if ( if (
!megacorpFac.isBanned && !megacorpFac.isBanned &&
!megacorpFac.isMember && !megacorpFac.isMember &&
@ -2112,7 +2112,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Bachman & Associates //Bachman & Associates
var bachmanandassociatesFac = Factions["Bachman & Associates"]; const bachmanandassociatesFac = Factions["Bachman & Associates"];
if ( if (
!bachmanandassociatesFac.isBanned && !bachmanandassociatesFac.isBanned &&
!bachmanandassociatesFac.isMember && !bachmanandassociatesFac.isMember &&
@ -2123,7 +2123,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Blade Industries //Blade Industries
var bladeindustriesFac = Factions["Blade Industries"]; const bladeindustriesFac = Factions["Blade Industries"];
if ( if (
!bladeindustriesFac.isBanned && !bladeindustriesFac.isBanned &&
!bladeindustriesFac.isMember && !bladeindustriesFac.isMember &&
@ -2134,7 +2134,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//NWO //NWO
var nwoFac = Factions["NWO"]; const nwoFac = Factions["NWO"];
if ( if (
!nwoFac.isBanned && !nwoFac.isBanned &&
!nwoFac.isMember && !nwoFac.isMember &&
@ -2145,7 +2145,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Clarke Incorporated //Clarke Incorporated
var clarkeincorporatedFac = Factions["Clarke Incorporated"]; const clarkeincorporatedFac = Factions["Clarke Incorporated"];
if ( if (
!clarkeincorporatedFac.isBanned && !clarkeincorporatedFac.isBanned &&
!clarkeincorporatedFac.isMember && !clarkeincorporatedFac.isMember &&
@ -2156,7 +2156,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//OmniTek Incorporated //OmniTek Incorporated
var omnitekincorporatedFac = Factions["OmniTek Incorporated"]; const omnitekincorporatedFac = Factions["OmniTek Incorporated"];
if ( if (
!omnitekincorporatedFac.isBanned && !omnitekincorporatedFac.isBanned &&
!omnitekincorporatedFac.isMember && !omnitekincorporatedFac.isMember &&
@ -2167,7 +2167,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Four Sigma //Four Sigma
var foursigmaFac = Factions["Four Sigma"]; const foursigmaFac = Factions["Four Sigma"];
if ( if (
!foursigmaFac.isBanned && !foursigmaFac.isBanned &&
!foursigmaFac.isMember && !foursigmaFac.isMember &&
@ -2178,7 +2178,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//KuaiGong International //KuaiGong International
var kuaigonginternationalFac = Factions["KuaiGong International"]; const kuaigonginternationalFac = Factions["KuaiGong International"];
if ( if (
!kuaigonginternationalFac.isBanned && !kuaigonginternationalFac.isBanned &&
!kuaigonginternationalFac.isMember && !kuaigonginternationalFac.isMember &&
@ -2261,7 +2261,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Chongqing //Chongqing
var chongqingFac = Factions["Chongqing"]; const chongqingFac = Factions["Chongqing"];
if ( if (
!chongqingFac.isBanned && !chongqingFac.isBanned &&
!chongqingFac.isMember && !chongqingFac.isMember &&
@ -2273,7 +2273,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Sector-12 //Sector-12
var sector12Fac = Factions["Sector-12"]; const sector12Fac = Factions["Sector-12"];
if ( if (
!sector12Fac.isBanned && !sector12Fac.isBanned &&
!sector12Fac.isMember && !sector12Fac.isMember &&
@ -2285,7 +2285,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//New Tokyo //New Tokyo
var newtokyoFac = Factions["New Tokyo"]; const newtokyoFac = Factions["New Tokyo"];
if ( if (
!newtokyoFac.isBanned && !newtokyoFac.isBanned &&
!newtokyoFac.isMember && !newtokyoFac.isMember &&
@ -2297,7 +2297,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Aevum //Aevum
var aevumFac = Factions["Aevum"]; const aevumFac = Factions["Aevum"];
if ( if (
!aevumFac.isBanned && !aevumFac.isBanned &&
!aevumFac.isMember && !aevumFac.isMember &&
@ -2309,7 +2309,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Ishima //Ishima
var ishimaFac = Factions["Ishima"]; const ishimaFac = Factions["Ishima"];
if ( if (
!ishimaFac.isBanned && !ishimaFac.isBanned &&
!ishimaFac.isMember && !ishimaFac.isMember &&
@ -2321,7 +2321,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Volhaven //Volhaven
var volhavenFac = Factions["Volhaven"]; const volhavenFac = Factions["Volhaven"];
if ( if (
!volhavenFac.isBanned && !volhavenFac.isBanned &&
!volhavenFac.isMember && !volhavenFac.isMember &&
@ -2333,7 +2333,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Speakers for the Dead //Speakers for the Dead
var speakersforthedeadFac = Factions["Speakers for the Dead"]; const speakersforthedeadFac = Factions["Speakers for the Dead"];
if ( if (
!speakersforthedeadFac.isBanned && !speakersforthedeadFac.isBanned &&
!speakersforthedeadFac.isMember && !speakersforthedeadFac.isMember &&
@ -2352,7 +2352,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//The Dark Army //The Dark Army
var thedarkarmyFac = Factions["The Dark Army"]; const thedarkarmyFac = Factions["The Dark Army"];
if ( if (
!thedarkarmyFac.isBanned && !thedarkarmyFac.isBanned &&
!thedarkarmyFac.isMember && !thedarkarmyFac.isMember &&
@ -2372,7 +2372,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//The Syndicate //The Syndicate
var thesyndicateFac = Factions["The Syndicate"]; const thesyndicateFac = Factions["The Syndicate"];
if ( if (
!thesyndicateFac.isBanned && !thesyndicateFac.isBanned &&
!thesyndicateFac.isMember && !thesyndicateFac.isMember &&
@ -2392,7 +2392,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Silhouette //Silhouette
var silhouetteFac = Factions["Silhouette"]; const silhouetteFac = Factions["Silhouette"];
if ( if (
!silhouetteFac.isBanned && !silhouetteFac.isBanned &&
!silhouetteFac.isMember && !silhouetteFac.isMember &&
@ -2407,7 +2407,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Tetrads //Tetrads
var tetradsFac = Factions["Tetrads"]; const tetradsFac = Factions["Tetrads"];
if ( if (
!tetradsFac.isBanned && !tetradsFac.isBanned &&
!tetradsFac.isMember && !tetradsFac.isMember &&
@ -2423,7 +2423,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//SlumSnakes //SlumSnakes
var slumsnakesFac = Factions["Slum Snakes"]; const slumsnakesFac = Factions["Slum Snakes"];
if ( if (
!slumsnakesFac.isBanned && !slumsnakesFac.isBanned &&
!slumsnakesFac.isMember && !slumsnakesFac.isMember &&
@ -2439,10 +2439,10 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Netburners //Netburners
var netburnersFac = Factions["Netburners"]; const netburnersFac = Factions["Netburners"];
var totalHacknetRam = 0; let totalHacknetRam = 0;
var totalHacknetCores = 0; let totalHacknetCores = 0;
var totalHacknetLevels = 0; let totalHacknetLevels = 0;
for (let i = 0; i < this.hacknetNodes.length; ++i) { for (let i = 0; i < this.hacknetNodes.length; ++i) {
const v = this.hacknetNodes[i]; const v = this.hacknetNodes[i];
if (typeof v === "string") { if (typeof v === "string") {
@ -2470,7 +2470,7 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
//Tian Di Hui //Tian Di Hui
var tiandihuiFac = Factions["Tian Di Hui"]; const tiandihuiFac = Factions["Tian Di Hui"];
if ( if (
!tiandihuiFac.isBanned && !tiandihuiFac.isBanned &&
!tiandihuiFac.isMember && !tiandihuiFac.isMember &&
@ -2503,11 +2503,11 @@ export function checkForFactionInvitations(this: IPlayer): Faction[] {
} }
/************* BitNodes **************/ /************* BitNodes **************/
export function setBitNodeNumber(this: IPlayer, n: number) { export function setBitNodeNumber(this: IPlayer, n: number): void {
this.bitNodeN = n; this.bitNodeN = n;
} }
export function queueAugmentation(this: IPlayer, name: string) { export function queueAugmentation(this: IPlayer, name: string): void {
for (const i in this.queuedAugmentations) { for (const i in this.queuedAugmentations) {
if (this.queuedAugmentations[i].name == name) { if (this.queuedAugmentations[i].name == name) {
console.warn(`tried to queue ${name} twice, this may be a bug`); console.warn(`tried to queue ${name} twice, this may be a bug`);
@ -2526,7 +2526,7 @@ export function queueAugmentation(this: IPlayer, name: string) {
} }
/************* Coding Contracts **************/ /************* Coding Contracts **************/
export function gainCodingContractReward(this: IPlayer, reward: ICodingContractReward, difficulty = 1) { export function gainCodingContractReward(this: IPlayer, reward: ICodingContractReward, difficulty = 1): string {
if (reward == null || reward.type == null || reward == null) { if (reward == null || reward.type == null || reward == null) {
return `No reward for this contract`; return `No reward for this contract`;
} }
@ -2539,7 +2539,7 @@ export function gainCodingContractReward(this: IPlayer, reward: ICodingContractR
reward.type = CodingContractRewardType.FactionReputationAll; reward.type = CodingContractRewardType.FactionReputationAll;
return this.gainCodingContractReward(reward); return this.gainCodingContractReward(reward);
} }
var repGain = CONSTANTS.CodingContractBaseFactionRepGain * difficulty; const repGain = CONSTANTS.CodingContractBaseFactionRepGain * difficulty;
Factions[reward.name].playerReputation += repGain; Factions[reward.name].playerReputation += repGain;
return `Gained ${repGain} faction reputation for ${reward.name}`; return `Gained ${repGain} faction reputation for ${reward.name}`;
case CodingContractRewardType.FactionReputationAll: case CodingContractRewardType.FactionReputationAll:
@ -2547,7 +2547,7 @@ export function gainCodingContractReward(this: IPlayer, reward: ICodingContractR
// Ignore Bladeburners and other special factions for this calculation // Ignore Bladeburners and other special factions for this calculation
const specialFactions = ["Bladeburners"]; const specialFactions = ["Bladeburners"];
var factions = this.factions.slice(); const factions = this.factions.slice();
factions = factions.filter((f) => { factions = factions.filter((f) => {
return !specialFactions.includes(f); return !specialFactions.includes(f);
}); });
@ -2573,13 +2573,13 @@ export function gainCodingContractReward(this: IPlayer, reward: ICodingContractR
reward.type = CodingContractRewardType.FactionReputationAll; reward.type = CodingContractRewardType.FactionReputationAll;
return this.gainCodingContractReward(reward); return this.gainCodingContractReward(reward);
} }
var repGain = CONSTANTS.CodingContractBaseCompanyRepGain * difficulty; const repGain = CONSTANTS.CodingContractBaseCompanyRepGain * difficulty;
Companies[reward.name].playerReputation += repGain; Companies[reward.name].playerReputation += repGain;
return `Gained ${repGain} company reputation for ${reward.name}`; return `Gained ${repGain} company reputation for ${reward.name}`;
break; break;
case CodingContractRewardType.Money: case CodingContractRewardType.Money:
default: default:
var moneyGain = CONSTANTS.CodingContractBaseMoneyGain * difficulty * BitNodeMultipliers.CodingContractMoney; const moneyGain = CONSTANTS.CodingContractBaseMoneyGain * difficulty * BitNodeMultipliers.CodingContractMoney;
this.gainMoney(moneyGain); this.gainMoney(moneyGain);
this.recordMoneySource(moneyGain, "codingcontract"); this.recordMoneySource(moneyGain, "codingcontract");
return `Gained ${numeralWrapper.formatMoney(moneyGain)}`; return `Gained ${numeralWrapper.formatMoney(moneyGain)}`;
@ -2588,7 +2588,7 @@ export function gainCodingContractReward(this: IPlayer, reward: ICodingContractR
/* eslint-enable no-case-declarations */ /* eslint-enable no-case-declarations */
} }
export function travel(this: IPlayer, to: CityName) { export function travel(this: IPlayer, to: CityName): boolean {
if (Cities[to] == null) { if (Cities[to] == null) {
console.warn(`Player.travel() called with invalid city: ${to}`); console.warn(`Player.travel() called with invalid city: ${to}`);
return false; return false;
@ -2598,7 +2598,7 @@ export function travel(this: IPlayer, to: CityName) {
return true; return true;
} }
export function gotoLocation(this: IPlayer, to: LocationName) { export function gotoLocation(this: IPlayer, to: LocationName): boolean {
if (Locations[to] == null) { if (Locations[to] == null) {
console.warn(`Player.gotoLocation() called with invalid location: ${to}`); console.warn(`Player.gotoLocation() called with invalid location: ${to}`);
return false; return false;
@ -2608,21 +2608,21 @@ export function gotoLocation(this: IPlayer, to: LocationName) {
return true; return true;
} }
export function canAccessResleeving(this: IPlayer) { export function canAccessResleeving(this: IPlayer): boolean {
return this.bitNodeN === 10 || SourceFileFlags[10] > 0; return this.bitNodeN === 10 || SourceFileFlags[10] > 0;
} }
export function giveExploit(this: IPlayer, exploit: Exploit) { export function giveExploit(this: IPlayer, exploit: Exploit): void {
if (!this.exploits.includes(exploit)) { if (!this.exploits.includes(exploit)) {
this.exploits.push(exploit); this.exploits.push(exploit);
} }
} }
export function getIntelligenceBonus(this: IPlayer, weight: number) { export function getIntelligenceBonus(this: IPlayer, weight: number): number {
return calculateIntelligenceBonus(this.intelligence, weight); return calculateIntelligenceBonus(this.intelligence, weight);
} }
export function getCasinoWinnings(this: IPlayer) { export function getCasinoWinnings(this: IPlayer): number {
return this.moneySourceA.casino; return this.moneySourceA.casino;
} }

@ -6,7 +6,6 @@ import { Bladeburner } from "./Bladeburner/Bladeburner";
import { Companies, initCompanies } from "./Company/Companies"; import { Companies, initCompanies } from "./Company/Companies";
import { resetIndustryResearchTrees } from "./Corporation/IndustryData"; import { resetIndustryResearchTrees } from "./Corporation/IndustryData";
import { Programs } from "./Programs/Programs"; import { Programs } from "./Programs/Programs";
import { Engine } from "./engine";
import { Faction } from "./Faction/Faction"; import { Faction } from "./Faction/Faction";
import { Factions, initFactions } from "./Faction/Factions"; import { Factions, initFactions } from "./Faction/Factions";
import { joinFaction } from "./Faction/FactionHelpers"; import { joinFaction } from "./Faction/FactionHelpers";
@ -155,7 +154,7 @@ function prestigeSourceFile(flume: boolean): void {
Player.prestigeSourceFile(); Player.prestigeSourceFile();
prestigeWorkerScripts(); // Delete all Worker Scripts objects prestigeWorkerScripts(); // Delete all Worker Scripts objects
var homeComp = Player.getHomeComputer(); const homeComp = Player.getHomeComputer();
// Delete all servers except home computer // Delete all servers except home computer
prestigeAllServers(); // Must be done before initForeignServers() prestigeAllServers(); // Must be done before initForeignServers()
@ -180,14 +179,14 @@ function prestigeSourceFile(flume: boolean): void {
homeComp.cpuCores = 1; homeComp.cpuCores = 1;
// Reset favor for Companies // Reset favor for Companies
for (var member in Companies) { for (const member in Companies) {
if (Companies.hasOwnProperty(member)) { if (Companies.hasOwnProperty(member)) {
Companies[member].favor = 0; Companies[member].favor = 0;
} }
} }
// Reset favor for factions // Reset favor for factions
for (var member in Factions) { for (const member in Factions) {
if (Factions.hasOwnProperty(member)) { if (Factions.hasOwnProperty(member)) {
Factions[member].favor = 0; Factions[member].favor = 0;
} }
@ -199,7 +198,7 @@ function prestigeSourceFile(flume: boolean): void {
} }
// Delete all Augmentations // Delete all Augmentations
for (var name in Augmentations) { for (const name in Augmentations) {
if (Augmentations.hasOwnProperty(name)) { if (Augmentations.hasOwnProperty(name)) {
delete Augmentations[name]; delete Augmentations[name];
} }

@ -2,7 +2,7 @@ import React, { useState, useEffect } from "react";
import { use } from "../../ui/Context"; import { use } from "../../ui/Context";
import { getAvailableCreatePrograms } from "../ProgramHelpers"; import { getAvailableCreatePrograms } from "../ProgramHelpers";
import { Box, ButtonGroup, Tooltip, Typography } from "@mui/material"; import { Box, Tooltip, Typography } from "@mui/material";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
export function ProgramsRoot(): React.ReactElement { export function ProgramsRoot(): React.ReactElement {

@ -17,17 +17,17 @@ export function setRedPillFlag(b: boolean): void {
} }
function giveSourceFile(bitNodeNumber: number): void { function giveSourceFile(bitNodeNumber: number): void {
var sourceFileKey = "SourceFile" + bitNodeNumber.toString(); const sourceFileKey = "SourceFile" + bitNodeNumber.toString();
var sourceFile = SourceFiles[sourceFileKey]; const sourceFile = SourceFiles[sourceFileKey];
if (sourceFile == null) { if (sourceFile == null) {
console.error(`Could not find source file for Bit node: ${bitNodeNumber}`); console.error(`Could not find source file for Bit node: ${bitNodeNumber}`);
return; return;
} }
// Check if player already has this source file // Check if player already has this source file
var alreadyOwned = false; let alreadyOwned = false;
var ownedSourceFile = null; let ownedSourceFile = null;
for (var i = 0; i < Player.sourceFiles.length; ++i) { for (let i = 0; i < Player.sourceFiles.length; ++i) {
if (Player.sourceFiles[i].n === bitNodeNumber) { if (Player.sourceFiles[i].n === bitNodeNumber) {
alreadyOwned = true; alreadyOwned = true;
ownedSourceFile = Player.sourceFiles[i]; ownedSourceFile = Player.sourceFiles[i];
@ -51,7 +51,7 @@ function giveSourceFile(bitNodeNumber: number): void {
); );
} }
} else { } else {
var playerSrcFile = new PlayerOwnedSourceFile(bitNodeNumber, 1); const playerSrcFile = new PlayerOwnedSourceFile(bitNodeNumber, 1);
Player.sourceFiles.push(playerSrcFile); Player.sourceFiles.push(playerSrcFile);
if (bitNodeNumber === 5 && Player.intelligence === 0) { if (bitNodeNumber === 5 && Player.intelligence === 0) {
// Artificial Intelligence // Artificial Intelligence

@ -1,7 +1,6 @@
import { loadAliases, loadGlobalAliases, Aliases, GlobalAliases } from "./Alias"; import { loadAliases, loadGlobalAliases, Aliases, GlobalAliases } from "./Alias";
import { Companies, loadCompanies } from "./Company/Companies"; import { Companies, loadCompanies } from "./Company/Companies";
import { CONSTANTS } from "./Constants"; import { CONSTANTS } from "./Constants";
import { Engine } from "./engine";
import { Factions, loadFactions } from "./Faction/Factions"; import { Factions, loadFactions } from "./Faction/Factions";
import { loadAllGangs, AllGangs } from "./Gang/AllGangs"; import { loadAllGangs, AllGangs } from "./Gang/AllGangs";
import { loadMessages, initMessages, Messages } from "./Message/MessageHelpers"; import { loadMessages, initMessages, Messages } from "./Message/MessageHelpers";
@ -18,12 +17,9 @@ import { setTimeoutRef } from "./utils/SetTimeoutRef";
import * as ExportBonus from "./ExportBonus"; import * as ExportBonus from "./ExportBonus";
import { dialogBoxCreate } from "../utils/DialogBox"; import { dialogBoxCreate } from "../utils/DialogBox";
import { clearEventListeners } from "../utils/uiHelpers/clearEventListeners";
import { Reviver, Generic_toJSON, Generic_fromJSON } from "../utils/JSONReviver"; import { Reviver, Generic_toJSON, Generic_fromJSON } from "../utils/JSONReviver";
import { save } from "./db"; import { save } from "./db";
import Decimal from "decimal.js";
/* SaveObject.js /* SaveObject.js
* Defines the object used to save/load games * Defines the object used to save/load games
*/ */
@ -47,14 +43,14 @@ class BitburnerSaveObject {
this.PlayerSave = JSON.stringify(Player); this.PlayerSave = JSON.stringify(Player);
// Delete all logs from all running scripts // Delete all logs from all running scripts
var TempAllServers = JSON.parse(JSON.stringify(AllServers), Reviver); const TempAllServers = JSON.parse(JSON.stringify(AllServers), Reviver);
for (var ip in TempAllServers) { for (const ip in TempAllServers) {
var server = TempAllServers[ip]; const server = TempAllServers[ip];
if (server == null) { if (server == null) {
continue; continue;
} }
for (var i = 0; i < server.runningScripts.length; ++i) { for (let i = 0; i < server.runningScripts.length; ++i) {
var runningScriptObj = server.runningScripts[i]; const runningScriptObj = server.runningScripts[i];
runningScriptObj.logs.length = 0; runningScriptObj.logs.length = 0;
runningScriptObj.logs = []; runningScriptObj.logs = [];
} }
@ -74,7 +70,7 @@ class BitburnerSaveObject {
if (Player.inGang()) { if (Player.inGang()) {
this.AllGangsSave = JSON.stringify(AllGangs); this.AllGangsSave = JSON.stringify(AllGangs);
} }
var saveString = btoa(unescape(encodeURIComponent(JSON.stringify(this)))); const saveString = btoa(unescape(encodeURIComponent(JSON.stringify(this))));
return saveString; return saveString;
} }
@ -94,13 +90,13 @@ class BitburnerSaveObject {
const epochTime = Math.round(Date.now() / 1000); const epochTime = Math.round(Date.now() / 1000);
const bn = Player.bitNodeN; const bn = Player.bitNodeN;
const filename = `bitburnerSave_BN${bn}x${SourceFileFlags[bn]}_${epochTime}.json`; const filename = `bitburnerSave_BN${bn}x${SourceFileFlags[bn]}_${epochTime}.json`;
var file = new Blob([saveString], { type: "text/plain" }); const file = new Blob([saveString], { type: "text/plain" });
if (window.navigator.msSaveOrOpenBlob) { if (window.navigator.msSaveOrOpenBlob) {
// IE10+ // IE10+
window.navigator.msSaveOrOpenBlob(file, filename); window.navigator.msSaveOrOpenBlob(file, filename);
} else { } else {
// Others // Others
var a = document.createElement("a"), const a = document.createElement("a"),
url = URL.createObjectURL(file); url = URL.createObjectURL(file);
a.href = url; a.href = url;
a.download = filename; a.download = filename;
@ -124,7 +120,7 @@ class BitburnerSaveObject {
// Makes necessary changes to the loaded/imported data to ensure // Makes necessary changes to the loaded/imported data to ensure
// the game stills works with new versions // the game stills works with new versions
function evaluateVersionCompatibility(ver: string) { function evaluateVersionCompatibility(ver: string): void {
// We have to do this because ts won't let us otherwise // We have to do this because ts won't let us otherwise
const anyPlayer = Player as any; const anyPlayer = Player as any;
// This version refactored the Company/job-related code // This version refactored the Company/job-related code
@ -239,7 +235,7 @@ function loadGame(saveString: string): boolean {
} }
if (saveObj.hasOwnProperty("VersionSave")) { if (saveObj.hasOwnProperty("VersionSave")) {
try { try {
var ver = JSON.parse(saveObj.VersionSave, Reviver); const ver = JSON.parse(saveObj.VersionSave, Reviver);
evaluateVersionCompatibility(ver); evaluateVersionCompatibility(ver);
if (window.location.href.toLowerCase().includes("bitburner-beta")) { if (window.location.href.toLowerCase().includes("bitburner-beta")) {
@ -265,7 +261,7 @@ function loadGame(saveString: string): boolean {
return true; return true;
} }
function createNewUpdateText() { function createNewUpdateText(): void {
dialogBoxCreate( dialogBoxCreate(
"New update!<br>" + "New update!<br>" +
"Please report any bugs/issues through the github repository " + "Please report any bugs/issues through the github repository " +
@ -274,7 +270,7 @@ function createNewUpdateText() {
); );
} }
function createBetaUpdateText() { function createBetaUpdateText(): void {
dialogBoxCreate( dialogBoxCreate(
"You are playing on the beta environment! This branch of the game " + "You are playing on the beta environment! This branch of the game " +
"features the latest developments in the game. This version may be unstable.<br>" + "features the latest developments in the game. This version may be unstable.<br>" +
@ -288,4 +284,4 @@ Reviver.constructors.BitburnerSaveObject = BitburnerSaveObject;
export { saveObject, loadGame }; export { saveObject, loadGame };
let saveObject = new BitburnerSaveObject(); const saveObject = new BitburnerSaveObject();

@ -104,7 +104,7 @@ async function parseOnlyRamCalculate(
} }
let script = null; let script = null;
let fn = nextModule.startsWith("./") ? nextModule.slice(2) : nextModule; const fn = nextModule.startsWith("./") ? nextModule.slice(2) : nextModule;
for (const s of otherScripts) { for (const s of otherScripts) {
if (s.filename === fn) { if (s.filename === fn) {
script = s; script = s;
@ -147,14 +147,14 @@ async function parseOnlyRamCalculate(
if (ref.endsWith(".*")) { if (ref.endsWith(".*")) {
// A prefix reference. We need to find all matching identifiers. // A prefix reference. We need to find all matching identifiers.
const prefix = ref.slice(0, ref.length - 2); const prefix = ref.slice(0, ref.length - 2);
for (let ident of Object.keys(dependencyMap).filter((k) => k.startsWith(prefix))) { for (const ident of Object.keys(dependencyMap).filter((k) => k.startsWith(prefix))) {
for (let dep of dependencyMap[ident] || []) { for (const dep of dependencyMap[ident] || []) {
if (!resolvedRefs.has(dep)) unresolvedRefs.push(dep); if (!resolvedRefs.has(dep)) unresolvedRefs.push(dep);
} }
} }
} else { } else {
// An exact reference. Add all dependencies of this ref. // An exact reference. Add all dependencies of this ref.
for (let dep of dependencyMap[ref] || []) { for (const dep of dependencyMap[ref] || []) {
if (!resolvedRefs.has(dep)) unresolvedRefs.push(dep); if (!resolvedRefs.has(dep)) unresolvedRefs.push(dep);
} }
} }
@ -162,7 +162,7 @@ async function parseOnlyRamCalculate(
// Check if this identifier is a function in the workerScript environment. // Check if this identifier is a function in the workerScript environment.
// If it is, then we need to get its RAM cost. // If it is, then we need to get its RAM cost.
try { try {
function applyFuncRam(func: any) { function applyFuncRam(func: any): number {
if (typeof func === "function") { if (typeof func === "function") {
try { try {
let res; let res;
@ -235,9 +235,9 @@ function parseOnlyCalculateDeps(code: string, currentModule: string): any {
// If we reference this internal name, we're really referencing that external name. // If we reference this internal name, we're really referencing that external name.
// Filled when we import names from other modules. // Filled when we import names from other modules.
let internalToExternal: { [key: string]: string | undefined } = {}; const internalToExternal: { [key: string]: string | undefined } = {};
let additionalModules: string[] = []; const additionalModules: string[] = [];
// References get added pessimistically. They are added for thisModule.name, name, and for // References get added pessimistically. They are added for thisModule.name, name, and for
// any aliases. // any aliases.
@ -256,7 +256,7 @@ function parseOnlyCalculateDeps(code: string, currentModule: string): any {
// If we discover a dependency identifier, state.key is the dependent identifier. // If we discover a dependency identifier, state.key is the dependent identifier.
// walkDeeper is for doing recursive walks of expressions in composites that we handle. // walkDeeper is for doing recursive walks of expressions in composites that we handle.
function commonVisitors() { function commonVisitors(): any {
return { return {
Identifier: (node: any, st: any) => { Identifier: (node: any, st: any) => {
if (objectPrototypeProperties.includes(node.name)) { if (objectPrototypeProperties.includes(node.name)) {

@ -10,7 +10,7 @@ import { numeralWrapper } from "../ui/numeralFormat";
import { compareArrays } from "../../utils/helpers/compareArrays"; import { compareArrays } from "../../utils/helpers/compareArrays";
export function scriptCalculateOfflineProduction(runningScript: RunningScript) { export function scriptCalculateOfflineProduction(runningScript: RunningScript): void {
//The Player object stores the last update time from when we were online //The Player object stores the last update time from when we were online
const thisUpdate = new Date().getTime(); const thisUpdate = new Date().getTime();
const lastUpdate = Player.lastUpdate; const lastUpdate = Player.lastUpdate;
@ -83,8 +83,12 @@ export function scriptCalculateOfflineProduction(runningScript: RunningScript) {
//Returns a RunningScript object matching the filename and arguments on the //Returns a RunningScript object matching the filename and arguments on the
//designated server, and false otherwise //designated server, and false otherwise
export function findRunningScript(filename: string, args: (string | number)[], server: BaseServer) { export function findRunningScript(
for (var i = 0; i < server.runningScripts.length; ++i) { filename: string,
args: (string | number)[],
server: BaseServer,
): RunningScript | null {
for (let i = 0; i < server.runningScripts.length; ++i) {
if (server.runningScripts[i].filename === filename && compareArrays(server.runningScripts[i].args, args)) { if (server.runningScripts[i].filename === filename && compareArrays(server.runningScripts[i].args, args)) {
return server.runningScripts[i]; return server.runningScripts[i];
} }
@ -94,8 +98,8 @@ export function findRunningScript(filename: string, args: (string | number)[], s
//Returns a RunningScript object matching the pid on the //Returns a RunningScript object matching the pid on the
//designated server, and false otherwise //designated server, and false otherwise
export function findRunningScriptByPid(pid: number, server: BaseServer) { export function findRunningScriptByPid(pid: number, server: BaseServer): RunningScript | null {
for (var i = 0; i < server.runningScripts.length; ++i) { for (let i = 0; i < server.runningScripts.length; ++i) {
if (server.runningScripts[i].pid === pid) { if (server.runningScripts[i].pid === pid) {
return server.runningScripts[i]; return server.runningScripts[i];
} }

@ -1,7 +1,5 @@
import React, { useState } from "react"; import React, { useState } from "react";
import { Options } from "./Options"; import { Options } from "./Options";
import { StdButton } from "../../ui/React/StdButton";
import { removePopup } from "../../ui/React/createPopup";
import { Modal } from "../../ui/React/Modal"; import { Modal } from "../../ui/React/Modal";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";

@ -1,9 +1,7 @@
import React, { useState, useEffect, useRef } from "react"; import React, { useState, useEffect, useRef } from "react";
import { StdButton } from "../../ui/React/StdButton";
import Editor from "@monaco-editor/react"; import Editor from "@monaco-editor/react";
import * as monaco from "monaco-editor"; import * as monaco from "monaco-editor";
type IStandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor; type IStandaloneCodeEditor = monaco.editor.IStandaloneCodeEditor;
import { createPopup } from "../../ui/React/createPopup";
import { OptionsModal } from "./OptionsModal"; import { OptionsModal } from "./OptionsModal";
import { Options } from "./Options"; import { Options } from "./Options";
import { js_beautify as beautifyCode } from "js-beautify"; import { js_beautify as beautifyCode } from "js-beautify";
@ -32,7 +30,6 @@ import TextField from "@mui/material/TextField";
import IconButton from "@mui/material/IconButton"; import IconButton from "@mui/material/IconButton";
import SettingsIcon from "@mui/icons-material/Settings"; import SettingsIcon from "@mui/icons-material/Settings";
let loaded = false;
let symbols: string[] = []; let symbols: string[] = [];
(function () { (function () {
const ns = NetscriptFunctions({} as WorkerScript); const ns = NetscriptFunctions({} as WorkerScript);
@ -293,7 +290,6 @@ export function Root(props: IProps): React.ReactElement {
}); });
monaco.languages.typescript.javascriptDefaults.addExtraLib(libSource, "netscript.d.ts"); monaco.languages.typescript.javascriptDefaults.addExtraLib(libSource, "netscript.d.ts");
monaco.languages.typescript.typescriptDefaults.addExtraLib(libSource, "netscript.d.ts"); monaco.languages.typescript.typescriptDefaults.addExtraLib(libSource, "netscript.d.ts");
loaded = true;
} }
return ( return (

@ -1,6 +1,3 @@
import { Engine } from "./engine";
import { createStatusText } from "./ui/createStatusText";
function getDB(): Promise<IDBObjectStore> { function getDB(): Promise<IDBObjectStore> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!window.indexedDB) { if (!window.indexedDB) {
@ -24,7 +21,7 @@ function getDB(): Promise<IDBObjectStore> {
reject(`Failed to get IDB ${ev}`); reject(`Failed to get IDB ${ev}`);
}; };
indexedDbRequest.onsuccess = function (this: IDBRequest<IDBDatabase>, ev: Event) { indexedDbRequest.onsuccess = function (this: IDBRequest<IDBDatabase>) {
const db = this.result; const db = this.result;
if (!db) { if (!db) {
reject("database loadign result was undefined"); reject("database loadign result was undefined");
@ -35,11 +32,6 @@ function getDB(): Promise<IDBObjectStore> {
}); });
} }
interface ILoadCallback {
success: (s: string) => void;
error?: () => void;
}
export function load(): Promise<string> { export function load(): Promise<string> {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
await getDB() await getDB()
@ -59,11 +51,6 @@ export function load(): Promise<string> {
}); });
} }
interface ISaveCallback {
success: () => void;
error?: () => void;
}
export function save(saveString: string): Promise<void> { export function save(saveString: string): Promise<void> {
return getDB().then((db) => { return getDB().then((db) => {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {

@ -231,7 +231,7 @@ const Engine: {
} }
if (Engine.Counters.passiveFactionGrowth <= 0) { if (Engine.Counters.passiveFactionGrowth <= 0) {
var adjustedCycles = Math.floor(5 - Engine.Counters.passiveFactionGrowth); const adjustedCycles = Math.floor(5 - Engine.Counters.passiveFactionGrowth);
processPassiveFactionRepGain(adjustedCycles); processPassiveFactionRepGain(adjustedCycles);
Engine.Counters.passiveFactionGrowth = 5; Engine.Counters.passiveFactionGrowth = 5;
} }
@ -334,7 +334,7 @@ const Engine: {
} }
// Hacknet Nodes offline progress // Hacknet Nodes offline progress
var offlineProductionFromHacknetNodes = processHacknetEarnings(Player, numCyclesOffline); const offlineProductionFromHacknetNodes = processHacknetEarnings(Player, numCyclesOffline);
const hacknetProdInfo = hasHacknetServers(Player) ? ( const hacknetProdInfo = hasHacknetServers(Player) ? (
<>{Hashes(offlineProductionFromHacknetNodes)} hashes</> <>{Hashes(offlineProductionFromHacknetNodes)} hashes</>
) : ( ) : (
@ -384,7 +384,7 @@ const Engine: {
} }
// Update total playtime // Update total playtime
var time = numCyclesOffline * CONSTANTS._idleSpeed; const time = numCyclesOffline * CONSTANTS._idleSpeed;
if (Player.totalPlaytime == null) { if (Player.totalPlaytime == null) {
Player.totalPlaytime = 0; Player.totalPlaytime = 0;
} }

@ -12,7 +12,7 @@ ReactDOM.render(
document.getElementById("mainmenu-container"), document.getElementById("mainmenu-container"),
); );
function rerender() { function rerender(): void {
refreshTheme(); refreshTheme();
ReactDOM.render( ReactDOM.render(
<Theme> <Theme>

@ -23,7 +23,7 @@ export function LoadingScreen(): React.ReactElement {
}); });
useEffect(() => { useEffect(() => {
async function doLoad() { async function doLoad(): Promise<void> {
await load() await load()
.then((saveString) => { .then((saveString) => {
Engine.load(saveString); Engine.load(saveString);

@ -32,7 +32,7 @@ declare module "@mui/material/styles" {
let theme: Theme; let theme: Theme;
export function refreshTheme() { export function refreshTheme(): void {
theme = createTheme({ theme = createTheme({
colors: { colors: {
hp: Settings.theme.hp, hp: Settings.theme.hp,

@ -3,7 +3,6 @@ import { Modal } from "./Modal";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import TextField from "@mui/material/TextField"; import TextField from "@mui/material/TextField";
import DoneIcon from "@mui/icons-material/Done";
import IconButton from "@mui/material/IconButton"; import IconButton from "@mui/material/IconButton";
import ReplyIcon from "@mui/icons-material/Reply"; import ReplyIcon from "@mui/icons-material/Reply";
import { Color, ColorPicker } from "material-ui-color"; import { Color, ColorPicker } from "material-ui-color";

@ -97,10 +97,6 @@ export function WorkInProgressRoot(): React.ReactElement {
player.finishClass(true); player.finishClass(true);
router.toCity(); router.toCity();
} }
function unfocus(): void {
player.stopFocusing();
router.toCity();
}
let stopText = ""; let stopText = "";
if ( if (

@ -10,7 +10,7 @@ export interface IReviverValue {
// a `data` property. If it finds them, and finds a matching // a `data` property. If it finds them, and finds a matching
// constructor that has a `fromJSON` property on it, it hands // constructor that has a `fromJSON` property on it, it hands
// off to that `fromJSON` fuunction, passing in the value. // off to that `fromJSON` fuunction, passing in the value.
export function Reviver(key: string, value: IReviverValue | null) { export function Reviver(key: string, value: IReviverValue | null): any {
if (value == null) { if (value == null) {
console.log("Reviver WRONGLY called with key: " + key + ", and value: " + value); console.log("Reviver WRONGLY called with key: " + key + ", and value: " + value);
return 0; return 0;
@ -32,6 +32,8 @@ export function Reviver(key: string, value: IReviverValue | null) {
} }
return value; return value;
} }
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace Reviver { export namespace Reviver {
export const constructors: { [key: string]: any } = {}; export const constructors: { [key: string]: any } = {};
} }
@ -47,6 +49,7 @@ export namespace Reviver {
// regardless of whether it's an "own" property.) // regardless of whether it's an "own" property.)
// Returns: The structure (which will then be turned into a string // Returns: The structure (which will then be turned into a string
// as part of the JSON.stringify algorithm) // as part of the JSON.stringify algorithm)
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function Generic_toJSON(ctorName: string, obj: any, keys?: string[]): IReviverValue { export function Generic_toJSON(ctorName: string, obj: any, keys?: string[]): IReviverValue {
if (!keys) { if (!keys) {
keys = Object.keys(obj); // Only "own" properties are included keys = Object.keys(obj); // Only "own" properties are included
@ -67,6 +70,7 @@ export function Generic_toJSON(ctorName: string, obj: any, keys?: string[]): IRe
// `ctor` The constructor to call // `ctor` The constructor to call
// `data` The data to apply // `data` The data to apply
// Returns: The object // Returns: The object
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function Generic_fromJSON<T>(ctor: new () => T, data: any): T { export function Generic_fromJSON<T>(ctor: new () => T, data: any): T {
const obj: any = new ctor(); const obj: any = new ctor();
for (const name in data) { for (const name in data) {