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/admin-host-inventory.js', import.meta.url), 'utf8'); class Node { constructor(tag = 'div') { this.tagName = tag.toUpperCase(); this.children = []; this.dataset = {}; this.attributes = new Map(); this.listeners = new Map(); this.hidden = false; this.disabled = false; this.isConnected = true; this.open = false; this.value = ''; this._text = ''; this.style = { setProperty() {}, removeProperty() {} }; const classes = new Set(); this.classList = { add: x => classes.add(x), remove: x => classes.delete(x) }; } set textContent(value) { this._text = String(value); this.children = []; } get textContent() { return this._text + this.children.map(item => item.textContent).join(''); } set innerHTML(_) { throw new Error('Never interpret diagnostic content as HTML.'); } get options() { return this.children; } append(...values) { this.children.push(...values); } add(option) { this.children.push(option); } replaceChildren(...values) { this._text = ''; this.children = values; } setAttribute(key, value) { this.attributes.set(key, String(value)); } addEventListener(key, handler) { const listeners = this.listeners.get(key) || []; listeners.push(handler); this.listeners.set(key, listeners); } dispatch(key, fields = {}) { const event = { target: this, button: 0, defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, ...fields }; for (const listener of this.listeners.get(key) || []) listener(event); } closest(selector) { return selector === '[data-inventory-detail]' && this.dataset.inventoryDetail ? this : null; } focus() {} getBoundingClientRect() { return { left: 0, right: 500, top: 0, bottom: 800 }; } } class Option extends Node { constructor(label, value) { super('option'); this.textContent = label; this.value = String(value); } } const flush = async () => { for (let i = 0; i < 20; i += 1) await Promise.resolve(); }; const firstId = 'a'.repeat(32); const secondId = 'b'.repeat(32); function attempt(id = firstId, changes = {}) { return { attempt_id: id, host_id: 7, host_name: '示例宿主机', source: 'manual', source_label: '管理员手动同步', started_at: 1234, finished_at: 1242, duration_ms: 8000, duration_is_final: true, outcome: 'timeout', outcome_label: '超时', stage: 'capacity_request', stage_label: '请求容量数据', error_code: 'engine_http_timeout', error_message: '超时;引擎阶段未确认', applied: false, timeout_ms: 8000, http_status: null, panel_version: 'inventory-v1', php_version: '8.5.0', generation: 1, stages: [], ...changes }; } function page(items = [attempt()], pageNumber = 1) { return { items, pagination: { page: pageNumber, per_page: 20, total: 21, total_pages: 2 }, filters: { host_id: '7', outcome: 'all', page: pageNumber, per_page: 20 }, hosts: [{ id: '7', name: '示例宿主机' }], summary: { last_attempt_at: 1234, last_success_at: 1230, last_failure_at: 1242, in_progress: 0, consecutive_failures: 1 } }; } function fixture(initial = page()) { const ids = [...source.matchAll(/byId\('([^']+)'\)/g)].map(match => match[1]); ids.push('inventory-previous', 'inventory-next', 'inventory-outcome', 'inventory-per-page', ...['last_attempt_at', 'last_success_at', 'last_failure_at'].map(key => `inventory-summary-${key}`)); const nodes = Object.fromEntries([...new Set(ids)].map(id => [id, new Node()])); nodes['admin-inventory-bootstrap'].textContent = JSON.stringify(initial); nodes['inventory-body'].textContent = 'SSR records'; nodes['inventory-filter'].elements = { namedItem: key => nodes[({ host_id: 'inventory-host', outcome: 'inventory-outcome', per_page: 'inventory-per-page' })[key]] }; const root = new Node(); const document = new Node(); document.documentElement = new Node(); document.body = new Node(); document.getElementById = id => nodes[id]; document.createElement = tag => new Node(tag); document.querySelector = selector => selector === '[data-admin-host-inventory]' ? root : null; const window = new Node(); window.scrollX = 0; window.scrollY = 100; window.scrollTo = () => {}; window.VenixDrawerMotion = { openDrawerWithMotion: dialog => { dialog.open = true; }, closeDrawerWithMotion: dialog => { dialog.open = false; return Promise.resolve(true); }, }; const location = { origin: 'https://example.test', href: 'https://example.test/admin/host-inventory?host_id=7' }; const history = { state: null, pushState(value, _, url) { this.state = value; location.href = String(url); } }; let now = 0; let lastTimer = 0; const timers = new Map(); const requests = []; const setTimeout = (callback, delay) => { const id = ++lastTimer; timers.set(id, { callback, due: now + delay }); return id; }; const fetch = (url, options) => new Promise((resolve, reject) => { requests.push({ url, options, resolve, reject, settled: false }); }); vm.runInNewContext(source, { document, window, location, history, URL, Node, Option, Date, AbortController, fetch, setTimeout, clearTimeout: id => timers.delete(id), console }, { filename: 'admin-host-inventory.js' }); return { nodes, root, window, requests, location, async click(id) { if (!nodes[id].disabled) nodes[id].dispatch('click'); await flush(); }, async open(id = firstId) { const button = new Node('button'); button.dataset.inventoryDetail = id; root.dispatch('click', { target: button }); await flush(); }, async respond(payload, request = requests.find(item => !item.settled), status = 200) { assert.ok(request); request.settled = true; request.resolve({ ok: status < 300, status, json: async () => payload }); await flush(); }, async advance(ms) { const end = now + ms; while (true) { const next = [...timers.entries()].filter(([, timer]) => timer.due <= end).sort((a, b) => a[1].due - b[1].due)[0]; if (!next) break; now = next[1].due; timers.delete(next[0]); next[1].callback(); await flush(); } now = end; await flush(); }, }; } // SSR and idle pages never trigger requests. Refresh reads only history, and // opening a detail does not retrieve engine evidence until the explicit click. { const test = fixture(); await test.advance(120000); assert.equal(test.requests.length, 0, 'The SSR page must not refetch or poll.'); assert.equal(test.nodes['inventory-body'].textContent, 'SSR records'); await test.click('inventory-refresh'); assert.equal(test.requests.length, 1); assert.match(test.requests[0].url, /^\/api\/v1\/admin\/host-inventory\?host_id=7$/); const unsafe = attempt(firstId, { host_name: '', error_message: '' }); await test.respond(page([unsafe])); assert.match(test.nodes['inventory-body'].textContent, /