增加游戏玩法界面和各个弹窗初版

This commit is contained in:
zpx committed 2026-11-20 18:51:48 +08:00
1 parent e84e14783e
commit eb48d8e845
211 files changed
+59920 -21

No files matched your search

+560
View File
@@ -0,0 +1,560 @@
import { test } from 'node:test';
import { strict as assert } from 'node:assert';
import { BETS, PAYLINES, PAYTABLE, SYMBOLS, evaluate, spin } from '../assets/orchard/scripts/SlotsMath';
import type { SpinResult, SymbolId } from '../assets/orchard/scripts/SlotsMath';
import { GameSession, initialState } from '../assets/orchard/scripts/GameSession';
import type { GameState } from '../assets/orchard/scripts/GameSession';
import { GameRepository } from '../assets/orchard/scripts/GameRepository';
// 独立规则夹具,避免用被测常量证明自身。 / Independent fixtures, not production-derived expectations.
const ORDINARY = ['seven', 'bell', 'bar', 'strawberry', 'blueberry', 'plum', 'cherry', 'watermelon'] as const;
const SYMBOL_IDS: SymbolId[] = [...ORDINARY, 'wild', 'scatter'];
const WEIGHTS = [3, 5, 7, 10, 11, 13, 15, 30, 2, 4];
const ODDS: Record<typeof ORDINARY[number], [number, number, number]> = {
seven: [45, 158, 675], bell: [36, 113, 450], bar: [27, 90, 360],
strawberry: [18, 54, 203], blueberry: [14, 45, 158], plum: [9, 27, 90],
cherry: [5, 18, 68], watermelon: [5, 14, 45],
};
const LINES = ['MMMMM', 'TTTTT', 'BBBBB', 'TMBMT', 'BMTMB', 'MTTTM', 'MBBBM', 'MTBTM', 'MBTBM',
'TMMMT', 'BMMMB', 'TTMMB', 'BBMMT', 'TMMBB', 'BMMTT', 'MTMMM', 'MBMMM', 'MMMTM', 'MMMBM', 'MTMBM']
.map(line => [...line].map(row => ({ T: 0, M: 1, B: 2 })[row as 'T' | 'M' | 'B']));
const SCOPE = 'https://example.test/FruitFixture/guest-a';
const DAY = 86_400_000;
const NOW = Date.parse('2026-11-20T12:00:00Z');
const copy = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;
function board(symbol: SymbolId = 'scatter'): SymbolId[][] {
return Array.from({ length: 5 }, () => Array<SymbolId>(3).fill(symbol));
}
function sample(symbol: SymbolId): number {
const index = SYMBOL_IDS.indexOf(symbol);
return (WEIGHTS.slice(0, index).reduce((sum, weight) => sum + weight, 0) + WEIGHTS[index] / 2) / 100;
}
function draws(values: number[]): () => number {
let index = 0;
return () => {
assert.ok(index < values.length, 'unexpected random draw');
return values[index++];
};
}
function randomFor(value: SymbolId[][], extra: number[] = []): () => number {
return draws([...value.flat().map(sample), ...extra]);
}
// 全部候选按最长前缀算奖后取最大;与实现共享的只有公开类型。 / Independent line-award oracle.
function expectedWins(value: SymbolId[][], bet: number) {
return LINES.flatMap((rows, line) => {
const candidates = ORDINARY.map(symbol => {
let count = 0;
while (count < 5 && (value[count][rows[count]] === symbol || value[count][rows[count]] === 'wild')) count++;
return { line, symbol, count, amount: count < 3 ? 0 : bet / 20 * ODDS[symbol][count - 3] };
}).sort((a, b) => b.amount - a.amount);
return candidates[0].amount === 0 ? [] : [candidates[0]];
});
}
function verifyEvaluation(value: SymbolId[][], bet: number): SpinResult {
const before = copy(value);
const result = evaluate(value, bet);
const expected = expectedWins(value, bet);
assert.deepEqual(result.board, before);
assert.deepEqual(value, before, 'evaluation must not mutate the caller board');
assert.deepEqual(result.wins.map(win => ({ line: win.line, symbol: win.symbol, count: win.count, amount: win.amount })), expected);
assert.equal(result.win, expected.reduce((sum, win) => sum + win.amount, 0));
assert.equal(new Set(result.wins.map(win => win.line)).size, result.wins.length, 'at most one award per line');
assert.equal(result.wildColumn, null);
return result;
}
function memory() {
const values = new Map<string, string>();
return {
values, reads: 0, writes: 0, failRead: 0, failWrite: false, silent: false, corrupt: false,
beforeWrite: null as (() => void) | null,
afterWrite: null as (() => void) | null,
getItem(key: string): string | null {
this.reads++;
if (this.failRead > 0) { this.failRead--; throw new Error('fixture read failure'); }
return values.get(key) ?? null;
},
setItem(key: string, value: string): void {
this.writes++;
this.beforeWrite?.();
if (this.failWrite) throw new Error('fixture quota failure');
if (!this.silent) values.set(key, this.corrupt ? '{broken write' : value);
this.afterWrite?.();
},
};
}
type Memory = ReturnType<typeof memory>;
function session(random: () => number = () => sample('scatter'), now: () => number = () => NOW, storage = memory()) {
const game = new GameSession(new GameRepository(storage, SCOPE), random, now);
return { game, storage };
}
function persisted(storage: Memory): GameState {
const saved = new GameRepository(storage, SCOPE).load();
assert.ok(saved);
return saved;
}
function assertUnchanged(game: GameSession, storage: Memory, action: () => unknown): void {
const before = game.state;
const raw = [...storage.values];
assert.throws(action);
assert.deepEqual(game.state, before, 'rejected operation mutated memory');
assert.deepEqual([...storage.values], raw, 'rejected operation overwrote storage');
}
function freeReady(random: () => number = () => sample('scatter')) {
let triggered = false;
let normalDraws = 0;
const fixture = session(() => {
if (!triggered) {
normalDraws++;
if (normalDraws === 15) triggered = true;
return sample('scatter');
}
return random();
});
const trigger = fixture.game.beginSpin();
assert.equal(trigger.awarded, 16);
fixture.game.completeSpin();
assert.equal(fixture.game.state.phase, 'free-trigger');
fixture.game.startFree();
assert.equal(fixture.game.state.phase, 'free-ready');
return fixture;
}
test('gameplay constants exactly match the approved weights, 20 ordered paylines and paytable', () => {
assert.deepEqual(SYMBOLS, SYMBOL_IDS);
assert.deepEqual(BETS, [1000, 2000, 5000, 10000, 20000, 50000]);
assert.deepEqual(PAYLINES, LINES);
assert.equal(new Set(PAYLINES.map(line => line.join(''))).size, 20);
assert.deepEqual(PAYTABLE, ODDS);
});
test('every payline pays all eight symbols at 3/4/5 from the left and sums overlapping lines', () => {
for (let line = 0; line < LINES.length; line++) {
for (const symbol of ORDINARY) {
for (const count of [3, 4, 5]) {
const value = board();
for (let col = 0; col < count; col++) value[col][LINES[line][col]] = symbol;
const result = verifyEvaluation(value, 2000);
const target = result.wins.find(win => win.line === line);
assert.ok(target, `missing line=${line}, symbol=${symbol}, count=${count}`);
assert.deepEqual({ symbol: target.symbol, count: target.count, amount: target.amount },
{ symbol, count, amount: 100 * ODDS[symbol][count - 3] });
}
}
}
});
test('all legal bet levels scale line awards from total bet divided by twenty', () => {
for (const bet of [1000, 2000, 5000, 10000, 20000, 50000]) {
const result = verifyEvaluation(board('cherry'), bet);
assert.equal(result.win, bet * 68);
assert.equal(result.wins.length, 20);
}
});
test('WILD substitution pays the highest candidate, including a shorter seven and all-WILD', () => {
for (const [symbols, symbol, count, multiplier] of [
[['wild', 'wild', 'wild', 'bell', 'bell'], 'bell', 5, 450],
[['wild', 'wild', 'wild', 'watermelon', 'bell'], 'seven', 3, 45],
[['wild', 'wild', 'wild', 'wild', 'wild'], 'seven', 5, 675],
[['wild', 'wild', 'watermelon', 'watermelon', 'bell'], 'watermelon', 4, 14],
[['cherry', 'wild', 'cherry', 'scatter', 'cherry'], 'cherry', 3, 5],
] as const) {
const value = symbols.map(value => Array<SymbolId>(3).fill(value));
const result = verifyEvaluation(value, 2000);
assert.equal(result.wins.length, 20);
for (const win of result.wins) {
assert.equal(win.symbol, symbol); assert.equal(win.count, count); assert.equal(win.amount, multiplier * 100);
}
}
});
test('SCATTER interrupts ordinary lines, has no line award and cannot be substituted by WILD', () => {
for (const symbols of [
['scatter', 'cherry', 'cherry', 'cherry', 'cherry'],
['cherry', 'scatter', 'cherry', 'cherry', 'cherry'],
['wild', 'wild', 'scatter', 'wild', 'wild'],
['watermelon', 'bell', 'watermelon', 'watermelon', 'watermelon'],
] as SymbolId[][]) {
assert.equal(verifyEvaluation(symbols.map(symbol => Array<SymbolId>(3).fill(symbol)), 2000).win, 0);
}
const scatter = verifyEvaluation(board(), 2000);
assert.deepEqual(scatter.wins, []); assert.equal(scatter.scatters, 15);
});
test('SCATTER anywhere awards exactly 8/12/16 normal spins at 3/4/5 through 15', () => {
const positions = [14, 0, 7, 4, 11, 2, 9, 6, 13, 1, 8, 5, 12, 3, 10];
for (let count = 0; count <= 15; count++) {
const value = board('cherry');
for (const position of positions.slice(0, count)) value[Math.floor(position / 3)][position % 3] = 'scatter';
const result = evaluate(value, 2000);
assert.equal(result.scatters, count);
assert.equal(result.awarded, count < 3 ? 0 : count === 3 ? 8 : count === 4 ? 12 : 16);
}
});
test('normal draws independently use all exact weight intervals, with fifteen draws per spin', () => {
let lower = 0;
for (let symbol = 0; symbol < SYMBOL_IDS.length; symbol++) {
for (const value of [lower / 100, (lower + WEIGHTS[symbol] - 0.000001) / 100]) {
let calls = 0;
const result = spin(2000, false, () => { calls++; return value; });
assert.deepEqual(result.board, board(SYMBOL_IDS[symbol]));
assert.equal(calls, 15);
assert.equal(result.wildColumn, null);
}
lower += WEIGHTS[symbol];
}
const value: SymbolId[][] = [
['seven', 'bell', 'bar'], ['strawberry', 'blueberry', 'plum'], ['cherry', 'watermelon', 'wild'],
['scatter', 'seven', 'bell'], ['bar', 'cherry', 'plum'],
];
assert.deepEqual(spin(2000, false, randomFor(value)), evaluate(value, 2000));
});
test('free spins uniformly select exactly one column, preserve SCATTER, evaluate after conversion and never retrigger', () => {
const original = board('cherry');
for (let column = 0; column < 5; column++) original[column][1] = 'scatter';
const before = copy(original);
for (let column = 0; column < 5; column++) {
for (const selector of [column / 5, (column + 1) / 5 - 0.00000001]) {
const result = spin(2000, true, randomFor(original, [selector]));
const expected = copy(original);
expected[column][0] = 'wild'; expected[column][2] = 'wild';
assert.equal(result.wildColumn, column);
assert.deepEqual(result.board, expected);
assert.deepEqual(result.wins, evaluate(expected, 2000).wins);
assert.equal(result.win, evaluate(expected, 2000).win);
assert.equal(result.scatters, 5);
assert.equal(result.awarded, 0);
}
}
assert.deepEqual(original, before);
const firstColumnWild = spin(2000, true, draws([...Array<number>(15).fill(sample('bell')), 0]));
assert.equal(firstColumnWild.win, 2000 * 450);
});
test('invalid random samples are rejected at every draw, including the free column selection', () => {
for (const invalid of [-1, -Number.EPSILON, 1, 1.1, NaN, Infinity, -Infinity]) {
for (const index of [0, 7, 14]) {
const values = Array<number>(15).fill(sample('cherry')); values[index] = invalid;
assert.throws(() => spin(2000, false, draws(values)));
}
assert.throws(() => spin(2000, true, draws([...Array<number>(15).fill(sample('cherry')), invalid])));
}
assert.throws(() => spin(2000, false, () => { throw Error('entropy unavailable'); }));
});
test('malformed boards and unsupported bets fail before they can be settled', () => {
const malformed: unknown[] = [null, [], board().slice(0, 4), [...board(), ['cherry']], board().map(col => col.slice(0, 2)),
[['unknown', 'cherry', 'cherry'], ...board().slice(1)]];
for (const value of malformed) assert.throws(() => evaluate(value as SymbolId[][], 2000));
for (const bet of [0, -2000, 1500, NaN, Infinity, Number.MAX_SAFE_INTEGER]) {
assert.throws(() => evaluate(board(), bet));
assert.throws(() => spin(bet, false, () => sample('cherry')));
}
});
test('initial state grants once and returns fresh board, settings and snapshots', () => {
const first = initialState(); const second = initialState();
assert.equal(first.version, 1); assert.equal(first.balance, 100000); assert.equal(first.bet, 2000);
assert.equal(first.lastWin, 0); assert.equal(first.phase, 'idle'); assert.equal(first.sequence, 0);
assert.equal(first.free, null); assert.equal(first.pending, null); assert.equal(first.lastClaimDay, null);
assert.deepEqual(Object.keys(first.settings).sort(), ['music', 'sound', 'vibration']);
for (const value of Object.values(first.settings)) assert.equal(typeof value, 'boolean');
first.board[0][0] = first.board[0][0] === 'seven' ? 'bell' : 'seven'; first.settings.music = !first.settings.music;
assert.notDeepEqual(first, second); assert.deepEqual(initialState(), second);
const { game, storage } = session(); const writes = storage.writes;
assert.equal(storage.values.size, 1, 'one JSON snapshot per scope');
const restored = new GameSession(new GameRepository(storage, SCOPE), () => { throw Error('restore must not draw'); });
assert.deepEqual(restored.state, game.state); assert.equal(storage.writes, writes);
});
test('beginSpin atomically commits the paid bet, winnings and pending animation exactly once', () => {
const { game, storage } = session(() => sample('cherry'));
const writes = storage.writes;
const result = game.beginSpin(); const committed = game.state;
assert.equal(result.win, 136000);
assert.equal(committed.balance, 100000 - 2000 + 136000);
assert.equal(committed.lastWin, result.win); assert.equal(committed.phase, 'spinning');
assert.equal(committed.sequence, 1); assert.equal(committed.pending?.id, 1);
assert.equal(committed.pending?.free, false); assert.deepEqual(committed.pending?.result, result);
assert.deepEqual(committed.board, result.board); assert.equal(committed.free, null);
assert.equal(storage.writes, writes + 1, 'money and pending result require one write');
assert.deepEqual(persisted(storage), committed);
assertUnchanged(game, storage, () => game.beginSpin());
game.completeSpin();
assert.equal(game.state.phase, 'idle'); assert.equal(game.state.pending, null);
assert.equal(game.state.balance, committed.balance); assert.equal(game.state.lastWin, result.win);
const after = game.state; const afterWrites = storage.writes;
try { game.completeSpin(); } catch { /* Duplicate completion may reject or no-op; it cannot commit. */ }
assert.deepEqual(game.state, after); assert.equal(storage.writes, afterWrites);
});
test('pending refresh replays without RNG, charging, awarding or any restoration write', () => {
const { game, storage } = session(() => sample('cherry'));
game.beginSpin(); const before = persisted(storage); const writes = storage.writes;
const restored = new GameSession(new GameRepository(storage, SCOPE), () => { throw Error('pending replay drew again'); });
assert.equal(restored.state.phase, 'spinning'); assert.deepEqual(restored.state.pending, before.pending);
assert.deepEqual(restored.state, before); assert.equal(storage.writes, writes);
restored.completeSpin();
assert.equal(restored.state.balance, before.balance); assert.equal(restored.state.lastWin, before.lastWin);
assert.equal(restored.state.sequence, before.sequence); assert.equal(restored.state.pending, null);
assertUnchanged(game, storage, () => game.completeSpin());
});
test('bet changes are restricted to idle supported bets; insufficient balance never draws or commits', () => {
let calls = 0;
const { game, storage } = session(() => { calls++; return sample('scatter'); });
for (const bet of [1000, 2000, 5000, 10000, 20000, 50000]) {
game.setBet(bet); assert.equal(game.state.bet, bet); assert.equal(game.state.balance, 100000);
}
for (const bet of [0, 1500, NaN, Infinity]) assertUnchanged(game, storage, () => game.setBet(bet));
const repo = new GameRepository(storage, SCOPE); const seed = repo.load()!; seed.balance = 49999; repo.save(seed);
const poor = new GameSession(new GameRepository(storage, SCOPE), () => { calls++; return sample('cherry'); });
const beforeCalls = calls;
assertUnchanged(poor, storage, () => poor.beginSpin()); assert.equal(calls, beforeCalls);
const active = session().game; active.beginSpin(); assert.throws(() => active.setBet(1000));
});
test('normal award is separate from free total, free bets stay locked and scatter never retriggers', () => {
// 3 scatter + 12 cherries still pays ordinary lines on the trigger. / Trigger payout is not free-spin total.
const triggerBoard = board('cherry'); triggerBoard[4] = ['scatter', 'scatter', 'scatter'];
let paid = false; let draw = 0;
const triggerRandom = randomFor(triggerBoard);
const { game, storage } = session(() => {
if (!paid) { const result = triggerRandom(); if (++draw === 15) paid = true; return result; }
return sample('bell');
});
const trigger = game.beginSpin(); const afterTrigger = game.state.balance;
assert.equal(trigger.awarded, 8); assert.ok(trigger.win > 0);
assert.deepEqual(game.state.free, { remaining: 8, awarded: 8, total: 0, bet: 2000 });
assert.equal(game.state.lastWin, trigger.win);
game.completeSpin(); assert.equal(game.state.phase, 'free-trigger');
assertUnchanged(game, storage, () => game.beginSpin());
assertUnchanged(game, storage, () => game.setBet(1000));
game.startFree(); assert.equal(game.state.phase, 'free-ready');
assertUnchanged(game, storage, () => game.setBet(5000));
let total = 0;
for (let index = 0; index < 8; index++) {
const writes = storage.writes;
const result = game.beginSpin(); total += result.win;
assert.equal(result.awarded, 0); assert.equal(game.state.pending?.free, true);
assert.equal(game.state.free?.remaining, 7 - index); assert.equal(game.state.free?.awarded, 8);
assert.equal(game.state.free?.total, total); assert.equal(game.state.free?.bet, 2000);
assert.equal(game.state.balance, afterTrigger + total); assert.equal(game.state.lastWin, result.win);
assert.equal(storage.writes, writes + 1, 'free win, remaining count and pending must commit together');
game.completeSpin();
assert.equal(game.state.phase, index === 7 ? 'free-result' : 'free-ready');
}
assert.ok(total > 0); assert.equal(game.state.free?.total, total);
assertUnchanged(game, storage, () => game.beginSpin());
game.closeFreeResult();
assert.equal(game.state.phase, 'idle'); assert.equal(game.state.free, null);
assert.equal(game.state.balance, afterTrigger + total); game.setBet(5000);
});
test('free SCATTER preserves all cells, consumes exactly the awarded spins and cannot add spins', () => {
const { game } = freeReady(); const balance = game.state.balance;
for (let index = 0; index < 16; index++) {
const result = game.beginSpin();
assert.deepEqual(result.board, board()); assert.equal(result.scatters, 15); assert.equal(result.awarded, 0);
assert.equal(result.win, 0); assert.equal(game.state.free?.remaining, 15 - index);
game.completeSpin(); assert.equal(game.state.balance, balance);
}
assert.equal(game.state.phase, 'free-result'); assert.equal(game.state.free?.total, 0);
});
test('refresh preserves trigger, ready, intermediate pending, final pending and result without grants', () => {
const { game, storage } = freeReady();
const restore = () => new GameSession(new GameRepository(storage, SCOPE), () => sample('scatter'));
assert.deepEqual(restore().state, game.state);
let current = restore();
for (let index = 0; index < 16; index++) {
current.beginSpin(); const before = current.state; const writes = storage.writes;
current = restore();
assert.equal(current.state.phase, 'spinning'); assert.deepEqual(current.state, before);
assert.equal(storage.writes, writes);
current.completeSpin();
}
assert.equal(current.state.phase, 'free-result'); assert.deepEqual(restore().state, current.state);
const triggerFixture = session(); triggerFixture.game.beginSpin(); triggerFixture.game.completeSpin();
const trigger = new GameSession(new GameRepository(triggerFixture.storage, SCOPE), () => { throw Error('trigger restore draw'); });
assert.equal(trigger.state.phase, 'free-trigger'); assert.deepEqual(trigger.state.free, triggerFixture.game.state.free);
});
test('daily gift is once per UTC day and reset countdown crosses midnight and leap day', () => {
let time = Date.parse('2028-02-28T23:59:59.000Z');
const { game, storage } = session(undefined, () => time);
assert.equal(game.canClaimDaily(), true); assert.equal(game.nextResetMs(), 1000);
assert.equal(game.claimDaily(), true); assert.equal(game.state.balance, 120000);
assert.equal(game.state.lastClaimDay, '2028-02-28'); assert.equal(game.canClaimDaily(), false);
const writes = storage.writes;
assert.equal(game.claimDaily(), false); assert.equal(storage.writes, writes);
const restored = new GameSession(new GameRepository(storage, SCOPE), undefined, () => time);
assert.equal(restored.canClaimDaily(), false); assert.equal(restored.claimDaily(), false);
time += 1000;
assert.equal(restored.nextResetMs(), DAY); assert.equal(restored.canClaimDaily(), true);
assert.equal(restored.claimDaily(), true); assert.equal(restored.state.balance, 140000);
assert.equal(restored.state.lastClaimDay, '2028-02-29');
time = Date.parse('2028-03-01T00:00:00Z');
assert.equal(restored.claimDaily(), true); assert.equal(restored.state.lastClaimDay, '2028-03-01');
assert.equal(restored.state.balance, 160000);
});
test('preferences persist independently and exposed state/results cannot mutate a saved snapshot', () => {
const { game, storage } = session(() => sample('cherry'));
for (const key of ['music', 'sound', 'vibration'] as const) game.setPreference(key, false);
assert.deepEqual(game.state.settings, { music: false, sound: false, vibration: false });
const result = game.beginSpin(); const committed = copy(game.state);
result.board[0][0] = 'scatter'; result.wins[0].amount = 0; result.win = 0;
const exposed = game.state; exposed.balance = 0; exposed.board[0][0] = 'scatter'; exposed.settings.music = true;
exposed.pending!.result.board[1][0] = 'scatter'; exposed.pending!.result.wins[0].amount = 0;
assert.deepEqual(game.state, committed); assert.deepEqual(persisted(storage), committed);
game.completeSpin(); const restored = new GameSession(new GameRepository(storage, SCOPE));
assert.deepEqual(restored.state.settings, { music: false, sound: false, vibration: false });
});
test('repository snapshots and initial grants are isolated by caller-provided service/product/guest scope', () => {
const storage = memory(); const first = new GameRepository(storage, SCOPE);
assert.equal(first.load(), null);
const state = initialState(); first.save(state); state.balance = 1; state.settings.music = false;
const loaded = first.load()!; assert.equal(loaded.balance, 100000);
loaded.balance = 2; loaded.board[0][0] = 'scatter';
assert.equal(first.load()!.balance, 100000);
for (const scope of ['https://other.test/FruitFixture/guest-a', 'https://example.test/OtherProduct/guest-a',
'https://example.test/FruitFixture/guest-b']) {
const another = new GameRepository(storage, scope); assert.equal(another.load(), null);
const other = new GameSession(another); assert.equal(other.state.balance, 100000);
other.claimDaily(); assert.equal(other.state.balance, 120000);
assert.equal(first.load()!.balance, 100000);
}
assert.equal(storage.values.size, 4);
});
test('repository rejects invalid state invariants before writing', () => {
const { storage } = session();
const mutations: ((value: GameState) => void)[] = [
state => { state.version = 2 as 1; }, state => { state.balance = -1; }, state => { state.balance = 1.5; },
state => { state.balance = Number.MAX_SAFE_INTEGER + 1; }, state => { state.bet = 1500; },
state => { state.lastWin = -1; }, state => { state.sequence = -1; },
state => { state.board.pop(); }, state => { state.board[0][0] = 'invalid' as SymbolId; },
state => { state.lastClaimDay = '2026-02-30'; }, state => { state.phase = 'spinning'; },
state => { state.phase = 'free-trigger'; }, state => { state.settings.music = 1 as unknown as boolean; },
state => { state.free = { remaining: 9, awarded: 8, total: 0, bet: 2000 }; state.phase = 'free-ready'; },
];
for (const mutate of mutations) {
const repository = new GameRepository(storage, SCOPE); const invalid = repository.load()!; mutate(invalid);
const before = [...storage.values]; const writes = storage.writes;
assert.throws(() => repository.save(invalid));
assert.deepEqual([...storage.values], before); assert.equal(storage.writes, writes);
}
});
test('corrupt or incompatible existing JSON is rejected without overwriting or giving a new balance', () => {
for (const corrupt of ['{invalid', 'null', '[]', '{}', '42', '"invalid"', '{"version":2}']) {
const { storage } = session(); const key = [...storage.values.keys()][0]; storage.values.set(key, corrupt);
const writes = storage.writes;
assert.throws(() => new GameSession(new GameRepository(storage, SCOPE)));
assert.equal(storage.values.get(key), corrupt); assert.equal(storage.writes, writes);
}
});
test('unavailable initial storage never silently creates an in-memory grant', () => {
for (const mode of ['read', 'write', 'silent'] as const) {
const storage = memory();
if (mode === 'read') storage.failRead = 1;
if (mode === 'write') storage.failWrite = true;
if (mode === 'silent') storage.silent = true;
assert.throws(() => new GameSession(new GameRepository(storage, SCOPE)));
assert.equal(storage.values.size, 0);
}
});
test('failed and silent writes keep spin, bet, daily and preferences unchanged in memory', () => {
for (const mode of ['failWrite', 'silent'] as const) {
for (const action of [
(game: GameSession) => game.beginSpin(), (game: GameSession) => game.setBet(5000),
(game: GameSession) => game.claimDaily(), (game: GameSession) => game.setPreference('sound', false),
]) {
const { game, storage } = session(() => sample('cherry'));
storage[mode] = true;
assertUnchanged(game, storage, () => action(game));
}
}
});
test('failed complete/start/close writes keep the current pending or free state replayable', () => {
const { game, storage } = session(); game.beginSpin();
storage.failWrite = true; assertUnchanged(game, storage, () => game.completeSpin());
storage.failWrite = false; game.completeSpin();
storage.failWrite = true; assertUnchanged(game, storage, () => game.startFree());
storage.failWrite = false; game.startFree();
for (let index = 0; index < 16; index++) { game.beginSpin(); game.completeSpin(); }
assert.equal(game.state.phase, 'free-result');
storage.failWrite = true; assertUnchanged(game, storage, () => game.closeFreeResult());
storage.failWrite = false; game.closeFreeResult(); assert.equal(game.state.phase, 'idle');
});
test('readback verification detects a corrupt write without publishing the new in-memory state', () => {
const { game, storage } = session(() => sample('cherry')); const before = game.state;
storage.corrupt = true;
assert.throws(() => game.beginSpin()); assert.deepEqual(game.state, before);
storage.corrupt = false;
assert.throws(() => new GameSession(new GameRepository(storage, SCOPE)));
});
test('an uncertain commit with failing readback recovers saved pending and cannot be charged twice', () => {
const { game, storage } = session(() => sample('cherry')); const before = game.state;
storage.afterWrite = () => { storage.failRead = 1; };
assert.throws(() => game.beginSpin()); assert.deepEqual(game.state, before);
storage.afterWrite = null;
const committed = new GameSession(new GameRepository(storage, SCOPE), () => { throw Error('uncertain commit redraw'); });
assert.equal(committed.state.phase, 'spinning'); assert.equal(committed.state.balance, 234000);
assertUnchanged(game, storage, () => game.beginSpin());
committed.completeSpin(); assert.equal(committed.state.balance, 234000);
});
test('stale sessions cannot overwrite a concurrent spin or daily claim in the same guest scope', () => {
for (const action of [(game: GameSession) => game.beginSpin(), (game: GameSession) => game.claimDaily()]) {
const { game, storage } = session(() => sample('cherry'));
const stale = new GameSession(new GameRepository(storage, SCOPE), () => sample('cherry'), () => NOW);
action(game); const committed = persisted(storage); const writes = storage.writes;
assertUnchanged(stale, storage, () => action(stale));
assert.deepEqual(persisted(storage), committed); assert.equal(storage.writes, writes);
}
});
test('same-page reentrant storage writes cannot allow two sessions to settle the same revision', () => {
const { game, storage } = session(() => sample('cherry'));
const competitor = new GameSession(new GameRepository(storage, SCOPE), () => sample('cherry'));
const competingBefore = competitor.state; let attempted = false;
storage.beforeWrite = () => {
storage.beforeWrite = null; attempted = true;
assert.throws(() => competitor.beginSpin());
};
game.beginSpin();
assert.equal(attempted, true); assert.deepEqual(competitor.state, competingBefore);
assert.equal(game.state.balance, 234000); assert.deepEqual(persisted(storage), game.state);
});
test('entropy failure aborts a spin before balance, sequence or persisted pending can change', () => {
for (const invalidAt of [0, 14]) {
let calls = 0;
const { game, storage } = session(() => ++calls > invalidAt ? NaN : sample('cherry'));
assertUnchanged(game, storage, () => game.beginSpin());
}
const { game, storage } = freeReady(draws([...Array<number>(15).fill(sample('bell')), 1]));
assertUnchanged(game, storage, () => game.beginSpin());
});
+482
View File
@@ -0,0 +1,482 @@
import { test } from 'node:test';
import { strict as assert } from 'node:assert';
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { basename, dirname, extname, join, parse, resolve } from 'node:path';
import { AutoSpinQueue } from '../assets/orchard/scripts/AutoSpinQueue';
import { ART, ART_KEYS, FONT_UUID, SYMBOL_ART } from '../assets/orchard/scripts/OrchardAssets';
import { SYMBOLS } from '../assets/orchard/scripts/SlotsMath';
// Inspect saved references, not authoring/runtime source text. Node active flags remain editable.
type Entry = Record<string, any>;
const scene: Entry[] = JSON.parse(readFileSync('assets/Orchard.scene', 'utf8'));
const nodes = scene.filter(entry => entry.__type__ === 'cc.Node');
function dereference(ref: Entry): Entry {
assert.ok(ref && Number.isInteger(ref.__id__), 'expected a saved scene reference');
const entry = scene[ref.__id__];
assert.ok(entry, `missing scene entry ${ref.__id__}`);
return entry;
}
function node(name: string): Entry {
const matches = nodes.filter(entry => entry._name === name);
assert.equal(matches.length, 1, `expected one ${name}`);
return matches[0];
}
function children(parent: Entry): Entry[] {
return parent._children.map(dereference);
}
function component(owner: Entry, type: string): Entry {
const matches = owner._components.map(dereference).filter((entry: Entry) => entry.__type__ === type);
assert.equal(matches.length, 1, `${owner._name}: expected one ${type}`);
assert.equal(dereference(matches[0].node), owner, `${owner._name}: component owner`);
return matches[0];
}
function descendants(parent: Entry): Entry[] {
return children(parent).flatMap(child => [child, ...descendants(child)]);
}
function size(owner: Entry): { width: number; height: number } {
const { width, height } = component(owner, 'cc.UITransform')._contentSize;
return { width, height };
}
function position(owner: Entry): { x: number; y: number; z: number } {
const { x, y, z } = owner._lpos;
return { x, y, z };
}
function uuid(ref: Entry): string {
assert.equal(typeof ref?.__uuid__, 'string', 'expected a saved asset UUID');
return ref.__uuid__;
}
interface Asset { path: string; meta: Entry; }
interface Frame extends Asset { frame: Entry; }
const assets: Asset[] = ['visuals', 'emblems', 'dialogs', 'typefaces'].flatMap(folder => {
const directory = join('assets', 'orchard', folder);
return readdirSync(directory).filter(name => name.endsWith('.meta')).map(name => ({
path: join(directory, name.slice(0, -5)),
meta: JSON.parse(readFileSync(join(directory, name), 'utf8')) as Entry,
}));
});
const frames = new Map<string, Frame>();
for (const asset of assets) {
for (const frame of Object.values(asset.meta.subMetas ?? {}) as Entry[]) {
if (frame.importer === 'sprite-frame') {
assert.ok(!frames.has(frame.uuid), `duplicate frame UUID: ${frame.uuid}`);
frames.set(frame.uuid, { ...asset, frame });
}
}
}
function frameFor(id: string): Frame {
const asset = frames.get(id);
assert.ok(asset, `frame ${id} must resolve through orchard metadata`);
assert.ok(existsSync(asset.path), `missing image ${asset.path}`);
assert.equal(asset.meta.importer, 'image');
return asset;
}
function spriteKey(owner: Entry): string {
return parse(frameFor(uuid(component(owner, 'cc.Sprite')._spriteFrame)).path).name;
}
function controller(): Entry {
const matches = scene.filter(entry => Array.isArray(entry.artFrames));
assert.equal(matches.length, 1, 'one saved artwork controller');
assert.equal(dereference(matches[0].node), node('Canvas'));
return matches[0];
}
// Explicit, bounded provenance map; never recursively scan the source artwork directories.
const sourceByImport: Record<string, string> = {
'amethyst-fruit': '02-main-screen/symbols/plum.png',
'berry-satin': '02-main-screen/ui/background.jpg',
'bonus-award-caption': '10-free-spins-trigger/awarded.png',
'bonus-award-emblem': '10-free-spins-trigger/scatter.png',
'bonus-award-title': '10-free-spins-trigger/title.png',
'bonus-begin': '10-free-spins-trigger/start.png',
'bonus-cherries': '02-main-screen/symbols/scatter.png',
'bonus-dismiss': '12-free-spins-result/continue-button.png',
'bonus-heading': '02-main-screen/ui/text-free-spins.png',
'bonus-prize-card': '02-main-screen/ui/total-win-no-number.png',
'bonus-summary-amount': '12-free-spins-result/coin-value-frame-no-number.png',
'bonus-summary-caption': '12-free-spins-result/total-win-label.png',
'bonus-summary-garnish': '12-free-spins-result/cherries-decoration.png',
'bonus-summary-shell': '12-free-spins-result/popup-background.png',
'bonus-summary-title': '12-free-spins-result/free-spins-complete-title.png',
'century-idle': '05-auto-spin-setup/count_100_normal.png',
'century-picked': '05-auto-spin-setup/count_100_selected.png',
'claimed-shell': '07-free-coins-claimed/panel-background.png',
'claimed-heading': '07-free-coins-claimed/title-no-close.png',
'claimed-caption': '07-free-coins-claimed/daily-label.png',
'claimed-garnish': '07-free-coins-claimed/reward.png',
'crest-lockup': '02-main-screen/ui/logo.png',
'crimson-berry': '02-main-screen/symbols/strawberry.png',
'daily-pill': '02-main-screen/ui/free_coins.png',
'dismiss-orb': '03-settings/button-close.png',
'effects-row': '03-settings/row-sound.png',
'empty-wallet-garnish': '08-insufficient-coins/fruit-and-coins.png',
'empty-wallet-gift': '08-insufficient-coins/free-coins-button.png',
'empty-wallet-heading': '08-insufficient-coins/title.png',
'empty-wallet-later': '08-insufficient-coins/not-now-button.png',
'empty-wallet-note': '08-insufficient-coins/description.png',
'empty-wallet-shell': '08-insufficient-coins/popup-background.png',
'gift-amount': '06-free-coins-available/amount-bar-no-text.png',
'gift-collect': '06-free-coins-available/claim-button.png',
'gift-collected': '07-free-coins-claimed/claimed-button.png',
'gift-daily': '06-free-coins-available/daily-label.png',
'gift-garnish': '06-free-coins-available/reward.png',
'gift-heading': '06-free-coins-available/title.png',
'gift-shell': '06-free-coins-available/panel-background.png',
'guide-pill': '02-main-screen/ui/paytable.png',
'half-idle': '05-auto-spin-setup/count_50_normal.png',
'half-picked': '05-auto-spin-setup/count_50_selected.png',
'halt-orb': '02-main-screen/ui/stop-button.png',
'haptics-row': '03-settings/row-vibration.png',
'indigo-bunch': '02-main-screen/symbols/blueberry.png',
'instructions-pill': '03-settings/button-how-to-play.png',
'launch-orb': '02-main-screen/ui/spin.png',
'melody-row': '03-settings/row-music.png',
'neon-grid': '02-main-screen/ui/reel.png',
'paired-rubies': '02-main-screen/symbols/cherry.png',
'preferences-heading': '03-settings/title-settings.png',
'preferences-orb': '02-main-screen/ui/settings.png',
'preferences-shell': '03-settings/panel.png',
'prism-chime': '02-main-screen/symbols/bell.png',
'prize-heading': '02-main-screen/ui/win_label.png',
'prize-plaque': '02-main-screen/ui/win_panel.png',
'quarter-idle': '05-auto-spin-setup/count_25_normal.png',
'quarter-picked': '05-auto-spin-setup/count_25_selected.png',
'remaining-heading': '02-main-screen/ui/text-left.png',
'repeat-confirm': '05-auto-spin-setup/start_auto_spin.png',
'repeat-garnish': '05-auto-spin-setup/cherry_decoration.png',
'repeat-heading': '02-main-screen/ui/text-auto-spins.png',
'repeat-orb': '02-main-screen/ui/auto.png',
'repeat-shell': '05-auto-spin-setup/popup_background.png',
'repeat-title': '05-auto-spin-setup/auto_spin_title.png',
'resting-orb': '02-main-screen/ui/spin-disabled.png',
'round-prize-card': '02-main-screen/ui/current-win-no-number.png',
'rounds-ribbon': '02-main-screen/ui/free-spins-banner-empty.png',
'ruby-seven': '02-main-screen/symbols/seven.png',
'starburst-joker': '02-main-screen/symbols/wild.png',
'summer-wedge': '02-main-screen/symbols/watermelon.png',
'ten-idle': '05-auto-spin-setup/count_10_normal.png',
'ten-picked': '05-auto-spin-setup/count_10_selected.png',
'toggle-dim': '03-settings/switch-off.png',
'toggle-lit': '03-settings/switch-on.png',
'violet-ingot': '02-main-screen/symbols/bar.png',
'wager-down': '02-main-screen/ui/minus.png',
'wager-heading': '02-main-screen/ui/bet_label.png',
'wager-plaque': '02-main-screen/ui/bet_panel.png',
'wager-up': '02-main-screen/ui/plus.png',
'wallet-pill': '02-main-screen/ui/coin_bar.png',
'amber-numerals': '02-main-screen/font/golden-numbers.fnt',
'amber-glyph-atlas': '02-main-screen/font/golden-numbers.png',
};
const queueState = (queue: AutoSpinQueue) => ({ active: queue.active, remaining: queue.remaining });
function assertRejected(queue: AutoSpinQueue, action: () => void): void {
const before = queueState(queue);
assert.throws(action);
assert.deepEqual(queueState(queue), before, 'rejection must preserve the queue');
}
for (const count of [10, 25, 50, 100]) {
test(`automatic ${count}: consume includes the last zero and stays active until STOP`, () => {
const queue = new AutoSpinQueue();
assert.deepEqual(queueState(queue), { active: false, remaining: 0 });
assertRejected(queue, () => queue.consume());
queue.start(count);
assert.deepEqual(queueState(queue), { active: true, remaining: count });
for (let remaining = count - 1; remaining >= 0; remaining--) {
queue.consume();
assert.deepEqual(queueState(queue), { active: true, remaining });
for (const next of [10, 25, 50, 100]) assertRejected(queue, () => queue.start(next));
}
assertRejected(queue, () => queue.consume());
queue.stop();
assert.deepEqual(queueState(queue), { active: false, remaining: 0 });
assertRejected(queue, () => queue.consume());
queue.start(count);
assert.deepEqual(queueState(queue), { active: true, remaining: count });
});
}
test('invalid automatic counts reject without changing an idle or active queue', () => {
const queue = new AutoSpinQueue();
const invalid: unknown[] = [-100, -1, 0, 1, 9, 11, 24, 26, 49, 51, 99, 101, 10.5,
NaN, Infinity, -Infinity, '10', '25', null, undefined, true, {}, []];
for (const active of [false, true]) {
if (active) { queue.start(25); queue.consume(); }
for (const count of invalid) assertRejected(queue, () => queue.start(count as number));
}
});
test('STOP clears all future rounds immediately and is safe to repeat', () => {
for (const count of [10, 25, 50, 100]) {
for (const consumed of [0, 1, count - 1, count]) {
const queue = new AutoSpinQueue(); queue.start(count);
for (let index = 0; index < consumed; index++) queue.consume();
queue.stop();
assert.deepEqual(queueState(queue), { active: false, remaining: 0 });
assertRejected(queue, () => queue.consume());
queue.stop();
assert.deepEqual(queueState(queue), { active: false, remaining: 0 });
queue.start(10);
assert.deepEqual(queueState(queue), { active: true, remaining: 10 });
}
}
});
test('independent queue stays stopped through a simulated free-spin countdown and its end', () => {
// Simulate the caller stopping at the free trigger; this is not a view integration test.
for (const awarded of [8, 12, 16]) {
const queue = new AutoSpinQueue(); queue.start(100); queue.consume();
assert.equal(queue.remaining, 99);
queue.stop();
for (let freeRemaining = awarded; freeRemaining >= 0; freeRemaining--) {
assert.deepEqual(queueState(queue), { active: false, remaining: 0 });
assertRejected(queue, () => queue.consume());
}
assert.deepEqual(queueState(new AutoSpinQueue()), { active: false, remaining: 0 });
queue.start(25);
assert.deepEqual(queueState(queue), { active: true, remaining: 25 });
}
});
test('saved Canvas is 1080 by 1920 with automatic Widget alignment disabled', () => {
const canvas = node('Canvas');
assert.deepEqual(size(canvas), { width: 1080, height: 1920 });
assert.deepEqual(position(canvas), { x: 540, y: 960, z: 0 });
component(canvas, 'cc.Canvas');
const widget = component(canvas, 'cc.Widget');
assert.equal(widget._enabled, false);
assert.equal(widget._alignFlags, 0);
});
test('saved five masked reels have six cells each and exactly fifteen visible slot centres', () => {
const reels = nodes.filter(entry => /^ReelWindow\d+$/.test(entry._name));
assert.equal(reels.length, 5);
const visibleCentres: { x: number; y: number }[] = [];
for (let column = 0; column < 5; column++) {
const reel = node(`ReelWindow${column}`);
assert.equal(dereference(reel._parent), node('Canvas'));
assert.deepEqual(size(reel), { width: 200, height: 690 });
assert.deepEqual(position(reel), { x: -410 + column * 205, y: 145, z: 0 });
const mask = component(reel, 'cc.Mask');
assert.equal(mask._type, 0, 'rectangular clipping');
assert.equal(mask._inverted, false);
const cells = children(reel);
assert.deepEqual(cells.map(cell => cell._name).sort(), ['Cell0', 'Cell1', 'Cell2', 'Cell3', 'Cell4', 'Cell5']);
const anchor = component(reel, 'cc.UITransform')._anchorPoint;
assert.deepEqual({ x: anchor.x, y: anchor.y }, { x: .5, y: .5 });
let visible = 0;
for (let row = 0; row < 6; row++) {
const cell = cells.find(entry => entry._name === `Cell${row}`)!;
assert.equal(dereference(cell._parent), reel);
assert.deepEqual(position(cell), { x: 0, y: 230 - row * 230, z: 0 });
assert.ok(size(cell).width <= 198 + 1e-6 && size(cell).height <= 212 + 1e-6);
assert.ok(size(cell).width > 0 && size(cell).height > 0);
const source = frameFor(uuid(component(cell, 'cc.Sprite')._spriteFrame)).frame.userData;
assert.ok(Math.abs(size(cell).width / size(cell).height - source.rawWidth / source.rawHeight) < 1e-6);
assert.ok(Object.values(SYMBOL_ART).includes(spriteKey(cell)), 'cell uses a logical symbol frame');
const { x, y } = position(cell);
if (Math.abs(x) < 100 && Math.abs(y) < 345) {
visible++;
assert.ok(Math.abs(x) + size(cell).width / 2 <= 100);
assert.ok(Math.abs(y) + size(cell).height / 2 <= 345);
visibleCentres.push({ x: position(reel).x + x, y: position(reel).y + y });
}
}
assert.equal(visible, 3);
}
assert.deepEqual(visibleCentres, Array.from({ length: 5 }, (_, column) =>
[375, 145, -85].map(y => ({ x: -410 + column * 205, y }))).flat());
assert.equal(new Set(visibleCentres.map(value => `${value.x},${value.y}`)).size, 15);
});
test('all saved artFrames resolve to distinct orchard imports in runtime lookup order', () => {
const saved: Entry[] = controller().artFrames;
assert.equal(saved.length, 81);
assert.equal(ART_KEYS.length, 81);
const ids = saved.map(uuid);
assert.equal(new Set(ids).size, 81);
assert.deepEqual(ids, ART_KEYS.map(key => ART[key]));
assert.deepEqual(ids.map(id => parse(frameFor(id).path).name), ART_KEYS);
for (const entry of scene.filter(value => value.__type__ === 'cc.Sprite')) {
const id = uuid(entry._spriteFrame);
frameFor(id);
assert.ok(ids.includes(id), 'every saved sprite is backed by the bound runtime art set');
}
});
test('every imported image/font basename is renamed against its explicitly mapped source', () => {
const imported = assets.filter(asset => ['image', 'bitmap-font'].includes(asset.meta.importer));
assert.equal(imported.length, 83, '81 artwork images, one font atlas and one bitmap font');
assert.deepEqual(imported.map(asset => parse(asset.path).name).sort(), Object.keys(sourceByImport).sort());
for (const asset of imported) {
const name = parse(asset.path).name;
const source = sourceByImport[name];
assert.ok(source, `missing source mapping for ${name}`);
assert.notEqual(name.toLowerCase(), parse(source).name.toLowerCase(), `${name} must be renamed`);
assert.equal(extname(asset.path), extname(source));
assert.ok(statSync(asset.path).isFile(), `import exists: ${asset.path}`);
assert.ok(statSync(join('美术资源', source)).isFile(), `mapped source exists: ${source}`);
}
});
test('saved main amounts, counters and companion dialogs reference the renamed amber font', () => {
const font = assets.find(asset => asset.meta.uuid === uuid(controller().numerals));
assert.ok(font, 'saved numeral font resolves through orchard metadata');
assert.equal(font.meta.importer, 'bitmap-font');
assert.equal(basename(font.path), 'amber-numerals.fnt');
assert.equal(font.meta.uuid, FONT_UUID);
for (const name of ['NormalPrizeAmount', 'RoundsCount', 'RoundPrizeAmount', 'BonusPrizeAmount',
'WagerAmount', 'GiftAmount', 'BonusAwardCount', 'BonusSummaryAmount',
'GuideLineBet0', 'GuideLineBet1', 'GuideDailyAmount']) {
const label = component(node(name), 'cc.Label');
assert.equal(uuid(label._font), font.meta.uuid, name);
assert.equal(label._isSystemFontUsed, false, name);
}
for (const label of scene.filter(entry => entry.__type__ === 'cc.Label' && entry._font)) {
assert.equal(uuid(label._font), font.meta.uuid, 'no stale bitmap font reference');
}
const normalWallet = component(node('WalletAmount'), 'cc.Label');
assert.equal(normalWallet._isSystemFontUsed, true);
assert.equal(normalWallet._font, null, 'normal wallet must not use the gold bitmap font');
assert.deepEqual(normalWallet._color, { __type__: 'cc.Color', r: 255, g: 255, b: 255, a: 255 });
});
test('amber bitmap font page names an existing renamed atlas and defines all twelve glyphs', () => {
const font = assets.find(asset => asset.meta.uuid === uuid(controller().numerals));
assert.ok(font);
const text = readFileSync(font.path, 'utf8');
const pages = [...text.matchAll(/^page\s+id=(\d+)\s+file="([^"]+)"\s*$/gm)];
assert.equal(pages.length, 1);
assert.equal(pages[0][1], '0');
const atlasName = pages[0][2];
assert.equal(atlasName, 'amber-glyph-atlas.png');
const atlasPath = join(dirname(font.path), atlasName);
assert.ok(statSync(atlasPath).isFile());
const atlas = assets.find(asset => resolve(asset.path) === resolve(atlasPath));
assert.ok(atlas, 'atlas has orchard metadata');
assert.equal(font.meta.userData.textureUuid, atlas.meta.uuid);
const config = font.meta.userData._fntConfig;
assert.equal(config.atlasName, atlasName, 'imported font metadata agrees with the fnt page');
assert.match(text, /^chars\s+count=12\s*$/m);
const glyphs = [...text.matchAll(/^char\s+id=(\d+)\s+.*?\bpage=(\d+)\b/gm)];
const expected = [44, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
assert.deepEqual(glyphs.map(match => Number(match[1])).sort((a, b) => a - b), expected);
assert.ok(glyphs.every(match => match[2] === '0'));
assert.deepEqual(Object.keys(config.fontDefDictionary).map(Number).sort((a, b) => a - b), expected);
});
test('normal prize, rounds ribbon and bonus prizes are separate saved groups with correct art', () => {
const groups: Record<string, string[]> = {
NormalPrize: ['NormalPrizePlate', 'NormalPrizeTitle', 'NormalPrizeAmount'],
RoundsRibbon: ['RoundsPlate', 'RoundsHeading', 'RoundsCount', 'RoundsSuffix'],
BonusPrize: ['RoundPrizePlate', 'BonusPrizePlate', 'RoundPrizeAmount', 'BonusPrizeAmount'],
};
assert.equal(new Set(Object.keys(groups).map(name => node(name))).size, 3);
for (const [name, expected] of Object.entries(groups)) {
const group = node(name);
assert.equal(dereference(group._parent), node('Canvas'));
assert.deepEqual(children(group).map(child => child._name).sort(), expected.slice().sort());
for (const child of children(group)) assert.equal(dereference(child._parent), group);
}
for (const [name, key] of [
['NormalPrizePlate', 'prize-plaque'], ['NormalPrizeTitle', 'prize-heading'],
['RoundsPlate', 'rounds-ribbon'], ['RoundsHeading', 'bonus-heading'],
['RoundsSuffix', 'remaining-heading'], ['RoundPrizePlate', 'round-prize-card'],
['BonusPrizePlate', 'bonus-prize-card'], ['RepeatAccess', 'repeat-orb'],
]) assert.equal(spriteKey(node(name)), key, name);
for (const key of ['repeat-heading', 'bonus-heading']) {
const index = ART_KEYS.indexOf(key);
assert.ok(index >= 0);
const heading = frameFor(uuid(controller().artFrames[index]));
assert.equal(parse(heading.path).name, key);
assert.equal(heading.frame.userData.rawWidth, 354);
assert.equal(heading.frame.userData.rawHeight, 58);
}
assert.notEqual(ART['repeat-heading'], ART['bonus-heading']);
const automaticOrb = node('RepeatAccess');
assert.ok(![automaticOrb, ...descendants(automaticOrb)].some(owner =>
owner._components.map(dereference).some((entry: Entry) => entry.__type__ === 'cc.Label')),
'AUTO orb must not carry the remaining-count label');
assert.equal(dereference(node('RoundsCount')._parent), node('RoundsRibbon'));
const count = position(node('RoundsCount')), orb = position(automaticOrb);
assert.ok(Math.abs(count.x - orb.x) > (size(node('RoundsCount')).width + size(automaticOrb).width) / 2 ||
Math.abs(count.y - orb.y) > (size(node('RoundsCount')).height + size(automaticOrb).height) / 2,
'saved count must not overlap the AUTO orb');
});
test('eight independent saved modal groups share a full-screen input-blocking Shade', () => {
const layer = node('ModalLayer');
assert.equal(dereference(layer._parent), node('Canvas'));
const dialogs = ['RepeatDialog', 'PreferencesDialog', 'GiftDialog', 'EmptyWalletDialog',
'BonusAwardDialog', 'BonusSummaryDialog', 'GuideDialog', 'ErrorDialog'];
assert.deepEqual(children(layer).map(child => child._name).sort(), ['Shade', ...dialogs].sort());
assert.equal(children(layer)[0], node('Shade'), 'shade is behind all modal groups');
const owned = new Set<Entry>();
for (const name of dialogs) {
const dialog = node(name);
assert.equal(dereference(dialog._parent), layer);
assert.ok(children(dialog).length > 0, `${name} has its own controls`);
for (const entry of [dialog, ...descendants(dialog)]) {
assert.ok(!owned.has(entry), 'modal groups must not share or nest controls');
owned.add(entry);
}
}
const shade = node('Shade');
component(shade, 'cc.BlockInputEvents');
component(shade, 'cc.Graphics');
assert.equal(dereference(shade._parent), layer);
assert.ok(size(shade).width >= 1080 && size(shade).height >= 1920);
assert.deepEqual(position(shade), { x: 0, y: 0, z: 0 });
});
test('full reference composites are excluded from imported and saved runtime images', () => {
const references = ['02-main-screen', '03-settings', '05-auto-spin-setup',
'06-auto-spin-active', '06-free-coins-available', '07-free-coins-claimed',
'08-insufficient-coins', '10-free-spins-trigger', '11-free-spins-active',
'12-free-spins-result', 'layout-preview', '00-overview'];
const runtimeIds = new Set<string>(controller().artFrames.map(uuid));
for (const sprite of scene.filter(entry => entry.__type__ === 'cc.Sprite')) runtimeIds.add(uuid(sprite._spriteFrame));
for (const asset of assets.filter(entry => entry.meta.importer === 'image')) {
const key = parse(asset.path).name;
assert.ok(!references.includes(key), `reference composite imported: ${key}`);
const source = sourceByImport[key];
assert.ok(source);
assert.ok(!references.includes(parse(source).name), `reference composite mapped: ${source}`);
}
for (const id of runtimeIds) {
const image = frameFor(id);
const { rawWidth, rawHeight } = image.frame.userData;
if (rawWidth === 1080 && rawHeight === 1920) {
assert.equal(parse(image.path).name, 'berry-satin', 'only the isolated background may fill the screen');
assert.equal(sourceByImport['berry-satin'], '02-main-screen/ui/background.jpg');
}
}
});
test('all ordinary symbol frames are distinct from one another, SCATTER and WILD in saved help', () => {
assert.deepEqual(Object.keys(SYMBOL_ART).sort(), [...SYMBOLS].sort());
const savedFrames = new Set<string>(controller().artFrames.map(uuid));
const ids: string[] = [];
for (const symbol of SYMBOLS) {
const key = SYMBOL_ART[symbol];
const id = ART[key];
const saved = node(symbol === 'wild' ? 'GuideWildSymbol' : symbol === 'scatter' ? 'GuideScatterSymbol' : `GuideSymbol_${symbol}`);
assert.equal(uuid(component(saved, 'cc.Sprite')._spriteFrame), id, symbol);
assert.ok(savedFrames.has(id));
assert.equal(basename(dirname(frameFor(id).path)), 'emblems');
ids.push(id);
}
assert.equal(ids.length, 10);
assert.equal(new Set(ids).size, 10, 'eight ordinary symbols, SCATTER and WILD need separate frames');
});
+550
View File
@@ -1,6 +1,10 @@
import { test } from 'node:test';
import { strict as assert } from 'node:assert';
import { readFileSync, readdirSync } from 'node:fs';
import { transpileModule, ModuleKind, ScriptTarget } from 'typescript';
import { GuestLoginPresenter } from '../assets/login/scripts/GuestLoginPresenter';
import { GameRepository } from '../assets/orchard/scripts/GameRepository';
import { GameSession } from '../assets/orchard/scripts/GameSession';
import { StartupProgress } from '../assets/startup/scripts/StartupProgress';
test('waiting progress stays monotonic and below completion, even after long waits', () => {
@@ -70,4 +74,550 @@ test('loading binds the existing login without hiding its request-owning node',
const hidden = loading.loginControls.map((ref: Entry) => scene[ref.__id__]._name);
assert.ok(hidden.includes('GuestAccess')); assert.ok(hidden.includes('PrivacyLink'));
assert.ok(!hidden.includes('WelcomeComposition')); assert.ok(!hidden.includes('BrandMark'));
});
// Exercise the real adapters with tiny engine ports, without importing credentials or booting a scene.
function adapter<T>(file: string, imports: Record<string, unknown>): T {
const compiled = transpileModule(readFileSync(file, 'utf8'), {
compilerOptions: { module: ModuleKind.CommonJS, target: ScriptTarget.ES2020, experimentalDecorators: true },
});
const exports = {};
new Function('require', 'exports', compiled.outputText)((id: string) => {
assert.ok(Object.prototype.hasOwnProperty.call(imports, id), `Unexpected adapter import: ${id}`);
return imports[id];
}, exports);
return exports as T;
}
class TestNode {
active = true;
isValid = true;
private listeners = new Map<string, { callback: (...args: any[]) => void; target: unknown }[]>();
on(event: string, callback: (...args: any[]) => void, target: unknown): void {
this.listeners.set(event, [...(this.listeners.get(event) ?? []), { callback, target }]);
}
off(event: string, callback: (...args: any[]) => void, target: unknown): void {
this.listeners.set(event, (this.listeners.get(event) ?? []).filter(item => item.callback !== callback || item.target !== target));
}
emit(event: string, ...args: unknown[]): void {
for (const item of this.listeners.get(event) ?? []) item.callback.apply(item.target, args);
}
}
function pendingScene() {
let resolve!: (scene: any) => void;
let reject!: (error: Error) => void;
const promise = new Promise<any>((yes, no) => { resolve = yes; reject = no; });
return { promise, resolve, reject };
}
function loadingHarness() {
const pending = pendingScene();
const calls = { signIn: 0, prepare: 0, load: 0, clear: 0, launch: 0 };
let sceneRequest = pending.promise;
let transitionFailure: 'before' | 'after' | null = null;
const loaded = { scene: { getComponentInChildren: (name: string) => name === 'OrchardView' ? { enabled: true } : null } };
class TestComponent { node = new TestNode(); enabledInHierarchy = true; isValid = true; }
const engine = {
_decorator: { ccclass: () => (type: unknown) => type, property: (...args: unknown[]) => args.length > 1 ? undefined : () => {} },
Component: TestComponent, Node: TestNode, Button: { EventType: { CLICK: 'click' } },
Label: class {}, Sprite: class {}, SpriteFrame: class {}, SceneAsset: class {}, UITransform: class {},
director: { runSceneImmediate: () => {
calls.launch++;
if (transitionFailure === 'before') throw new Error('private transition error');
loading.onDisable(); Object.assign(loading, { isValid: false }); loading.onDestroy();
if (transitionFailure === 'after') throw new Error('private transition error');
} },
};
const { GuestLoginView: Login } = adapter<typeof import('../assets/login/scripts/GuestLoginView')>(
'assets/login/scripts/GuestLoginView.ts', {
cc: engine, './GuestLoginPresenter': { GuestLoginPresenter },
'./GuestRuntime': { createGuestLogin: () => ({ signIn: async () => {
calls.signIn++; return { guestId: identity, token: 'fixture-token', expires: 1 };
} }) },
});
const runtime = {
LOCK_IN_USE: 'This saved game is already open in another tab. Close it and tap the guest button to retry.',
LOCK_UNAVAILABLE: 'Exclusive saved game access is unavailable on this platform. Please use a supported browser and retry.',
session: null as GameSession | null,
prepareExclusive: async (id: string, signal?: AbortSignal): Promise<GameSession> => {
assert.equal(id, identity); calls.prepare++;
const session = {} as GameSession;
runtime.session = session;
signal?.addEventListener('abort', () => runtime.clear(session), { once: true });
return session;
},
loadScene: () => { calls.load++; return sceneRequest; },
clear: (expected?: GameSession) => {
if (expected && runtime.session !== expected) return;
runtime.session = null; calls.clear++;
},
};
const { StartupLoadingView: Loading } = adapter<typeof import('../assets/startup/scripts/StartupLoadingView')>(
'assets/startup/scripts/StartupLoadingView.ts', {
cc: engine, '../../login/scripts/GuestLoginView': { GuestLoginView: Login },
'../../orchard/scripts/OrchardRuntime': { OrchardRuntime: runtime }, './StartupProgress': { StartupProgress },
});
const login = new Login();
const button = { node: new TestNode(), interactable: true, isValid: true };
const status = { node: new TestNode(), string: '' };
login.guestButton = button as unknown as NonNullable<typeof login.guestButton>;
login.statusLabel = status as unknown as NonNullable<typeof login.statusLabel>;
const loading = new Loading();
const panel = new TestNode();
const percent = { string: '' };
loading.login = login;
loading.panel = panel as unknown as NonNullable<typeof loading.panel>;
loading.loginControls = [button.node, status.node] as unknown as typeof loading.loginControls;
loading.meter = { node: new TestNode(), getComponent: () => ({ setContentSize: () => {} }) } as unknown as NonNullable<typeof loading.meter>;
loading.percentage = percent as NonNullable<typeof loading.percentage>;
loading.caption = { string: '' } as NonNullable<typeof loading.caption>;
loading.onLoad(); login.onLoad(); loading.onEnable();
return { loading, login, calls, runtime, button, status, panel, percent, pending, loaded,
useScene: (request: Promise<any>) => { sceneRequest = request; },
failTransition: (when: 'before' | 'after') => { transitionFailure = when; } };
}
const identity = '0123456789abcdef0123456789abcdef';
const flush = async () => { for (let turn = 0; turn < 16; turn++) await Promise.resolve(); };
function finishLoading(view: { update(dt: number): void }): void {
for (let frame = 0; frame < 8; frame++) view.update(.1);
}
test('authenticated state waits for the credential-free success event and scene dependencies before 100%', async () => {
const h = loadingHarness();
assert.equal(h.panel.active, false);
let authenticatedState = false;
h.login.node.on('guest-login-state-changed', (state: { phase: string }) => {
if (state.phase === 'authenticated') {
authenticatedState = true;
assert.equal(h.calls.prepare, 0); assert.equal(h.login.guestId, null);
}
}, null);
h.button.node.emit('click');
h.loading.update(.1); h.loading.update(.1);
const waiting = Number.parseInt(h.percent.string);
await flush();
assert.equal(authenticatedState, true); assert.notEqual(h.percent.string, '100%');
assert.equal(h.login.guestId, identity);
assert.equal(h.calls.prepare, 1); assert.equal(h.calls.load, 1);
assert.ok(Number.parseInt(h.percent.string) >= waiting);
finishLoading(h.loading); assert.equal(h.calls.launch, 0);
h.pending.resolve(h.loaded); await flush();
h.loading.update(.1); h.loading.update(.1); h.loading.update(.1);
assert.equal(h.percent.string, '100%'); assert.equal(h.panel.active, true); assert.equal(h.calls.launch, 0);
h.loading.update(.1);
assert.equal(h.calls.launch, 1);
});
test('scene failure restores a usable guest button and retries preparation without authenticating again', async () => {
const h = loadingHarness();
h.button.node.emit('click'); await flush();
h.pending.reject(new Error('private loader details')); await flush();
assert.equal(h.panel.active, false); assert.equal(h.status.node.active, true);
assert.match(h.status.string, /tap the guest button to retry/);
assert.ok(!h.status.string.includes('private')); assert.equal(h.button.interactable, true);
h.useScene(Promise.resolve(h.loaded));
h.button.node.emit('click'); h.button.node.emit('click'); await flush();
finishLoading(h.loading);
assert.equal(h.calls.signIn, 1); assert.equal(h.calls.prepare, 2); assert.equal(h.calls.launch, 1);
});
test('storage failure is sanitized and the authenticated preparation can retry', async () => {
const h = loadingHarness();
h.runtime.prepareExclusive = async () => { throw new Error('private storage key'); };
h.button.node.emit('click'); await flush();
assert.equal(h.calls.load, 0); assert.equal(h.panel.active, false);
assert.match(h.status.string, /saved game has not been reset/); assert.ok(!h.status.string.includes('private'));
h.runtime.prepareExclusive = async () => { h.calls.prepare++; return {} as GameSession; };
h.useScene(Promise.resolve(h.loaded)); h.button.node.emit('click'); await flush();
finishLoading(h.loading);
assert.equal(h.calls.signIn, 1); assert.equal(h.calls.launch, 1);
});
test('disabled or destroyed loading ignores late scenes and an enabled authenticated view can resume', async () => {
for (const destroy of [false, true]) {
const h = loadingHarness(); h.button.node.emit('click'); await flush();
Object.assign(h.loading, { enabledInHierarchy: false }); h.loading.onDisable();
if (destroy) { Object.assign(h.loading, { isValid: false }); h.loading.onDestroy(); }
h.pending.resolve(h.loaded); await flush(); finishLoading(h.loading);
assert.equal(h.calls.launch, 0); assert.equal(h.panel.active, false);
if (!destroy) {
h.useScene(Promise.resolve(h.loaded)); Object.assign(h.loading, { enabledInHierarchy: true }); h.loading.onEnable(); await flush();
finishLoading(h.loading); assert.equal(h.calls.launch, 1); assert.equal(h.calls.signIn, 1);
}
}
});
test('missing game view is recoverable and pure authentication mode keeps the existing success display', async () => {
const h = loadingHarness();
h.useScene(Promise.resolve({ scene: { getComponentInChildren: () => null } }));
h.button.node.emit('click'); await flush(); finishLoading(h.loading);
assert.equal(h.calls.launch, 0); assert.equal(h.button.interactable, true);
const pure = loadingHarness(); pure.loading.transitionToGame = false;
let ready = 0; pure.loading.node.on('startup-preparation-ready', () => ready++, null);
pure.button.node.emit('click'); await flush(); finishLoading(pure.loading);
assert.equal(ready, 1); assert.equal(pure.calls.prepare, 0); assert.equal(pure.calls.launch, 0);
assert.equal(pure.status.string, 'Signed in successfully.'); assert.equal(pure.status.node.active, true);
});
test('local runtime isolates authenticated guests, refuses corrupt saves and uses all 32 random bits', () => {
const values = new Map<string, string>();
const storage = { getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); } };
const { OrchardRuntime: Runtime } = adapter<typeof import('../assets/orchard/scripts/OrchardRuntime')>(
'assets/orchard/scripts/OrchardRuntime.ts', {
cc: { sys: { localStorage: storage }, assetManager: {} }, './GameRepository': { GameRepository }, './GameSession': { GameSession },
'../../login/scripts/GuestRuntime': { GUEST_SERVICE: { origin: 'https://fixture.test/', product: 'Fixture' } },
});
const cryptoDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'crypto');
let bits = 0;
try {
Object.defineProperty(globalThis, 'crypto', { configurable: true, value: {
getRandomValues: (array: Uint32Array) => { array[0] = bits; return array; },
} });
assert.throws(() => Runtime.getSession(), /Sign in to continue\./);
assert.throws(() => Runtime.prepare(''), /Sign in to continue\./); assert.equal(values.size, 0);
const first = Runtime.prepare(identity); assert.equal(Runtime.getSession(), first);
const scope = `fruit-pop:game:v1:${encodeURIComponent(`https://fixture.test|Fixture|${identity}`)}`;
assert.deepEqual([...values.keys()], [scope]);
const injected = first as unknown as { random(): number };
assert.equal(injected.random(), 0); bits = 0xffffffff;
assert.equal(injected.random(), 0xffffffff / 0x100000000); assert.ok(injected.random() < 1);
first.setBet(5000); Runtime.clear();
assert.throws(() => Runtime.getSession(), /Sign in to continue\./);
assert.equal(Runtime.prepare(identity).state.bet, 5000);
assert.equal(Runtime.prepare('fedcba9876543210fedcba9876543210').state.bet, 2000);
values.set(scope, 'corrupt existing save');
assert.throws(() => Runtime.prepare(identity), /saved game has not been reset/);
assert.equal(values.get(scope), 'corrupt existing save'); assert.equal(Runtime.session, null);
Object.defineProperty(globalThis, 'crypto', { configurable: true, value: undefined });
assert.throws(() => Runtime.prepare(identity), /Secure game preparation is unavailable/);
assert.equal(values.get(scope), 'corrupt existing save');
} finally {
if (cryptoDescriptor) Object.defineProperty(globalThis, 'crypto', cryptoDescriptor);
else Reflect.deleteProperty(globalThis, 'crypto');
}
});
type Runtime = typeof import('../assets/orchard/scripts/OrchardRuntime').OrchardRuntime;
function exclusiveHarness() {
const navigatorDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'navigator');
const cryptoDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'crypto');
const values = new Map<string, string>();
const held = new Map<string, object>();
const reads: string[] = [];
const writes: string[] = [];
const requests: { name: string; options: LockOptions; deliver(): void; settled: boolean }[] = [];
const runtimes: Runtime[] = [];
let deferred = false;
const locks = {
request: (name: string, options: LockOptions, callback: (lock: Lock | null) => unknown): Promise<unknown> => {
return new Promise((resolve, reject) => {
let delivered = false;
const request = { name, options, settled: false, deliver: () => {
if (delivered) return;
delivered = true;
const owner = {};
const available = !held.has(name);
if (available) held.set(name, owner);
const finish = (): void => {
if (held.get(name) === owner) held.delete(name);
request.settled = true;
};
try {
const result = callback(available ? { name, mode: 'exclusive' } : null);
Promise.resolve(result).then(value => { finish(); resolve(value); }, error => { finish(); reject(error); });
} catch (error) { finish(); reject(error); }
} };
requests.push(request);
if (!deferred) queueMicrotask(request.deliver);
});
},
};
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: { locks } });
Object.defineProperty(globalThis, 'crypto', { configurable: true, value: {
getRandomValues: (array: Uint32Array) => { array.fill(0); return array; },
} });
const createRuntime = (): Runtime => {
const { OrchardRuntime } = adapter<{ OrchardRuntime: Runtime }>('assets/orchard/scripts/OrchardRuntime.ts', {
cc: { sys: { localStorage: {
getItem: (key: string) => { assert.ok(held.has(key), 'storage read before exclusive acquisition'); reads.push(key); return values.get(key) ?? null; },
setItem: (key: string, value: string) => { assert.ok(held.has(key), 'storage write without exclusive ownership'); writes.push(key); values.set(key, value); },
} }, assetManager: {} },
'./GameRepository': { GameRepository }, './GameSession': { GameSession },
'../../login/scripts/GuestRuntime': { GUEST_SERVICE: { origin: 'https://fixture.test/', product: 'Fixture' } },
});
runtimes.push(OrchardRuntime);
return OrchardRuntime;
};
return { values, held, reads, writes, requests, locks, createRuntime,
defer: () => { deferred = true; },
restore: async () => {
for (const runtime of runtimes) runtime.clear();
for (const request of requests) request.deliver();
await flush();
if (navigatorDescriptor) Object.defineProperty(globalThis, 'navigator', navigatorDescriptor);
else Reflect.deleteProperty(globalThis, 'navigator');
if (cryptoDescriptor) Object.defineProperty(globalThis, 'crypto', cryptoDescriptor);
else Reflect.deleteProperty(globalThis, 'crypto');
},
};
}
async function withExclusiveHarness(action: (h: ReturnType<typeof exclusiveHarness>) => Promise<void>): Promise<void> {
const harness = exclusiveHarness();
try { await action(harness); } finally { await harness.restore(); }
}
test('exclusive preparation denies another tab immediately without reading or writing its save', async () => {
await withExclusiveHarness(async h => {
const owner = h.createRuntime();
const contender = h.createRuntime();
const session = await owner.prepareExclusive(identity);
const scope = `fruit-pop:game:v1:${encodeURIComponent(`https://fixture.test|Fixture|${identity}`)}`;
assert.equal(h.requests[0].name, scope);
assert.deepEqual(h.requests[0].options, { mode: 'exclusive', ifAvailable: true });
assert.equal(h.requests[0].settled, false); assert.equal(h.held.size, 1);
const reads = h.reads.length; const writes = h.writes.length;
await assert.rejects(contender.prepareExclusive(identity), { message: contender.LOCK_IN_USE });
assert.equal(h.reads.length, reads); assert.equal(h.writes.length, writes);
assert.equal(contender.session, null); assert.equal(owner.getSession(), session);
session.setBet(5000); assert.equal(h.requests[0].settled, false);
owner.clear(); await flush();
assert.equal(h.requests[0].settled, true); assert.equal(h.held.size, 0);
const restored = await contender.prepareExclusive(identity);
assert.equal(restored.state.bet, 5000); assert.equal(restored.state.balance, 100_000);
assert.equal(h.writes.length, writes + 1);
});
});
test('unsupported browsers and lock service errors never touch saved data and can retry', async () => {
await withExclusiveHarness(async h => {
const runtime = h.createRuntime();
for (const navigator of [undefined, {}, { locks: {} }, { locks: { request: () => { throw new Error('private lock details'); } } },
{ locks: { request: () => Promise.reject(new Error('private lock details')) } }]) {
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: navigator });
await assert.rejects(runtime.prepareExclusive(identity), { message: runtime.LOCK_UNAVAILABLE });
assert.equal(runtime.session, null); assert.equal(h.reads.length, 0); assert.equal(h.writes.length, 0);
}
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: { locks: h.locks } });
await runtime.prepareExclusive(identity);
assert.equal(h.writes.length, 1);
});
});
test('same guest reuses its lifetime lock and rereads the stored session without granting again', async () => {
await withExclusiveHarness(async h => {
const runtime = h.createRuntime();
const first = await runtime.prepareExclusive(identity);
first.setBet(5000);
const reads = h.reads.length; const writes = h.writes.length;
const next = await runtime.prepareExclusive(identity);
assert.notEqual(next, first); assert.equal(next.state.bet, 5000);
assert.equal(h.requests.length, 1); assert.equal(h.requests[0].settled, false);
assert.ok(h.reads.length > reads); assert.equal(h.writes.length, writes);
runtime.clear(first); await flush();
assert.equal(runtime.getSession(), next); assert.equal(h.requests[0].settled, false);
});
});
test('switching guests releases only the old scope and invalid guests never write', async () => {
await withExclusiveHarness(async h => {
const runtime = h.createRuntime();
const old = await runtime.prepareExclusive(identity);
old.setBet(5000);
const other = await runtime.prepareExclusive('fedcba9876543210fedcba9876543210');
assert.equal(h.requests[0].settled, true); assert.equal(h.requests[1].settled, false);
assert.notEqual(h.requests[0].name, h.requests[1].name);
assert.equal(other.state.bet, 2000); assert.equal(h.held.size, 1);
runtime.clear(old); assert.equal(runtime.getSession(), other);
const writes = h.writes.length;
await assert.rejects(runtime.prepareExclusive(''), /Sign in to continue\./); await flush();
assert.equal(h.writes.length, writes); assert.equal(runtime.session, null); assert.equal(h.held.size, 0);
});
});
test('clear and cancellation settle a delayed acquisition without writing or clearing a newer lock', async () => {
for (const cancel of ['clear', 'abort'] as const) {
await withExclusiveHarness(async h => {
h.defer();
const runtime = h.createRuntime();
const controller = new AbortController();
const stale = runtime.prepareExclusive(identity, controller.signal);
const rejected = assert.rejects(stale, /cancelled/);
assert.equal(h.reads.length, 0); assert.equal(h.writes.length, 0);
if (cancel === 'clear') runtime.clear(); else controller.abort();
await rejected;
const current = runtime.prepareExclusive(identity);
h.requests[1].deliver(); const session = await current;
h.requests[0].deliver(); await flush();
assert.equal(runtime.getSession(), session); assert.equal(h.requests[1].settled, false);
assert.equal(h.writes.length, 1); assert.equal(h.held.size, 1);
runtime.clear(); runtime.clear(); await flush(); assert.equal(h.held.size, 0);
});
}
});
test('concurrent same-guest preparation shares one request and an obsolete abort cannot release the new owner', async () => {
await withExclusiveHarness(async h => {
h.defer();
const runtime = h.createRuntime();
const firstController = new AbortController();
const secondController = new AbortController();
const first = runtime.prepareExclusive(identity, firstController.signal);
const rejected = assert.rejects(first, /cancelled/);
const second = runtime.prepareExclusive(identity, secondController.signal);
firstController.abort();
assert.equal(h.requests.length, 1);
h.requests[0].deliver(); const session = await second; await rejected;
assert.equal(runtime.getSession(), session); assert.equal(h.writes.length, 1);
assert.equal(h.requests[0].settled, false);
secondController.abort(); await flush();
assert.equal(runtime.session, null); assert.equal(h.held.size, 0);
});
});
test('a late old-guest callback cannot prepare or release the current guest', async () => {
await withExclusiveHarness(async h => {
h.defer();
const runtime = h.createRuntime();
const stale = runtime.prepareExclusive(identity);
const rejected = assert.rejects(stale, /cancelled/);
const current = runtime.prepareExclusive('fedcba9876543210fedcba9876543210');
await rejected;
h.requests[1].deliver(); const session = await current;
h.requests[0].deliver(); await flush();
assert.equal(runtime.getSession(), session); assert.equal(h.writes.length, 1);
assert.equal(h.requests[0].settled, true); assert.equal(h.requests[1].settled, false);
});
});
test('cancellation between lock acquisition and restoration never reads or writes the old session', async () => {
await withExclusiveHarness(async h => {
h.defer();
const runtime = h.createRuntime();
const controller = new AbortController();
const stale = runtime.prepareExclusive(identity, controller.signal);
const rejected = assert.rejects(stale, /cancelled/);
h.requests[0].deliver();
controller.abort();
assert.equal(h.reads.length, 0); assert.equal(h.writes.length, 0);
const current = runtime.prepareExclusive('fedcba9876543210fedcba9876543210');
h.requests[1].deliver();
const session = await current; await rejected; await flush();
assert.equal(runtime.getSession(), session); assert.equal(h.writes.length, 1);
assert.equal(h.requests[0].settled, true); assert.equal(h.requests[1].settled, false);
});
});
test('cancelled callers and corrupt preparation never retain a lock or overwrite data', async () => {
await withExclusiveHarness(async h => {
const runtime = h.createRuntime();
const controller = new AbortController(); controller.abort();
await assert.rejects(runtime.prepareExclusive(identity, controller.signal), /cancelled/);
assert.equal(h.requests.length, 0); assert.equal(h.writes.length, 0);
const key = `fruit-pop:game:v1:${encodeURIComponent(`https://fixture.test|Fixture|${identity}`)}`;
h.values.set(key, 'corrupt existing save');
await assert.rejects(runtime.prepareExclusive(identity), /saved game has not been reset/); await flush();
assert.equal(h.values.get(key), 'corrupt existing save'); assert.equal(h.writes.length, 0);
assert.equal(h.requests[0].settled, true); assert.equal(h.held.size, 0);
assert.equal(runtime.session, null);
});
});
test('an immediate same-guest retry after clear reacquires and never overwrites the save', async () => {
await withExclusiveHarness(async h => {
const runtime = h.createRuntime();
const first = await runtime.prepareExclusive(identity); first.setBet(5000);
runtime.clear();
const second = await runtime.prepareExclusive(identity);
assert.equal(second.state.bet, 5000); assert.equal(h.writes.length, 2);
assert.equal(h.requests.length, 2); assert.equal(h.requests[0].settled, true);
assert.equal(h.requests[1].settled, false);
assert.equal(h.held.size, 1);
});
});
test('loading shows a fixed lock denial, retries without reauthentication and hands the session to the game', async () => {
const h = loadingHarness();
const prepare = h.runtime.prepareExclusive;
h.runtime.prepareExclusive = async () => { throw new Error(h.runtime.LOCK_IN_USE); };
h.button.node.emit('click'); await flush();
assert.equal(h.status.string, h.runtime.LOCK_IN_USE);
assert.equal(h.button.interactable, true); assert.equal(h.panel.active, false); assert.equal(h.calls.load, 0);
h.runtime.prepareExclusive = prepare;
h.useScene(Promise.resolve(h.loaded)); h.button.node.emit('click'); await flush();
const session = h.runtime.session;
assert.ok(session); finishLoading(h.loading);
assert.equal(h.calls.signIn, 1); assert.equal(h.calls.launch, 1);
assert.equal(h.calls.clear, 0); assert.equal(h.runtime.session, session);
});
test('loading releases failed scenes and destruction but successful scene handoff keeps the lock', async () => {
const failed = loadingHarness(); failed.button.node.emit('click'); await flush();
failed.pending.reject(new Error('private scene error')); await flush();
assert.equal(failed.runtime.session, null); assert.equal(failed.calls.clear, 1);
const missing = loadingHarness();
missing.useScene(Promise.resolve({ scene: { getComponentInChildren: () => null } }));
missing.button.node.emit('click'); await flush();
assert.equal(missing.runtime.session, null); assert.equal(missing.calls.clear, 1);
const cancelled = loadingHarness(); cancelled.button.node.emit('click'); await flush();
cancelled.loading.onDestroy(); assert.equal(cancelled.runtime.session, null); assert.equal(cancelled.calls.clear, 1);
const success = loadingHarness(); success.useScene(Promise.resolve(success.loaded));
success.button.node.emit('click'); await flush(); finishLoading(success.loading);
assert.equal(success.calls.launch, 1); assert.equal(success.calls.clear, 0);
});
test('failed scene handoff releases the session even if the old loading view has already been destroyed', async () => {
for (const when of ['before', 'after'] as const) {
const h = loadingHarness();
h.failTransition(when); h.useScene(Promise.resolve(h.loaded));
h.button.node.emit('click'); await flush(); finishLoading(h.loading);
assert.equal(h.calls.launch, 1); assert.equal(h.runtime.session, null); assert.equal(h.calls.clear, 1);
if (when === 'before') {
assert.equal(h.button.interactable, true); assert.equal(h.panel.active, false);
assert.match(h.status.string, /Unable to open the game/); assert.ok(!h.status.string.includes('private'));
}
}
});
test('loading ignores a late exclusive preparation without loading a scene or clearing a newer session', async () => {
const h = loadingHarness(); const late = pendingScene();
let signal: AbortSignal | undefined;
const prepare = h.runtime.prepareExclusive;
h.runtime.prepareExclusive = async (_id, cancellation) => { signal = cancellation; return late.promise; };
h.button.node.emit('click'); await flush();
Object.assign(h.loading, { enabledInHierarchy: false }); h.loading.onDisable();
assert.equal(signal?.aborted, true);
h.runtime.prepareExclusive = prepare; h.useScene(Promise.resolve(h.loaded));
Object.assign(h.loading, { enabledInHierarchy: true }); h.loading.onEnable(); await flush();
const current = h.runtime.session;
late.resolve({}); await flush(); finishLoading(h.loading);
assert.equal(h.calls.load, 1); assert.equal(h.calls.launch, 1);
assert.equal(h.runtime.session, current); assert.equal(h.calls.clear, 0);
});
test('a late scene failure after cancellation cannot release the resumed session', async () => {
const h = loadingHarness(); h.button.node.emit('click'); await flush();
const previous = h.runtime.session;
Object.assign(h.loading, { enabledInHierarchy: false }); h.loading.onDisable();
assert.equal(h.calls.clear, 1); assert.equal(h.runtime.session, null);
h.useScene(Promise.resolve(h.loaded));
Object.assign(h.loading, { enabledInHierarchy: true }); h.loading.onEnable(); await flush();
const current = h.runtime.session;
assert.notEqual(current, previous);
h.pending.reject(new Error('late old failure')); await flush(); finishLoading(h.loading);
assert.equal(h.runtime.session, current); assert.equal(h.calls.clear, 1); assert.equal(h.calls.launch, 1);
});
test('a late preparation rejection and login cancellation do not clear a newer preparation', async () => {
const h = loadingHarness(); const late = pendingScene();
let signal: AbortSignal | undefined;
const prepare = h.runtime.prepareExclusive;
h.runtime.prepareExclusive = async (_id, cancellation) => { signal = cancellation; return late.promise; };
h.button.node.emit('click'); await flush();
h.login.render({ phase: 'idle', message: '', enabled: true });
assert.equal(signal?.aborted, true); assert.equal(h.panel.active, false);
h.runtime.prepareExclusive = prepare; h.useScene(Promise.resolve(h.loaded));
Object.assign(h.loading, { enabledInHierarchy: false }); h.loading.onDisable();
Object.assign(h.loading, { enabledInHierarchy: true }); h.loading.onEnable(); await flush();
const current = h.runtime.session;
late.reject(new Error('private stale prepare error')); await flush(); finishLoading(h.loading);
assert.equal(h.calls.launch, 1); assert.equal(h.calls.clear, 0); assert.equal(h.runtime.session, current);
assert.ok(!h.status.string.includes('private'));
});