ravenous_roll20/tests/test_worker.mjs

354 lines
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { test } from 'node:test';
import vm from 'node:vm';
const sheet = readFileSync(new URL('../build/ravenous.html', import.meta.url), 'utf8');
const script = sheet.match(/<script type="text\/worker">([\s\S]*?)<\/script>/)?.[1];
assert.ok(script, 'generated sheet worker exists; run ./scripts/build.sh first');
const generatedData = name => JSON.parse(sheet.match(new RegExp(`const ${name} = ([\\s\\S]*?);\\n`))?.[1]);
function worker(initial = {}) {
const attrs = { ...initial };
const handlers = new Map();
const rolls = [];
const queuedRolls = [];
let nextRow = 0;
const context = {
on(events, callback) {
for (const event of events.split(/\s+/)) {
if (!handlers.has(event)) handlers.set(event, []);
handlers.get(event).push(callback);
}
},
getAttrs(names, callback) {
callback(Object.fromEntries(names.map(name => [name, attrs[name]])));
},
setAttrs(values, options, callback) {
Object.assign(attrs, values);
(typeof options === 'function' ? options : callback)?.();
},
getSectionIDs(section, callback) {
const prefix = `repeating_${section}_`;
callback([...new Set(Object.keys(attrs).filter(key => key.startsWith(prefix))
.map(key => key.slice(prefix.length).split('_')[0]))]);
},
generateRowID: () => nextRow++ === 0 ? 'newrow' : `row${nextRow}`,
removeRepeatingRow(row) {
const prefix = row + '_';
for (const key of Object.keys(attrs)) if (key.startsWith(prefix)) delete attrs[key];
},
startRoll(command, callback) {
const queued = queuedRolls.shift();
assert.ok(queued, `No scripted result for ${command}`);
const roll = { command, rollId: queued.rollId, computed: undefined };
rolls.push(roll);
callback({ rollId: roll.rollId, results: Object.fromEntries(
Object.entries(queued.results).map(([name, result]) => [name, { result }])) });
},
finishRoll(rollId, computed) {
const roll = rolls.find(item => item.rollId === rollId);
assert.ok(roll);
roll.computed = computed;
},
};
vm.runInNewContext(script, context, { filename: 'ravenous-worker.js' });
const fire = (event, payload = {}) => {
for (const callback of handlers.get(event) || []) callback(payload);
};
const queueRoll = (rollId, results) => queuedRolls.push({ rollId, results });
return { attrs, fire, queueRoll, rolls };
}
test('opening the sheet recalculates base and temporary values', () => {
const { attrs, fire } = worker({ force: '3', force_manual: '2', agilite: '4', volonte: '2', stage: '3' });
fire('sheet:opened');
assert.equal(attrs.force_total, 5);
assert.equal(attrs.torque, 15); // Derived from permanent Force.
assert.equal(attrs.hp_limbs_max, 7);
assert.equal(attrs.hp_torso_max, 9);
assert.equal(attrs.toxicite_max, 11);
assert.equal(attrs.parade_total, 5); // Default Parade characteristic is Force.
});
test('theme selection is mirrored to the CSS state with a safe default', () => {
const sheetWorker = worker({ theme: 'steel' });
sheetWorker.fire('sheet:opened');
assert.equal(sheetWorker.attrs.theme_state, 'steel');
sheetWorker.attrs.theme = 'draan';
sheetWorker.fire('change:theme');
assert.equal(sheetWorker.attrs.theme_state, 'draan');
sheetWorker.attrs.theme = 'unknown-theme';
sheetWorker.fire('change:theme');
assert.equal(sheetWorker.attrs.theme, 'warm');
assert.equal(sheetWorker.attrs.theme_state, 'warm');
});
test('selected resistances and live protections update mitigation', () => {
const { attrs, fire } = worker({
force: '3', resist_fire: '2', damage_apply_fire: '1',
resist_slash: '1', damage_apply_slash: '1',
repeating_protections_a_active: '1', repeating_protections_a_integrity: '2', repeating_protections_a_protection: '4',
repeating_protections_b_active: '1', repeating_protections_b_integrity: '0', repeating_protections_b_protection: '9',
});
fire('sheet:opened');
assert.equal(attrs.damage_resistance_total, 3);
assert.equal(attrs.active_protection_total, 4);
assert.equal(attrs.active_first_protection, 4);
assert.equal(attrs.active_mitigation_total, 7);
fire('clicked:clear_damage_resistances');
assert.equal(attrs.damage_resistance_total, 0);
});
test('technique selector adds one row and rejects a duplicate', () => {
const [key, technique] = Object.entries(generatedData('TECHNIQUES'))[0];
const { attrs, fire } = worker({ technique_to_add: key });
fire('clicked:add_technique');
assert.equal(attrs.repeating_techniques_newrow_name, technique.name);
assert.equal(attrs.repeating_techniques_newrow_school, technique.school_label);
assert.equal(attrs.repeating_techniques_newrow_source_key, key);
fire('clicked:add_technique');
assert.match(attrs.technique_message, /déjà présente/);
});
test('opening the sheet capitalizes old imported school names without changing edits', () => {
const sheetWorker = worker({
repeating_techniques_old_source_key: 'artilleur:0',
repeating_techniques_old_school: 'artilleur',
repeating_techniques_edited_source_key: 'artilleur:1',
repeating_techniques_edited_school: 'École maison',
});
sheetWorker.fire('sheet:opened');
assert.equal(sheetWorker.attrs.repeating_techniques_old_school, 'Artilleur');
assert.equal(sheetWorker.attrs.repeating_techniques_edited_school, 'École maison');
});
test('skill roll reports a critical success and a threshold failure', () => {
const sheetWorker = worker({ force: '3', parade: '2', skill_die: '10', character_name: 'Test' });
sheetWorker.fire('sheet:opened');
sheetWorker.queueRoll('critical', { roll: 1 });
sheetWorker.fire('clicked:skill_parade');
assert.equal(sheetWorker.rolls[0].computed.outcome, 'Réussite critique');
assert.equal(sheetWorker.rolls[0].computed.margin, 4);
sheetWorker.queueRoll('failure', { roll: 5 });
sheetWorker.fire('clicked:skill_parade');
assert.equal(sheetWorker.rolls[1].computed.outcome, 'Échec');
sheetWorker.attrs.skill_die = '4';
sheetWorker.queueRoll('critical-failure', { roll: 4 });
sheetWorker.fire('clicked:skill_parade');
assert.match(sheetWorker.rolls[2].command, /1d4cs1cf4/);
assert.equal(sheetWorker.rolls[2].computed.outcome, 'Échec critique');
});
test('attack and defense cap remaining successes at RMax', () => {
const prefix = 'repeating_attacks_a_';
const sheetWorker = worker({
[prefix + 'name']: 'Test', [prefix + 'dice']: '5', [prefix + 'threshold']: '6',
[prefix + 'base_damage']: '4', [prefix + 'damage_per_success']: '2',
[prefix + 'break_damage']: '3', [prefix + 'rmax']: '2',
});
sheetWorker.queueRoll('attack1', { attack_roll: 4 });
sheetWorker.fire('clicked:repeating_attacks:attack', { sourceAttribute: prefix + 'attack' });
assert.equal(sheetWorker.rolls[0].computed.attack_successes, 4);
assert.match(sheetWorker.rolls[0].command, /\?\{Nombre de dés\|5\}d10/);
sheetWorker.queueRoll('defense1', { defense_roll: 1 });
sheetWorker.fire('clicked:repeating_attacks:defend', {
sourceAttribute: prefix + 'defend', originalRollId: 'attack1',
});
assert.equal(sheetWorker.rolls[1].computed.finalsuccesses, 2);
assert.equal(sheetWorker.rolls[1].computed.damage, 6);
assert.match(sheetWorker.rolls[1].command, /@\{target\|Défenseur\|character_name\}/);
assert.doesNotMatch(sheetWorker.rolls[1].command, /@\{selected\|/);
});
test('automatic attack successes work with dice enabled or disabled', () => {
const prefix = 'repeating_attacks_fixed_';
const sheetWorker = worker({
[prefix + 'name']: 'Fixe', [prefix + 'dice']: '4', [prefix + 'threshold']: '6',
[prefix + 'auto_successes']: '3', [prefix + 'roll_dice']: '1', [prefix + 'rmax']: '9',
});
sheetWorker.queueRoll('with-dice', { attack_roll: 2 });
sheetWorker.fire('clicked:repeating_attacks:attack', { sourceAttribute: prefix + 'attack' });
assert.equal(sheetWorker.rolls[0].computed.attack_successes, 5);
assert.match(sheetWorker.rolls[0].command, /\?\{Nombre de dés\|4\}d10/);
assert.match(sheetWorker.rolls[0].command, /\{\{autosuccesses=3\}\}/);
sheetWorker.attrs[prefix + 'roll_dice'] = '0';
sheetWorker.queueRoll('without-dice', { attack_roll: 0 });
sheetWorker.fire('clicked:repeating_attacks:attack', { sourceAttribute: prefix + 'attack' });
assert.equal(sheetWorker.rolls[1].computed.attack_successes, 3);
assert.doesNotMatch(sheetWorker.rolls[1].command, /\?\{Nombre de dés/);
assert.match(sheetWorker.rolls[1].command, /\{\{attack_roll=\[\[0\]\]\}\}/);
});
test('Subir reports damage and armor break after selected mitigation', () => {
const prefix = 'repeating_attacks_a_';
const sheetWorker = worker({
[prefix + 'name']: 'Test', [prefix + 'base_damage']: '8',
[prefix + 'damage_per_success']: '2', [prefix + 'break_damage']: '6',
[prefix + 'rmax']: '3',
});
// Roll20 resolves the defender's attribute references and query before the callback.
sheetWorker.queueRoll('damage1', { remaining: 2, selected_resistance: 1, location_protection: 70004 });
sheetWorker.fire('clicked:repeating_attacks:take_damage', { sourceAttribute: prefix + 'take_damage' });
assert.match(sheetWorker.rolls[0].command, /@\{target\|Défenseur\|damage_resistance_total\}/);
assert.doesNotMatch(sheetWorker.rolls[0].command, /@\{selected\|/);
assert.equal(sheetWorker.rolls[0].computed.incoming_damage, 10);
assert.equal(sheetWorker.rolls[0].computed.resistance_reduction, 2);
assert.equal(sheetWorker.rolls[0].computed.protection_reduction, 7);
assert.equal(sheetWorker.rolls[0].computed.damage, 1);
assert.equal(sheetWorker.rolls[0].computed.break_damage, 1);
});
test('origin stage picker adds its powers once and preserves custom rows', () => {
const origins = generatedData('ORIGINS');
const stagePowers = origins.dragon_1.powers.filter(power => power.stage === '1');
const sheetWorker = worker({
origin_key: 'dragon_1',
power_stage_to_add: '1',
repeating_powers_custom_name: 'Pouvoir maison',
repeating_powers_custom_description: 'Texte libre',
});
sheetWorker.fire('change:origin_key');
let keys = Object.keys(sheetWorker.attrs).filter(key => key.startsWith('repeating_powers_') && key.endsWith('_source_key'));
assert.equal(keys.length, 0);
assert.equal(sheetWorker.attrs.origin, 'Ür-Dragon, Maître des Cieux');
assert.equal(sheetWorker.attrs.repeating_powers_custom_name, 'Pouvoir maison');
sheetWorker.fire('clicked:add_power_stage');
keys = Object.keys(sheetWorker.attrs).filter(key => key.startsWith('repeating_powers_') && key.endsWith('_source_key'));
assert.equal(keys.length, stagePowers.length);
const firstKey = keys[0].replace(/_source_key$/, '');
assert.ok(sheetWorker.attrs[firstKey + '_name']);
assert.ok(sheetWorker.attrs[firstKey + '_stage']);
sheetWorker.fire('clicked:add_power_stage');
assert.match(sheetWorker.attrs.power_message, /déjà présents/);
assert.equal(Object.keys(sheetWorker.attrs).filter(key => key.startsWith('repeating_powers_') && key.endsWith('_source_key')).length, stagePowers.length);
sheetWorker.attrs.power_stage_to_add = '2';
sheetWorker.fire('clicked:add_power_stage');
assert.equal(Object.keys(sheetWorker.attrs).filter(key => key.startsWith('repeating_powers_') && key.endsWith('_source_key')).length,
stagePowers.length + origins.dragon_1.powers.filter(power => power.stage === '2').length);
sheetWorker.attrs.origin_key = 'dragon_2';
sheetWorker.fire('change:origin_key');
assert.equal(sheetWorker.attrs.repeating_powers_custom_name, 'Pouvoir maison');
assert.equal(Object.keys(sheetWorker.attrs).filter(key => key.startsWith('repeating_powers_') && key.endsWith('_source_key')).length,
stagePowers.length + origins.dragon_1.powers.filter(power => power.stage === '2').length);
});
test('start turn shows only active start reminders and leaves manual effects active', () => {
const sheetWorker = worker({
character_name: 'Ariane',
repeating_modifiers_start_active: '1',
repeating_modifiers_start_name: 'Régénération',
repeating_modifiers_start_duration_type: 'manual',
repeating_modifiers_start_start_reminder: 'Récupérez 3 PV.',
repeating_modifiers_start_end_reminder: 'Ne doit pas apparaître.',
repeating_modifiers_inactive_active: '0',
repeating_modifiers_inactive_name: 'Poison terminé',
repeating_modifiers_inactive_start_reminder: 'Ne doit pas apparaître non plus.',
});
sheetWorker.queueRoll('start-turn', {});
sheetWorker.fire('clicked:start_turn');
assert.equal(sheetWorker.rolls.length, 1);
assert.match(sheetWorker.rolls[0].command, /Début du tour/);
assert.match(sheetWorker.rolls[0].command, /Régénération/);
assert.match(sheetWorker.rolls[0].command, /Récupérez 3 PV/);
assert.doesNotMatch(sheetWorker.rolls[0].command, /Ne doit pas apparaître/);
assert.equal(sheetWorker.attrs.repeating_modifiers_start_active, '1');
});
test('an empty turn phase does not produce a chat card', () => {
const sheetWorker = worker({
repeating_modifiers_manual_active: '1',
repeating_modifiers_manual_name: 'Effet sans rappel',
repeating_modifiers_manual_duration_type: 'manual',
});
sheetWorker.fire('clicked:end_turn');
assert.equal(sheetWorker.rolls.length, 0);
assert.equal(sheetWorker.attrs.repeating_modifiers_manual_active, '1');
});
test('bulk removal deletes only inactive effects and reports the result', () => {
const sheetWorker = worker({
repeating_modifiers_active_active: '1', repeating_modifiers_active_name: 'Actif',
repeating_modifiers_old_active: '0', repeating_modifiers_old_name: 'Terminé',
});
sheetWorker.fire('clicked:removeinactiveeffects');
assert.equal(sheetWorker.attrs.repeating_modifiers_active_name, 'Actif');
assert.equal(sheetWorker.attrs.repeating_modifiers_old_name, undefined);
assert.equal(sheetWorker.attrs.effect_phase_message, '1 effet(s) inactif(s) supprimé(s).');
});
test('end turn decrements matching durations and reports reminders and expiration', () => {
const sheetWorker = worker({
repeating_modifiers_poison_active: '1',
repeating_modifiers_poison_name: 'Poison',
repeating_modifiers_poison_duration_type: 'turns',
repeating_modifiers_poison_remaining: '1',
repeating_modifiers_poison_countdown_phase: 'end',
repeating_modifiers_poison_end_reminder: 'Subissez 2 dégâts.',
repeating_modifiers_poison_removal_reminder: 'Le poison se dissipe.',
repeating_modifiers_aura_active: '1',
repeating_modifiers_aura_name: 'Aura',
repeating_modifiers_aura_duration_type: 'turns',
repeating_modifiers_aura_remaining: '2',
repeating_modifiers_aura_countdown_phase: 'start',
repeating_modifiers_aura_end_reminder: 'L’aura pulse.',
});
sheetWorker.queueRoll('end-turn', {});
sheetWorker.fire('clicked:end_turn');
assert.equal(sheetWorker.attrs.repeating_modifiers_poison_remaining, 0);
assert.equal(sheetWorker.attrs.repeating_modifiers_poison_active, '0');
assert.equal(sheetWorker.attrs.repeating_modifiers_aura_remaining, '2');
assert.equal(sheetWorker.attrs.repeating_modifiers_aura_active, '1');
assert.match(sheetWorker.rolls[0].command, /Fin du tour/);
assert.match(sheetWorker.rolls[0].command, /Subissez 2 dégâts/);
assert.match(sheetWorker.rolls[0].command, /Le poison se dissipe/);
assert.match(sheetWorker.rolls[0].command, /Poison/);
assert.match(sheetWorker.rolls[0].command, /L’aura pulse/);
});
test('applying a consumable copies its reminder configuration into an active effect', () => {
const prefix = 'repeating_consumables_potion_';
const sheetWorker = worker({
[prefix + 'name']: 'Élixir solaire',
[prefix + 'description']: 'Une chaleur bienfaisante.',
[prefix + 'duration']: '3 tours',
[prefix + 'duration_type']: 'turns',
[prefix + 'remaining']: '3',
[prefix + 'countdown_phase']: 'end',
[prefix + 'start_reminder']: 'Gagnez 1 Jauge.',
[prefix + 'end_reminder']: 'La lumière faiblit.',
[prefix + 'removal_reminder']: 'La lumière disparaît.',
});
sheetWorker.fire('clicked:repeating_consumables:applyeffect', {
sourceAttribute: prefix + 'applyeffect',
});
const effect = 'repeating_modifiers_newrow_';
assert.equal(sheetWorker.attrs[effect + 'active'], '1');
assert.equal(sheetWorker.attrs[effect + 'name'], 'Élixir solaire');
assert.equal(sheetWorker.attrs[effect + 'description'], 'Une chaleur bienfaisante.');
assert.equal(sheetWorker.attrs[effect + 'duration'], '3 tours');
assert.equal(sheetWorker.attrs[effect + 'duration_type'], 'turns');
assert.equal(sheetWorker.attrs[effect + 'remaining'], '3');
assert.equal(sheetWorker.attrs[effect + 'countdown_phase'], 'end');
assert.equal(sheetWorker.attrs[effect + 'start_reminder'], 'Gagnez 1 Jauge.');
assert.equal(sheetWorker.attrs[effect + 'end_reminder'], 'La lumière faiblit.');
assert.equal(sheetWorker.attrs[effect + 'removal_reminder'], 'La lumière disparaît.');
assert.equal(sheetWorker.attrs.consumable_message, 'Effet ajouté : Élixir solaire.');
});
test('a technique can be copied to a manual effect for reminder configuration', () => {
const source = 'repeating_techniques_tech_';
const sheetWorker = worker({ [source + 'name']: 'Danse ardente',
[source + 'effect']: 'Inflige des dégâts à la fin du tour.' });
sheetWorker.fire('clicked:repeating_techniques:trackeffect', {
sourceAttribute: source + 'trackeffect',
});
const effect = 'repeating_modifiers_newrow_';
assert.equal(sheetWorker.attrs[effect + 'active'], '1');
assert.equal(sheetWorker.attrs[effect + 'name'], 'Danse ardente');
assert.equal(sheetWorker.attrs[effect + 'description'], 'Inflige des dégâts à la fin du tour.');
assert.equal(sheetWorker.attrs[effect + 'duration_type'], 'manual');
assert.equal(sheetWorker.attrs.technique_message, 'Effet ajouté : Danse ardente.');
});