Use ts-node instead of Sucrase (#8369)

This commit is contained in:
Annika 2021-07-09 19:59:22 -07:00 committed by GitHub
parent c27cc7ae64
commit c134195915
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
55 changed files with 228 additions and 240 deletions

View File

@ -16,7 +16,7 @@ jobs:
strategy:
matrix:
node-version: [12.x]
node-version: [14.x]
steps:
- uses: actions/checkout@v2

View File

@ -415,11 +415,12 @@ export class RandomGen3Teams extends RandomGen4Teams {
counter.get('physicalpool') + counter.get('specialpool') > 0
);
const runEnforcementChecker = (checkerName: string) => (
this.moveEnforcementCheckers[checkerName]?.(
const runEnforcementChecker = (checkerName: string) => {
if (!this.moveEnforcementCheckers[checkerName]) return false;
return this.moveEnforcementCheckers[checkerName](
movePool, moves, abilities, types, counter, species as Species, teamDetails
)
);
);
};
if (!cull && !isSetup && moveIsRejectable) {
// There may be more important moves that this Pokemon needs

View File

@ -630,11 +630,12 @@ export class RandomGen4Teams extends RandomGen5Teams {
cull = true;
}
const runEnforcementChecker = (checkerName: string) => (
this.moveEnforcementCheckers[checkerName]?.(
const runEnforcementChecker = (checkerName: string) => {
if (!this.moveEnforcementCheckers[checkerName]) return false;
return this.moveEnforcementCheckers[checkerName](
movePool, moves, abilities, types, counter, species as Species, teamDetails
)
);
);
};
const moveIsRejectable = (
!move.weather &&

View File

@ -549,11 +549,12 @@ export class RandomGen5Teams extends RandomGen6Teams {
cull = true;
}
const runEnforcementChecker = (checkerName: string) => (
this.moveEnforcementCheckers[checkerName]?.(
const runEnforcementChecker = (checkerName: string) => {
if (!this.moveEnforcementCheckers[checkerName]) return false;
return this.moveEnforcementCheckers[checkerName](
movePool, moves, abilities, types, counter, species as Species, teamDetails
)
);
);
};
// Pokemon should have moves that benefit their Type/Ability/Weather, as well as moves required by its forme
if (
!cull &&

View File

@ -864,11 +864,12 @@ export class RandomGen6Teams extends RandomGen7Teams {
cull = true;
}
const runEnforcementChecker = (checkerName: string) => (
this.moveEnforcementCheckers[checkerName]?.(
const runEnforcementChecker = (checkerName: string) => {
if (!this.moveEnforcementCheckers[checkerName]) return false;
return this.moveEnforcementCheckers[checkerName](
movePool, moves, abilities, types, counter, species as Species, teamDetails
)
);
);
};
// Pokemon should have moves that benefit their Type/Ability/Weather, as well as moves required by its forme
if (

View File

@ -1048,11 +1048,12 @@ export class RandomGen7Teams extends RandomTeams {
}
counter = this.queryMoves(moves, species.types, abilities, movePool);
const runEnforcementChecker = (checkerName: string) => (
this.moveEnforcementCheckers[checkerName]?.(
const runEnforcementChecker = (checkerName: string) => {
if (!this.moveEnforcementCheckers[checkerName]) return false;
return this.moveEnforcementCheckers[checkerName](
movePool, moves, abilities, types, counter, species as Species, teamDetails
)
);
);
};
// Iterate through the moves again, this time to cull them:
for (const moveid of moves) {

View File

@ -1743,11 +1743,12 @@ export class RandomTeams {
}
counter = this.queryMoves(moves, species.types, abilities, movePool);
const runEnforcementChecker = (checkerName: string) => (
this.moveEnforcementCheckers[checkerName]?.(
const runEnforcementChecker = (checkerName: string) => {
if (!this.moveEnforcementCheckers[checkerName]) return false;
return this.moveEnforcementCheckers[checkerName](
movePool, moves, abilities, types, counter, species as Species, teamDetails
)
);
);
};
// Iterate through the moves again, this time to cull them:
for (const moveid of moves) {

View File

@ -20,7 +20,6 @@ type Worker = cluster.Worker;
const ROOT_DIR = path.resolve(__dirname, '..');
export const processManagers: ProcessManager[] = [];
export const disabled = false;
export function exec(args: string, execOptions?: child_process.ExecOptions): Promise<{stderr: string, stdout: string}>;
export function exec(
@ -112,7 +111,7 @@ export class QueryProcessWrapper<T, U> implements ProcessWrapper {
debug?: string;
constructor(file: string, messageCallback?: (message: string) => any) {
this.process = child_process.fork(file, [], {cwd: ROOT_DIR});
this.process = child_process.fork(file, [], {cwd: ROOT_DIR, execArgv: ['-r', 'ts-node/register']});
this.taskId = 0;
this.pendingTasks = new Map();
this.pendingRelease = null;
@ -212,7 +211,7 @@ export class StreamProcessWrapper implements ProcessWrapper {
messageCallback?: (message: string) => any;
constructor(file: string, messageCallback?: (message: string) => any) {
this.process = child_process.fork(file, [], {cwd: ROOT_DIR});
this.process = child_process.fork(file, [], {cwd: ROOT_DIR, execArgv: ['-r', 'ts-node/register']});
this.messageCallback = messageCallback;
this.process.on('message', (message: string) => {
@ -351,7 +350,7 @@ export class RawProcessWrapper implements ProcessWrapper, StreamWorker {
this.process = cluster.fork(env);
this.workerid = this.process.id;
} else {
this.process = child_process.fork(file, [], {cwd: ROOT_DIR, env}) as any;
this.process = child_process.fork(file, [], {cwd: ROOT_DIR, env, execArgv: ['-r', 'ts-node/register']}) as any;
}
this.process.on('message', (message: string) => {
@ -396,6 +395,7 @@ export class RawProcessWrapper implements ProcessWrapper, StreamWorker {
* string and returns a string or Promise<string>.
*/
export abstract class ProcessManager<T extends ProcessWrapper = ProcessWrapper> {
static disabled = false;
processes: T[] = [];
releasingProcesses: T[] = [];
crashedProcesses: T[] = [];
@ -482,7 +482,7 @@ export abstract class ProcessManager<T extends ProcessWrapper = ProcessWrapper>
}
spawn(count = 1, force?: boolean) {
if (!this.isParentProcess) return;
if (disabled && !force) return;
if (ProcessManager.disabled && !force) return;
const spawnCount = count - this.processes.length;
for (let i = 0; i < spawnCount; i++) {
this.spawnOne(force);
@ -490,7 +490,7 @@ export abstract class ProcessManager<T extends ProcessWrapper = ProcessWrapper>
}
spawnOne(force?: boolean) {
if (!this.isParentProcess) throw new Error('Must use in parent process');
if (disabled && !force) return null;
if (ProcessManager.disabled && !force) return null;
const process = this.createProcess();
process.process.on('disconnect', () => this.releaseCrashed(process));
this.processes.push(process);
@ -702,6 +702,7 @@ export class RawProcessManager extends ProcessManager<RawProcessWrapper> {
exec: this.filename,
// @ts-ignore TODO: update type definition
cwd: ROOT_DIR,
execArgv: ['-r', 'ts-node/register'],
});
}

View File

@ -4,10 +4,11 @@
"version": "0.11.7",
"main": ".sim-dist/index.js",
"dependencies": {
"@swc/core": "^1.2.61",
"@types/better-sqlite3": "^5.4.0",
"probe-image-size": "^5.0.0",
"sockjs": "^0.3.21",
"sucrase": "^3.15.0"
"ts-node": "^10.0.0"
},
"optionalDependencies": {
"better-sqlite3": "^7.1.0",
@ -17,13 +18,14 @@
"nodemailer": "^6.4.6",
"permessage-deflate": "^0.1.7",
"sql-template-strings": "^2.2.2",
"sqlite": "^3.0.6"
"sqlite": "^3.0.6",
"sucrase": "^3.15.0"
},
"secretDependencies": {
"node-oom-heapdump": "^1.2.0"
},
"engines": {
"node": ">=12.0.0"
"node": ">=14.0.0"
},
"scripts": {
"start": "node pokemon-showdown start",
@ -33,10 +35,10 @@
"lint": "eslint . --cache --ext .js,.ts",
"fix": "eslint . --cache --ext .js,.ts --fix",
"full-lint": "eslint . --cache --ext .js,.ts --max-warnings 0",
"pretest": "npm run lint && npm run build",
"pretest": "npm run lint",
"test": "mocha",
"posttest": "npm run tsc",
"full-test": "npm run full-lint && npm run build && npm run tsc && mocha --forbid-only -g \".*\""
"full-test": "npm run full-lint && npm run tsc && mocha --timeout 6000 --forbid-only -g \".*\""
},
"husky": {
"hooks": {

View File

@ -22,13 +22,6 @@ function build() {
built = true;
}
try {
require.resolve('./.sim-dist/dex');
} catch (err) {
if (err.code !== 'MODULE_NOT_FOUND') throw err; // should never happen
build();
}
function readTeam(stream) {
return stream.readLine().then(line => {
if (line.startsWith('[') || line.includes('|')) return line;
@ -36,6 +29,30 @@ function readTeam(stream) {
});
}
function registerTSNode() {
require('ts-node').register({project: './tsconfig.json', files: true, transpileOnly: true, transpiler: 'ts-node/transpilers/swc-experimental'});
}
// enable require()ing TypeScript files
function setupTSNode() {
try {
registerTSNode();
} catch (e) {
console.log(`Installing dependencies...`);
require('child_process').execSync('npm install --production', {stdio: 'inherit'});
registerTSNode();
}
}
function sucraseBuild() {
try {
require.resolve('./.sim-dist/dex');
} catch (err) {
if (err.code !== 'MODULE_NOT_FOUND') throw err; // should never happen
build();
}
}
if (!process.argv[2] || /^[0-9]+$/.test(process.argv[2])) {
// Start the server.
//
@ -43,9 +60,8 @@ if (!process.argv[2] || /^[0-9]+$/.test(process.argv[2])) {
// when launching with this file the same way app.js normally allows, e.g. to
// host on port 9000:
// $ ./pokemon-showdown 9000
if (!built) build();
require('module')._load('./.server-dist', module, true);
setupTSNode();
require('module')._load('./server', module, true);
} else switch (process.argv[2]) {
case 'help':
case 'h':
@ -94,15 +110,13 @@ if (!process.argv[2] || /^[0-9]+$/.test(process.argv[2])) {
case 'start':
{
process.argv.splice(2, 1);
if (process.argv.includes('--skip-build')) {
built = true;
}
if (!built) build();
require('module')._load('./.server-dist', module, true);
setupTSNode();
require('module')._load('./server', module, true);
break;
}
case 'generate-team':
{
sucraseBuild();
var Teams = require('./.sim-dist/teams').Teams;
var seed = process.argv[4] ? process.argv[4].split(',').map(Number) : undefined;
console.log(Teams.pack(Teams.generate(process.argv[3], {seed})));
@ -110,6 +124,7 @@ if (!process.argv[2] || /^[0-9]+$/.test(process.argv[2])) {
break;
case 'validate-team':
{
sucraseBuild();
var Teams = require('./.sim-dist/teams').Teams;
var TeamValidator = require('./.sim-dist/team-validator').TeamValidator;
var validator = TeamValidator.get(process.argv[3]);
@ -134,6 +149,7 @@ if (!process.argv[2] || /^[0-9]+$/.test(process.argv[2])) {
break;
case 'simulate-battle':
{
sucraseBuild();
var BattleTextStream = require('./.sim-dist/battle-stream').BattleTextStream;
var Streams = require('./.lib-dist/streams');
var stdin = Streams.stdin();
@ -185,6 +201,7 @@ if (!process.argv[2] || /^[0-9]+$/.test(process.argv[2])) {
case 'unpack-team':
case 'json-team':
{
sucraseBuild();
var Teams = require('./.sim-dist/teams').Teams;
var Streams = require('./.lib-dist/streams');
var stdin = Streams.stdin();
@ -203,6 +220,7 @@ if (!process.argv[2] || /^[0-9]+$/.test(process.argv[2])) {
break;
case 'pack-team':
{
sucraseBuild();
var Teams = require('./.sim-dist/teams').Teams;
var Streams = require('./.lib-dist/streams');
var stdin = Streams.stdin();
@ -221,6 +239,7 @@ if (!process.argv[2] || /^[0-9]+$/.test(process.argv[2])) {
break;
case 'export-team':
{
sucraseBuild();
var Teams = require('./.sim-dist/teams').Teams;
var Streams = require('./.lib-dist/streams');
var stdin = Streams.stdin();

View File

@ -122,13 +122,6 @@ async function updateserver(context: Chat.CommandContext, codePath: string) {
}
}
async function rebuild(context: Chat.CommandContext, force?: boolean) {
const [, , stderr] = await bash(`node ./build${force ? ' force' : ''}`, context);
if (stderr) {
throw new Chat.ErrorMessage(`Crash while rebuilding: ${stderr}`);
}
}
export const commands: Chat.ChatCommands = {
potd(target, room, user) {
this.canUseConsole();
@ -518,8 +511,6 @@ export const commands: Chat.ChatCommands = {
if (Monitor.updateServerLock) {
return this.errorReply("Wait for /updateserver to finish before hotpatching.");
}
this.sendReply("Rebuilding...");
await rebuild(this);
const lock = Monitor.hotpatchLock;
const hotpatches = [
@ -529,7 +520,7 @@ export const commands: Chat.ChatCommands = {
target = toID(target);
try {
Utils.clearRequireCache({exclude: ['/.lib-dist/process-manager']});
Utils.clearRequireCache({exclude: ['/lib/process-manager']});
if (target === 'all') {
if (lock['all']) {
return this.errorReply(`Hot-patching all has been disabled by ${lock['all'].by} (${lock['all'].reason})`);
@ -563,10 +554,7 @@ export const commands: Chat.ChatCommands = {
const processManagers = ProcessManager.processManagers;
for (const manager of processManagers.slice()) {
if (
manager.filename.startsWith(FS('server/chat-plugins').path) ||
manager.filename.startsWith(FS('.server-dist/chat-plugins').path)
) {
if (manager.filename.startsWith(FS('server/chat-plugins').path)) {
void manager.destroy();
}
}
@ -742,7 +730,7 @@ export const commands: Chat.ChatCommands = {
const processManagers = ProcessManager.processManagers;
for (const manager of processManagers.slice()) {
if (manager.filename.startsWith(FS('.server-dist/modlog').path)) void manager.destroy();
if (manager.filename.startsWith(FS('server/modlog').path)) void manager.destroy();
}
const {mainModlog} = require('../modlog');
@ -775,7 +763,7 @@ export const commands: Chat.ChatCommands = {
`You can disable various hot-patches with /nohotpatch. For more information on this, see /help nohotpatch`,
`/hotpatch chat - reloads the chat-commands and chat-plugins directories`,
`/hotpatch validator - spawn new team validator processes`,
`/hotpatch formats - reload the .sim-dist/dex.js tree, rebuild and rebroad the formats list, and spawn new simulator and team validator processes`,
`/hotpatch formats - reload the sim/dex.ts tree, reload the formats list, and spawn new simulator and team validator processes`,
`/hotpatch dnsbl - reloads IPTools datacenters`,
`/hotpatch punishments - reloads new punishments code`,
`/hotpatch loginserver - reloads new loginserver code`,
@ -1209,8 +1197,6 @@ export const commands: Chat.ChatCommands = {
this.addGlobalModAction(`${user.name} used /updateserver${target === 'public' ? ' public' : ''}`);
}
this.sendReply(`Rebuilding...`);
await rebuild(this);
this.sendReply(success ? `DONE` : `FAILED, old changes restored.`);
Monitor.updateServerLock = false;
@ -1220,13 +1206,8 @@ export const commands: Chat.ChatCommands = {
`/updateserver private - Updates only the server's private code. Requires: console access`,
],
async rebuild(target, room, user, connection) {
this.canUseConsole();
Monitor.updateServerLock = true;
this.sendReply(`Rebuilding...`);
await rebuild(this, true);
Monitor.updateServerLock = false;
this.sendReply(`DONE`);
rebuild() {
this.errorReply("`/rebuild` is no longer necessary; TypeScript files are automatically transpiled as they are loaded.");
},
/*********************************************************

View File

@ -9,7 +9,7 @@
*/
import {FS, Utils} from '../../lib';
import {ScavMods, TwistEvent} from './scavenger-games.js';
import {ScavMods, TwistEvent} from './scavenger-games';
import {ChatHandler} from '../chat';
type GameTypes = 'official' | 'regular' | 'mini' | 'unrated' | 'practice' | 'recycled';

View File

@ -137,7 +137,7 @@ import ProbeModule = require('probe-image-size');
const probe: (url: string) => Promise<{width: number, height: number}> = ProbeModule;
const EMOJI_REGEX = /[\p{Emoji_Modifier_Base}\p{Emoji_Presentation}\uFE0F]/u;
const TRANSLATION_DIRECTORY = `${__dirname}/../.translations-dist`;
const TRANSLATION_DIRECTORY = `${__dirname}/../translations`;
class PatternTester {
// This class sounds like a RegExp
@ -1616,7 +1616,7 @@ export const Chat = new class {
const languageID = Dex.toID(dirname);
const files = await dir.readdir();
for (const filename of files) {
if (!filename.endsWith('.js')) continue;
if (!filename.endsWith('.ts')) continue;
const content: Translations = require(`${TRANSLATION_DIRECTORY}/${dirname}/${filename}`).translations;
@ -1774,11 +1774,8 @@ export const Chat = new class {
loadPlugin(file: string) {
let plugin;
if (file.endsWith('.ts')) {
if (file.endsWith('.ts') || file.endsWith('.js')) {
plugin = require(`./${file.slice(0, -3)}`);
} else if (file.endsWith('.js')) {
// Switch to server/ because we'll be in .server-dist/ after this file is compiled
plugin = require(`../server/${file}`);
} else {
return;
}

View File

@ -24,7 +24,7 @@
*
* It exports the global table `Rooms.rooms`.
*
* Dex - from .sim-dist/dex.ts
* Dex - from sim/dex.ts
*
* Handles getting data about Pokemon, items, etc.
*
@ -48,99 +48,83 @@
// features, so that it doesn't crash old versions of Node.js, so we
// can successfully print the "We require Node.js 8+" message.
// Check for version and dependencies
try {
// I've gotten enough reports by people who don't use the launch
// script that this is worth repeating here
[].flatMap(x => x);
} catch (e) {
throw new Error("We require Node.js version 12 or later; you're using " + process.version);
}
try {
require.resolve('../.sim-dist/index');
const sucraseVersion = require('sucrase').getVersion().split('.');
if (
parseInt(sucraseVersion[0]) < 3 ||
(parseInt(sucraseVersion[0]) === 3 && parseInt(sucraseVersion[1]) < 12)
) {
throw new Error("Sucrase version too old");
}
} catch (e) {
throw new Error("Dependencies are unmet; run `node build` before launching Pokemon Showdown again.");
// Check for version
const nodeVersion = parseInt(process.versions.node);
if (isNaN(nodeVersion) || nodeVersion < 14) {
throw new Error("We require Node.js version 14 or later; you're using " + process.version);
}
import {FS, Repl} from '../lib';
/*********************************************************
* Load configuration
*********************************************************/
import * as ConfigLoader from './config-loader';
global.Config = ConfigLoader.Config;
import {Monitor} from './monitor';
global.Monitor = Monitor;
global.__version = {head: ''};
void Monitor.version().then((hash: any) => {
global.__version.tree = hash;
});
if (Config.watchconfig) {
FS(require.resolve('../config/config')).onModify(() => {
try {
global.Config = ConfigLoader.load(true);
// ensure that battle prefixes configured via the chat plugin are not overwritten
// by battle prefixes manually specified in config.js
Chat.plugins['username-prefixes']?.prefixManager.refreshConfig(true);
Monitor.notice('Reloaded ../config/config.js');
} catch (e) {
Monitor.adminlog("Error reloading ../config/config.js: " + e.stack);
}
});
}
/*********************************************************
* Set up most of our globals
* This is in a function because swc runs `import` before any code,
* and many of our imports require the `Config` global to be set up.
*********************************************************/
function setupGlobals() {
const ConfigLoader = require('./config-loader');
global.Config = ConfigLoader.Config;
import {Dex} from '../sim/dex';
global.Dex = Dex;
global.toID = Dex.toID;
const {Monitor} = require('./monitor');
global.Monitor = Monitor;
global.__version = {head: ''};
void Monitor.version().then((hash: any) => {
global.__version.tree = hash;
});
import {Teams} from '../sim/teams';
global.Teams = Teams;
if (Config.watchconfig) {
FS(require.resolve('../config/config')).onModify(() => {
try {
global.Config = ConfigLoader.load(true);
// ensure that battle prefixes configured via the chat plugin are not overwritten
// by battle prefixes manually specified in config.js
Chat.plugins['username-prefixes']?.prefixManager.refreshConfig(true);
Monitor.notice('Reloaded ../config/config.js');
} catch (e) {
Monitor.adminlog("Error reloading ../config/config.js: " + e.stack);
}
});
}
import {LoginServer} from './loginserver';
global.LoginServer = LoginServer;
const {Dex} = require('../sim/dex');
global.Dex = Dex;
global.toID = Dex.toID;
import {Ladders} from './ladders';
global.Ladders = Ladders;
const {Teams} = require('../sim/teams');
global.Teams = Teams;
import {Chat} from './chat';
global.Chat = Chat;
const {LoginServer} = require('./loginserver');
global.LoginServer = LoginServer;
import {Users} from './users';
global.Users = Users;
const {Ladders} = require('./ladders');
global.Ladders = Ladders;
import {Punishments} from './punishments';
global.Punishments = Punishments;
const {Chat} = require('./chat');
global.Chat = Chat;
import {Rooms} from './rooms';
global.Rooms = Rooms;
// We initialize the global room here because roomlogs.ts needs the Rooms global
Rooms.global = new Rooms.GlobalRoomState();
const {Users} = require('./users');
global.Users = Users;
import * as Verifier from './verifier';
global.Verifier = Verifier;
Verifier.PM.spawn();
const {Punishments} = require('./punishments');
global.Punishments = Punishments;
import {Tournaments} from './tournaments';
global.Tournaments = Tournaments;
const {Rooms} = require('./rooms');
global.Rooms = Rooms;
// We initialize the global room here because roomlogs.ts needs the Rooms global
Rooms.global = new Rooms.GlobalRoomState();
import {IPTools} from './ip-tools';
global.IPTools = IPTools;
void IPTools.loadHostsAndRanges();
const Verifier = require('./verifier');
global.Verifier = Verifier;
Verifier.PM.spawn();
const {Tournaments} = require('./tournaments');
global.Tournaments = Tournaments;
const {IPTools} = require('./ip-tools');
global.IPTools = IPTools;
void IPTools.loadHostsAndRanges();
}
setupGlobals();
if (Config.crashguard) {
// graceful crash - allow current battles to finish before restarting

View File

@ -4,8 +4,8 @@ import {EventMethods} from './dex-conditions';
import {Tags} from '../data/tags';
const DEFAULT_MOD = 'gen8';
const MAIN_FORMATS = `${__dirname}/../.config-dist/formats`;
const CUSTOM_FORMATS = `${__dirname}/../.config-dist/custom-formats`;
const MAIN_FORMATS = `${__dirname}/../config/formats`;
const CUSTOM_FORMATS = `${__dirname}/../config/custom-formats`;
export interface FormatData extends Partial<Format>, EventMethods {
name: string;

View File

@ -39,8 +39,8 @@ import {Format, DexFormats} from './dex-formats';
import {Utils} from '../lib';
const BASE_MOD = 'gen8' as ID;
const DATA_DIR = path.resolve(__dirname, '../.data-dist');
const MODS_DIR = path.resolve(__dirname, '../.data-dist/mods');
const DATA_DIR = path.resolve(__dirname, '../data');
const MODS_DIR = path.resolve(__dirname, '../data/mods');
const dexes: {[mod: string]: ModdedDex} = Object.create(null);

View File

@ -1,6 +1,6 @@
{
"compilerOptions": {
"lib": ["es2019"],
"lib": ["es2020"],
"emitDeclarationOnly": true,
"outDir": "../.sim-dist",
"declaration": true,

View File

@ -3,7 +3,7 @@
const path = require('path');
const fs = require('fs');
const assert = require('./assert');
const Sim = require('./../.sim-dist');
const Sim = require('./../sim');
const Dex = Sim.Dex;
const cache = new Map();

View File

@ -1,7 +1,7 @@
'use strict';
const assert = require('assert').strict;
const Dashycode = require('./../../.lib-dist/dashycode');
const Dashycode = require('./../../lib/dashycode');
describe('Dashycode', function () {
const ascii = Array.from({length: 0x80}, (v, i) => i);

View File

@ -1,5 +1,7 @@
'use strict';
require('ts-node').register({project: './tsconfig.json', files: true, transpileOnly: true, transpiler: 'ts-node/transpilers/swc-experimental'});
const path = require('path');
const fs = require('fs');
@ -35,7 +37,7 @@ config.fakeladder = false;
// Don't log monitor messages to the console (necessary so that chat monitor tests don't clog up stdout)
config.loglevel = 3;
require('./../.lib-dist/process-manager').disabled = true;
require('./../lib/process-manager').ProcessManager.disabled = true;
// stop chatrooms from loading through modifying the require cache
try {
@ -44,11 +46,11 @@ try {
} catch (e) {}
// Don't create a REPL
require('../.lib-dist/repl').Repl.start = noop;
require('../lib/repl').Repl.start = noop;
// Start the server.
// NOTE: This used "server" before when we needed ".server-dist"
require('../.server-dist');
// NOTE: This used "server" before when we needed "server"
require('../server');
LoginServer.disabled = true;
Ladders.disabled = true;

View File

@ -5,7 +5,7 @@
'use strict';
const assert = require('../assert');
const {Utils} = require('../../.lib-dist');
const {Utils} = require('../../lib');
const {testTeam, isValidSet, validateLearnset} = require('./tools');
const ALL_GENS = [1, 2, 3, 4, 5, 6, 7, 8];
@ -65,7 +65,7 @@ describe('Battle Factory and BSS Factory data should be valid (slow)', () => {
for (const filename of ['bss-factory-sets', 'mods/gen7/bss-factory-sets', 'mods/gen7/factory-sets', 'mods/gen6/factory-sets']) {
it(`${filename}.json should contain valid sets (slow)`, function () {
this.timeout(0);
const setsJSON = require(`../../.data-dist/${filename}.json`);
const setsJSON = require(`../../data/${filename}.json`);
const mod = filename.split('/')[1] || 'gen' + Dex.gen;
const genNum = isNaN(mod[3]) ? Dex.gen : mod[3];

View File

@ -5,7 +5,7 @@
const {testSet, testNotBothMoves, testHasSTAB, testAlwaysHasMove} = require('./tools');
const assert = require('../assert');
const {Dex} = require('../../.sim-dist/dex');
const {Dex} = require('../../sim/dex');
describe('[Gen 8] Random Battle', () => {
const options = {format: 'gen8randombattle'};

View File

@ -7,8 +7,8 @@
'use strict';
const assert = require("../assert");
const Teams = require('./../../.sim-dist/teams').Teams;
const TeamValidator = require('../../.sim-dist/team-validator').TeamValidator;
const Teams = require('./../../sim/teams').Teams;
const TeamValidator = require('../../sim/team-validator').TeamValidator;
/**
* Unit test helper for Pokemon sets

View File

@ -6,11 +6,11 @@
'use strict';
const assert = require('assert').strict;
const moderation = require('../../../.server-dist/chat-commands/moderation');
const moderation = require('../../../server/chat-commands/moderation');
const {makeUser} = require('../../users-utils');
describe('room promotions', () => {
describe('room promotions', function () {
before(() => {
Rooms.global.addChatRoom('Promotion Testing');
this.room = Rooms.get('promotiontesting');

View File

@ -8,7 +8,7 @@
const assert = require('assert').strict;
const {makeUser} = require('../../users-utils');
const {Filters} = require('../../../.server-dist/chat-plugins/chat-monitor');
const {Filters} = require('../../../server/chat-plugins/chat-monitor');
describe('Chat monitor', () => {
describe('regex generator', () => {
@ -27,7 +27,7 @@ describe('Chat monitor', () => {
assert.deepEqual(Filters.stripWordBoundaries(regex), /test/iu);
});
describe('evasion regexes', () => {
describe('evasion regexes', function () {
before(() => {
this.evasionRegex = Filters.generateRegex('slur', true);
});
@ -49,15 +49,15 @@ describe('Chat monitor', () => {
});
});
describe('in-room tests', () => {
describe('in-room tests', function () {
before(() => {
this.room = Rooms.get('lobby');
this.user = makeUser("Unit Tester");
this.connection = this.user.connections[0];
this.user.joinRoom(this.room.roomid, this.connection);
Chat.loadPlugins();
this.parse = async function (message) {
Chat.loadPlugins();
const context = new Chat.CommandContext({
message,
room: this.room,

View File

@ -6,7 +6,7 @@
const assert = require('../../assert').strict;
const datasearch = require('../../../.server-dist/chat-plugins/datasearch');
const datasearch = require('../../../server/chat-plugins/datasearch');
describe("Datasearch Plugin", () => {
it('should return pokemon with pivot moves', async () => {

View File

@ -6,7 +6,7 @@
'use strict';
const assert = require('assert').strict;
const hosts = require('../../../.server-dist/chat-plugins/hosts');
const hosts = require('../../../server/chat-plugins/hosts');
describe("Hosts plugin", () => {
it('should properly visualize an empty list of ranges', () => {

View File

@ -6,9 +6,9 @@
'use strict';
const assert = require('assert').strict;
const Repeats = require('../../../.server-dist/chat-plugins/repeats').Repeats;
const Repeats = require('../../../server/chat-plugins/repeats').Repeats;
describe("Repeats plugin", () => {
describe("Repeats plugin", function () {
before(() => {
this.room = Rooms.createChatRoom('repeatstest');
});

View File

@ -6,7 +6,7 @@
'use strict';
const assert = require('assert').strict;
const Responder = require('../../../.server-dist/chat-plugins/responder').AutoResponder;
const Responder = require('../../../server/chat-plugins/responder').AutoResponder;
const room = Rooms.createChatRoom('etheria');
const Help = new Responder(room);

View File

@ -3,7 +3,7 @@
const assert = require('assert').strict;
const {makeUser} = require('../../users-utils');
const trivia = require('../../../.server-dist/chat-plugins/trivia');
const trivia = require('../../../server/chat-plugins/trivia');
const Trivia = trivia.Trivia;
const FirstModeTrivia = trivia.FirstModeTrivia;
const TimerModeTrivia = trivia.TimerModeTrivia;

View File

@ -5,9 +5,9 @@
'use strict';
const assert = require('assert').strict;
const {PrefixManager} = require('../../../.server-dist/chat-plugins/username-prefixes');
const {PrefixManager} = require('../../../server/chat-plugins/username-prefixes');
describe('PrefixManager', () => {
describe('PrefixManager', function () {
beforeEach(() => {
this.prefixManager = new PrefixManager();
Config.forcedprefixes = {privacy: [], modchat: []};

View File

@ -4,7 +4,7 @@
* @author mia-pi-git
*/
'use strict';
const YoutubeInterface = require('../../../.server-dist/chat-plugins/youtube').YoutubeInterface;
const YoutubeInterface = require('../../../server/chat-plugins/youtube').YoutubeInterface;
const assert = require('../../assert');
describe(`Youtube features`, function () {

View File

@ -6,8 +6,8 @@
'use strict';
const assert = require('assert').strict;
const IPTools = require('../../.server-dist/ip-tools').IPTools;
const Utils = require('../../.lib-dist/utils').Utils;
const IPTools = require('../../server/ip-tools').IPTools;
const Utils = require('../../lib/utils').Utils;
describe("IP tools", () => {
it('should resolve 127.0.0.1 to localhost', async () => {

View File

@ -2,7 +2,7 @@
const assert = require('assert').strict;
global.Ladders = require('../../.server-dist/ladders').Ladders;
global.Ladders = require('../../server/ladders').Ladders;
const {makeUser} = require('../users-utils');
describe('Matchmaker', function () {

View File

@ -5,7 +5,8 @@
'use strict';
const modlog = Config.usesqlite ? new (require('../../.server-dist/modlog')).Modlog('/dev/null', ':memory:') : null;
const ModlogConstructor = Config.usesqlite ? (require('../../server/modlog')).Modlog : null;
const modlog = ModlogConstructor ? new ModlogConstructor('/dev/null', ':memory:') : null;
const assert = require('assert').strict;
Config.usesqlitemodlog = true;

View File

@ -7,7 +7,7 @@
*/
const assert = require('../assert');
const {makeUser, makeConnection} = require('../users-utils');
const {Punishments} = require('../../.server-dist/punishments');
const {Punishments} = require('../../server/punishments');
const TEST_PUNISHMENT_DURATION = 1000; // 1 second
@ -64,7 +64,7 @@ describe("Punishments", () => {
});
});
describe('broader, more integrated Punishments tests', () => {
describe('broader, more integrated Punishments tests', function () {
before(() => {
this.room = Rooms.get('lobby');
@ -101,10 +101,10 @@ describe('broader, more integrated Punishments tests', () => {
});
it.skip('should expire on its own', done => {
assert(Punishments.hasRoomPunishType(this.room, 'roombanmeplease', 'ROOMBAN'));
assert(Punishments.hasRoomPunishType(this.room, 'roombanmeplease', 'ROOMBAN'), `should be in effect`);
setTimeout(() => {
assert(!Punishments.hasRoomPunishType(this.room, 'roombanmeplease', 'ROOMBAN'));
assert(!Punishments.hasRoomPunishType(this.room, 'roombanmeplease', 'ROOMBAN'), `should have expired`);
done();
}, TEST_PUNISHMENT_DURATION);
});

View File

@ -39,7 +39,7 @@ describe('Simulator abstraction layer features', function () {
describe('BattleStream', function () {
it('should work (slow)', async function () {
Config.simulatorprocesses = 1;
const PM = require('../../.server-dist/room-battle').PM;
const PM = require('../../server/room-battle').PM;
assert.equal(PM.processes.length, 0);
PM.spawn(1, true);
assert.equal(PM.processes[0].getLoad(), 0);

View File

@ -21,8 +21,8 @@ describe('Rooms features', function () {
describe('BasicRoom', function () {
describe('getGame', function () {
it('should return the game only when the gameids match', function () {
const Hangman = require('../../.server-dist/chat-plugins/hangman').Hangman;
const UNO = require('../../.server-dist/chat-plugins/uno').UNO;
const Hangman = require('../../server/chat-plugins/hangman').Hangman;
const UNO = require('../../server/chat-plugins/uno').UNO;
const room = Rooms.createChatRoom('r/relationshipadvice');
const game = new Hangman(room, makeUser(), 'There\'s a lot of red flags here');
room.game = game;

View File

@ -12,7 +12,7 @@ describe('Dex data', function () {
assert.equal(entry.name, entry.name.trim(), `Pokemon name "${entry.name}" should not start or end with whitespace`);
assert(entry.color, `Pokemon ${entry.name} must have a color.`);
assert(entry.heightm, `Pokemon ${entry.name} must have a heightm.`);
assert(entry.heightm, `Pokemon ${entry.name} must have a height.`);
if (entry.forme) {
// entry is a forme of a base species
@ -146,7 +146,7 @@ describe('Dex data', function () {
}
});
it('should have valid Formats', function () {
it('should have valid Formats (slow)', function () {
for (const format of Dex.formats.all()) {
try {
Dex.formats.getRuleTable(format);

View File

@ -2,7 +2,7 @@
const assert = require('./../assert');
const common = require('./../common');
const Utils = require('../../.lib-dist/utils').Utils;
const Utils = require('../../lib/utils').Utils;
const BASE_TEAM_ORDER = [1, 2, 3, 4, 5, 6];
const SINGLES_TEAMS = {

View File

@ -5,12 +5,12 @@ const assert = require('./../assert');
describe('Mod loader', function () {
it('should work fine in any order', function () {
{
const Dex = require('./../../.sim-dist/dex').Dex;
const Dex = require('./../../sim/dex').Dex;
assert.equal(Dex.mod('gen2').species.getLearnset('nidoking').bubblebeam.join(','), '1M');
assert.equal(Dex.mod('gen2').moves.get('crunch').secondaries[0].boosts.def, undefined);
}
{
const Dex = require('./../../.sim-dist/dex').Dex;
const Dex = require('./../../sim/dex').Dex;
Dex.mod('gen2').species.getLearnset('nidoking');
Dex.mod('gen4').moves.get('crunch');
assert.equal(Dex.mod('gen2').species.getLearnset('nidoking').bubblebeam.join(','), '1M');

View File

@ -1,6 +1,6 @@
'use strict';
const PRNG = require('../../../.sim-dist/prng').PRNG;
const PRNG = require('../../../sim/prng').PRNG;
const assert = require('../../assert');
const testSeed = [1, 2, 3, 4];

View File

@ -2,8 +2,8 @@
const assert = require('./../../assert');
const common = require('./../../common');
const Battle = require('./../../../.sim-dist/battle').Battle;
const State = require('./../../../.sim-dist/state').State;
const Battle = require('./../../../sim/battle').Battle;
const State = require('./../../../sim/state').State;
const TEAMS = [[
{species: 'Mew', ability: 'synchronize', item: 'assaultvest', moves: ['psychic']},

View File

@ -2,7 +2,7 @@
const assert = require('./../../assert');
const common = require('./../../common');
const Sim = require('./../../../.sim-dist');
const Sim = require('./../../../sim');
let battle;

View File

@ -2,7 +2,7 @@
const assert = require('./../../assert');
const common = require('./../../common');
const Sim = require('./../../../.sim-dist');
const Sim = require('./../../../sim');
let battle;

View File

@ -1,8 +1,8 @@
'use strict';
const assert = require('assert').strict;
const TeamValidator = require('../../.sim-dist/team-validator').TeamValidator;
const Teams = require('../../.sim-dist/teams').Teams;
const TeamValidator = require('../../sim/team-validator').TeamValidator;
const Teams = require('../../sim/teams').Teams;
describe('Team Validator', function () {
it('should have valid formats to work with', function () {

View File

@ -2,7 +2,7 @@
const assert = require('assert').strict;
const {ExhaustiveRunner} = require('../../../.sim-dist/tools/exhaustive-runner');
const {ExhaustiveRunner} = require('../../../sim/tools/exhaustive-runner');
describe('ExhaustiveRunner (slow)', async function () {
it('should run successfully', async function () {

View File

@ -2,7 +2,7 @@
const assert = require('assert').strict;
const {MultiRandomRunner} = require('../../../.sim-dist/tools/multi-random-runner');
const {MultiRandomRunner} = require('../../../sim/tools/multi-random-runner');
describe('MultiRandomRunner (slow)', async function () {
it('should run successfully', async function () {

View File

@ -6,7 +6,7 @@
const assert = require('assert').strict;
const converter = require('../../../tools/modlog/converter');
const ml = require('../../../.server-dist/modlog');
const ml = require('../../../server/modlog');
const garfieldCopypasta = [
`[2020-08-24T03:52:00.917Z] (staff) AUTOLOCK: [guest903036] [127.0.0.1]: "Now where could my pipe be?" This... I always come to this, because I was a young man, I'm older now, and I still don't have the secrets, the answers, so this question still rings true, Jon looks up and he thinks: "Now where could my pipe be?", and then it happens, you see it, you see... it's almost like divine intervention, suddenly, it is there, and it overpowers you, a cat is smoking a pipe. It is the mans pipe, it's Jon's pipe, but the cat, this cat, Garfield, is smoking the pipe, and from afar, and from someplace near, but not clear... near but not clear, the man calls out, Jon calls out, he is shocked. "Garfield!" he shouts. Garfield, the cats name. But let's take a step back. Let us examine this from all sides, all perspectives, and when I first came across this comic strip, I was at my fathers house. The newspaper had arrived, and I picked it up for him, and brought it`,

View File

@ -1,7 +1,7 @@
'use strict';
/** @type {typeof import('../lib/streams').ObjectReadWriteStream} */
const ObjectReadWriteStream = require('../.lib-dist/streams').ObjectReadWriteStream;
const ObjectReadWriteStream = require('../lib/streams').ObjectReadWriteStream;
/** @extends {ObjectReadWriteStream<string>} */
class WorkerStream extends ObjectReadWriteStream {

View File

@ -227,12 +227,6 @@ exports.transpile = (doForce, decl) => {
]);
}
if (sucrase('./tools/modlog', './tools/modlog')) {
replace('./tools/modlog/converter.js', [
{regex: /(require\(.*?)(server|lib)/g, replace: `$1.$2-dist`},
]);
}
if (!fs.existsSync('./.data-dist/README.md')) {
const text = '**NOTE**: This folder contains the compiled output of the `data/` directory.\n' +
'You should be editing the `.ts` files there and then running `npm run build` or\n' +

View File

@ -19,6 +19,7 @@
'use strict';
require('ts-node').register();
const child_process = require('child_process');
const path = require('path');
const fs = require('fs');
@ -51,8 +52,6 @@ Chat.plural = function (num, plural = 's', singular = '') {
}
return (num !== 1 ? plural : singular);
};
// Sigh. Yay globals!
global.toID = require('../../.sim-dist/dex').Dex.getId;
const importer = require('./importer.js');

View File

@ -5,7 +5,8 @@
'use strict';
const Dex = require('../../.sim-dist/dex').Dex;
require('ts-node').register();
const Dex = require('../../sim/dex').Dex;
global.toID = Dex.getId;
const smogon = require('smogon');

View File

@ -36,18 +36,13 @@ if (process.argv[2]) {
}
}
const child_process = require('child_process');
const path = require('path');
const shell = cmd => child_process.execSync(cmd, {stdio: 'inherit', cwd: path.resolve(__dirname, '../..')});
shell('node build');
const Dex = require('../../.sim-dist/dex').Dex;
global.toID = require('../../.sim-dist/dex').Dex.getId;
require('ts-node').register({project: './tsconfig.json', files: true, transpileOnly: true, transpiler: 'ts-node/transpilers/swc-experimental'});
const Dex = require('../../sim/dex').Dex;
global.Config = {allowrequestingties: false};
Dex.includeModData();
const {ExhaustiveRunner} = require('../../.sim-dist/tools/exhaustive-runner');
const {MultiRandomRunner} = require('../../.sim-dist/tools/multi-random-runner');
const {ExhaustiveRunner} = require('../../sim/tools/exhaustive-runner');
const {MultiRandomRunner} = require('../../sim/tools/multi-random-runner');
// Tracks whether some promises threw errors that weren't caught so we can log
// and exit with a non-zero status to fail any tests. This "shouldn't happen"

View File

@ -1,15 +1,16 @@
{
"compilerOptions": {
"lib": ["es2019"],
"lib": ["es2020"],
"noEmit": true,
"target": "esnext",
"module": "commonjs",
"target": "es2020",
"module": "CommonJS",
"moduleResolution": "node",
"strict": true,
"allowJs": true,
"checkJs": true,
"incremental": true,
"allowUnreachableCode": false
"allowUnreachableCode": false,
"esModuleInterop": true
},
"types": ["node"],
"exclude": [
@ -27,5 +28,10 @@
"./tools/set-import/*.ts",
"./tools/modlog/*.ts",
"./translations/**/*.ts",
]
],
"ts-node": {
"files": true,
"transpileOnly": true,
"transpiler": "ts-node/transpilers/swc-experimental",
}
}