import assert from 'node:assert/strict'; import test from 'node:test'; import { readFileSync } from 'node:fs'; import { runInNewContext } from 'node:vm'; import { createElement, isValidElement, type ReactElement, type ReactNode } from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import * as jsxRuntime from 'react/jsx-runtime'; import ts from 'typescript'; import * as board from '../game/board'; import * as catalog from '../game/catalog'; import * as coalitionAlliance from '../game/coalition-alliance'; import * as publicDeals from '../game/public-deals'; import { PublicDealList, PublicDeals, publicDealOfferAction, publicDealRequests } from '../components/public-deals'; import type { Action, GameView } from '../game/engine'; type Element = ReactElement<{children?:ReactNode; [key:string]:unknown}>; function elements(node: ReactNode): Element[] { if (Array.isArray(node)) return node.flatMap(elements); if (!isValidElement<{children?:ReactNode; [key:string]:unknown}>(node)) return []; return [node, ...elements(node.props.children)]; } function label(node: ReactNode): string { if (Array.isArray(node)) return node.map(label).join(''); return typeof node === 'string' || typeof node === 'number' ? String(node) : ''; } const first = {kind:'deferredBribe' as const,payer:'a',recipient:'b',amount:2,dueTurn:2}; const second = {kind:'deferredBribe' as const,payer:'a',recipient:'b',amount:3,dueTurn:3}; const deal = {id:'deal',from:'a',to:'b',terms:'Two payments.',turn:2,status:'active',releaseVotes:[], additionalPayments:[{payment:first,paymentStatus:'pending'}, {payment:second,paymentStatus:'pending'}]}; const base = {status:'playing',turn:2,me:'a',roomControl:null,coalitionState:null, players:[{id:'a',name:'Alice',faction:'atreides',ally:null},{id:'b',name:'Basil',faction:'harkonnen',ally:null}], deals:[deal],deferredDealPaymentOptions:{'deal:payment:0':{blocked:null},'deal:payment:1':{blocked:'Keep funds for the first payment.'}}, } as unknown as GameView; void test('offer helper sends distinct exact payment terms with legacy payment and travel', () => { const immediate = {kind:'immediateBribe' as const,payer:'b',recipient:'a',amount:1}; const travel = {kind:'ship' as const,territory:'carthag',minimum:1,answer:true}; assert.deepEqual(publicDealOfferAction(['b'],' Terms ',immediate,'a',2,travel,[first,second]), {type:'dealOffer',target:'b',terms:'Terms',payment:immediate,travel,additionalPayments:[first,second]}); assert.deepEqual(publicDealOfferAction(['b'],'Terms',undefined,'a',2,undefined,[]), {type:'dealOffer',target:'b',terms:'Terms'}); for (const terms of [[{...first,payer:'outsider'}],[{...first,recipient:'a'}],[{...first,amount:0}], [{...first,dueTurn:1}],Array.from({length:13},() => first)]) assert.equal(publicDealOfferAction(['b'],'Terms',undefined,'a',2,undefined,terms),null); }); void test('each additional payment has its own visible status, quote and exact pay action', () => { const html = renderToStaticMarkup(createElement(PublicDealList,{game:base,disabled:false,act() {}})); assert.match(html,/Additional payment 1/); assert.match(html,/Additional payment 2/); assert.match(html,/exactly 2 spice/); assert.match(html,/exactly 3 spice/); assert.match(html,/Keep funds for the first payment/); const calls:Action[] = []; const nodes = elements(PublicDealList({game:base,disabled:false,act(action) {calls.push(action);}})); const one = nodes.find(node => label(node.props.children) === 'Pay additional payment 1'); const two = nodes.find(node => label(node.props.children) === 'Pay additional payment 2'); assert.ok(one && two); assert.equal(one.props.disabled,false); assert.equal(two.props.disabled,true); (one.props.onClick as () => void)(); assert.deepEqual(calls,[{type:'dealPay',deal:'deal',paymentIndex:0}]); assert.deepEqual(publicDealRequests(base),[['payment','deal','0']]); const paid = {...base,deals:[{...deal,additionalPayments:[{payment:first,paymentStatus:'paid'}, {payment:second,paymentStatus:'pending'}]}]} as unknown as GameView; const after = elements(PublicDealList({game:paid,disabled:false,act() {}})); assert.equal(after.find(node => label(node.props.children) === 'Pay additional payment 1'),undefined); assert.ok(after.find(node => label(node.props.children) === 'Pay additional payment 2')); assert.deepEqual(publicDealRequests(paid),[]); const recipient = {...base,me:'b'} as GameView; assert.equal(elements(PublicDealList({game:recipient,disabled:false,act() {}})) .some(node => label(node.props.children) === 'Pay additional payment 1'),false); }); /** Exercise the actual hook callbacks in a stateful React-compatible VM; this * is a component-control test, not a hydrated-browser claim. */ function form() { const states:unknown[] = [], refs:{current:unknown}[] = [], sent:Action[] = []; let stateCursor = 0, refCursor = 0; const exported:{PublicDeals?:typeof PublicDeals} = {}; runInNewContext(ts.transpileModule(readFileSync(new URL('../components/public-deals.tsx',import.meta.url),'utf8'),{ compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX}, }).outputText,{exports:exported,require(name:string) { if (name === 'react/jsx-runtime') return jsxRuntime; if (name === 'react') return {useState(initial:unknown) { const index = stateCursor++; if (!(index in states)) states[index] = typeof initial === 'function' ? initial() : initial; return [states[index],(next:unknown) => {states[index] = typeof next === 'function' ? next(states[index]) : next;}]; },useRef(initial:unknown) {const index = refCursor++; return refs[index] ??= {current:initial};},useEffect() {}}; if (name === '@/components/ui/button') return {Button:'button'}; if (name === '@/game/board') return board; if (name === '@/game/catalog') return catalog; if (name === '@/game/coalition-alliance') return coalitionAlliance; if (name === '@/game/public-deals') return publicDeals; throw Error(`Unexpected import ${name}`); }}); assert.ok(exported.PublicDeals); const game = {...base,deals:[]} as GameView; const render = () => {stateCursor = 0; refCursor = 0; return elements(exported.PublicDeals!({game,busy:false,act(action) {sent.push(action);}}));}; const click = (name:string) => {const button = render().find(node => node.type === 'button' && label(node.props.children) === name); assert.ok(button); assert.equal(button.props.disabled,false); (button.props.onClick as () => void)();}; const field = (index:number) => {const sets = render().filter(node => node.type === 'fieldset' && elements(node).some(child => child.type === 'legend' && JSON.stringify(child.props.children).includes('Additional payment'))); assert.ok(sets[index]); return elements(sets[index]);}; return {render,click,field,sent}; } void test('authoring callbacks add, edit and remove independent deferred terms', () => { const ui = form(); const recipient = ui.render().find(node => node.type === 'input' && node.props.type === 'checkbox'); assert.ok(recipient); (recipient.props.onChange as (event:{target:{checked:boolean}}) => void)({target:{checked:true}}); ui.click('Add deferred payment'); ui.click('Add deferred payment'); for (let index = 0; index < 2; index++) { for (const [position,value] of [[0,'a'],[1,'b']] as const) { const select = ui.field(index).filter(node => node.type === 'select')[position]; assert.ok(select); (select.props.onChange as (event:{target:{value:string}}) => void)({target:{value}}); } for (const [position,value] of [[0,String(index+2)],[1,String(index+2)]] as const) { const input = ui.field(index).filter(node => node.type === 'input' && node.props.type === 'number')[position]; assert.ok(input); (input.props.onChange as (event:{target:{value:string}}) => void)({target:{value}}); } } ui.click('Remove additional payment 1'); const terms = ui.render().find(node => node.type === 'textarea'); assert.ok(terms); (terms.props.onChange as (event:{target:{value:string}}) => void)({target:{value:'One retained term'}}); const submit = ui.render().find(node => node.type === 'button' && node.props.type === 'submit'); assert.ok(submit); assert.equal(submit.props.disabled,false); const root = ui.render().find(node => node.type === 'form'); assert.ok(root); (root.props.onSubmit as (event:{preventDefault():void}) => void)({preventDefault() {}}); assert.deepEqual(JSON.parse(JSON.stringify(ui.sent)),[{type:'dealOffer',target:'b',terms:'One retained term',additionalPayments:[second]}]); });