Greatly Improve Memory Overhead & Fix some typing errors #8
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
good first issue
help wanted
invalid
question
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
pokebedrock/pokebedrock-showdown!8
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "greatly-reduce-memory"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Reduced Memory usage by 100MB!!! will need to improve more but this is great.
Summary by CodeRabbit
Bug Fixes
Refactor
Behavior Change
Chore
📝 Walkthrough
Walkthrough
Replaced generated module maps with an explicit DataRegistry and inline imports; removed build-time generation of dex/random-battles maps; Dex/teams now fallback to base mod when registry entries are missing; runtime Config access switched to guarded global lookups and several Dex static calls moved to instance context.
Changes
sim/dex-module-map.tsDexMods,DexModuleMap) and its long list of requires.sim/dex.tsDataRegistrybuilt from inline imports;loadDataFilenow reads the registry;ModdedDex.mod/forGen/forFormatfall back to base (gen9) when a mod is unregistered;includeModssimplified to construct only the pokebedrock mod.sim/random-battles-module-map.tsRandomBattlesModslist and mappings; replaced withgetRandomBattlesModule(mod: string)that returns only the Gen9 teams module for'gen9'andundefinedotherwise.sim/teams.tsTeams.getGeneratornow assigns the random-battles module to a localrbModule, null-checks it, and throws an explicitErrorif missing before using.default.sim/dex-formats.tsformat.modto a lazy fallback toDEFAULT_MODwith a clarifying comment to avoid startup crashes for legacy gens.tools/build-utils.jstranspile()now callsesbuild.buildSyncdirectly.data/rulesets.tsConfiguses with guarded(global as any).Config?....and host fallbacks for potd and generated URLs; switched someDex.*calls tothis.dex.*; added an explicitconst stat: keyof StatsTableannotation.package.json0.1.13to0.1.14.Sequence Diagram(s)
Estimated code review effort
🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
sim/dex-formats.tsand relates to formats-loading/fallback behavior.Poem
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
✨ Finishing Touches
📝 Generate docstrings
🧪 Generate unit tests (beta)
greatly-reduce-memoryThanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share
Comment
@coderabbitai helpto get the list of available commands and usage tips.Actionable comments posted: 1
🤖 Fix all issues with AI agents
🧹 Nitpick comments (1)
@ -29,3 +1,1 @@'randomroulette': require('../data/random-battles/randomroulette/teams'),'sharedpower': require('../data/random-battles/sharedpower/teams'),}[module];export const getRandomBattlesModule = (mod: string): { default: any } | undefined => {⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
Repository: smell-of-curry/pokebedrock-showdown
Length of output: 777
🏁 Script executed:
Repository: smell-of-curry/pokebedrock-showdown
Length of output: 1413
🏁 Script executed:
Repository: smell-of-curry/pokebedrock-showdown
Length of output: 1120
🏁 Script executed:
Repository: smell-of-curry/pokebedrock-showdown
Length of output: 1207
🏁 Script executed:
Repository: smell-of-curry/pokebedrock-showdown
Length of output: 170
🏁 Script executed:
Repository: smell-of-curry/pokebedrock-showdown
Length of output: 1246
🏁 Script executed:
Repository: smell-of-curry/pokebedrock-showdown
Length of output: 145
🏁 Script executed:
Repository: smell-of-curry/pokebedrock-showdown
Length of output: 3659
Active random battle formats will fail during team generation.
The stub breaks all random battle formats defined in
config/formats.tsexcept the four hardcoded Gen 9 special cases (gen9ssb, gen9babyrandombattle, gen9randombattle with CAP tag, gen9freeforallrandombattle). When any other random battle format attempts to generate teams, it falls through to theelsebranch insim/teams.tsand callsgetRandomBattlesModule(), which returnsundefined, throwing "Random battles module not found for mod: {mod}".The following formats in
config/formats.tswill fail:Either restore the module map for supported generations or remove these format definitions.
🤖 Prompt for AI Agents
✅ Addressed in commit
d79a615Pull request overview
This PR aims to reduce runtime/build memory overhead by removing the auto-generated “module map” approach and replacing it with a smaller, inline registry plus stubs to avoid pulling in large sets of modules (notably mod data and random-battles team generators).
Changes:
sim/dex-module-map.tsusage with inline static imports + a minimalDataRegistryinsim/dex.ts.sim/random-battles-module-map.tsand added an explicit error insim/teams.tswhen a module can’t be found.Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 6 comments.
Show a summary per file
ModdedDexinstances.getRandomBattlesModuleand throws if the module isn’t found.undefined.💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
@ -624,7 +624,9 @@ export class DexFormats {if (format.bestOfDefault === undefined) format.bestOfDefault = false;This change removes the explicit error for formats that reference an unknown/non-registered mod and instead creates a ModdedDex instance. Given the new restricted DataRegistry, this can mask configuration errors and/or cause formats to run with inherited base data rather than the intended mod. Recommend either restoring the validation error (fail fast) or validating that the mod’s Scripts/data are actually loadable before creating the ModdedDex.
@ -41,2 +72,4 @@'../data/mods/pokebedrock/scripts': ModPBScripts,};const BASE_MOD = 'gen9' as ID;DataRegistry only includes base data + pokebedrock, but the repo’s format list references many other mods (gen1–gen8, other OMs). With the current loadDataFile behavior, those mods will silently inherit base (gen9) data/scripts, leading to incorrect generation logic rather than loading their own data or failing fast. Consider either (a) restoring/keeping dynamic loading for mod data files when not present in the registry, or (b) expanding the registry at least to include each supported mod’s Scripts (gen) and any required data files, and keep the “nonexistent mod” validation for unsupported mods.
@ -446,24 +485,19 @@ export class ModdedDex {}loadDataFile currently returns early for any
basePathcontainingmods/when the module isn’t in DataRegistry. This causes modded dexes (e.g. gen1/gen8/etc) to skip loading their own data files and fall back to inheriting the parent’s tables, which will produce incorrect behavior for non-base generations/mods. Suggest falling back torequire(filePath)(or another lazy loader) when DataRegistry doesn’t contain an entry, at least for mods that exist on disk, and reserving the early-return only for truly unsupported mods.includeMods now only registers the pokebedrock mod. Other parts of the codebase (e.g. formats list / validation, mod enumeration) historically assume Dex.includeMods preloads the available mods. If the intent is to support the full set of mods in config/formats.ts, this will leave Dex.dexes incomplete and can lead to unexpected lazy-creation paths. Consider either keeping a lightweight mod listing (e.g. scripts-only) or retaining the previous mod-discovery behavior while still avoiding eager loading of all mod data.
@ -29,3 +1,1 @@'randomroulette': require('../data/random-battles/randomroulette/teams'),'sharedpower': require('../data/random-battles/sharedpower/teams'),}[module];export const getRandomBattlesModule = (mod: string): { default: any } | undefined => {getRandomBattlesModule is currently a stub that always returns undefined, but sim/teams.ts depends on it for random team generation in most formats. As-is, random battles will consistently error at runtime. If the goal is to avoid bundling all generators, consider mapping only the actually-supported mods (e.g. gen9) or returning a lazy require for the requested module instead of undefined.
@ -713,3 +715,4 @@TeamGenerator = rbModule.default;}return new TeamGenerator(format, seed);With sim/random-battles-module-map.ts now stubbed to always return undefined, this code path will throw for most random battle formats (including standard "[Gen 9] Random Battle" where
formatIDdoesn’t match the special cases). Either implement getRandomBattlesModule for the required mods (at least gen9) or add a fallback to the existing dynamic require approach when the static map returns undefined.@ -446,24 +485,19 @@ export class ModdedDex {}Non-pokebedrock mods silently load incorrect gen9 data
Medium Severity
The
loadDataFilesilent fallback was broadened frombasePath.includes('mods/pokebedrock')tobasePath.includes('mods/'), butDataRegistryonly contains base and pokebedrock data. Combined with the lazyModdedDexcreation (which replaced error throws), any non-pokebedrock mod loaded viaDex.mod(),Dex.forFormat(), or custom formats will silently inherit all gen9 base data — wrong type chart, moves, abilities, and mechanics — instead of failing with a clear error. Server code paths likeDex.mod('gen1')indatasearch.tswould return gen9 data.Additional Locations (2)
sim/dex-formats.ts#L626-L630sim/dex.ts#L537-L539Bugbot Autofix prepared fixes for 1 of the 1 bugs found in the latest run.
@ -624,7 +624,9 @@ export class DexFormats {if (format.bestOfDefault === undefined) format.bestOfDefault = false;Removed mod validation causes delayed confusing errors
Medium Severity
The old fail-fast validation (
throw new Error("Format requires nonexistent mod")) was replaced with lazyModdedDexcreation. Sinceconfig/formats.tsstill references gen3–gen8 and blankcanvas mods, theseModdedDexinstances are created during format loading but will crash with a confusingTypeErrorduring data loading —loadDataFilethrows aTypeErrorfor entries missing fromDataRegistry, and the catch block only suppressesMODULE_NOT_FOUND/ENOENTcodes, so theTypeErrorpropagates.Additional Locations (1)
sim/dex.ts#L487-L504@ -29,3 +1,1 @@'randomroulette': require('../data/random-battles/randomroulette/teams'),'sharedpower': require('../data/random-battles/sharedpower/teams'),}[module];export const getRandomBattlesModule = (mod: string): { default: any } | undefined => {Gen 9 Random Battle breaks due to stub module
High Severity
getRandomBattlesModulealways returnsundefined, but[Gen 9] Random Battle(and several other random formats inconfig/formats.ts) fall through to theelsebranch ingetGeneratorthat calls this function. The format IDgen9randombattlematches thegen9randombattlesubstring check on line 706, but fails the+pokemontag:capruleTable condition, so it isn't caught by the special cases and hits the stub. This throwsError: Random battles module not found for mod: gen9when any standard Gen 9 random battle is started.Additional Locations (1)
sim/teams.ts#L709-L714Bugbot Autofix prepared fixes for 2 of the 2 bugs found in the latest run.
Lazy mod creation crashes on missing DataRegistry entries
High Severity
mod()andforFormat()lazily createModdedDexfor unregistered mods, butloadDataFilewill throw aTypeErrorfor any mod not inDataRegistry(except pokebedrock). TheTypeErrorbypasses theMODULE_NOT_FOUNDcatch guard and crashes. This affects any call toforGen()with non-9 values, including thenatdexmodrule atrulesets.ts:141which loops from gen 9 down to gen 7 when validating non-standard items in National Dex formats. The oldforFormat()had a clear "ModdedDex not found" error; the new code fails with a confusing message about file exports.Additional Locations (2)
sim/dex.ts#L487-L494sim/dex.ts#L217-L221Startup crash: non-gen9 formats require unregistered mods
High Severity
includeMods()now only registerspokebedrock, butconfig/formats.tsstill contains ~10 format entries withmod: 'gen8','gen7','gen6','gen5','gen4', and'gen3'. When formats load, the validation checkif (!this.dex.dexes[format.mod])index-formats.tswill throw for each of these since onlybase,gen9, andpokebedrockexist indexes. This crashes the server at startup before any battle can occur.Additional Locations (1)
sim/dex-formats.ts#L628-L631@ -29,3 +1,1 @@'randomroulette': require('../data/random-battles/randomroulette/teams'),'sharedpower': require('../data/random-battles/sharedpower/teams'),}[module];export const getRandomBattlesModule = (mod: string): { default: any } | undefined => {Exported
RandomBattlesModsconstant is never imported anywhereLow Severity
RandomBattlesModsis exported but has zero import sites in the codebase. A grep for its name finds only the definition inrandom-battles-module-map.ts. This is unused dead code that could be removed.Bugbot Autofix prepared fixes for 3 of the 3 bugs found in the latest run.
RandomBattlesModsconstant is never imported anywhereActionable comments posted: 1
🤖 Fix all issues with AI agents
🧹 Nitpick comments (2)
⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
Repository: smell-of-curry/pokebedrock-showdown
Length of output: 3527
Fix return type: teams module has named exports, not a default export.
The teams.ts module uses named exports (
export interface,export class, etc.), notexport default. WithesModuleInterop: truein TypeScript config,require('../data/random-battles/gen9/teams')returns an object with named properties (e.g.,{ TeamData, BattleFactorySpecies, MoveCounter, ... }), not{ default: any }.The return type annotation is incorrect and will cause runtime errors if
.defaultis accessed. Update the return type to match the actual exported shape, or refactor to use ES imports instead ofrequire().🤖 Prompt for AI Agents
Cursor Bugbot has reviewed your changes and found 1 potential issue.
@ -628,1 +627,4 @@// If a format requires a mod that is not registered, fall back to default// This prevents startup crashes when legacy gens are present in formats listif (!this.dex.dexes[format.mod]) format.mod = DEFAULT_MOD;Silent mod fallback makes gen9ssb team generator unreachable
High Severity
The
[Gen 9] Super Staff Bros Ultimateformat inconfig/formats.tsspecifiesmod: 'gen9ssb', butincludeMods()only registers'pokebedrock'. During format loading,this.dex.dexes['gen9ssb']is undefined, soformat.modis silently rewritten to'gen9'. This makes themod === 'gen9ssb'check inteams.tsgetGeneratorunreachable — the SSB-specific random team generator (data/mods/gen9ssb/random-teams) is never loaded, and the format silently falls through to the generic gen9 random team generator instead.Additional Locations (2)
sim/teams.ts#L701-L703sim/dex.ts#L539-L541Actionable comments posted: 1
🧹 Nitpick comments (3)
🤖 Prompt for all review comments with AI agents
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
5d3a465e-b351-4124-a93d-6e7b0c49c6ba📥 Commits
Reviewing files that changed from the base of the PR and between
f2d9258887and45ff0ad3cc.⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json📒 Files selected for processing (3)
package.jsonsim/dex.tssim/teams.ts✅ Files skipped from review due to trivial changes (1)
⚠️ Potential issue | 🟡 Minor
🧩 Analysis chain
🏁 Script executed:
Repository: smell-of-curry/pokebedrock-showdown
Length of output: 2419
Add warning to
forGen()fallback for unsupported gens to prevent silent data mismatches.The code silently returns gen 9 data when
forGen()is called with gen < 9. This affects real validation code:data/rulesets.tsexplicitly callsforGen(5)and iterates throughforGen(gen)with decremented gen values (lines 141, 536, 1696) to fetch historical gen-specific item and move data. Silent fallback causes data mismatch—these validators would incorrectly receive gen 9 data instead of the requested gen's rules.Add a console warning to make the fallback observable:
Suggested change
📝 Committable suggestion
🤖 Prompt for AI Agents