import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import vm from 'node:vm'; const source = await readFile(new URL('../public/cloud/invoices.js', import.meta.url), 'utf8'); const template = await readFile( new URL('../resources/views/venix/cloud/pages/invoices.tpl', import.meta.url), 'utf8', ); const tick = () => new Promise(resolve => setImmediate(resolve)); class Node { constructor(tag) { Object.assign(this, { tagName: tag.toUpperCase(), children: [], listeners: new Map(), attributes: new Map(), className: '', value: '', hidden: false, disabled: false, text: '', href: '', }); } set textContent(value) { this.text = String(value); this.replaceChildren(); } get textContent() { return this.text + this.children.map(child => child.textContent).join(''); } append(...children) { this.children.push(...children); } replaceChildren(...children) { this.children = [...children]; } setAttribute(name, value) { this.attributes.set(name, String(value)); } addEventListener(name, handler) { if (!this.listeners.has(name)) this.listeners.set(name, []); this.listeners.get(name).push(handler); } async fire(name) { const event = { target: this, currentTarget: this, defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, }; for (const handler of this.listeners.get(name) || []) await handler(event); await tick(); return event; } } const invoice = id => ({ id: String(id), purpose: 'renewal', title_key: 'billing.purpose.renewal', amount: '999.00', status: 'void', created_at: 1, renews_expires_at: 2_000_100_000, created_display: `服务端时间-${id}`, amount_display: `$10.0${id}`, status_key: `test.status.${id}`, status_class: 'warning', context_display: `服务端上下文-${id}`, context_segments: [ { kind: 'copy', key: 'billing.context.renewal_expiry' }, { kind: 'timestamp', value: 2_000_100_000 }, ], show_fulfillment: true, fulfillment_key: `test.fulfillment.${id}`, fulfillment_class: 'running', polling_required: false, }); const payload = (id, overrides = {}) => ({ invoices: [invoice(id)], purpose: 'all', filters: { purpose: 'all', status: 'all', keyword: '' }, pagination: { page: 1, per_page: 25, total: 1, total_pages: 1, has_previous: false, has_next: false, from: 1, to: 1 }, balance: '20.00', balance_display: '$20.00', ...overrides, }); const deferred = () => { let resolve; let reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; }; async function setup() { const nodes = new Map(); for (const match of template.matchAll(/<([a-z][a-z0-9]*)\b[^>]*\bid="([^"]+)"[^>]*>/g)) { nodes.set(match[2], new Node(match[1])); } nodes.set('cloud-page-error', new Node('p')); nodes.get('invoices-bootstrap').textContent = JSON.stringify(payload(1)); const documentEvents = new Map(); const windowEvents = new Map(); const document = { hidden: false, getElementById: id => nodes.get(id) || null, createElement: tag => new Node(tag), addEventListener: (name, handler) => documentEvents.set(name, handler), }; const location = new URL('https://panel.example.test/user/cloud/invoices'); location.assign = value => { location.href = new URL(value, location.href).href; }; const calls = []; let responder = () => Promise.reject(new Error('Unexpected invoice request')); const fetch = (url, options = {}) => { calls.push({ url, options }); return responder(url, options); }; const window = { setTimeout: () => 1, clearTimeout() {}, addEventListener: (name, handler) => windowEvents.set(name, handler), }; const history = { state: null, replaceState(_state, _title, next) { location.href = new URL(next, location.href).href; }, }; const copy = { text(key, parameters = {}) { if (key === 'billing.purpose.renewal') return '实例续费'; if (key === 'billing.context.renewal_expiry') return '对应实例到期 '; if (key === 'billing.list.invoice_meta') { return `账单 #${parameters.id} · ${parameters.time}`; } if (key === 'billing.list.detail') return '账单详情'; if (key === 'billing.list.amount') return '金额'; if (key === 'billing.list.empty') return '暂无账单。'; if (key === 'billing.pagination.label') { return `第 ${parameters.page} / ${parameters.pages} 页 · 共 ${parameters.total} 条`; } if (key === 'billing.value.time_missing') return '时间未记录'; if (key.startsWith('test.status.')) return `服务端状态-${key.split('.').at(-1)}`; if (key.startsWith('test.fulfillment.')) return `服务端履约-${key.split('.').at(-1)}`; return key; }, date(value) { return value.toLocaleString('zh-CN', { hour12: false }); }, }; const context = vm.createContext({ AbortController, URL, URLSearchParams, console, document, fetch, history, location, window, Date, Error, VenixUserCopy: copy, }); vm.runInContext( source.replace('export async function initialize()', 'async function initialize()') + '\nglobalThis.page = { initialize, state };', context, { filename: 'invoices.js' }, ); await context.page.initialize(); return { nodes, calls, location, state: context.page.state, respondWith(fn) { responder = fn; }, event(name, event = {}) { return windowEvents.get(name)?.(event); }, documentEvent(name) { return documentEvents.get(name)?.(); }, setHidden(value) { document.hidden = value === true; }, }; } const response = value => ({ ok: true, status: 200, json: async () => structuredClone(value) }); { const page = await setup(); assert.equal(page.calls.length, 0, 'SSR hydration repeated the initial invoice GET.'); const first = deferred(); const second = deferred(); page.respondWith((_url, options) => page.calls.length === 1 ? first.promise : second.promise); page.nodes.get('invoices-keyword-filter').value = 'first-vm'; await page.nodes.get('invoices-filter-form').fire('submit'); page.nodes.get('invoices-keyword-filter').value = 'second-vm'; await page.nodes.get('invoices-filter-form').fire('submit'); assert.equal(page.calls.length, 2, 'A newer filter was discarded while the first read was pending.'); assert.equal(page.calls[0].options.signal.aborted, true, 'A superseded invoice read was not aborted.'); second.resolve(response(payload(2, { balance: '999.00', balance_display: '20.00 EUR', filters: { purpose: 'all', status: 'all', keyword: 'second-vm' }, pagination: { page: 1, per_page: 25, total: 30, total_pages: 2, has_previous: false, has_next: true, from: 1, to: 25 }, }))); await tick(); await tick(); assert.equal(page.state.invoices[0].id, '2'); assert.match(page.location.search, /keyword=second-vm/); const rendered = page.nodes.get('invoices-list').textContent; assert.match(rendered, new RegExp(new Date(1000).toLocaleString( 'zh-CN', { hour12: false }, ).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), 'Invoice list did not format the canonical creation timestamp in the browser.'); assert.doesNotMatch(rendered, /服务端时间-2/, 'Invoice list retained the panel-time creation string.'); assert.match(rendered, /\$10\.02/, 'Invoice list ignored the server-rendered amount.'); assert.match(rendered, /服务端状态-2/, 'Invoice list reinterpreted the canonical invoice status.'); assert.match(rendered, /对应实例到期/, 'Invoice list ignored the server-owned context segments.'); assert.doesNotMatch(rendered, /服务端上下文-2/, 'Invoice list retained the panel-time context string.'); assert.match(rendered, /服务端履约-2/, 'Invoice list rebuilt its fulfillment state from raw task fields.'); assert.doesNotMatch(rendered, /\$999\.00/, 'Invoice list formatted the raw amount instead of consuming its presentation.'); assert.equal(page.nodes.get('invoices-balance').textContent, '20.00 EUR', 'Invoice list reformatted the raw wallet balance instead of consuming its presentation.'); first.resolve(response(payload(1, { filters: { purpose: 'all', status: 'all', keyword: 'first-vm' }, }))); await tick(); await tick(); assert.equal(page.state.invoices[0].id, '2', 'A stale invoice response overwrote the newest filter result.'); const next = deferred(); page.respondWith(() => next.promise); await page.nodes.get('invoices-next').fire('click'); assert.match(page.calls.at(-1).url, /page=2/); assert.match(page.calls.at(-1).url, /keyword=second-vm/); next.resolve(response(payload(3, { filters: { purpose: 'all', status: 'all', keyword: 'second-vm' }, pagination: { page: 2, per_page: 25, total: 30, total_pages: 2, has_previous: true, has_next: false, from: 26, to: 30 }, }))); await tick(); await tick(); assert.match(page.location.search, /page=2/); const backgroundRead = deferred(); page.respondWith(() => backgroundRead.promise); page.nodes.get('invoices-keyword-filter').value = 'background-safe'; await page.nodes.get('invoices-filter-form').fire('submit'); const backgroundCall = page.calls.at(-1); page.setHidden(true); page.documentEvent('visibilitychange'); assert.equal(backgroundCall.options.signal.aborted, false, 'Changing tab visibility cancelled a user-requested invoice filter.'); backgroundRead.resolve(response(payload(4, { filters: { purpose: 'all', status: 'all', keyword: 'background-safe' }, }))); await tick(); await tick(); assert.equal(page.state.invoices[0].id, '4', 'A valid filtered response was discarded only because the tab was hidden.'); page.setHidden(false); page.documentEvent('visibilitychange'); const failed = deferred(); page.respondWith(() => failed.promise); await page.nodes.get('invoices-refresh').fire('click'); failed.reject(new Error('temporary failure')); await tick(); await tick(); assert.equal(page.state.invoices[0].id, '4', 'A failed refresh erased the last confirmed invoice list.'); } console.log('Cloud invoice list hydration, filters and read-race checks passed.');