import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import vm from 'node:vm'; const moduleSource = await readFile( new URL('../public/cloud/vpc.js', import.meta.url), 'utf8', ); // The page module has one local UI import and one exported bootstrap function. // Remove only that module syntax, then expose the shipped helpers from the same // lexical scope. This keeps the assertions coupled to production behavior // without copying status projection logic into the test. const source = moduleSource .replace(/^import[^\n]+\n/u, '') .replace('export async function initialize()', 'async function initialize()') + `\n;globalThis.__vpcBehavior = { state, normalizeRoot, configurationReady, awaitingMembers, rootStatus, childStatus, statusPill, errorLabel, needsPolling, powerWorkflow, renderPowerWorkflow, handleDetailInput, createRegionOptions, hasPendingCreateIntent, openCreateModal, closeCreateModal, createVpc, saveEditor, cancelReadbacks, applyBootstrapPayload, };\n`; class Node { constructor() { this.children = []; this.attributes = new Map(); this.dataset = {}; this.className = ''; this.disabled = false; this.hidden = true; this.textContent = ''; this.title = ''; this.value = ''; this.isConnected = true; this.resetCount = 0; this.classList = { add() {}, remove() {} }; } append(...children) { this.children.push(...children); } get firstChild() { return this.children[0] || null; } replaceChildren(...children) { this.children = [...children]; } removeAttribute(name) { this.attributes.delete(name); if (name === 'title') this.title = ''; } reset() { this.resetCount += 1; } focus() { document.activeElement = this; } } class OptionNode extends Node { constructor(label, value, defaultSelected = false, selected = false) { super(); this.textContent = String(label); this.value = String(value); this.defaultSelected = defaultSelected; this.selected = selected; } } const ids = [ 'vpc-page-notice', 'vpc-page-error', 'vpc-create-region', 'vpc-create-open', 'vpc-create-submit', 'vpc-create-availability', 'vpc-create-region-hint', 'vpc-create-modal', 'vpc-create-form', 'vpc-create-name', 'vpc-create-close', 'vpc-create-cancel', 'vpc-create-error', ]; const nodes = Object.fromEntries(ids.map(id => [id, new Node()])); const document = { activeElement: null, body: new Node(), getElementById: id => nodes[id] || null, createElement: () => new Node(), }; let clearedTimers = 0; const context = { document, HTMLElement: Node, Option: OptionNode, clearTimeout() { clearedTimers += 1; }, console, globalThis: null, }; context.globalThis = context; vm.runInNewContext(source, context, { filename: 'vpc.js' }); const { state, normalizeRoot, configurationReady, awaitingMembers, rootStatus, childStatus, statusPill, errorLabel, needsPolling, powerWorkflow, renderPowerWorkflow, handleDetailInput, createRegionOptions, hasPendingCreateIntent, openCreateModal, closeCreateModal, createVpc, saveEditor, cancelReadbacks, applyBootstrapPayload, } = context.__vpcBehavior; assert.match(errorLabel('vpc_private_guest_restart_required'), /完全关机.*核对 \/ 重试.*写入.*启动.*来宾网络核验/u, 'A running first attachment must explain the complete stop/apply/start/verify sequence.'); assert.match(errorLabel('vpc_private_remove_requires_stopped'), /完全关机.*核对 \/ 重试.*移除.*IP.*保留/u, 'An installed private NIC must keep its address reserved while requesting a stopped cleanup.'); assert.match(errorLabel('vpc_private_guest_stopped'), /上次回读时.*关机.*开机后.*仍待核验/u, 'Stopped configuration proof must describe its observation, not the current power state.'); assert.doesNotMatch(errorLabel('vpc_private_guest_stopped'), /目前已关机|启动实例后/u, 'A completed automatic start must not leave an instruction to start the instance again.'); const stoppedBadge = statusPill(childStatus('stopped')); assert.equal(stoppedBadge.textContent, '回读时已关机'); assert.equal(stoppedBadge.className, 'vpc-state-pill stopped'); assert.equal(childStatus('unreviewed-remote-state'), 'unknown', 'Recognizing stopped evidence must not accept arbitrary upstream states.'); assert.match(errorLabel('vpc_private_guest_shutdown_pending'), /等待.*完全关机/u); assert.match(errorLabel('vpc_instance_operation_pending'), /实例详情.*核对任务/u); assert.match(errorLabel('vpc_private_guest_probe_permission_denied'), /权限策略.*私网路由.*管理员.*SELinux.*尚未确认可用/u); const deniedGuestProbe = normalizeRoot({ vpc_key: 'denied-guest-probe', state: 'degraded', sync_state: 'waiting', usable: false, member_count: 2, last_error_code: 'vpc_private_guest_probe_permission_denied', }); assert.equal(deniedGuestProbe.usable, false); assert.equal(deniedGuestProbe.last_error_code, 'vpc_private_guest_probe_permission_denied'); assert.equal(rootStatus(deniedGuestProbe), 'waiting'); assert.equal(errorLabel('unreviewed_remote_secret'), '', 'Unreviewed engine diagnostics must not become public page instructions.'); const workflowDocument = (phase, overrides = {}) => ({ vpc: { vpc_key: 'workflow-vpc', last_operation_id: 'current-operation', state: 'active', usable: true }, operations: [{ operation_id: 'current-operation', kind: 'member_attach', power_workflow: { phase, instance_id: 42, original_running: true, resume_cancelled: false, error_code: null, ...overrides } }], }); const nodeText = node => [node.textContent, ...node.children.map(nodeText)].join(' '); for (const [phase, label] of [ ['preflight', '准备自动处理'], ['shutting_down', '正在请求正常关机'], ['waiting_stopped', '等待实例完全关机'], ['applying', '正在写入私网配置'], ['configured', '私网配置已确认'], ['starting', '正在恢复开机'], ['paused', '自动流程已暂停'], ['completed', '自动流程已完成'], ]) { const doc = workflowDocument(phase); assert.equal(powerWorkflow(doc).title, label); assert.match(nodeText(renderPowerWorkflow(doc)), /实例 #42/u); state.selected = doc; state.vpcs = [doc.vpc]; assert.equal(needsPolling(), !['paused', 'completed'].includes(phase), 'A non-terminal power workflow must keep polling even after network readiness is projected.'); } const detaching = workflowDocument('applying'); detaching.operations[0].kind = 'member_detach'; assert.equal(powerWorkflow(detaching).title, '正在移除私网配置'); const paused = workflowDocument('paused', { error_code: 'vpc_power_shutdown_timeout', resume_cancelled: true, }); Object.assign(paused.vpc, { configured: false, usable: false, state: 'degraded', sync_state: 'waiting', }); state.selected = paused; state.vpcs = [paused.vpc]; assert.equal(rootStatus(paused.vpc), 'waiting'); assert.equal(needsPolling(), false, 'A paused pre-configuration workflow must wait for an explicit retry instead of polling forever.'); const pauseText = nodeText(renderPowerWorkflow(paused)); assert.match(pauseText, /关机等待超时.*未强制断电.*实例详情.*核对 \/ 重试/u); assert.match(pauseText, /手动电源操作.*不再自动恢复开机/u); assert.match(nodeText(renderPowerWorkflow(workflowDocument('paused', { error_code: 'vpc_power_start_timeout', }))), /启动命令已接受.*开机超时.*实例详情.*不会重复发送启动命令/u, 'Accepted start timeout must direct state verification without promising a replay.'); assert.match(nodeText(renderPowerWorkflow(workflowDocument('paused', { error_code: 'vpc_power_command_rejected', }))), /已确认未执行.*手动完成.*不会重新发送已失败的电源命令/u, 'A durable rejected child command must guide manual recovery, not promise a resend.'); assert.match(nodeText(renderPowerWorkflow(workflowDocument('paused', { error_code: 'vpc_power_configuration_unconfirmed', }))), /配置尚未完整确认.*自动流程已暂停.*管理员.*实例详情处理电源/u, 'Incomplete host proof must clearly disclose pause and the available power recovery path.'); for (const [code, guidance] of [ ['vpc_apply_coordination_busy', /协调资源.*占用.*自动流程已暂停.*管理员.*coordination claim.*数据库状态.*不要重复加入或退出/u], ['vpc_apply_coordination_uncertain', /协调结果未确认.*自动流程已暂停.*管理员.*原操作记录.*数据库状态.*不要重复加入或退出/u], ['vpc_apply_coordination_unavailable', /协调数据库暂不可用.*自动流程已暂停.*管理员.*数据库连接.*coordination claim.*核对原操作/u], ]) { assert.match(nodeText(renderPowerWorkflow(workflowDocument('paused', { error_code: code, }))), guidance, `${code} must direct administrators to coordination and database evidence.`); } assert.match(nodeText(renderPowerWorkflow(workflowDocument('completed', { original_running: false, }))), /原本已关机.*保持关机/u); const completedWithoutGuestProof = workflowDocument('completed'); Object.assign(completedWithoutGuestProof.vpc, { configured: true, usable: false, state: 'active', sync_state: 'applied', last_error_code: '', }); assert.equal(configurationReady(completedWithoutGuestProof.vpc), true); assert.equal(rootStatus(completedWithoutGuestProof.vpc), 'active', 'Guest health must not reopen an exact host-configuration receipt.'); assert.match(nodeText(renderPowerWorkflow(completedWithoutGuestProof)), /来宾网络可用性将单独核验/u); assert.match(errorLabel('vpc_private_guest_stopped'), /上次回读时.*仍待核验/u); state.selected = completedWithoutGuestProof; state.vpcs = [completedWithoutGuestProof.vpc]; assert.equal(needsPolling(), false, 'A completed config-exact operation must not poll forever for guest-only health.'); assert.equal(completedWithoutGuestProof.vpc.usable, false); for (const mutate of [ doc => { doc.vpc.last_operation_id = 'newer-operation'; }, doc => { doc.operations[0].kind = 'acl_replace'; }, doc => { doc.operations[0].power_workflow.phase = 'unknown-remote-phase'; }, doc => { delete doc.operations[0].power_workflow; }, ]) { const doc = workflowDocument('starting'); mutate(doc); assert.equal(powerWorkflow(doc), null, 'Legacy, stale and unknown workflow data must not project an automatic power action.'); assert.equal(renderPowerWorkflow(doc), null); } const untrustedFields = powerWorkflow(workflowDocument('paused', { error_code: 'remote-secret-error', original_running: 'false', resume_cancelled: 'true', })); assert.equal(untrustedFields.error, ''); assert.equal(untrustedFields.originalRunning, null); assert.equal(untrustedFields.resumeCancelled, false); state.selected = null; state.vpcs = []; // Known guest evidence remains actionable member guidance. It must not make a // config-exact root look pending or keep the root polling loop alive. const guestProbeGuidance = [ ['vpc_private_guest_agent_unavailable', /来宾代理.*实例已启动.*代理服务/u], ['vpc_private_guest_probe_unsupported', /来宾代理.*核验所需能力.*管理员.*尚未确认可用/u], ['vpc_private_guest_probe_uncertain', /结果未确认.*原探测记录.*不要重复加入/u], ['vpc_private_guest_probe_deadline_exceeded', /核验超时.*稍后核对.*管理员/u], ['vpc_private_guest_probe_reap_required', /尚未完成核销.*原探测记录.*不要重复加入/u], ['vpc_private_guest_address_mismatch', /私网地址.*不一致.*重新核对/u], ['vpc_private_guest_route_mismatch', /私网路由.*不一致.*重新核对/u], ['vpc_private_guest_link_mismatch', /私网网卡.*检查网卡状态.*重新核对/u], ]; for (const [code, guidance] of guestProbeGuidance) { assert.match(errorLabel(code), guidance, `${code} must show reviewed, actionable guidance instead of generic waiting.`); const pendingGuest = normalizeRoot({ vpc_key: 'guest-pending', state: 'active', sync_state: 'applied', configured: true, usable: false, member_count: 2, last_error_code: '', }); assert.equal(pendingGuest.last_error_code, ''); assert.equal(pendingGuest.usable, false, 'Rendering a specific guest diagnosis must not invent a readiness receipt.'); assert.equal(configurationReady(pendingGuest), true); assert.equal(awaitingMembers(pendingGuest), false); assert.equal(rootStatus(pendingGuest), 'active'); state.vpcs = [pendingGuest]; state.selected = null; assert.equal(needsPolling(), false, 'Guest-only health must not reopen automatic root reconciliation.'); } state.vpcs = []; assert.equal(errorLabel('vpc_private_guest_probe_unknown_unsafe_payload'), '', 'Unreviewed guest diagnostics must not bypass the public guidance whitelist.'); const emptyReservation = { state: 'applying', sync_state: 'applied', usable: false, setup_state: 'awaiting_members', member_count: 0, last_error_code: '', }; assert.equal(awaitingMembers(emptyReservation), true); assert.equal(rootStatus(emptyReservation), 'awaiting_members', 'A newly reserved VPC with no members is an actionable setup step, not a failure.'); for (const lastErrorCode of ['vpc_no_members', 'vpc_no_participating_hosts']) { const legacyReservation = { state: 'degraded', sync_state: 'failed', usable: false, last_error_code: lastErrorCode, }; assert.equal(rootStatus(legacyReservation), 'awaiting_members', `${lastErrorCode} must keep pre-projection rows usable as a neutral empty state.`); } const explicitUnsafeProjection = normalizeRoot({ state: 'degraded', sync_state: 'failed', usable: false, setup_state: null, member_count: 0, last_error_code: 'vpc_no_participating_hosts', }); assert.equal(rootStatus(explicitUnsafeProjection), 'degraded', 'Explicit null setup_state/member_count fields must let the server reject an unsafe empty ledger.'); assert.equal(rootStatus(normalizeRoot({ state: 'degraded', sync_state: 'failed', usable: false, last_error_code: 'vpc_no_participating_hosts', })), 'awaiting_members', 'Only a truly legacy projection may use the closed-set gate fallback.'); assert.equal(rootStatus({ state: 'degraded', sync_state: 'failed', usable: false, member_count: 0, last_error_code: 'vpc_host_apply_failed', }), 'degraded', 'A real host failure must not be hidden by an empty member count.'); assert.equal(rootStatus({ ...emptyReservation, state: 'deleting', sync_state: 'failed', last_error_code: 'vpc_no_participating_hosts', }), 'deleting', 'Deletion owns the root even when stale empty-state evidence remains.'); assert.equal(rootStatus({ ...emptyReservation, state: 'degraded', sync_state: 'failed', member_count: 1, }), 'degraded', 'A non-empty VPC must not consume stale awaiting-members projection.'); state.selected = null; state.vpcs = [{ vpc_key: 'empty', ...emptyReservation }]; assert.equal(Boolean(needsPolling()), false, 'An empty reservation is stable and must not enter the eight-second convergence loop.'); state.vpcs = [{ vpc_key: 'failed', state: 'degraded', sync_state: 'failed', usable: false, member_count: 1, last_error_code: 'vpc_host_apply_failed', }]; assert.equal(needsPolling(), true, 'A real degraded VPC remains in fast polling.'); state.vpcs = []; state.selected = null; assert.equal(needsPolling(), false); assert.equal(typeof needsPolling(), 'boolean', 'Polling projection must always return a boolean.'); function detailTarget(editor) { return { closest(selector) { assert.equal(selector, '#vpc-route-editor, #vpc-acl-editor'); return editor === 'route' || editor === 'acl' ? {} : null; }, matches() { return false; }, }; } state.detailDirty = false; handleDetailInput({ target: detailTarget('member') }); assert.equal(state.detailDirty, false, 'Member and other detail inputs must not pause polling as unsaved route/ACL edits.'); for (const editor of ['route', 'acl']) { state.detailDirty = false; nodes['vpc-page-notice'].hidden = true; handleDetailInput({ target: detailTarget(editor) }); assert.equal(state.detailDirty, true, `${editor} edits must mark the detail dirty.`); assert.equal(nodes['vpc-page-notice'].hidden, false); assert.match(nodes['vpc-page-notice'].textContent, /未保存修改/); } state.busy = false; state.regions = []; createRegionOptions(); assert.equal(nodes['vpc-create-region'].disabled, true); assert.equal(nodes['vpc-create-open'].disabled, true, 'Create must stay unavailable when the server exposes no Fabric-backed region.'); assert.equal(nodes['vpc-create-submit'].disabled, true); assert.equal(nodes['vpc-create-availability'].hidden, false); assert.match(nodes['vpc-create-region-hint'].textContent, /暂不能创建 VPC/); state.regions = [{ id: 7, name: 'Hong Kong' }]; createRegionOptions(); assert.equal(nodes['vpc-create-region'].disabled, false); assert.equal(nodes['vpc-create-open'].disabled, false); assert.equal(nodes['vpc-create-submit'].disabled, false); assert.equal(nodes['vpc-create-availability'].hidden, true); assert.deepEqual(nodes['vpc-create-region'].children.map(option => option.value), ['', '7']); const retryForm = nodes['vpc-create-form']; retryForm.dataset.requestKey = 'vpc-create-12345678'; retryForm.dataset.requestFingerprint = '{"name":"retry","region_id":7}'; assert.equal(hasPendingCreateIntent(retryForm), true); nodes['vpc-create-modal'].hidden = false; state.createFocusReturn = nodes['vpc-create-open']; closeCreateModal(); assert.equal(retryForm.dataset.requestKey, 'vpc-create-12345678', 'Closing the modal after an attempted create must preserve its idempotency key.'); const resetsBeforeRetry = retryForm.resetCount; openCreateModal(); assert.equal(retryForm.resetCount, resetsBeforeRetry, 'Reopening an ambiguous create must preserve its form intent for a safe retry.'); closeCreateModal(true, true); assert.equal(hasPendingCreateIntent(retryForm), false, 'Only an acknowledged success or explicit reset may clear the create intent.'); state.busy = false; state.regions = [{ id: 7, name: 'Hong Kong' }]; const invalidForm = { checkValidity: () => false, reportValidityCalled: false, reportValidity() { this.reportValidityCalled = true; }, }; const clearedBeforeInvalidSubmit = clearedTimers; await createVpc({ preventDefault() {}, currentTarget: invalidForm }); assert.equal(invalidForm.reportValidityCalled, true); assert.equal(clearedTimers, clearedBeforeInvalidSubmit, 'An invalid create form must not stop status polling.'); state.selectedKey = 'unsafe-empty'; state.selected = { vpc: normalizeRoot({ vpc_key: 'unsafe-empty', state: 'degraded', sync_state: 'failed', usable: false, setup_state: null, member_count: 0, last_error_code: 'vpc_no_participating_hosts', }), members: [] }; await saveEditor('routes'); assert.match(nodes['vpc-page-error'].textContent, /有可用成员后/, 'Every zero-member detail must reject policy saves, including explicit unsafe projections.'); let abortedReadbacks = 0; state.refreshEpoch = 2; state.bootstrapEpoch = 3; state.listEpoch = 4; state.detailEpoch = 5; state.bootstrapController = { abort() { abortedReadbacks += 1; } }; state.listController = { abort() { abortedReadbacks += 1; } }; state.detailController = { abort() { abortedReadbacks += 1; } }; cancelReadbacks(); assert.equal(abortedReadbacks, 3); assert.deepEqual([ state.refreshEpoch, state.bootstrapEpoch, state.listEpoch, state.detailEpoch, ], [3, 4, 5, 6], 'A mutation must invalidate every in-flight read generation.'); assert.equal(state.bootstrapController, null); assert.equal(state.listController, null); assert.equal(state.detailController, null); const token = 'a'.repeat(64); state.userId = ''; applyBootstrapPayload({ user: { user_id: '9', csrf_token: token }, regions: [{ id: 8, name: 'Singapore' }], instances: [{ id: 12, name: 'vm-12' }], }, false); assert.deepEqual(state.regions, [{ id: 8, name: 'Singapore' }]); assert.deepEqual(state.instances, [{ id: 12, name: 'vm-12' }]); console.log('Cloud VPC user-page projection, retry, policy-gate, polling and candidate-refresh behavior passed.');