import assert from 'node:assert/strict'; import test from 'node:test'; import { getPageDeliveryContract, markPageDeliveryContractReady, normalizeDeliveryRelativePath, preparePageDeliveryContract, releaseMaterializedPageDeliveryContracts, } from './mindspace-delivery-contract.mjs'; test('normalizes only safe public HTML delivery paths', () => { assert.equal(normalizeDeliveryRelativePath('public/survey.html'), 'public/survey.html'); assert.equal(normalizeDeliveryRelativePath('/public/nested/report.html'), 'public/nested/report.html'); assert.equal(normalizeDeliveryRelativePath('public/../secret.html'), null); assert.equal(normalizeDeliveryRelativePath('public/report.js'), null); }); test('contract lifecycle writes preparing then ready against the same route key', async () => { const calls = []; const pool = { async query(sql, params) { calls.push({ sql, params }); if (sql.includes('SELECT id, data_mode')) return [[{ id: 'contract-1', data_mode: 'pg_required', status: 'preparing' }]]; if (sql.includes('UPDATE h5_page_delivery_contracts')) return [{ affectedRows: 1 }]; return [{ affectedRows: 1 }]; }, }; const contract = await preparePageDeliveryContract({ pool, userId: 'user-1', requestId: 'request-1', relativePath: 'public/form.html', pgRequired: true, }); assert.equal(contract.status, 'preparing'); assert.equal(contract.dataMode, 'pg_required'); const prepareCall = calls.find((call) => call.sql.includes('INSERT INTO h5_page_delivery_contracts')); assert.equal(prepareCall.params[4], 'pg_required'); const current = await getPageDeliveryContract({ pool, userId: 'user-1', relativePath: 'public/form.html' }); assert.equal(current.status, 'preparing'); assert.equal(await markPageDeliveryContractReady({ pool, userId: 'user-1', relativePath: 'public/form.html' }), true); assert.ok(calls.some((call) => call.sql.includes("status = 'ready'"))); }); test('releaseMaterializedPageDeliveryContracts skips pg_required until allowed', async () => { const calls = []; const pool = { async query(sql, params) { calls.push({ sql, params }); if (sql.includes('SELECT id, data_mode')) { const path = params?.[1]; if (path === 'public/form.html') { return [[{ id: 'c1', data_mode: 'pg_required', status: 'preparing' }]]; } if (path === 'public/report.html') { return [[{ id: 'c2', data_mode: 'static', status: 'preparing' }]]; } return [[]]; } if (sql.includes("status = 'ready'")) return [{ affectedRows: 1 }]; return [{ affectedRows: 0 }]; }, }; assert.deepEqual( await releaseMaterializedPageDeliveryContracts({ pool, userId: 'user-1', relativePaths: ['public/form.html', 'public/report.html'], allowPgRequired: false, }), ['public/report.html'], ); assert.deepEqual( await releaseMaterializedPageDeliveryContracts({ pool, userId: 'user-1', relativePaths: ['public/form.html'], allowPgRequired: true, }), ['public/form.html'], ); });