import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import vm from 'node:vm'; import { servicePaused } from '../public/cloud/instance-service.js'; const root = new URL('../', import.meta.url); const instances = readFileSync(new URL('public/cloud/instances.js', root), 'utf8'); const runtime = readFileSync(new URL('public/cloud/runtime.js', root), 'utf8'); const template = readFileSync( new URL('resources/views/venix/cloud/pages/instances.tpl', root), 'utf8', ); function section(source, start, end) { const offset = source.indexOf(start); assert.notEqual(offset, -1, `Missing source marker: ${start}`); const limit = source.indexOf(end, offset + start.length); assert.notEqual(limit, -1, `Missing source marker: ${end}`); return source.slice(offset, limit); } function evaluate(source, names, globals = {}) { const context = vm.createContext({ Date, ...globals }); vm.runInContext( `${source}\nglobalThis.__exports = { ${names.join(', ')} };`, context, ); return context.__exports; } const copy = new Map([ ['instances.state.paused', '已暂停'], ['instances.state.running', '运行中'], ['instance_detail.state.paused', '已暂停'], ['instance_detail.state.running', '运行中'], ]); const t = key => copy.get(key) ?? key; const listPresentation = evaluate( section(instances, 'function firstText(', 'function vmRegion('), ['stateDisplay', 'stateCategoryForVm'], { servicePaused, t }, ); const detailPresentation = evaluate( section(runtime, 'function localPowerMutation(', 'function renderVmDetail(') + section(runtime, 'function stateCategory(', 'function diskLabel('), ['detailStateDisplay'], { servicePaused, state: { powerMutation: null }, t }, ); const now = Math.floor(Date.now() / 1000); const expiredRunning = { state: 'running', state_fresh: true, state_sync_status: 'fresh', service_status: 'expired_grace', service_expires_at: now - 60, // Simulate a page that crossed its expiry between two status polls. The // browser must switch presentation from its timestamp even before refresh. service_paused: false, }; const activeRunning = { ...expiredRunning, service_status: 'active', service_expires_at: now + 3600, service_paused: false, }; const exemptRunning = { ...expiredRunning, service_status: 'exempt', service_paused: false, }; assert.equal(listPresentation.stateDisplay(expiredRunning).label, '已暂停'); assert.equal(listPresentation.stateDisplay(expiredRunning).category, 'other'); assert.equal(listPresentation.stateCategoryForVm(expiredRunning), 'other'); assert.equal(detailPresentation.detailStateDisplay(expiredRunning).label, '已暂停'); assert.equal(detailPresentation.detailStateDisplay(expiredRunning).category, 'other'); assert.equal(listPresentation.stateDisplay(activeRunning).label, '运行中'); assert.equal(detailPresentation.detailStateDisplay(activeRunning).label, '运行中'); assert.equal(listPresentation.stateDisplay(exemptRunning).label, '运行中'); assert.equal(detailPresentation.detailStateDisplay(exemptRunning).label, '运行中'); assert.match(template, /