fix: RangeError on Rotate sectors + bundle load crash (viewer 5.13.1, engine 4.10.3)

- Replace all iterator spreads ([...map.values()] etc) with Array.from() across
  engine and viewer: under the TS->babel downlevel chain they compiled to
  __spreadArrays, which reads .length on an iterator and produced
  'RangeError: invalid array length' on 'Sector rotations finished' (the
  reported boardgamers.space crash), plus several latent same-class sites.
- Break the research-tracks.ts -> ../index barrel import cycle (imports
  Event/Expansion from leaf modules now): the cycle left Engine in TDZ and
  the whole bundle failed with 'Cannot access engine_Engine before
  initialization' at module eval under the rebuilt module order.
- Fix stale cache-loader output producing raw vue_1.default accesses for the
  vue webpack external (window.Vue has no .default): 'Cannot read properties
  of undefined (reading extend)' at load. Clean rebuild emits babel interop
  wrappers correctly. vue-global-shim.js added as belt-and-braces doc for the
  external's shape.
- Add autoprefixer as an explicit viewer devDependency (pnpm 11 no longer
  hoists it; the lib build failed on postCSS plugin load).
- Update stale spec type signatures surfaced by the import change (tile
  position as EventSource, loadFaction arity, ChargeRequest literal cast,
  AvailableCommand data narrowing, FederationInfo new fields).

Verified: engine 750 passing / 4 pending; viewer 809 passing; lint + prettier
clean; rebuilt UMD has zero iterator-spread call sites and loads + completes
sector rotation (with and without rotations) in Chromium against the real
bundle with CDN-provided Vue 2.
This commit is contained in:
coyotte508 2026-09-01 08:09:31 +00:00
commit bb39d47586
41 changed files with 253 additions and 96 deletions

74
AGENTS.md Normal file
View file

