167 lines
9.6 KiB
JavaScript
167 lines
9.6 KiB
JavaScript
/** Real Dice-Box / WASM / WebGL check, with no HTTP server or runtime network.
|
|
* `bun run sync:dice && bun run check:dice:browser`
|
|
* Install Chromium with `bun x playwright install chromium`, or set
|
|
* DICE_BROWSER_EXECUTABLE to an installed Chromium-based browser executable.
|
|
* This exercises desktop file:// support, not an Android WebView emulator.
|
|
*/
|
|
import { chromium } from 'playwright';
|
|
import { readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
|
|
import { resolve, dirname } from 'node:path';
|
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
import assert from 'node:assert/strict';
|
|
|
|
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
const assets = resolve(root, 'android/app/src/main/assets');
|
|
const output = resolve(process.env.DICE_QA_OUTPUT || resolve(root, 'android/dice-qa'));
|
|
mkdirSync(output, { recursive: true });
|
|
const harnessFile = resolve(assets, `.dice-qa-${process.pid}.html`);
|
|
const errors = [], requests = [], results = [];
|
|
const browser = await chromium.launch({
|
|
executablePath: process.env.DICE_BROWSER_EXECUTABLE || undefined,
|
|
headless: true,
|
|
args: ['--allow-file-access-from-files', '--enable-unsafe-swiftshader'],
|
|
});
|
|
try {
|
|
const page = await browser.newPage({ viewport: { width: 420, height: 480 }, deviceScaleFactor: 2 });
|
|
page.on('pageerror', error => errors.push(String(error)));
|
|
page.on('console', message => {
|
|
if (['error', 'warning'].includes(message.type())) errors.push(message.text());
|
|
});
|
|
page.on('requestfailed', request => errors.push(`${request.url()}: ${request.failure()?.errorText}`));
|
|
page.on('request', request => requests.push(request.url()));
|
|
await page.addInitScript(({ assetRoot }) => {
|
|
// Only map Android's virtual asset directory to the identical generated
|
|
// directory on desktop. Production fetch/Worker/WASM polyfills still run.
|
|
const open = XMLHttpRequest.prototype.open;
|
|
XMLHttpRequest.prototype.open = function (method, url, ...args) {
|
|
return open.call(this, method, String(url).replace('file:///android_asset', assetRoot), ...args);
|
|
};
|
|
window.messages = [];
|
|
window.completionCount = 0;
|
|
window.physicsCommands = {};
|
|
const post = MessagePort.prototype.postMessage;
|
|
MessagePort.prototype.postMessage = function (message, ...args) {
|
|
if (message?.action) window.physicsCommands[message.action] = (window.physicsCommands[message.action] || 0) + 1;
|
|
return post.call(this, message, ...args);
|
|
};
|
|
window.ReactNativeWebView = { postMessage: message => window.messages.push(JSON.parse(message)) };
|
|
}, { assetRoot: pathToFileURL(assets).href });
|
|
const html = readFileSync(resolve(assets, 'dice3d.html'), 'utf8').replace(
|
|
'<script src="./dice-bridge.js"></script>',
|
|
`<script>
|
|
const Original = DiceBoxModule.default;
|
|
window.boxes = [];
|
|
DiceBoxModule = {default: class extends Original {
|
|
constructor(options) {
|
|
super({...options, onRollComplete: result => { window.completionCount++; options.onRollComplete?.(result); }});
|
|
window.boxes.push(this);
|
|
}
|
|
}};
|
|
document.body.style.background = '#080b18';
|
|
</script><script src="./dice-bridge.js"></script>`,
|
|
);
|
|
writeFileSync(harnessFile, html);
|
|
await page.goto(pathToFileURL(harnessFile).href);
|
|
await page.waitForFunction(() => window.messages.some(message => message.type === 'READY'));
|
|
const send = (type, payload) => page.evaluate(({ type, payload }) => {
|
|
window.dispatchEvent(new MessageEvent('message', { data: JSON.stringify({ type, payload }) }));
|
|
}, { type, payload });
|
|
async function roll(theme, label, quality) {
|
|
const completedBefore = await page.evaluate(() => window.completionCount);
|
|
if (quality) await send('QUALITY', { level: quality });
|
|
await send('THEME', { theme });
|
|
await send('ROLL');
|
|
if (label === 'cosmic-high') {
|
|
await page.waitForTimeout(250);
|
|
await page.screenshot({ path: resolve(output, 'cosmic-rolling.png') });
|
|
}
|
|
await page.waitForFunction(count => window.messages.filter(message => message.type === 'ROLL_RESULT').length > count,
|
|
results.length, { timeout: 40000 });
|
|
await page.waitForFunction(() => window.boxes.at(-1).getVisualState()?.idle, null, { timeout: 10000 });
|
|
const result = await page.evaluate(() => ({
|
|
bridge: window.messages.filter(message => message.type === 'ROLL_RESULT').at(-1).payload.dice,
|
|
config: window.boxes.at(-1).config,
|
|
engine: window.boxes.at(-1).getRollResults(),
|
|
}));
|
|
results.push({ label, ...result });
|
|
const dice = result.engine.flatMap(group => group.rolls);
|
|
assert.equal(dice.length, 2, `${label}: expected two engine dice, not bridge fallback`);
|
|
assert.deepEqual(result.bridge, dice.map(die => die.value));
|
|
assert.ok(dice.every(die => Number.isInteger(die.value) && die.value >= 1 && die.value <= 6));
|
|
if (theme === 'cosmicBlackHole') {
|
|
const variant = { low: 'cosmicBlackHoleLow', medium: 'cosmicBlackHoleMedium', high: 'cosmicBlackHole' }[quality || 'high'];
|
|
assert.equal(result.config.theme, variant);
|
|
assert.ok(dice.every(die => die.theme === variant));
|
|
assert.ok(requests.some(url => url.includes(`/themes/${variant}/cosmic-black-hole.json`)), `${label}: model was not loaded`);
|
|
assert.ok(requests.some(url => url.includes(`/themes/${variant}/diffuse.png`)), `${label}: texture was not loaded`);
|
|
}
|
|
if (quality) assert.equal(result.config.scale, { low: 7.5, medium: 8.8, high: 10 }[quality]);
|
|
await page.screenshot({ path: resolve(output, `${label}.png`) });
|
|
const before = await page.evaluate(() => ({ visual: window.boxes.at(-1).getVisualState(),
|
|
commands: { ...window.physicsCommands }, completed: window.completionCount, messages: window.messages.length }));
|
|
const pixelsBefore = await page.screenshot();
|
|
await page.waitForTimeout(500);
|
|
const after = await page.evaluate(() => ({ visual: window.boxes.at(-1).getVisualState(),
|
|
commands: { ...window.physicsCommands }, completed: window.completionCount, messages: window.messages.length }));
|
|
const pixelsAfter = await page.screenshot({ path: resolve(output, `${label}-settled.png`) });
|
|
assert.deepEqual(after.visual.dice, before.visual.dice, 'Settled dice poses/geometry changed');
|
|
assert.ok(after.visual.dice.every(die => die.shaderReady), 'Shader is not ready');
|
|
assert.equal(after.visual.engineLoops, 0, 'Physics render loop still running');
|
|
assert.equal(after.completed, completedBefore + 1, 'Roll completion must happen once');
|
|
assert.equal(after.messages, before.messages, 'Duplicate bridge result while idle');
|
|
assert.deepEqual(after.commands, before.commands, 'Idle animation must not step or resume physics');
|
|
const animated = theme === 'cosmicBlackHole' && quality !== 'low';
|
|
if (animated) {
|
|
assert.ok(after.visual.frameId > before.visual.frameId, 'Animated theme stopped at rest');
|
|
assert.notDeepEqual(pixelsAfter, pixelsBefore, 'Animated pixels did not change');
|
|
} else {
|
|
assert.equal(after.visual.frameId, before.visual.frameId, 'Static theme wastes idle frames');
|
|
assert.deepEqual(pixelsAfter, pixelsBefore, 'Static theme pixels changed');
|
|
}
|
|
results.at(-1).idleValidation = { animated, frames: after.visual.frameId - before.visual.frameId, completionCount: after.completed };
|
|
if (quality === 'high') {
|
|
await send('VISIBILITY', { active: false });
|
|
const paused = await page.evaluate(() => window.boxes.at(-1).getVisualState());
|
|
await page.waitForTimeout(350);
|
|
const hidden = await page.evaluate(() => window.boxes.at(-1).getVisualState());
|
|
assert.equal(hidden.frameId, paused.frameId, 'Hidden WebView is still drawing');
|
|
assert.equal(hidden.seconds, paused.seconds, 'Hidden animation clock is advancing');
|
|
await send('VISIBILITY', { active: true });
|
|
await page.waitForFunction(frame => window.boxes.at(-1).getVisualState().frameId > frame, paused.frameId);
|
|
assert.ok(await page.evaluate(() => window.boxes.slice(0, -1).every(box => box.cosmicDisposed)), 'Old quality worlds were not disposed');
|
|
}
|
|
console.log(`${label}: ${result.bridge.join(', ')}`);
|
|
return result.bridge;
|
|
}
|
|
const facesSeen = new Set();
|
|
for (const quality of ['low', 'medium', 'high']) {
|
|
for (const value of await roll('cosmicBlackHole', `cosmic-${quality}`, quality)) facesSeen.add(value);
|
|
}
|
|
for (const theme of ['default', 'rust', 'blueGreenMetal', 'gemstone', 'gemstoneMarble', 'rock', 'wooden', 'smooth', 'smooth-pip', 'diceOfRolling']) {
|
|
await roll(theme, `existing-${theme}`);
|
|
}
|
|
// Re-enter every quality after third-party themes to catch stale shaders,
|
|
// cached model reuse and abandoned worker/render-loop errors.
|
|
for (const quality of ['low', 'medium', 'high']) {
|
|
for (const value of await roll('cosmicBlackHole', `cosmic-return-${quality}`, quality)) facesSeen.add(value);
|
|
}
|
|
// Exercise all six outcomes through real physics, without supplying values.
|
|
for (let i = 0; i < 24 && facesSeen.size < 6; i++) {
|
|
for (const value of await roll('cosmicBlackHole', `cosmic-faces-${i}`)) facesSeen.add(value);
|
|
}
|
|
assert.equal(facesSeen.size, 6, 'Did not observe all six values; rerun the random smoke check');
|
|
assert.deepEqual(errors, [], 'WebGL, worker, texture or file errors');
|
|
assert.ok(requests.every(url => /^(file:|blob:|data:)/.test(url)), 'Unexpected runtime network request');
|
|
for (const theme of ['cosmicBlackHoleLow', 'cosmicBlackHoleMedium', 'cosmicBlackHole']) {
|
|
for (const file of readdirSync(resolve(root, 'assets/dice-themes', theme))) {
|
|
assert.deepEqual(readFileSync(resolve(root, 'assets/dice-themes', theme, file)),
|
|
readFileSync(resolve(assets, 'dice-box/assets/themes', theme, file)));
|
|
}
|
|
}
|
|
console.log('PASS: both engine dice, all six outcomes, three qualities, all existing themes, local files only.');
|
|
} finally {
|
|
writeFileSync(resolve(output, 'browser-validation.json'), JSON.stringify({ results, errors, requests }, null, 2));
|
|
rmSync(harnessFile, { force: true });
|
|
await browser.close();
|
|
}
|