import assert from 'node:assert/strict'; import {test} from 'node:test'; import {applyAction, createGame, joinGame, newPlayer, viewGame, type Action, type Game} from '../game/engine'; import {TERRITORIES} from '../game/board'; import {traitorDeck} from '../game/traitors'; import {withoutEcazLoyalty} from '../game/ecaz-loyalty'; import {validateNexusTraitorSnapshot} from '../game/nexus-traitor-exchange'; import {botActions} from '../game/bots'; import { registerHooks } from 'node:module'; import { readFileSync } from 'node:fs'; import { Children, createElement, isValidElement } from 'react'; import type { ReactNode } from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import {DIFFICULTIES} from '../game/bot-profiles'; import {nextHarkonnenBetrayalNativeStep, settleHarkonnenBetrayalNativeCounters, } from './fixture-nexus-harkonnen-betrayal'; const aliases = registerHooks({ resolve(specifier, context, next) { return next(specifier === 'next/image' ? 'vinext/shims/image' : specifier === 'next/link' ? 'vinext/shims/link' : specifier, context); }, load(url, context, next) { if (!url.endsWith('.module.css')) return next(url, context); const css = readFileSync(new URL(url), 'utf8'); const classes = Object.fromEntries([...css.matchAll(/\.([a-zA-Z_][\w-]*)/g)].map(match => [match[1], match[1]])); return { format: 'module', source: `export default ${JSON.stringify(classes)}`, shortCircuit: true }; }, }); const { NexusHarkonnenBetrayal } = await import('../components/nexus-harkonnen-betrayal'); const act = (game:Game, actor:string, action:Action) => applyAction(game,actor,action); const player = (game:Game, id:string) => {const seat=game.players.find(p=>p.id===id);assert.ok(seat);return seat;}; const step = (game:Game) => { if(game.pendingGuildBetrayal) {const frame=game.pendingGuildBetrayal;const actor=frame.required.find(id=>!frame.passed.includes(id));assert.ok(actor);return act(game,actor,{type:'guildBetrayalPass',event:frame.invoice.event});} const next=nextHarkonnenBetrayalNativeStep(game); try {return act(game,next.actor,next.action);} catch (error) {throw Error(`Step ${game.turn}/${game.phase}/${game.decision?.kind} ${JSON.stringify(next)}: ${String(error)}`);}}; function advance(game:Game, until:(game:Game)=>boolean, limit=1800):Game { for(let i=0;ip.hand)].map(card=>card.id).sort(); } function traitors(game:Game):void { validateNexusTraitorSnapshot({reserve:game.traitorReserve!,players:game.players.map(({id,faction,traitors,faceDancers})=>({id,faction,traitors,...(faceDancers?{faceDancers}: {})}))},withoutEcazLoyalty(traitorDeck(game.players,game.expansions.includes('ix')),game.ecazLoyalty)); } /** Native public standalone Ecaz/Moritani start, original setup and second-turn Nexus * draw. Conserved unopened deck order, one held traitor and two physical * reserve positions are staged; battle selection, plans and call are real. */ function fixture(target:'ecaz'|'moritani') { const faction = target; let game=createGame('ADVHARKEXPANDED',newPlayer('i',faction,faction),true,['ecaz']); const partner = 'atreides'; for(const [id,faction] of [['h','harkonnen'],['r',partner],['g','guild']] as const) joinGame(game,newPlayer(id,faction,faction)); game=act(game,'i',{type:'moduleOption',module:'nexusCards',enabled:true}); for(const seat of game.players) game=act(game,seat.id,{type:'ready'}); game=act(game,'i',{type:'start',advancedPreview:true}); assert.equal(game.nexusHarkonnenBetrayalPreview,true); game=advance(game,state=>state.status==='playing'); const physical=inventory(game);traitors(game); assert.ok(Object.values(game.nexusCards!.cards!.hands).every(card=>card===null)); const identity=player(game,'i').leaders.find(leader=>!leader.dead && leader.id!==game.ecazLoyalty?.card)!.id; const h=player(game,'h'); if(!h.traitors.includes(identity)) { const replacement=h.traitors[0]; const owner=game.players.find(seat=>seat.id!=='h'&&seat.traitors.includes(identity)); if(owner) owner.traitors[owner.traitors.indexOf(identity)]=replacement; else { const dancer=game.players.flatMap(seat=>seat.faceDancers??[]).find(card=>card.leader===identity); if(dancer) dancer.leader=replacement; else {const index=game.traitorReserve!.indexOf(identity);assert.ok(index>=0);game.traitorReserve![index]=replacement;} } h.traitors[0]=identity; } traitors(game); const nexus=game.nexusCards!.cards!; const nx=nexus.deck.indexOf('harkonnen');assert.ok(nx>=0); nexus.deck.unshift(nexus.deck.splice(nx,1)[0]); for(let pos=0;pos<2;pos++) { const index=game.spiceDeck.findIndex((card,i)=>i>=pos&&'territory'in card);assert.ok(index>=pos); game.spiceDeck.splice(pos,0,game.spiceDeck.splice(index,1)[0]); } game=advance(game,state=>state.turn===2&&state.phase===1&&!state.response&&!state.decision); const worm=game.spiceDeck.findIndex(card=>'worm'in card&&!card.greatMaker&&!card.suppressed);assert.ok(worm>=0); game.spiceDeck.unshift(game.spiceDeck.splice(worm,1)[0]); // Keep Sandtrout from breaking the alliance during the second Spice Blow // before the genuine Nexus closes and awards its held card. for(let pos=1;pos<=2;pos++) { const index=game.spiceDeck.findIndex((card,i)=>i>=pos&&'territory'in card);assert.ok(index>=pos); game.spiceDeck.splice(pos,0,game.spiceDeck.splice(index,1)[0]); } game=advance(game,state=>state.nexus&&!state.spiceWindow&&!state.spiceResolution&&!state.response&&!state.decision); game=act(game,'h',{type:'alliance',target:'r'});game=act(game,'r',{type:'alliance',target:'h'}); game=advance(game,state=>state.turn>2||state.nexusCards?.phase?.stage==='drawing'); assert.equal(game.turn,2,`Nexus drawing was skipped: ${JSON.stringify(game.log.slice(-25))}`); assert.ok(game.nexusCards!.phase!.eligible.includes('i')); game=act(game,'i',{type:'nexusCardChoice',turn:game.turn,card:null,choice:'draw',ownRedraws:0}); assert.equal(game.nexusCards!.cards!.hands.i,'harkonnen'); game=advance(game,state=>state.phase===5&&!state.response&&!state.decision); const territory=TERRITORIES.find(t=>t.type==='sand'&&!t.sectors.includes(game.storm)&& game.players.every(p=>!Object.keys(p.forces).some(key=>key.startsWith(`${t.id}:`))));assert.ok(territory); for(const id of ['h','i']) {const seat=player(game,id);assert.ok(seat.reserves>0);seat.reserves--;seat.forces[`${territory.id}:${territory.sectors[0]}`]=1;} game=advance(game,state=>state.phase===6&&!!state.active&&!state.phaseOpening&&!state.response&&!state.decision); const chooser=game.active!;assert.ok(['h','i'].includes(chooser), `chooser ${chooser}; battle ${JSON.stringify(game.battle)}; decision ${JSON.stringify(game.decision)}; pending ${JSON.stringify(game.pendingGuildBetrayal)}; armies ${JSON.stringify(game.players.map(p=>[p.id,p.forces]))}`); game=act(game,chooser,{type:'chooseBattle',territory:territory.id,target:chooser==='h'?'i':'h'}); game=advance(game,state=>!!state.battle&&!state.response&&!state.decision&&!state.battle.preparation&& (!state.battle.preLeader||state.battle.preLeader.closed)); for(const id of [game.battle!.attacker,game.battle!.defender]) { const leader=id==='i'?identity:player(game,id).leaders.find(l=>!l.dead&&!l.usedAt)!.id; game=act(game,id,{type:'battlePlan',dial:0,leader}); } assert.equal(game.battle!.revealed,true); game=advance(game,state=>!state.response&&!state.decision); game=act(game,'h',{type:'traitorCall',call:true}); game=settleHarkonnenBetrayalNativeCounters(game); const reaction=viewGame(game,'i').nexusHarkonnenBetrayalReaction; assert.ok(reaction,'The actual expansion-roster traitor call opens native Betrayal'); assert.equal(reaction.canUse,true);assert.equal(reaction.identity,identity); assert.deepEqual(inventory(game),physical);traitors(game); return {game,event:reaction.event,identity,physical}; } function click(node: ReactNode, selector: string): boolean { for (const child of Children.toArray(node)) { if (!isValidElement<{children?: ReactNode; onClick?: () => void; 'data-testid'?: string}>(child)) continue; if (child.props['data-testid'] === selector && child.props.onClick) { child.props.onClick(); return true; } if (click(child.props.children, selector)) return true; } return false; } function select(game: ReturnType, choice: 'use'|'pass', busy = false): Action | undefined { let action: Action | undefined; click(NexusHarkonnenBetrayal({game, busy, act(value) { action = value; }}), `nexus-harkonnen-betrayal-${choice}`); return action; } function markup(game: ReturnType): string { return renderToStaticMarkup(createElement(NexusHarkonnenBetrayal, {game, busy: false, act() {}})); } for (const target of ['ecaz', 'moritani'] as const) { void test(`Advanced ${target} owner controls use and pass the real Harkonnen betrayal`, () => { const f = fixture(target); const owner = viewGame(f.game, 'i'); assert.ok(markup(owner).includes('Declared Harkonnen traitor acknowledgement')); assert.ok(markup(owner).includes('Inspect Harkonnen Nexus card')); assert.ok(markup(owner).includes(owner.allLeaders.find(leader => leader.id === f.identity)!.name)); const use = select(owner, 'use'); assert.deepEqual(use, {type: 'nexusHarkonnenBetrayalUse', event: f.event}); assert.equal(select(owner, 'use', true), undefined); assert.equal(select(owner, 'pass', true), undefined); // Public declaration, not private Harkonnen cards or the owner's face. for (const seat of f.game.players.filter(seat => seat.id !== 'i')) { const other = viewGame(f.game, seat.id); const html = markup(other); assert.ok(html.includes(other.allLeaders.find(leader => leader.id === f.identity)!.name)); assert.equal(html.includes('Inspect Harkonnen Nexus card'), false); for (const hidden of player(f.game, 'h').traitors.filter(id => id !== f.identity)) { assert.equal(html.includes(other.allLeaders.find(leader => leader.id === hidden)!.name), false); } assert.equal(select(other, 'use'), undefined); } // Event binding rejects a forged and previously consumed control without mutation. const before = structuredClone(f.game); assert.throws(() => act(f.game, 'i', {type: 'nexusHarkonnenBetrayalUse', event: `${f.event}-stale`})); assert.deepEqual(f.game, before); assert.ok(use); const used = act(f.game, 'i', use); assert.equal(used.pendingNexusHarkonnenBetrayal, null); assert.equal(used.nexusCards!.cards!.hands.i, null); assert.equal(player(used, 'h').traitors.includes(f.identity), false); assert.equal(used.pendingNexusHarkonnenReplacement?.identity, f.identity); assert.equal(select(viewGame(used, 'i'), 'use'), undefined); assert.throws(() => act(used, 'i', use)); assert.deepEqual(inventory(used), f.physical); traitors(used); let passed = f.game; for (const id of passed.pendingNexusHarkonnenBetrayal!.required) { const pass = select(viewGame(passed, id), 'pass'); assert.deepEqual(pass, {type: 'nexusHarkonnenBetrayalPass', event: f.event}); assert.ok(pass); passed = act(passed, id, pass); } assert.equal(passed.pendingNexusHarkonnenBetrayal, null); assert.equal(passed.nexusCards!.cards!.hands.i, 'harkonnen'); assert.equal(player(passed, 'h').traitors.includes(f.identity), true); assert.equal(passed.pendingNexusHarkonnenReplacement ?? null, null); assert.deepEqual(inventory(passed), f.physical); traitors(passed); }); void test(`Advanced ${target} bot has a legal Harkonnen Nexus response`, () => { const f = fixture(target); for (const difficulty of DIFFICULTIES) { const own = viewGame(f.game, 'i'); own.players.find(seat => seat.id === 'i')!.bot = difficulty; const use = botActions(own).find(action => action.type === 'nexusHarkonnenBetrayalUse'); assert.deepEqual(use, {type: 'nexusHarkonnenBetrayalUse', event: f.event}); assert.ok(use); const result = act(structuredClone(f.game), 'i', use); assert.equal(result.nexusCards!.cards!.hands.i, null); assert.equal(result.pendingNexusHarkonnenReplacement?.identity, f.identity); } }); } aliases.deregister();