@ -0,0 +1,74 @@
# AGENTS.md
Monorepo for the Gaia Project engine + viewer hosted on [boardgamers.space](https://boardgamers.space)
(BGS). pnpm workspace: `engine/` (rules engine, plain TS) and `viewer/` (Vue 2.7 UMD lib consumed by
the BGS iframe wrapper).
## Build & test
```bash
pnpm install # pnpm 10+; CI=true to avoid the modules-purge prompt in scripts
cd engine && npm test # mocha + ts-node (TS via tsconfig "module": "commonjs")
cd engine && npm run build # tsc -> dist/ (wrapper.js, index.js)
cd viewer && npm test # vue-cli unit tests (see note on NODE_OPTIONS below)
cd viewer && npm run package # lib build -> dist/package/viewer.umd.js + .min.js + .css
```
- Viewer unit tests: `NODE_OPTIONS="--localstorage-file=/tmp/gaia-test-ls.json --max-old-space-size=12288"`.
- **Always `rm -rf viewer/node_modules/.cache` before `npm run package`** if you changed TS
compiler options or anything that feeds cache-loader. Stale cache-loader output has shipped
broken bundles twice (iterator-spread helper regressing, and a `vue_1.default` interop crash).
When in doubt, nuke the cache — it is the single biggest "works on my rebuild, broke on theirs"
trap in this repo.
- The published UMD keeps `vue` and `bootstrap-vue` **external** — the host page provides them
(`window.Vue`, `window.BootstrapVue`). Never import them in a way that assumes a `.default`
shape; test any bundler/interop change by loading the built `viewer.umd.js` in a real browser
page that loads Vue 2 from a CDN, then exercising the viewer (`window.gaiaViewer.launch`).
- Downlevel safety: do NOT use `[...someMap.values()]` / `[...x.entries()]` /
`[...Array(n).keys()]` iterator spreads in shipped code. Under this toolchain they can
compile to TS's `__spreadArrays` helper, which reads `.length` on iterators → `Array(NaN)` →
`RangeError: invalid array length` at runtime (this broke "Rotate sectors" in 5.13.0).
Use `Array.from(...)` — safe under every downlevel chain.
## Publishing to boardgamers.space
You need an **admin token** (`bgs_admin_…`). Tokens are scoped and can be revoked; ask the BGS
admin for a current one. Do NOT commit tokens anywhere.
The game is registered on the v3 gameinfo service. Base URL: `https://admin.boardgamers.space/api/admin/gameinfo/gaia-project/3`.
All calls take `Authorization: Bearer <token>`.
1. **Engine** — publish the npm tarball (its `version` field becomes the engine version):
```bash
cd engine && npm run build && npm pack # -> gaia-project-engine-<version>.tgz
curl -X POST "$BASE/engine" -H "Authorization: Bearer $TOKEN" \
-F "file=@gaia-project-engine-4.10.3.tgz"
```
2. **Viewer files** — upload the freshly built bundle; js+css(+map) that belong together share a
`bundle` id:
```bash
curl -X POST "$BASE/viewer/file" -H "Authorization: Bearer $TOKEN" \
-F "file=@dist/package/viewer.umd.min.js" -F "type=js" -F "bundle=<new-bundle-id>"
curl -X POST "$BASE/viewer/file" -H "Authorization: Bearer $TOKEN" \
-F "file=@dist/package/viewer.css" -F "type=css" -F "bundle=<new-bundle-id>"
# same pattern for viewer.umd.min.js.map (type=map), same bundle id
```
Get a fresh `<new-bundle-id>` (uuidgen) — every upload gets a unique one, and the doc's
`viewer.url` then points at the new bundle's file URL.
3. **Update the doc** — `GET $BASE` to fetch the current gameinfo doc, update the `viewer.url`
(and `viewer.cssUrl` / engine fields if they changed), then `PUT $BASE` with the whole doc.
The PUT replaces the stored doc, so send everything back, not just the changed fields.
4. Verify on a real BGS game page afterwards (hard-reload; the platform may cache the old
viewer URL per game).
Before publishing: engine tests + viewer tests + `npm run package` all green, and the built
viewer verified in a real browser (see the loading test above).
## Repo conventions
- `master` is the release branch; feature work lands via PRs. Keep CI green: prettier, engine
eslint (warnings tolerated, errors not), viewer eslint, both test suites.
- lint-staged runs prettier on commit; if its import ordering fights a hand-made change,
commit with `--no-verify` after confirming `npm run prettier` is clean.
- Version bumps: `engine/package.json` and `viewer/package.json` independently, patch-level
for fixes. The engine tarball version is what BGS games record per game.

View file

@ -1,6 +1,6 @@
{
"name": "@gaia-project/engine",
"version": "4.10.2",
"version": "4.10.3",
"description": "Javascript engine for project gaia",
"main": "dist/index.js",
"types": "index.ts",

View file

@ -295,23 +295,25 @@ export function projectCanonicalState(engine: Engine): CanonicalState {
})),
}
: null,
hexes: [...engine.map.grid.values()].sort(compareHexes).map((hex) => ({
id: hex.toString(),
q: hex.q,
r: hex.r,
s: hex.s,
planet: hex.data.planet,
sector: hex.data.sector,
building: hex.data.building ?? null,
player: normalizeNullableNumber(hex.data.player),
federations: sortNumbers(hex.data.federations ?? []),
tradeTokens: sortNumbers(hex.data.tradeTokens ?? []),
customPosts: sortNumbers(hex.data.customPosts ?? []),
additionalMine: normalizeNullableNumber(hex.data.additionalMine),
powerRing: normalizeNullableNumber(hex.data.powerRing),
spaceship: hex.data.spaceship ?? null,
sectorCenter: hex.data.sectorCenter ? projectPoint(hex.data.sectorCenter) : null,
})),
hexes: Array.from(engine.map.grid.values())
.sort(compareHexes)
.map((hex) => ({
id: hex.toString(),
q: hex.q,
r: hex.r,
s: hex.s,
planet: hex.data.planet,
sector: hex.data.sector,
building: hex.data.building ?? null,
player: normalizeNullableNumber(hex.data.player),
federations: sortNumbers(hex.data.federations ?? []),
tradeTokens: sortNumbers(hex.data.tradeTokens ?? []),
customPosts: sortNumbers(hex.data.customPosts ?? []),
additionalMine: normalizeNullableNumber(hex.data.additionalMine),
powerRing: normalizeNullableNumber(hex.data.powerRing),
spaceship: hex.data.spaceship ?? null,
sectorCenter: hex.data.sectorCenter ? projectPoint(hex.data.sectorCenter) : null,
})),
},
players: engine.players.map((player) => ({
player: player.player,

View file

@ -84,7 +84,7 @@ function buildChallengeManifest() {
const advancedTechPositions = AdvTechTilePos.values(engine.expansions);
const ships = shipsInPlay(engine.expansions, engine.players.length);
const mapHexes = [...engine.map.grid.values()]
const mapHexes = Array.from(engine.map.grid.values())
.map((hex) => ({
id: hex.toString(),
q: hex.q,

View file

@ -30,7 +30,7 @@ export class GridTopology<HexType extends Hex<any>> {
/** Integer-indexed view of the grid, for algorithms that want to avoid Map/Set lookups in hot loops */
index(): GridIndex<HexType> {
if (this._index === undefined) {
const hexList = [...this.grid.values()];
const hexList = Array.from(this.grid.values());
const indexOf = new Map(hexList.map((hex, i) => [hex, i] as [HexType, number]));
const neighbourIndices = hexList.map((hex) => this.neighbours(hex).map((neighbour) => indexOf.get(neighbour)));
this._index = { hexList, indexOf, neighbourIndices };

View file

@ -73,5 +73,5 @@ export default function minimumPathLength<T>(groups: Array<Hex<T>[]>): number {
}
} while (modified);
return Math.max(...flatten([...shortestPaths.values()].map((v) => [...v.values()])));
return Math.max(...flatten(Array.from(shortestPaths.values()).map((v) => Array.from(v.values()))));
}

View file

@ -61,7 +61,7 @@ function spanningTreeWithHeuristic<T>(
if (destGroups.length > 2) {
// We pick all the hexes that are in the middle of the federation buildings, and try to create a network from them
startingPoints.push(
...[...grid.values()].filter(
...Array.from(grid.values()).filter(
(hex) =>
!destHexesSet.has(hex) &&
inRange(hex.q, minQ + 1, maxQ) &&

View file

@ -219,7 +219,7 @@ describe("legacy engine", () => {
terrans build m -4x2
`);
expect(() => new Engine(moves, { auction: false }, "4.6.10")).to.not.throw();
expect(() => new Engine(moves, { auction: undefined as any }, "4.6.10")).to.not.throw();
});
it("should be able to continue a legacy non-auction game", () => {

View file

@ -65,7 +65,7 @@ describe("AutoCharge", () => {
describe("askOrDeclineForPassedPlayer", () => {
describe("when passed & no remaining charges after income", () => {
const baseRequest: ChargeRequest = {
const baseRequest = {
playerHasPassed: true,
autoCharge: 3,
incomeSelection: {
@ -73,7 +73,7 @@ describe("AutoCharge", () => {
} as IncomeSelection,
minCharge: 1,
isLastRound: false,
} as ChargeRequest;
} as unknown as ChargeRequest;
it("should not decline if taklons can gain a power token", () => {
expect(

View file

@ -2,6 +2,7 @@ import { expect } from "chai";
import { Expansion, PlayerEnum } from "../index";
import { possibleBoardActions, possibleFreeActions } from "./available/actions";
import { choosableFactions } from "./available/setup";
import { AvailableCommand } from "./available/types";
import Engine, { AuctionVariant } from "./engine";
import { BoardAction, Faction } from "./enums";
import Player from "./player";
@ -99,7 +100,10 @@ describe("Available commands", () => {
const player = { data: d } as Player;
function possible() {
return possibleBoardActions(actions, player, false)[0].data.poweracts.map((a) => a.name);
const cmd = possibleBoardActions(actions, player, false)[0] as AvailableCommand & {
data: { poweracts: { name: string }[] };
};
return cmd.data.poweracts.map((a) => a.name);
}
expect(possible()).to.include("power1");
@ -117,14 +121,22 @@ describe("Available commands", () => {
BoardAction.values(Expansion.None).forEach((pos: BoardAction) => {
baseActions[pos] = null;
});
const baseNames = possibleBoardActions(baseActions, player, false)[0].data.poweracts.map((a) => a.name);
const baseNames = (
possibleBoardActions(baseActions, player, false)[0] as AvailableCommand & {
data: { poweracts: { name: string }[] };
}
).data.poweracts.map((a) => a.name);
expect(baseNames).to.include.members(["qic1", "qic3", "power1"]);
const lostFleetActions = {};
BoardAction.values(Expansion.LostFleet).forEach((pos: BoardAction) => {
lostFleetActions[pos] = null;
});
const lostFleetNames = possibleBoardActions(lostFleetActions, player, false)[0].data.poweracts.map((a) => a.name);
const lostFleetNames = (
possibleBoardActions(lostFleetActions, player, false)[0] as AvailableCommand & {
data: { poweracts: { name: string }[] };
}
).data.poweracts.map((a) => a.name);
expect(lostFleetNames).to.not.include.members(["qic1", "qic2", "qic3"]);
expect(lostFleetNames).to.include("power1");
});

View file

@ -4,6 +4,7 @@ import { qicForDistance, terraformingCost } from "../cost";
import Engine from "../engine";
import {
AdvTechTile,
AdvTechTilePos,
Building,
Command,
Faction,
@ -211,7 +212,7 @@ describe("possibleFederationTokenBuildMine", () => {
const player = engine.player(PlayerEnum.Player1);
if (withTerra) {
player.loadEvents(techTileEventWithSource(AdvTechTile.Terra, AdvTechTile.Terra));
player.loadEvents(techTileEventWithSource(AdvTechTile.Terra, AdvTechTilePos.Intelligence));
}
const target = cheapestHexNeedingRangeAndTerraforming(engine, PlayerEnum.Player1, Faction.Terrans);

View file

@ -1,6 +1,7 @@
import { expect } from "chai";
import { BoardAction, Booster, Building, Player } from "..";
import { version } from "../package.json";
import { AvailableCommand } from "./available/types";
import Engine, { AuctionVariant, createMoveToShow } from "./engine";
import {
AdvTechTile,
@ -180,7 +181,9 @@ describe("Engine", () => {
engine.move("p2 faction terrans");
while (engine.phase === Phase.SetupBuilding) {
const command = engine.generateAvailableCommandsIfNeeded().find((c) => c.name === Command.Build) as any;
const command = engine
.generateAvailableCommandsIfNeeded()
.find((c): c is AvailableCommand<Command.Build> => c.name === Command.Build) as any;
const building = command.data.buildings[0];
engine.move(`p${engine.playerToMove + 1} build ${building.building} ${building.coordinates}`);
}

View file

@ -236,7 +236,7 @@ export function createMoveToShow(move: string, player: Player, map: SpaceMap, ex
const formerPI =
player.faction === Faction.Ambas && move.includes(Command.PISwap)
? [...map.grid.values()].find((h) => h.buildingOf(player.player) === Building.PlanetaryInstitute)
? Array.from(map.grid.values()).find((h) => h.buildingOf(player.player) === Building.PlanetaryInstitute)
: null;
data.on("move-tokens", listener);

View file

@ -15,7 +15,7 @@ export function maxExplorationShuttles(nbPlayers: number): number {
}
export function spaceshipHex(map: SpaceMap, ship: Spaceship): GaiaHex | undefined {
return [...map.grid.values()].find((hex) => hex.data.spaceship === ship);
return Array.from(map.grid.values()).find((hex) => hex.data.spaceship === ship);
}
export function nextFreeExplorationSlot(players: Player[], ship: Spaceship): number | null {

View file

@ -10,7 +10,7 @@ describe("Bescods", () => {
const player = new Player(Expansion.None, PlayerEnum.Player1);
player.faction = Faction.Bescods;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
expect(player.data.knowledge).to.equal(3);
});

View file

@ -1,7 +1,7 @@
import { expect } from "chai";
import { BrainstoneWarning } from "../available/types";
import { AvailableCommand, BrainstoneWarning } from "../available/types";
import Engine from "../engine";
import { Player, PowerArea } from "../enums";
import { Command, Player, PowerArea } from "../enums";
describe("Taklons", () => {
it("should allow charge with +t freeIncome", () => {
@ -68,7 +68,12 @@ describe("Taklons", () => {
`);
it("should warn when wasting power charges", () => {
expect(new Engine([...moves, "taklons spend 2pw for 2c"]).availableCommands[0].data).to.deep.equal({
expect(
(
new Engine([...moves, "taklons spend 2pw for 2c"])
.availableCommands[0] as AvailableCommand<Command.BrainStone>
).data
).to.deep.equal({
choices: [
{
area: "area1",
@ -80,7 +85,7 @@ describe("Taklons", () => {
it("should ask about brainstone without warning", () => {
const e = new Engine([...moves, "taklons burn 3. spend 3pw for 3c"]);
expect(e.player(Player.Player1).data.brainstone).to.equal(PowerArea.Area3);
expect(e.availableCommands[0].data).to.deep.equal({
expect((e.availableCommands[0] as AvailableCommand<Command.BrainStone>).data).to.deep.equal({
choices: [
{ area: PowerArea.Area1, warning: undefined },
{ area: PowerArea.Area3, warning: undefined },

View file

@ -354,7 +354,7 @@ export const lfMapComposition: Oracle = {
}
// The board is generated once at init and never changes — checking every line is redundant
// but cheap; simpler and safer than trying to detect "setup just finished".
const ships = [...ctx.engine.map.grid.values()]
const ships = Array.from(ctx.engine.map.grid.values())
.map((hex) => hex.data.spaceship)
.filter((s): s is Spaceship => s !== undefined)
.sort();

View file

@ -395,7 +395,7 @@ export default class SpaceMap {
if (classifySectorId(coords) !== LostFleetSectorType.Space) {
// Interspace/Deep Space hexes ("IS3", "DS14_0") aren't part of a numbered/lettered sector and
// have no center-relative suffix; their toString() is already a unique address, so scan for it.
const hex = [...this.grid.values()].find((h) => h.toString() === coords);
const hex = Array.from(this.grid.values()).find((h) => h.toString() === coords);
assert(hex, `Can't find hex for Lost Fleet coordinate ${coords}`);
return { q: hex.q, r: hex.r, s: hex.s };
}

View file

@ -635,7 +635,7 @@ describe("Lost Fleet spaceship board actions", () => {
const engine = createLostFleetRoundMoveEngine(3);
const player = engine.player(PlayerEnum.Player1);
player.data.explorationShips[Spaceship.TFMars] = 1;
player.loadEvents(techTileEventWithSource(AdvTechTile.QAction, AdvTechTile.QAction));
player.loadEvents(techTileEventWithSource(AdvTechTile.QAction, AdvTechTilePos.Intelligence));
const command = availableSpaceshipActionCommand(engine, PlayerEnum.Player1);
const action = command.data.actions.find((a) => a.ship === Spaceship.TFMars && a.type === "qic");

View file

@ -26,7 +26,7 @@ describe("Player", () => {
const player = new Player(Expansion.None, PlayerEnum.Player1);
player.faction = Faction.Terrans;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
const { cost } = player.canBuild(null, null, Planet.Terra, Building.Mine, false, false, {
addedCost: [new Reward(1, Resource.Qic)],
@ -40,7 +40,7 @@ describe("Player", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.Terrans;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
player.data.ores = 20; // enough to afford the 3 terraform steps on top of the base mine cost
const { cost } = player.canBuild(null, null, Planet.Protoplanet, Building.Mine, false, false);
@ -53,7 +53,7 @@ describe("Player", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.Terrans;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
player.data.gaiaformers = 0; // every faction starts with 1 via GaiaProject research level 1
expect(player.canBuild(null, null, Planet.Asteroid, Building.Mine, false, false)).to.equal(null);
@ -63,7 +63,7 @@ describe("Player", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.Terrans;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
const { cost } = player.canBuild(null, null, Planet.Asteroid, Building.Mine, false, false);
@ -75,7 +75,7 @@ describe("Player", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.Darkanians;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
player.data.ores = 20; // enough to afford the terraform step on top of the base mine cost
const { cost } = player.canBuild(null, null, Planet.Terra, Building.Mine, false, false);
@ -89,7 +89,7 @@ describe("Player", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.SpaceGiants;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
player.data.ores = 20; // enough to afford both terraform steps on top of the base mine cost
const { cost } = player.canBuild(null, null, Planet.Terra, Building.Mine, false, false);
@ -104,7 +104,7 @@ describe("Player", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = faction;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
player.data.qics = 20; // enough to afford the 2 QIC surcharge
const { cost } = player.canBuild(null, null, Planet.Gaia, Building.Mine, false, false);
@ -118,7 +118,7 @@ describe("Player", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.Terrans;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
const { cost } = player.canBuild(null, null, Planet.Gaia, Building.Mine, false, false);
@ -133,7 +133,7 @@ describe("Player", () => {
const hex = new GaiaHex(0, 0, { sector: "s1", planet: Planet.Protoplanet });
player.faction = faction;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
player.data.ores = 20;
const { cost } = player.canBuild(map, hex, Planet.Protoplanet, Building.Mine, false, false);
@ -151,7 +151,7 @@ describe("Player", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.Terrans;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
const { cost } = player.canBuild(map, hex, Planet.Asteroid, Building.Mine, false, false);
player.build(Building.Mine, hex, cost, map);
@ -173,7 +173,7 @@ describe("Player", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.Terrans;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
const { cost } = player.canBuild(map, asteroid, Planet.Asteroid, Building.Mine, false, false);
player.build(Building.Mine, asteroid, cost, map);
@ -219,7 +219,7 @@ describe("Player", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.Darkanians;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
const baselineCredits = player.data.credits;
const baselineKnowledge = player.data.knowledge;
@ -418,7 +418,7 @@ describe("Player", () => {
it("should grant 8 VP and 8 credits for the Credit token", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.Terrans;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
const beforeVp = player.data.victoryPoints;
const beforeCredits = player.data.credits;
@ -431,7 +431,7 @@ describe("Player", () => {
it("should grant 4 VP and 4 knowledge for the Knowledge token", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.Terrans;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
const beforeVp = player.data.victoryPoints;
const beforeKnowledge = player.data.knowledge;
@ -444,7 +444,7 @@ describe("Player", () => {
it("should grant 4 VP, 2 ore, and 1 QIC for the OreQic token", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.Terrans;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
const beforeVp = player.data.victoryPoints;
const beforeOres = player.data.ores;
const beforeQic = player.data.qics;
@ -459,7 +459,7 @@ describe("Player", () => {
it("should grant 12 VP for the Vp token", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.Terrans;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
const beforeVp = player.data.victoryPoints;
player.gainSpaceshipFederationToken(SpaceshipFederation.Vp);
@ -470,7 +470,7 @@ describe("Player", () => {
it("should grant 7 VP and 2 power tokens placed directly into Area III for the PowerTokens token", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.Terrans;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
const beforeVp = player.data.victoryPoints;
const beforeArea3 = player.data.power.area3;
@ -483,7 +483,7 @@ describe("Player", () => {
it("should grant a Tech tile pick (TechTile reward) for the Tech token", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.Terrans;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
let gained = 0;
player.data.on(`gain-${Resource.TechTile}`, (count: number) => {
@ -499,7 +499,7 @@ describe("Player", () => {
for (const federation of [SpaceshipFederation.Range, SpaceshipFederation.Terraform]) {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.Terrans;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
const beforeVp = player.data.victoryPoints;
const beforeCredits = player.data.credits;
const beforeOres = player.data.ores;
@ -547,7 +547,7 @@ describe("Player", () => {
const player = new Player();
player.faction = Faction.Lantids;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
const hex = new GaiaHex(0, 0, {
sector: "s1",
planet: Planet.Lost,
@ -590,6 +590,8 @@ describe("Player", () => {
hexes: [],
planets: 0,
satellites: 5,
newSatellites: 0,
powerValue: 0,
},
],
};
@ -609,6 +611,8 @@ describe("Player", () => {
hexes: [lostPlanet],
planets: 0,
satellites: 5,
newSatellites: 0,
powerValue: 0,
},
],
};
@ -621,7 +625,7 @@ describe("Player", () => {
it("excludes Booster-granted special actions (already shown on the booster's own tile)", () => {
const player = new Player(Expansion.None, PlayerEnum.Player1);
player.faction = Faction.Terrans;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
player.loadEvents(boosterEvents(Booster.Booster4));
expect(player.actions.map((a) => a.rewards)).to.include("step");
@ -631,7 +635,7 @@ describe("Player", () => {
it("keeps faction-innate special actions with no tile of their own (e.g. Space Giants')", () => {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = Faction.SpaceGiants;
player.loadFaction(null);
player.loadFaction(null, Expansion.None);
expect(player.actions.map((a) => a.rewards)).to.include("2step");
expect(player.actionsWithoutTile.map((a) => a.rewards)).to.include("2step");

View file

@ -1236,7 +1236,7 @@ export default class Player extends EventEmitter {
const hexes = this.data.occupied.filter((hex) => !excluded.has(hex));
const buildingGroups = this.buildingGroups(hexes, map);
const buildingGroupsList = uniq([...buildingGroups.values()]);
const buildingGroupsList = uniq(Array.from(buildingGroups.values()));
const values = buildingGroupsList.map((buildings) =>
sum(buildings.map((node) => this.buildingValue(node, { federation: true })))
);
@ -1257,7 +1257,7 @@ export default class Player extends EventEmitter {
const federations: GaiaHex[][] = [];
const occupiedSet = new Set(this.data.occupied);
const mapTopology = topologyOf(map.grid);
const baseHexes = [...map.grid.values()].filter((hex) => !excluded.has(hex));
const baseHexes = Array.from(map.grid.values()).filter((hex) => !excluded.has(hex));
const buildWorkingGrid = (hexes: GaiaHex[]) =>
new Grid<Hex<{ cost: number }>>(
...hexes.map(
@ -1455,7 +1455,7 @@ export default class Player extends EventEmitter {
// Check if federation can be built with fewer satellites
if (!flexible) {
const allHexes = [...map.grid.values()].filter((hex) => !excluded.has(hex));
const allHexes = Array.from(map.grid.values()).filter((hex) => !excluded.has(hex));
const occupiedSet = new Set(this.data.occupied);
const workingGrid = new Grid<Hex<{ cost: number }>>(

View file

@ -1,4 +1,5 @@
import { expect } from "chai";
import { AvailableCommand } from "./available/types";
import Engine, { AuctionVariant, EngineOptions } from "./engine";
import { Command, Faction, Phase, Player as PlayerEnum } from "./enums";
@ -285,7 +286,9 @@ describe("Preference Split Auction variant", () => {
const partial = engineFor(picks + "p1 preferenceBid itars 20 taklons 12 xenos 6 terrans 2");
partial.generateAvailableCommandsIfNeeded();
const command = partial.availableCommands.find((c) => c.name === Command.PreferenceBid);
const command = partial.availableCommands.find(
(c): c is AvailableCommand<Command.PreferenceBid> => c.name === Command.PreferenceBid
);
expect(command.player).to.equal(PlayerEnum.Player2);
expect(command.data.budget).to.equal(40);
expect(command.data.factions).to.deep.equal([Faction.Itars, Faction.Taklons, Faction.Xenos, Faction.Terrans]);

View file

@ -1,5 +1,5 @@
import { Event, Expansion } from "../index";
import { hasExpansion, isResourceUsed, LostFleetEconomySide, ResearchField } from "./enums";
import { Expansion, hasExpansion, isResourceUsed, LostFleetEconomySide, ResearchField } from "./enums";
import Event from "./events";
const researchTracks: { [key in ResearchField]: string[][] } = {
[ResearchField.Terraforming]: [[], ["2o"], ["d"], ["d", "3pw"], ["2o"], []],

View file

@ -1,5 +1,6 @@
import { expect } from "chai";
import { MAX_SILENT_BID } from "./algorithms/silent-auction";
import { AvailableCommand } from "./available/types";
import Engine, { AuctionVariant } from "./engine";
import { Command, Faction, Phase } from "./enums";
@ -141,7 +142,9 @@ describe("Silent Auction variant", () => {
const engine = silent();
engine.generateAvailableCommandsIfNeeded();
const data = engine.availableCommands.find((c) => c.name === Command.SilentBid)?.data as any;
const data = engine.availableCommands.find(
(c): c is AvailableCommand<Command.SilentBid> => c.name === Command.SilentBid
)?.data as any;
expect(data.factions).to.deep.equal([Faction.Itars, Faction.Xenos, Faction.Taklons]);
expect(data.maxBid).to.equal(MAX_SILENT_BID);
});

View file

@ -1,6 +1,6 @@
import { expect } from "chai";
import "mocha";
import { AdvTechTile, Building, Expansion, Faction, Planet, Player as PlayerEnum } from "../enums";
import { AdvTechTile, AdvTechTilePos, Building, Expansion, Faction, Planet, Player as PlayerEnum } from "../enums";
import { GaiaHex } from "../gaia-hex";
import { classifySectorId, LostFleetSectorType } from "../lost-fleet-map";
import SpaceMap from "../map";
@ -10,7 +10,7 @@ import { techTileEventWithSource } from "./techs";
function newPlayer(faction = Faction.Terrans): Player {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = faction;
player.loadFaction(null);
player.loadFaction(null, Expansion.LostFleet);
return player;
}
@ -42,7 +42,7 @@ describe("Lost Fleet Advanced Tech tiles (RULES_CLARIFICATIONS.md §G2)", () =>
player.build(Building.Mine, hexes[0], [], map);
player.build(Building.Mine, hexes[1], [], map);
player.loadEvents(techTileEventWithSource(AdvTechTile.AsteroidPass, AdvTechTile.AsteroidPass));
player.loadEvents(techTileEventWithSource(AdvTechTile.AsteroidPass, AdvTechTilePos.Intelligence));
const beforeVp = player.data.victoryPoints;
player.receivePassIncome();
@ -61,7 +61,7 @@ describe("Lost Fleet Advanced Tech tiles (RULES_CLARIFICATIONS.md §G2)", () =>
player.build(Building.Academy2, hexes[2], [], map);
const beforeVp = player.data.victoryPoints;
player.loadEvents(techTileEventWithSource(AdvTechTile.Big, AdvTechTile.Big));
player.loadEvents(techTileEventWithSource(AdvTechTile.Big, AdvTechTilePos.Intelligence));
expect(player.data.victoryPoints).to.equal(beforeVp + 18);
});
@ -81,7 +81,7 @@ describe("Lost Fleet Advanced Tech tiles (RULES_CLARIFICATIONS.md §G2)", () =>
player.build(Building.Mine, sectorB[0], [], map);
const beforeVp = player.data.victoryPoints;
player.loadEvents(techTileEventWithSource(AdvTechTile.Deep, AdvTechTile.Deep));
player.loadEvents(techTileEventWithSource(AdvTechTile.Deep, AdvTechTilePos.Intelligence));
// 4 VP * 2 distinct sectors colonized (3 hexes total, but only 2 sectors).
expect(player.data.victoryPoints).to.equal(beforeVp + 8);
@ -100,7 +100,7 @@ describe("Lost Fleet Advanced Tech tiles (RULES_CLARIFICATIONS.md §G2)", () =>
player.build(Building.Mine, sectorA[0], [], map);
player.build(Building.Mine, sectorB[0], [], map);
player.loadEvents(techTileEventWithSource(AdvTechTile.DeepPass, AdvTechTile.DeepPass));
player.loadEvents(techTileEventWithSource(AdvTechTile.DeepPass, AdvTechTilePos.Intelligence));
const beforeVp = player.data.victoryPoints;
player.receivePassIncome();
@ -110,7 +110,7 @@ describe("Lost Fleet Advanced Tech tiles (RULES_CLARIFICATIONS.md §G2)", () =>
it("terra: grants 2 VP per terraforming step, scaling with multi-step colonizations", () => {
const player = newPlayer();
player.loadEvents(techTileEventWithSource(AdvTechTile.Terra, AdvTechTile.Terra));
player.loadEvents(techTileEventWithSource(AdvTechTile.Terra, AdvTechTilePos.Intelligence));
const beforeVp = player.data.victoryPoints;
player.receiveTerraformingStepTriggerIncome(3); // e.g. colonizing a Protoplanet (3 steps)

View file

@ -10,7 +10,7 @@ import { roundScoringEvents } from "./scoring";
function newPlayer(faction = Faction.Terrans): Player {
const player = new Player(Expansion.LostFleet, PlayerEnum.Player1);
player.faction = faction;
player.loadFaction(null);
player.loadFaction(null, Expansion.LostFleet);
return player;
}

3
pnpm-lock.yaml generated
View file

@ -178,6 +178,9 @@ importers:
'@vue/test-utils':
specifier: ^1.1.3
version: 1.3.6(vue-template-compiler@2.7.16)(vue@2.7.16)
autoprefixer:
specifier: 9.8.8
version: 9.8.8
chai:
specifier: ^4.3.0
version: 4.5.0

View file

@ -1,6 +1,6 @@
{
"name": "@gaia-project/viewer",
"version": "5.13.0",
"version": "5.13.1",
"description": "Functions to visualize the map and boards for gaia project inside html canvas",
"contributors": [
"coyotte508",
@ -63,6 +63,7 @@
"@vue/eslint-config-standard": "^5.1.2",
"@vue/eslint-config-typescript": "^5.0.2",
"@vue/test-utils": "^1.1.3",
"autoprefixer": "9.8.8",
"chai": "^4.3.0",
"chart.js": "^3.0.1",
"eslint": "^6.7.2",

View file

@ -304,7 +304,7 @@ export default class BuildingGroup extends Vue {
if (i < this.gaia) {
return PlanetEnum.Volcanic;
}
const onGaia = [...this.engine.map.grid.values()].filter(
const onGaia = Array.from(this.engine.map.grid.values()).filter(
(h) => h.buildingOf(this.player.player) === BuildingEnum.GaiaFormer && h.data.planet == PlanetEnum.Gaia
).length;
return i < onGaia + this.gaia ? PlanetEnum.Gaia : PlanetEnum.Transdim;

View file

@ -361,7 +361,7 @@ export default class SpaceMap extends Vue {
}
get looseHexes(): GaiaHex[] {
return [...this.map.grid.values()]
return Array.from(this.map.grid.values())
.filter((hex) => classifySectorId(hex.data.sector) !== LostFleetSectorType.Space)
.sort((a, b) => a.q - b.q || a.r - b.r || a.s - b.s);
}
@ -386,7 +386,7 @@ export default class SpaceMap extends Vue {
}
}
}
return [...groups.entries()].map(([id, hexes]) => {
return Array.from(groups.entries()).map(([id, hexes]) => {
const centers = hexes.map((h) => hexCenter(h));
const x = (centers.reduce((sum, c) => sum + c.x, 0) / centers.length) * HEX_SPREAD;
const y = (centers.reduce((sum, c) => sum + c.y, 0) / centers.length) * HEX_SPREAD;
@ -644,7 +644,7 @@ export default class SpaceMap extends Vue {
get colorLegend(): { class: string; text: string }[] {
if (this.mapModes.find((m) => m.type === MapModeType.leech || m.type == MapModeType.federations)) {
return [...Array(5).keys()].map((i) => ({ class: `power${i + 1}`, text: String(i + 1) }));
return Array.from({ length: 5 }, (_, i) => ({ class: `power${i + 1}`, text: String(i + 1) }));
}
return [];
}

View file

@ -78,7 +78,7 @@ export function researchEventsWithCounters(engine: Engine, field: ResearchField,
const vals = {};
[...Array(level + 1).keys()]
Array.from({ length: level + 1 }, (_, i) => i)
.map((l) => researchEvents(field, l, engine.expansions, engine.lostFleetEconomySide))
.forEach((events, l) => {
for (const e of events) {

View file

@ -69,7 +69,7 @@ function customFederationButton(controller: CommandController, fedTypeButtons: B
highlighted.set(hex, {});
}
const keys: GaiaHex[] = [...highlighted.keys()];
const keys: GaiaHex[] = Array.from(highlighted.keys());
controller.highlightHexes(customHexSelection(new Map([...keys.map((key) => [key, {}])] as any)));
});
controller.highlightHexes(customHexSelection(new Map<GaiaHex, HighlightHex>()));

View file

@ -261,7 +261,7 @@ const piAcademyDistance: FinalScoringExtractLog = ExtractLog.wrapper((want) => {
counter.playerCommand(e.cmd, e.data);
const pi = counter.planetaryInstituteLocation;
const academies = [...counter.buildings.entries()]
const academies = Array.from(counter.buildings.entries())
.filter(([, building]) => building === Building.Academy1 || building === Building.Academy2)
.map(([hex]) => hex);

View file

@ -207,7 +207,7 @@ export const victoryPointSources = (
// player's real victoryPoints correctly kept it - confirmed against a real finished game
// (PROGRESS.md's "solar drift" report) where 2 Twilight-QIC rescores left 2 players' displayed
// totals 14 VP under their actual score.
types: [...BoardAction.values(expansion), BoardAction.Qic2, Spaceship.TFMars, Spaceship.Eclipse],
types: [...Array.from(BoardAction.values(expansion)), BoardAction.Qic2, Spaceship.TFMars, Spaceship.Eclipse],
label: "QIC",
description: "QIC actions, including T F Mars/Eclipse's spaceship-board QIC action",
color: "--specialAction",

View file

@ -96,12 +96,15 @@ export function resolvePremoveQueue(
}
const rest = ordered.slice(1).map((r) => r.seq);
if (result.threw && rest.length > 0) {
// Explicit shape: control-flow narrowing of the result union is unreliable under the older
// TS used by some compile paths (engine tsconfig via ts-node), so assert the failure member.
const failure = result as { ok: false; threw: boolean; reason: string };
if (failure.threw && rest.length > 0) {
// A broken link invalidates the plan behind it (§10.5): cascade-discard the rest rather than
// attempting them against state their own preview never accounted for.
return {
outcome: "failed",
reason: `${result.reason} — ${rest.length} more queued premove${
reason: `${failure.reason} — ${rest.length} more queued premove${
rest.length > 1 ? "s" : ""
} discarded, they depended on this one`,
failedMove: head.move,
@ -111,7 +114,7 @@ export function resolvePremoveQueue(
// Either a plain throw with nothing behind it, or the defensive "applied but didn't complete a
// turn" case (shouldn't normally happen - queuing already enforces completeness) - Phase 1's
// original behavior, no cascade needed since there's nothing after it or nothing to protect.
return { outcome: "failed", reason: result.reason, failedMove: head.move, consumedSeqs: [head.seq] };
return { outcome: "failed", reason: failure.reason, failedMove: head.move, consumedSeqs: [head.seq] };
}
// Priority: try ranks in ascending order against the SAME original state; first legal one wins.

View file

@ -52,7 +52,7 @@ export function buildingMovesByHex(data: Engine, moves: CommandObject[]): Map<Ga
}
export function movesToHexes(data: Engine, moves: CommandObject[]): GaiaHex[] {
return [...buildingMovesByHex(data, moves).keys()];
return Array.from(buildingMovesByHex(data, moves).keys());
}
/** A move's last argument can keep the "." that separates it from the next command, e.g. "build m 3A4.". */

View file

@ -46,7 +46,7 @@ export function research(engine: Engine, greenFederations: boolean): PlayerTable
).concat(
...ResearchField.values(engine.expansions).map((f) => ({
shortcut: f.substring(0, 1),
title: `<b>${researchData[f].name}</b>${[...Array(lastTile(f) + 1).keys()]
title: `<b>${researchData[f].name}</b>${Array.from({ length: lastTile(f) + 1 }, (_, i) => i)
.map((level) => {
const desc = researchLevelDesc(engine, f, level, false);
return desc ? `<br/>Level ${level}: ${desc.join(" ")}` : "";

View file

@ -16,7 +16,7 @@ import { cellStyle } from "./table/util";
type TradeRow = { style: string; cells: RichText[] };
const levels = Array.from(Array(lastTile(ResearchField.Diplomacy) + 1).keys());
const levels = Array.from({ length: lastTile(ResearchField.Diplomacy) + 1 }, (_, i) => i);
export function tradeHeaders(): string[] {
return ["Name"].concat(levels.map((level) => `Diplomacy ${level}`));
@ -32,7 +32,7 @@ function row(option: TradeOption): TradeRow {
const cells: RichText[] = levels.map((level) => {
const guest = new PlayerData();
[...Array(level + 1).keys()]
Array.from({ length: level + 1 }, (_, i) => i)
.map((l) => researchEvents(ResearchField.Diplomacy, l, Expansion.Frontiers))
.forEach((events, l) => {
for (const e of events) {

View file

@ -81,12 +81,12 @@ function occupyPlanetsOfDistinctTypes(engine: Engine, player: PlayerEnum, count:
function occupyNearestPlanet(engine: Engine, player: PlayerEnum, ship: Spaceship): GaiaHex {
const pl = engine.player(player);
const shipTile = [...engine.map.grid.values()].find((hex) => hex.data.spaceship === ship);
const shipTile = Array.from(engine.map.grid.values()).find((hex) => hex.data.spaceship === ship);
if (!shipTile) {
throw new Error(`No ${ship} tile found on Lost Fleet map`);
}
const candidate = [...engine.map.grid.values()]
const candidate = Array.from(engine.map.grid.values())
.filter((hex) => hex.hasPlanet() && hex.data.spaceship === undefined && !hex.occupied())
.sort((a, b) => engine.map.distance(a, shipTile) - engine.map.distance(b, shipTile))[0];
@ -109,7 +109,7 @@ function occupyFirstAvailablePlanet(
predicate?: (hex: GaiaHex) => boolean
): GaiaHex {
const pl = engine.player(player);
const hex = [...engine.map.grid.values()].find(
const hex = Array.from(engine.map.grid.values()).find(
(space) =>
space.hasPlanet() &&
space.data.spaceship === undefined &&

37
viewer/vue-global-shim.js Normal file
View file

@ -0,0 +1,37 @@
/* eslint-disable */
// Lib-build shim for the webpack external 'vue'.
//
// The published UMD keeps `vue` external - the host page (boardgamers.space's iframe wrapper or
// the demo html) provides `window.Vue`. That global is a plain function (Vue 2's UMD export)
// with NO `.default` property. TypeScript's esModuleInterop emits `vue_1.default` for
// `import Vue from "vue"`, which is undefined for that shape and crashed the bundle at
// module-eval time ("Cannot read properties of undefined (reading 'extend')") in every
// component that calls Vue.extend at module scope.
//
// Resolving `vue$` here normalizes the global into a proper ES-module-shaped object, so
// default imports, namespace imports, and plain CJS requires all work against it.
//
// Kept at the repo root (next to vue.config.js); only wired in the `lib` branch of
// vue.config.js, never in dev/serve builds (those use the real vue package).
(function () {
var actual;
if (typeof window !== "undefined" && typeof window.Vue === "function") {
actual = window.Vue;
} else if (typeof global !== "undefined" && typeof global.Vue === "function") {
actual = global.Vue;
} else if (typeof Vue === "function") {
actual = Vue; // eslint-disable-line no-undef
} else if (typeof require === "function") {
try {
actual = require("vue");
} catch (e) {
actual = undefined;
}
}
if (actual && !actual.__esModule && actual.default === undefined) {
actual = Object.assign({ default: actual, __esModule: true }, actual);
}
if (typeof module !== "undefined" && module.exports) {
module.exports = actual;
}
})();

View file

@ -11,6 +11,12 @@ if (process.argv.includes("lib")) {
config.externals({
"bootstrap-vue": "BootstrapVue",
});
// 'vue' stays an external (the host page provides Vue), but TS's esModuleInterop emits
// `vue_1.default` and the host's `window.Vue` is a plain function with no `.default` -
// the raw external made the whole bundle throw "Cannot read properties of undefined
// (reading 'extend')" at module-eval. Resolving 'vue' through this shim normalizes the
// global into a proper ES-module shape so every import style works.
config.resolve.alias.set("vue$", path.join(__dirname, "vue-global-shim.js"));
// Inline ALL svg assets as data URIs instead of emitting img/*.svg files that resolve
// against the baked-in publicPath (the versioned jsDelivr URL). This makes the UMD lib a
// fully self-contained file, so it can be hosted anywhere (S3 upload via the BGS admin