#!/usr/bin/env node // ── Do core's own validators accept the event recipes? ───────────────────── // // `test/eventTemplates.test.js` runs against a FAKE core. It can say a recipe // builds the spec it means to; it cannot say core agrees, because the things core // would object to — a phase key's grammar, a step param that action no longer has, // a lease core cannot find, an input shape `registerEventTemplates` refuses — are // facts about core's code, not ours. A recipe core refuses is also worse than a // missing one: a template that fails `registerEventTemplates` fails the whole // module's load, and one whose `build()` returns a spec core rejects shows an // author "made a plan core cannot accept" for a form they filled in correctly. // // So this script puts the module through core's real loader and builds every // recipe through `buildFromTemplate`, which is the path the New event page takes: // inputs checked against the declaration, `build()` called, the spec run through // core's real `spec.validate` with this module's actions registered. // // It needs a core checkout with its server dependencies installed, and nothing // else: no database (the pool is pointed at a closed port, as core's own tests do // and for the same reason), no shard, no network except the one `npm ci` below. // // The module is COPIED to a temp directory as `uo`, never symlinked (core's loader // skips a link silently) and never installed over the checkout — a check that // rewrote the tree it was checking would be a strange thing to run locally. // `client/dist/entry.js` has to exist before the loader accepts the module at all; // CI builds it in the step before, and locally `npm run build --prefix client`. // // Usage: // node server/scripts/templateBuild.js --core --module const fs = require('fs') const os = require('os') const path = require('path') const { createRequire } = require('module') const { spawnSync } = require('child_process') // ── The fixtures ──────────────────────────────────────────────────────────── // // Every recipe, with and without its optional inputs, plus a few refusals, which // prove the author's sentence survives core's handling intact. An `expect` of // `'refused'` means core must answer `ok: false` with status 400 and the given // words in the first error; otherwise the build must come back `ok: true`, which // means the spec passed core's real validator. const FIXTURES = [ { template: 'uo.template.announce', label: 'text only', inputs: { text: 'The gates of Britain open at dusk. Gather at the bank.' }, }, { template: 'uo.template.announce', label: 'with colour and a news article', inputs: { text: 'The fair opens on Friday.', hue: 1153, newsTitle: 'The Britannian Midsummer Fair', newsMinutes: 2880 }, }, { template: 'uo.template.announce', label: 'news title, default length', inputs: { text: 'The fair opens on Friday.', newsTitle: 'The Fair' }, }, { template: 'uo.template.announce', label: 'a news length with no title is refused', inputs: { text: 'Hello', newsMinutes: 60 }, expect: 'refused', words: /news title/, }, { template: 'uo.template.boss_raid', label: 'required inputs only', inputs: { place: 'Felucca/Britain', creature: 'OrcCaptain', name: 'Gruk the Unbroken', minutes: 30 }, }, { template: 'uo.template.boss_raid', label: 'every input', inputs: { place: 'Felucca/Cities/Britain', creature: 'OrcCaptain', name: 'Gruk the Unbroken', minutes: 90, count: 3, strength: 2.5, message: 'Gruk and his warband march on Britain!', }, }, { template: 'uo.template.boss_raid', label: 'a count above the cap is refused', inputs: { place: 'Felucca/Britain', creature: 'OrcCaptain', name: 'Gruk', minutes: 30, count: 99 }, expect: 'refused', words: /bosses/, }, { template: 'uo.template.seasonal', label: 'required inputs only', inputs: { event: 'Fellowship', minutes: 180 }, }, { template: 'uo.template.seasonal', label: 'with a message, at the lease ceiling', inputs: { event: 'KrampusEncounter', minutes: 720, message: 'The Krampus has come to Britannia!' }, }, { template: 'uo.template.seasonal', label: 'an event the lease excludes is refused', inputs: { event: 'TreasuresOfTokuno', minutes: 60 }, expect: 'refused', words: /not a seasonal event/, }, { template: 'uo.template.gathering_giveaway', label: 'required inputs only', inputs: { place: 'Felucca/Britain', minutes: 30, item: 'gold' }, }, { template: 'uo.template.gathering_giveaway', label: 'every input', inputs: { place: 'Felucca/Cities/Britain', minutes: 45, item: 'gold', amount: 500, radius: 100, message: 'Come to Britain for a gift of gold!', }, }, { template: 'uo.template.gathering_giveaway', label: 'a non-stacking item, one each', inputs: { place: 'Felucca/Britain', minutes: 60, item: 'cloak' }, }, { template: 'uo.template.gathering_giveaway', label: 'a non-stacking item in quantity is refused', inputs: { place: 'Felucca/Britain', minutes: 60, item: 'cloak', amount: 5 }, expect: 'refused', words: /does not stack/, }, ] // ── Plumbing ──────────────────────────────────────────────────────────────── function parseArgs(argv) { const out = {} for (let i = 0; i < argv.length; i++) { if (argv[i] === '--core') out.core = argv[++i] else if (argv[i] === '--module') out.module = argv[++i] else throw new Error(`unknown argument "${argv[i]}"`) } if (!out.core || !out.module) { throw new Error('usage: node server/scripts/templateBuild.js --core --module ') } return { core: path.resolve(out.core), module: path.resolve(out.module) } } /** Copy the module as `/uo`, without `.git` or any `node_modules`, and install its production deps. */ function stageModule(moduleDir, tmpRoot) { const dest = path.join(tmpRoot, 'uo') fs.cpSync(moduleDir, dest, { recursive: true, filter: (src) => { const base = path.basename(src) return base !== '.git' && base !== 'node_modules' }, }) if (!fs.existsSync(path.join(dest, 'client', 'dist', 'entry.js'))) { throw new Error( `${path.join(moduleDir, 'client', 'dist', 'entry.js')} is missing — the loader refuses a module with no client chunk. ` + 'Build it first: npm run build --prefix client', ) } // What the release ships and CI installs: the production dependencies, from the // lockfile. One command string through a shell, because npm is a .cmd on Windows // and Node will not spawn one directly; the only path in it is our own temp dir. const install = spawnSync(`npm ci --omit=dev --no-audit --no-fund --prefix "${path.join(dest, 'server')}"`, { encoding: 'utf8', shell: true, }) if (install.status !== 0) { throw new Error(`npm ci in the staged module failed:\n${install.stdout || ''}${install.stderr || ''}`) } return dest } async function main() { const args = parseArgs(process.argv.slice(2)) const coreServer = path.join(args.core, 'server') if (!fs.existsSync(path.join(coreServer, 'node_modules'))) { throw new Error(`${coreServer}/node_modules is missing — run npm ci --prefix ${path.join(args.core, 'server')}`) } const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'uo-template-build-')) let exitCode = 1 let db = null try { stageModule(args.module, tmpRoot) // BEFORE core is required: the loader reads MODULES_DIR once, when its file is // evaluated, and the pool opens a connection lazily against whatever these say. // A closed port makes a stray query fail at once instead of hanging a check // that is meant to need no database. process.env.MODULES_DIR = tmpRoot process.env.DB_HOST = '127.0.0.1' process.env.DB_PORT = '59999' const coreRequire = createRequire(path.join(coreServer, 'package.json')) const express = coreRequire('express') db = coreRequire('./src/utils/db') const registries = coreRequire('./src/modules/registries') const loader = coreRequire('./src/modules/loader') const definitions = coreRequire('./src/model/events/eventDefinitions.model') // The module fills `admin.users.detail`, a slot core's own users router // declares as it is required (`registries.declareSlot`). Requiring that router // is what declares it for real, rather than this script claiming a slot exists. coreRequire('./src/router/v1/admin/users.router') // The same three tier routers core's own step-editor test hands the loader. loader.load({ public: express.Router(), admin: express.Router(), player: express.Router() }) const record = loader.list().find((m) => m.id === 'uo') if (!record || record.state !== 'registered') { throw new Error(`core did not register the module: ${record ? `${record.state} — ${record.reason}` : 'it was not found'}`) } // Core's own actions (`core.lease`, `core.wait`…) are what a recipe's spec may // name beside the module's, and they are registered separately from the scan. registries.registerCore() const catalog = registries.allEventTemplates().filter((t) => t.owner === 'uo') const registered = new Set(catalog.map((t) => t.id)) const covered = new Set(FIXTURES.map((f) => f.template)) let failures = 0 for (const id of registered) { if (!covered.has(id)) { failures++ console.log(`FAIL ${id} has no fixture in templateBuild.js`) } } for (const id of covered) { if (!registered.has(id)) { failures++ console.log(`FAIL ${id} is not registered by the module`) } } for (const fixture of FIXTURES) { const name = `${fixture.template} (${fixture.label})` let result try { result = await definitions.buildFromTemplate(fixture.template, fixture.inputs) } catch (err) { failures++ console.log(`FAIL ${name} threw: ${err.message}`) continue } if (fixture.expect === 'refused') { const said = (result.errors || [])[0] || '' if (result.ok === false && result.status === 400 && fixture.words.test(said)) { console.log(`OK ${name} refused: ${said}`) } else { failures++ console.log(`FAIL ${name} expected a 400 refusal matching ${fixture.words}, got ${JSON.stringify(result)}`) } continue } if (result.ok === true) { const phases = result.draft.spec.phases.map((p) => p.key).join(' > ') console.log(`OK ${name} "${result.draft.title}" [${phases}]`) } else { failures++ console.log(`FAIL ${name} status ${result.status}: ${(result.errors || []).join(' | ')}`) } } console.log(failures ? `\n${failures} failure(s)` : `\nAll ${FIXTURES.length} fixtures passed through core's registry and spec validator.`) exitCode = failures ? 1 : 0 } finally { // Close core's pool or the process hangs on it, then take the copy away. try { if (db && typeof db.close === 'function') await db.close() } catch { /* the pool never opened a connection; nothing to close */ } fs.rmSync(tmpRoot, { recursive: true, force: true }) } return exitCode } main().then( (code) => process.exit(code), (err) => { console.error(`templateBuild: ${err.message}`) process.exit(1) }, )