const assetVersion = new URL(import.meta.url).searchParams.get('v'); function versionedModuleUrl(path) { const url = new URL(path, import.meta.url); url.search = ''; if (assetVersion) url.searchParams.set('v', assetVersion); return url.href; } const [toastModule, taskObserver, instanceService] = await Promise.all([ import(versionedModuleUrl('./toast.js')), import(versionedModuleUrl('./task-observer.js')), import(versionedModuleUrl('./instance-service.js')), ]); const { toast } = toastModule; const { formatServiceDate, servicePaused, serviceTimestamp } = instanceService; const i18n = globalThis.VenixUserCopy; const t = (key, parameters = {}) => i18n.text(key, parameters); const { announceTaskAccepted, observeTask, resolvedTaskFailureNotice, taskSucceededWithoutRecovery, taskUrl, } = taskObserver; // PHP owns authentication, authorisation, ownership and purchasing. No Agent // address, token, host credential or unrestricted create API exists in this UI. const byId = (id) => document.getElementById(id); const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options) ?? Promise.resolve(false); const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], offers: [], regions: [], lines: [], linesEnabled: false, sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionId: '', selectedLineId: '', view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, reinstallPassword: '', reinstallPasswordDismissed: false, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, resourceController: null, mutationBusy: false, powerMutation: null, provisionIdempotency: '', provisionFingerprint: '', deployCloudSnapshotKey: '', deployCloudSnapshotName: '', deployBillingCycle: 'monthly', rescueActive: false, rescueStaged: false }; function vmPageText(detailKey, reinstallKey, parameters = {}) { return t(state.view === 'reinstall' ? reinstallKey : detailKey, parameters); } function safeRequestFailure(error) { const status = Number(error?.status); return t('common.error.request', { status: Number.isInteger(status) && status > 0 ? status : 0 }); } let vmStatusRequest = null; let vmStatusGeneration = 0; const activeTaskObservers = new Set(); // Keep the historical storage key so an interrupted deployment can still // reconcile to the same opening invoice. const PROVISION_INVOICE_STORAGE_PREFIX = 'virt-cloud:pending-order:'; const CLOUD_PATHS = Object.freeze({ instances: '/user/cloud/instances', deploy: '/user/cloud/deploy', backups: '/user/cloud/backups', keys: '/user/cloud/ssh-keys', invoices: '/user/cloud/invoices', }); const vmPagePath = (id, child = '') => `${CLOUD_PATHS.instances}/${encodeURIComponent(String(id))}${child ? `/${child}` : ''}`; const navigate = (path) => location.assign(path); const text = (id, value) => { byId(id).textContent = value ?? '—'; }; const items = (payload) => Array.isArray(payload) ? payload : Array.isArray(payload?.items) ? payload.items : Array.isArray(payload?.templates) ? payload.templates : Array.isArray(payload?.keys) ? payload.keys : Array.isArray(payload?.vms) ? payload.vms : []; function readBootstrap(id) { const source = byId(id); if (!source) return null; let payload; try { payload = JSON.parse(source.textContent || '{}'); } catch { throw new Error(t('common.error.bootstrap_invalid')); } if (!payload || typeof payload !== 'object' || Array.isArray(payload)) { throw new Error(t('common.error.bootstrap_missing')); } return payload; } function bootstrapItems(payload, ...names) { for (const name of names) if (Array.isArray(payload?.[name])) return payload[name]; return []; } function showError(id, message) { text(id, message); byId(id).hidden = !message; } async function copyText(value) { if (navigator.clipboard?.writeText) { try { await navigator.clipboard.writeText(value); return; } catch {} } const area = document.createElement('textarea'); area.value = value; area.style.position = 'fixed'; area.style.opacity = '0'; document.body.append(area); area.select(); try { if (!document.execCommand('copy')) throw new Error(t('common.error.copy')); } finally { area.value = ''; area.remove(); } } function requireSecureTransport() { if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) throw new Error(t('common.error.secure_transport')); } async function api(path, options = {}) { const expectedStatuses = options.expectedStatus === undefined ? null : (Array.isArray(options.expectedStatus) ? options.expectedStatus : [options.expectedStatus]); const requireTaskReceipt = options.requireTaskReceipt === true; const requestOptions = { ...options }; delete requestOptions.expectedStatus; delete requestOptions.requireTaskReceipt; const method = (options.method || 'GET').toUpperCase(); const headers = new Headers({ Accept: 'application/json', ...options.headers }); if (!['GET', 'HEAD'].includes(method)) { requireSecureTransport(); headers.set('X-CSRF-Token', state.csrfToken); if (options.body !== undefined) headers.set('Content-Type', 'application/json'); } const response = await fetch(path, { ...requestOptions, method, headers, credentials: 'same-origin', cache: 'no-store', body: options.body === undefined ? undefined : JSON.stringify(options.body) }); let payload = null; if (response.status !== 204) { try { payload = await response.json(); } catch { throw new Error(t('common.error.non_json')); } } if (response.status === 401) { clearCredential(); closeConsole(); location.assign('/auth/login'); throw new Error(t('common.error.login_expired')); } if (!response.ok || payload?.ret === 0) { const error = new Error(response.status === 422 ? t('common.error.invalid_input') : t('common.error.request', { status: response.status })); error.status = response.status; throw error; } if (expectedStatuses && !expectedStatuses.includes(response.status)) { const error = new Error(t('common.error.unexpected_status', { status: response.status })); error.status = response.status; error.mutationMayHaveApplied = true; throw error; } if (requireTaskReceipt && !taskUrl(payload)) { const error = new Error(t('common.error.task_receipt_invalid')); error.status = response.status; error.mutationMayHaveApplied = true; throw error; } return payload; } function normalizeVm(vm) { const legacyMutation = vm.can_mutate !== false; const canOperate = vm.can_operate === undefined ? legacyMutation : vm.can_operate === true; const canDelete = vm.can_delete === undefined ? legacyMutation : vm.can_delete === true; const canViewCredential = vm.can_view_credential !== false; return { ...vm, uuid: String(vm.uuid || vm.id || ''), api_id: String(vm.id || vm.uuid || ''), vcpu: vm.vcpu ?? vm.cpu_cores, memory_mib: vm.memory_mib, public_network_valid: vm.public_network_valid === true, public_ipv4: vm.public_network_valid === true ? String(vm.public_ipv4 || '') : '', public_ipv6: vm.public_network_valid === true ? String(vm.public_ipv6 || '') : '', can_operate: canOperate, can_delete: canDelete, can_view_credential: canViewCredential, password_available: canViewCredential && (vm.password_available === true || vm.has_initial_root_password === true) }; } function firstNumber(...values) { for (const value of values) { if (value === null || value === undefined || value === '') continue; const number = Number(value); if (Number.isFinite(number) && number >= 0) return number; } return null; } function firstText(...values) { for (const value of values) { if (value !== null && value !== undefined && String(value).trim() !== '') return String(value).trim(); } return ''; } function vmServiceData(vm) { const period = vm?.current_period && typeof vm.current_period === 'object' ? vm.current_period : vm?.service_period && typeof vm.service_period === 'object' ? vm.service_period : {}; const service = vm?.service && typeof vm.service === 'object' ? vm.service : period; const billing = vm?.billing && typeof vm.billing === 'object' ? vm.billing : {}; const traffic = vm?.traffic && typeof vm.traffic === 'object' ? vm.traffic : (service.traffic && typeof service.traffic === 'object' ? service.traffic : {}); const accountingMode = ['legacy', 'pooled', 'unlimited'].includes(String(vm?.traffic_accounting_mode || '')) ? String(vm.traffic_accounting_mode) : 'legacy'; const pool = vm?.traffic_pool && typeof vm.traffic_pool === 'object' ? vm.traffic_pool : {}; const projectionReady = accountingMode !== 'pooled' || pool.projection_ready === true; const trafficGib = firstNumber(vm?.traffic_gib, service.traffic_gib, period.traffic_gib, billing.traffic_gib); const quota = firstNumber(vm?.traffic_quota_bytes, service.traffic_quota_bytes, period.traffic_quota_bytes, billing.traffic_quota_bytes, traffic.quota_bytes, trafficGib === null ? null : trafficGib * 1024 ** 3); const rx = firstNumber(vm?.traffic_download_bytes, vm?.traffic_rx_bytes, vm?.download_rx_bytes, vm?.network_rx_total_bytes, service.traffic_download_bytes, service.traffic_rx_bytes, period.traffic_download_bytes, period.traffic_rx_bytes, traffic.rx_bytes, traffic.download_bytes); const tx = firstNumber(vm?.traffic_upload_bytes, vm?.traffic_tx_bytes, vm?.upload_tx_bytes, vm?.network_tx_total_bytes, service.traffic_upload_bytes, service.traffic_tx_bytes, period.traffic_upload_bytes, period.traffic_tx_bytes, traffic.tx_bytes, traffic.upload_bytes); const used = firstNumber(vm?.traffic_used_bytes, vm?.traffic_total_bytes, service.traffic_used_bytes, period.traffic_used_bytes, traffic.used_bytes, traffic.total_bytes, rx !== null && tx !== null ? rx + tx : null); const remaining = firstNumber(vm?.traffic_remaining_bytes, service.traffic_remaining_bytes, period.traffic_remaining_bytes, traffic.remaining_bytes, quota !== null && used !== null ? Math.max(0, quota - used) : null); const serviceExpiresAt = vm?.service_expires_at ?? vm?.expires_at ?? service.service_expires_at ?? service.expires_at ?? billing.expires_at ?? null; const status = firstText(vm?.service_status, service.status, period.status, billing.status, vm?.subscription_status); const networkStatus = firstText(vm?.network_status, service.network_status, period.network_status, traffic.network_status); const displayQuota = accountingMode === 'pooled' ? (projectionReady ? firstNumber(pool.active_entitlement_bytes) : null) : quota; const displayConsumed = accountingMode === 'pooled' ? (projectionReady ? firstNumber(pool.active_consumed_bytes) : null) : used; const displayRemaining = accountingMode === 'pooled' ? (projectionReady ? firstNumber(pool.available_bytes) : null) : remaining; return { quota: displayQuota, rx, tx, used, remaining: displayRemaining, progressUsed: displayConsumed, accountingMode, pool, projectionReady, serviceExpiresAt, status, networkStatus }; } function formatBytes(value) { if (value === null || !Number.isFinite(value) || value < 0) { return t('instance_detail.value.unavailable'); } return i18n.bytes(value); } function formatTrafficQuota(value) { return value === 0 ? t('instance_detail.value.unlimited_traffic') : formatBytes(value); } function serviceStatusInfo(data) { let status = data.status.toLowerCase().replace(/[\s-]+/g, '_'); if (!status && serviceTimestamp(data.serviceExpiresAt) !== null) status = serviceTimestamp(data.serviceExpiresAt) <= Date.now() ? 'expired' : 'active'; const labels = { active: ['active', 'active'], pending: ['pending', 'warning'], renewing: ['renewing', 'warning'], grace: ['grace', 'warning'], expired_grace: ['grace', 'warning'], grace_expired: ['grace', 'warning'], resume_pending: ['resume_pending', 'warning'], resuming: ['resuming', 'warning'], resume_failed: ['resume_failed', 'stopped'], suspending: ['suspending', 'warning'], suspending_expired: ['suspending_expired', 'warning'], suspended_expired: ['suspended_expired', 'stopped'], expired: ['expired', 'stopped'], suspend_failed: ['suspend_failed', 'stopped'], deletion_pending: ['deletion_pending', 'warning'], delete_pending: ['deletion_pending', 'warning'], deleting: ['deleting', 'warning'], deleting_expired: ['deleting', 'warning'], purge_pending: ['deletion_pending', 'warning'], purge_stopping: ['purge_stopping', 'warning'], purge_force_required: ['purge_force_required', 'stopped'], purge_deleting: ['deleting', 'warning'], purging: ['deleting', 'warning'], delete_failed: ['delete_failed', 'stopped'], purge_stop_failed: ['purge_stop_failed', 'stopped'], purge_failed: ['delete_failed', 'stopped'], suspended_traffic: ['suspended_traffic', 'stopped'], traffic_exhausted: ['traffic_exhausted', 'stopped'], exempt: ['exempt', 'active'], }; const [labelKey, className] = labels[status] || ['unknown', 'unknown']; return { label: t(`instance_detail.service.${labelKey}`), className }; } function networkStatusInfo(value) { const status = value.toLowerCase().replace(/[\s-]+/g, '_'); const labels = { active: ['active', 'active'], blocking: ['blocking', 'warning'], blocking_expired: ['blocking_expired', 'warning'], blocked_traffic: ['blocked_traffic', 'stopped'], blocked_expired: ['blocked_expired', 'stopped'], block_failed: ['block_failed', 'stopped'], restore_pending: ['restore_pending', 'warning'], restoring: ['restoring', 'warning'], expiry_block_failed: ['expiry_block_failed', 'stopped'], block_expired_failed: ['expiry_block_failed', 'stopped'], restore_failed: ['restore_failed', 'stopped'], configuration_invalid: ['configuration_invalid', 'stopped'], exempt: ['exempt', 'active'], }; const [labelKey, className] = labels[status] || ['unknown', 'unknown']; return { label: t(`instance_detail.network.${labelKey}`), className }; } function selectedVm() { return state.vms.find(vm => vm.uuid === state.selectedVmId); } function vmPath(vm = selectedVm()) { if (!vm) throw new Error(vmPageText('instance_detail.error.vm_unavailable', 'reinstall.error.vm_unavailable')); return `/api/v1/vms/${encodeURIComponent(vm.api_id)}`; } function clearCredential() { clearTimeout(state.credentialTimer); state.credentialPassword = ''; state.credentialVisible = false; if (byId('vm-detail-root-password')) text('vm-detail-root-password', '********'); byId('vm-detail-password-reveal')?.setAttribute('aria-pressed', 'false'); } const VM_DETAIL_TABS = ['operations', 'performance', 'operations-log', 'settings']; function setVmDetailTab(tab, focus = false) { const requested = tab === 'traffic' ? 'performance' : tab; const next = VM_DETAIL_TABS.includes(requested) ? requested : 'operations'; state.detailTab = next; for (const name of VM_DETAIL_TABS) { const button = byId(`vm-detail-tab-${name}`); const active = name === next; button.classList.toggle('active', active); button.setAttribute('aria-selected', String(active)); button.tabIndex = active ? 0 : -1; byId(`vm-detail-${name}-panel`).hidden = !active; } stopVmMetrics(); stopVmTrafficDaily(); if (state.view === 'detail') { if (next === 'performance') { startVmMetrics(); startVmTrafficDaily(); } } if (focus) byId(`vm-detail-tab-${next}`).focus(); } async function loadVms() { if (state.loadingVMs) return; state.loadingVMs = true; try { state.vms = items(await api('/api/v1/vms')).map(normalizeVm); showError('cloud-page-error', ''); if (byId('vm-table-body')) renderVMs(); const vm = selectedVm(); if (vm && state.view === 'detail') renderVmDetail(vm); else if (state.selectedVmId && !vm && ['detail', 'reinstall'].includes(state.view)) { throw new Error(vmPageText('instance_detail.error.vm_unavailable', 'reinstall.error.vm_unavailable')); } } catch (error) { showError('cloud-page-error', ['detail', 'reinstall'].includes(state.view) ? vmPageText('instance_detail.error.load', 'reinstall.error.load') : safeRequestFailure(error)); if (!state.vms.length && byId('vm-table-body')) renderVMs(true); } finally { state.loadingVMs = false; } } async function loadVm(apiId = selectedVm()?.api_id || document.body.dataset.vmId, raise = false) { const id = String(apiId || ''); if (!id) { const message = vmPageText('instance_detail.error.vm_id_missing', 'reinstall.error.vm_id_missing'); showError('cloud-page-error', message); if (raise) throw new Error(message); return null; } if (state.loadingVMs) return selectedVm() || null; state.loadingVMs = true; try { const vm = normalizeVm(await api(`/api/v1/vms/${encodeURIComponent(id)}`)); state.vms = [vm]; state.selectedVmId = vm.uuid; showError('cloud-page-error', ''); if (state.view === 'detail') renderVmDetail(vm); return vm; } catch (error) { showError('cloud-page-error', vmPageText('instance_detail.error.load', 'reinstall.error.load')); if (raise) throw error; return null; } finally { state.loadingVMs = false; } } function applyCloudUser(user = {}) { state.csrfToken = String(user.csrf_token || ''); if (!state.csrfToken) throw new Error(t('common.error.login_expired')); state.userId = String(user.user_id || ''); if (!/^\d+$/.test(state.userId)) throw new Error(t('common.error.login_expired')); state.username = user.username || user.user_name || user.email || t('common.shell.account.fallback'); state.admin = user.admin === true || user.is_admin === true || Number(user.is_admin) === 1; if (byId('current-username')) text('current-username', state.username); for (const id of ['cloud-admin-link', 'cloud-admin-menu-link']) { const link = byId(id); if (link) link.hidden = !state.admin; } } function hydrateVmDetailBootstrap(payload) { if (!payload || typeof payload !== 'object' || !payload.vm || typeof payload.vm !== 'object') { throw new Error(t('instance_detail.error.vm_data_invalid')); } state.view = 'detail'; applyCloudUser(payload.user || {}); const vm = normalizeVm(payload.vm); if (!vm.api_id || !vm.uuid) throw new Error(t('instance_detail.error.vm_id_missing')); state.vms = [vm]; state.selectedVmId = vm.uuid; return vm; } async function settleVmStatusRequest(promise, raise) { try { return await promise; } catch (error) { if (error?.name === 'AbortError') return null; showError('cloud-page-error', vmPageText('instance_detail.error.status_load', 'reinstall.error.load')); if (raise) throw error; return null; } } async function loadVmStatus(apiId = selectedVm()?.api_id || document.body.dataset.vmId, options = {}) { const settings = typeof options === 'boolean' ? { raise: options } : (options || {}); const raise = settings.raise === true; const live = settings.live === true; const force = settings.force === true; const id = String(apiId || ''); if (!id) { const message = vmPageText('instance_detail.error.vm_id_missing', 'reinstall.error.vm_id_missing'); showError('cloud-page-error', message); if (raise) throw new Error(message); return null; } const active = vmStatusRequest; if (active && active.apiId === id && !force && (!live || active.live)) { return settleVmStatusRequest(active.promise, raise); } active?.controller.abort(); const controller = new AbortController(); const generation = ++vmStatusGeneration; const request = { apiId: id, live, controller, promise: null }; request.promise = (async () => { try { const liveQuery = live ? '?live=1' : ''; const payload = await api(`/api/v1/vms/${encodeURIComponent(id)}/status${liveQuery}`, { signal: controller.signal }); if (controller.signal.aborted || generation !== vmStatusGeneration) return null; const current = selectedVm(); if (!current) throw new Error(vmPageText('instance_detail.error.vm_data_invalid', 'reinstall.error.vm_data_invalid')); if (String(current.api_id) !== id) return null; const update = payload?.vm && typeof payload.vm === 'object' ? payload.vm : payload; if (!update || typeof update !== 'object') throw new Error(vmPageText('instance_detail.error.vm_data_invalid', 'reinstall.error.vm_data_invalid')); const vm = normalizeVm({ ...current, ...update, id: current.api_id, uuid: current.uuid }); state.vms = [vm]; state.selectedVmId = vm.uuid; showError('cloud-page-error', ''); if (state.view === 'detail') renderVmDetail(vm); return vm; } catch (error) { // Superseded requests must be silent even when fetch had already // produced a non-abort error before the newer request took ownership. if (controller.signal.aborted || generation !== vmStatusGeneration) return null; throw error; } finally { if (vmStatusRequest === request) vmStatusRequest = null; } })(); vmStatusRequest = request; return settleVmStatusRequest(request.promise, raise); } function localPowerMutation(vm) { const mutation = state.powerMutation; return mutation && vm && String(mutation.vmId) === String(vm.api_id) ? mutation : null; } function powerTransition(vm) { const local = localPowerMutation(vm); if (local) return local.action; const operation = String(vm?.operation_transition || '').toLowerCase(); if (['start', 'shutdown', 'reinstall', 'upgrade', 'locked'].includes(operation)) return operation; if (vm?.state_transitioning !== true) return ''; const transition = String(vm.state_transition || '').toLowerCase(); return ['start', 'shutdown', 'reinstall', 'upgrade', 'locked'].includes(transition) ? transition : ''; } function renderVmDetail(vm) { const display = detailStateDisplay(vm); text('vm-detail-name-value', vm.name); text('vm-detail-state', display.label); byId('vm-detail-state').className = `state-pill ${display.category}`; const syncElement = byId('vm-detail-state-sync'); if (syncElement) { syncElement.textContent = display.note; syncElement.className = `vm-state-sync ${display.noteClass}`.trim(); syncElement.hidden = !display.note; } for (const id of ['vm-detail-region', 'vm-detail-header-region']) text(id, vmRegion(vm)); text('vm-detail-ipv4', vmIp(vm, 4)); text('vm-detail-ipv6', vmIp(vm, 6)); text('vm-detail-header-ip', vmIp(vm, 4)); text('vm-detail-header-created-at', vmCreatedAgo(vm)); const system = vmSystemInfo(vm); text('vm-detail-os-label', system.label); text('vm-detail-os', system.value); text('vm-detail-spec', `${vm.vcpu ?? '—'} vCPU · ${vm.memory_mib ?? '—'} MiB`); text('vm-detail-disk', diskLabel(vm)); text('vm-detail-ssh-user', vm.login_name || (vm.os_source === 'cloud_template' ? 'root' : t('instance_detail.value.not_recorded'))); const settingsHostname = byId('vm-detail-settings-current-hostname'); if (settingsHostname) settingsHostname.textContent = vm.guest_hostname || t('instance_detail.value.not_recorded'); byId('vm-detail-ipv4-copy').hidden = vmIp(vm, 4) === t('instance_detail.value.not_available'); byId('vm-detail-ipv6-copy').hidden = vmIp(vm, 6) === t('instance_detail.value.not_available'); text('vm-detail-root-password', !vm.can_view_credential ? t('instance_detail.value.no_permission') : vm.password_available ? (state.credentialVisible ? state.credentialPassword : '********') : t('instance_detail.value.not_recorded')); for (const id of ['vm-detail-password-reveal', 'vm-detail-password-copy']) byId(id).hidden = !vm.password_available; renderVmService(vm); const category = stateCategory(vm.state); const running = category === 'running'; const stopped = category === 'stopped'; const transition = powerTransition(vm); const powerBusy = localPowerMutation(vm) !== null || transition !== ''; const consoleAvailable = running || transition === 'shutdown'; const stateKnown = !['', 'unknown', 'nostate'].includes(String(vm.state || '').toLowerCase().replace(/[_\s-]+/g, '')); const primary = byId('vm-detail-primary-actions'); const danger = byId('vm-detail-danger-actions'); primary.replaceChildren(); danger.replaceChildren(); danger.closest('section').hidden = !vm.can_operate && !vm.can_delete; if (vm.can_operate) { primary.append(actionButton(t('instance_detail.actions.console'), () => openConsole(vm), { disabled: !consoleAvailable }), actionButton(t('instance_detail.actions.start'), () => powerAction('start'), { disabled: powerBusy || !stopped }), actionButton(t('instance_detail.actions.shutdown'), () => powerAction('shutdown'), { disabled: powerBusy || !running }), actionButton(t('instance_detail.actions.restart'), () => powerAction('reboot'), { disabled: powerBusy || !running })); danger.append(actionButton(t('instance_detail.danger.reinstall'), () => navigate(vmPagePath(vm.api_id, 'reinstall')), { variant: 'danger', disabled: powerBusy || !stateKnown || vm.os_source !== 'cloud_template' }), actionButton(t('instance_detail.danger.rescue'), () => navigate(`${vmPagePath(vm.api_id)}?tab=settings&setting=rescue`), { variant: 'danger', disabled: powerBusy || !stateKnown }), actionButton(t('instance_detail.danger.force_reset'), () => powerAction('reset', true), { variant: 'danger', disabled: powerBusy || !running }), actionButton(t('instance_detail.danger.force_off'), () => powerAction('poweroff', true), { variant: 'danger', disabled: powerBusy || !stateKnown || stopped })); } else { primary.append(makeElement('p', 'muted', vm.is_owner || vm.can_delete ? t('instance_detail.actions.unavailable') : t('instance_detail.actions.read_only'))); } if (vm.can_delete) danger.append(actionButton(t('instance_detail.danger.delete'), deleteVm, { variant: 'danger', disabled: powerBusy || !stopped })); if (state.mutationBusy) document.querySelectorAll('#vm-detail-primary-actions button,#vm-detail-danger-actions button').forEach(button => { button.disabled = true; }); document.dispatchEvent(new CustomEvent('cloud:vm-rendered', { detail: { vm } })); } function renderVmService(vm) { const data = vmServiceData(vm); const status = serviceStatusInfo(data); const statusElement = byId('vm-detail-service-status'); statusElement.textContent = status.label; statusElement.className = `service-pill ${status.className}`; const networkStatus = networkStatusInfo(data.networkStatus); const networkStatusElement = byId('vm-detail-network-status'); networkStatusElement.textContent = networkStatus.label; networkStatusElement.className = `service-pill ${networkStatus.className}`; text('vm-detail-service-expiry', formatServiceDate(data.serviceExpiresAt)); text('vm-detail-traffic-rx', formatBytes(data.rx)); text('vm-detail-traffic-tx', formatBytes(data.tx)); text('vm-detail-traffic-used', formatBytes(data.used)); const pooled = data.accountingMode === 'pooled'; const unlimited = data.accountingMode === 'unlimited' || (data.accountingMode === 'legacy' && data.quota === 0); text('vm-detail-traffic-description', pooled ? (data.projectionReady ? t('instance_detail.traffic.pooled_description') : t('instance_detail.traffic.pool_initializing')) : t('instance_detail.traffic.description')); text('vm-detail-traffic-used-label', pooled ? t('instance_detail.traffic.instance_sample_total') : t('instance_detail.traffic.used')); text('vm-detail-traffic-total-label', pooled ? t('instance_detail.traffic.pool_total_remaining') : t('instance_detail.traffic.total_remaining')); text('vm-detail-traffic-total-remaining', pooled && !data.projectionReady ? t('instance_detail.traffic.preparing_pair') : unlimited ? t('instance_detail.traffic.unlimited_pair') : `${formatBytes(data.quota)} / ${formatBytes(data.remaining)}`); const poolLink = byId('vm-detail-traffic-pool-link'); if (poolLink) { poolLink.hidden = !pooled; poolLink.textContent = pooled ? t('instance_detail.traffic.view_named_pool', { name: firstText(data.pool.name, t('instance_detail.traffic.shared_pool')) }) : t('instance_detail.traffic.view_pool'); } const progress = byId('vm-detail-traffic-progress'); progress.setAttribute('aria-label', pooled ? t('instance_detail.traffic.pool_usage') : t('instance_detail.traffic.plan_usage')); const ratio = data.quota !== null && data.quota > 0 && data.progressUsed !== null ? Math.max(0, Math.min(100, data.progressUsed / data.quota * 100)) : null; progress.hidden = ratio === null; if (ratio !== null) { progress.setAttribute('aria-valuenow', String(Math.round(ratio * 10) / 10)); byId('vm-detail-traffic-progress-bar').style.width = `${ratio}%`; progress.classList.toggle('is-exhausted', ratio >= 100); } else { progress.removeAttribute('aria-valuenow'); byId('vm-detail-traffic-progress-bar').style.width = '0'; progress.classList.remove('is-exhausted'); } } function taskFailureMessage(task, fallback = t('common.tasks.error.execution_failed')) { const resolvedNotice = resolvedTaskFailureNotice(task); if (resolvedNotice) return resolvedNotice; if (task?.recovery?.pending === true || task?.effect_may_have_applied) { return t('common.tasks.warning.effect_unknown'); } return task?.safe_to_resubmit === false ? t('common.tasks.warning.no_resubmit') : fallback; } function observeAcceptedTask(result, detail = {}, handlers = {}) { if (!taskUrl(result)) return null; announceTaskAccepted(result, detail); const handle = observeTask(result, handlers); if (!handle.url) return null; activeTaskObservers.add(handle); void handle.done.finally(() => activeTaskObservers.delete(handle)); return handle; } async function powerAction(action, dangerous = false) { const vm = selectedVm(); if (!vm?.can_operate) return toast(t('instance_detail.power.unavailable'), 'error'); if (state.mutationBusy || state.powerMutation) return; if (dangerous) { const resetting = action === 'reset'; const confirmed = await requestUserConfirmation({ title: resetting ? t('instance_detail.power.force_reset_title') : t('instance_detail.power.force_off_title'), message: resetting ? t('instance_detail.power.force_reset_body', { name: vm.name }) : t('instance_detail.power.force_off_body', { name: vm.name }), confirmText: resetting ? t('instance_detail.danger.force_reset') : t('instance_detail.danger.force_off'), tone: 'danger', }); if (!confirmed) return; } const mutation = { vmId: vm.api_id, action }; state.powerMutation = mutation; renderVmDetail(vm); try { const result = await api(`${vmPath(vm)}/actions`, { method: 'POST', body: { action }, expectedStatus: 202, requireTaskReceipt: true, }); const observer = observeAcceptedTask(result, { title: t('instance_detail.power.task_title') }, { onTerminal: task => { if (!taskSucceededWithoutRecovery(task)) { toast(taskFailureMessage(task), 'error', t('instance_detail.power.recovery_title')); } void loadVmStatus(vm.api_id, { live: true, force: true }); }, }); toast(observer ? t('instance_detail.power.accepted') : t('instance_detail.power.invalid_receipt'), observer ? 'success' : 'error', t('instance_detail.power.task_title')); } catch (error) { toast(error?.mutationMayHaveApplied ? t('common.tasks.warning.effect_unknown') : t('instance_detail.power.submit_failed'), 'error'); void loadVmStatus(vm.api_id, { live: true, force: true }); } finally { if (state.powerMutation === mutation) state.powerMutation = null; if (selectedVm()) renderVmDetail(selectedVm()); } } async function deleteVm() { const vm = selectedVm(); if (!vm?.can_delete) return toast(t('instance_detail.delete.forbidden'), 'error'); if (state.mutationBusy || state.powerMutation) return; const confirmed = await requestUserConfirmation({ title: t('instance_detail.delete.title'), message: t('instance_detail.delete.body', { name: vm.name }), confirmText: t('instance_detail.delete.confirm'), tone: 'danger', requiredText: vm.name, requiredLabel: t('instance_detail.delete.required_label'), }); if (!confirmed) return; state.mutationBusy = true; setDetailBusy(true); try { const result = await api(vmPath(vm), { method: 'DELETE', body: { confirmation_name: vm.name, delete_disks: true }, expectedStatus: 202, requireTaskReceipt: true, }); announceTaskAccepted(result, { title: t('instance_detail.delete.task_title') }); toast(t('instance_detail.delete.accepted'), 'success', t('instance_detail.delete.task_title')); navigate(CLOUD_PATHS.instances); } catch (error) { toast(error?.mutationMayHaveApplied ? t('common.tasks.warning.effect_unknown') : t('instance_detail.delete.submit_failed'), 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } } function setDetailBusy(busy) { if (!busy && selectedVm()) renderVmDetail(selectedVm()); else if (busy) document.querySelectorAll('#vm-detail-primary-actions button,#vm-detail-danger-actions button').forEach(button => { button.disabled = true; }); } async function credential(copy = false) { const vm = selectedVm(); if (!vm?.can_view_credential || !vm.password_available) return; if (!copy && state.credentialVisible) return clearCredential(); const id = vm.api_id; try { const result = await api(`${vmPath(vm)}/credential`, { method: 'POST' }); if (selectedVm()?.api_id !== id || state.view !== 'detail') return; if (!result?.password) throw new Error(t('instance_detail.error.credential_unavailable')); if (copy) { await copyText(result.password); } else { state.credentialPassword = result.password; state.credentialVisible = true; text('vm-detail-root-password', result.password); byId('vm-detail-password-reveal').setAttribute('aria-pressed', 'true'); clearTimeout(state.credentialTimer); state.credentialTimer = setTimeout(clearCredential, 30000); } } catch { toast(t('instance_detail.error.credential_unavailable'), 'error'); } } async function loadKeys() { state.sshKeys = items(await api('/api/v1/ssh-keys')); if (byId('ssh-keys-list')) renderKeys(); if (byId('vm-guest-ssh-key-cards')) renderKeyCards('create'); if (byId('reinstall-ssh-key-cards')) renderKeyCards('reinstall'); } function renderKeys() { const container = byId('ssh-keys-list'); container.replaceChildren(); if (!state.sshKeys.length) { return container.append(makeElement('p', 'muted', t('ssh_keys.empty.title'))); } for (const key of state.sshKeys) { const row = makeElement('div', 'ssh-key-row'); const details = makeElement('div', 'ssh-key-details'); details.append(makeElement('strong', '', key.name), makeElement('small', '', key.fingerprint || '')); const actions = makeElement('div', 'ssh-key-actions'); const button = actionButton(t('ssh_keys.action.delete'), async () => { const confirmed = await requestUserConfirmation({ title: t('ssh_keys.confirm.delete.title'), message: t('ssh_keys.confirm.delete.body', { name: key.name }), confirmText: t('ssh_keys.confirm.delete.button'), tone: 'danger', }); if (!confirmed) return; try { await api(`/api/v1/ssh-keys/${encodeURIComponent(key.id)}`, { method: 'DELETE' }); await loadKeys(); } catch { toast(t('ssh_keys.error.delete'), 'error'); } }); button.classList.add('ssh-key-delete'); actions.append(button); row.append(details, actions); container.append(row); } } function renderKeyCards(kind) { const id = kind === 'create' ? 'vm-guest-ssh-key-cards' : 'reinstall-ssh-key-cards'; const container = byId(id); if (!container) return; container.replaceChildren(); const deployment = kind === 'create'; if (!state.sshKeys.some(key => String(key.id) === state.selectedKeys[kind])) state.selectedKeys[kind] = ''; for (const key of state.sshKeys) { const keyId = String(key.id); const selected = state.selectedKeys[kind] === keyId; const fingerprint = String(key.fingerprint || '').trim(); const button = makeElement('button', 'ssh-key-option'); button.type = 'button'; button.dataset.keyId = keyId; button.dataset.keyFingerprint = fingerprint; button.setAttribute('aria-pressed', String(selected)); button.setAttribute('aria-label', deployment ? t(selected ? 'deploy.config.ssh_deselect' : 'deploy.config.ssh_select', { name: key.name, fingerprint: fingerprint || t('deploy.config.fingerprint_missing'), }) : t(selected ? 'reinstall.ssh_key.deselect' : 'reinstall.ssh_key.select', { name: key.name, fingerprint: fingerprint || t('reinstall.ssh_key.fingerprint_missing'), })); const icon = makeElement('i', 'mdi mdi-key-variant ssh-key-choice-icon'); icon.setAttribute('aria-hidden', 'true'); const copy = makeElement('span', 'ssh-key-choice-copy'); const fingerprintLabel = makeElement('small', 'ssh-key-choice-fingerprint', fingerprint || (deployment ? t('deploy.config.fingerprint_label_missing') : t('reinstall.ssh_key.fingerprint_missing'))); if (fingerprint) fingerprintLabel.title = fingerprint; copy.append(makeElement('strong', 'ssh-key-choice-label', key.name), fingerprintLabel); const check = makeElement('span', 'ssh-key-choice-check', '✓'); check.setAttribute('aria-hidden', 'true'); button.append(icon, copy, check); button.addEventListener('click', () => { state.selectedKeys[kind] = state.selectedKeys[kind] === keyId ? '' : keyId; container.querySelectorAll('.ssh-key-option').forEach((option) => { const optionSelected = option.dataset.keyId === state.selectedKeys[kind]; const optionName = option.querySelector('.ssh-key-choice-label')?.textContent || ''; const optionFingerprint = option.dataset.keyFingerprint || (deployment ? t('deploy.config.fingerprint_missing') : t('reinstall.ssh_key.fingerprint_missing')); option.setAttribute('aria-pressed', String(optionSelected)); option.setAttribute('aria-label', deployment ? t(optionSelected ? 'deploy.config.ssh_deselect' : 'deploy.config.ssh_select', { name: optionName, fingerprint: optionFingerprint, }) : t(optionSelected ? 'reinstall.ssh_key.deselect' : 'reinstall.ssh_key.select', { name: optionName, fingerprint: optionFingerprint, })); }); }); container.append(button); } if (!state.sshKeys.length) container.append(makeElement('p', 'muted', deployment ? t('deploy.config.ssh_empty') : t('reinstall.ssh_key.empty'))); } function flagForCountry(code) { const normalized = String(code || '').trim().toUpperCase(); if (!/^[A-Z]{2}$/.test(normalized)) return '🌐'; return String.fromCodePoint(...Array.from(normalized, character => 127397 + character.charCodeAt(0))); } function saleRegions() { const regions = []; const seen = new Set(); for (const region of state.regions) { const id = String(region?.id ?? ''); if (!/^[1-9]\d*$/.test(id) || seen.has(id)) continue; seen.add(id); regions.push({ id, countryCode: String(region.country_code || '').trim().toUpperCase(), name: String(region.name || t('deploy.region.unset')).trim() || t('deploy.region.unset'), }); } return regions; } function saleLines(regionId = state.selectedRegionId) { const lines = []; const seen = new Set(); for (const line of state.lines) { const id = String(line?.id ?? ''); if (!/^[1-9]\d*$/.test(id) || seen.has(id) || String(line?.region_id ?? '') !== String(regionId) || (!state.linesEnabled && line?.is_default !== true)) continue; seen.add(id); lines.push({ id, regionId: String(line.region_id), name: String(line.name || t('deploy.line.unset')).trim() || t('deploy.line.unset'), isDefault: line.is_default === true, }); } return lines; } function saleOffers(regionId = state.selectedRegionId, lineId = state.selectedLineId) { return state.offers.filter(offer => /^[1-9]\d*$/.test(String(offer?.id ?? '')) && String(offer?.region_id ?? '') === String(regionId) && String(offer?.line_id ?? '') === String(lineId) && String(offer?.currency || '').toUpperCase() === 'USD'); } function isOfferSellable(offer) { return offer?.sellable === true; } function defaultSaleLine(lines) { return lines.find(line => line.isDefault) || lines[0] || null; } function applySaleCatalog(catalog) { state.regions = bootstrapItems(catalog, 'regions'); state.lines = bootstrapItems(catalog, 'lines'); state.offers = bootstrapItems(catalog, 'offers'); state.linesEnabled = catalog?.lines_enabled === true; const regions = saleRegions(); const requestedRegionId = String(catalog?.default_region_id ?? ''); state.selectedRegionId = regions.some(region => region.id === requestedRegionId) ? requestedRegionId : (regions[0]?.id || ''); const lines = saleLines(state.selectedRegionId); const requestedLineId = String(catalog?.default_line_id ?? ''); state.selectedLineId = lines.some(line => line.id === requestedLineId) ? requestedLineId : (defaultSaleLine(lines)?.id || ''); byId('vm-region').value = state.selectedRegionId; byId('vm-line').value = state.selectedLineId; } function setDeploymentStepEnabled(id, enabled) { const step = byId(id); if (!step) return; step.classList.toggle('is-disabled', !enabled); step.setAttribute('aria-disabled', String(!enabled)); } function selectedSaleOffer() { return saleOffers().find(item => String(item.id) === byId('vm-offer')?.value) || null; } const DEPLOY_BILLING_CYCLES = Object.freeze({ monthly: { days: 30, divisor: 1, labelKey: 'deploy.summary.cycle_monthly' }, quarterly: { days: 90, divisor: 3, labelKey: 'deploy.summary.cycle_quarterly' }, annual: { days: 365, divisor: 12, labelKey: 'deploy.summary.cycle_annual' }, }); function offerBillingCycles(offer) { const cycles = {}; if (!Array.isArray(offer?.billing_cycles)) return cycles; offer.billing_cycles.forEach(item => { const code = String(item?.code || ''); const definition = DEPLOY_BILLING_CYCLES[code]; const price = Number(item?.price); const backupPrice = Number(item?.backup_price); if (!definition || Number(item?.days) !== definition.days || !Number.isFinite(price) || price < 0 || !Number.isFinite(backupPrice) || backupPrice < 0) return; cycles[code] = { code, days: definition.days, price, backupPrice }; }); return cycles; } function syncDeploymentBillingCycles(offer, backupSelected) { const fieldset = byId('vm-billing-cycles'); const cycles = offerBillingCycles(offer); const complete = Object.keys(DEPLOY_BILLING_CYCLES) .every(code => Boolean(cycles[code])); let selectedCode = state.deployBillingCycle; if (!cycles[selectedCode]) selectedCode = cycles.monthly ? 'monthly' : ''; state.deployBillingCycle = selectedCode; if (fieldset) { fieldset.hidden = !offer; fieldset.disabled = !offer || !complete || state.mutationBusy; fieldset.querySelectorAll('input[name="billing_cycle"]').forEach(input => { input.checked = input.value === selectedCode; input.closest('.deployment-billing-cycle')?.classList.toggle( 'is-selected', input.checked ); }); } Object.entries(DEPLOY_BILLING_CYCLES).forEach(([code, definition]) => { const cycle = cycles[code]; const total = cycle ? cycle.price + (backupSelected ? cycle.backupPrice : 0) : NaN; const price = byId(`vm-billing-${code}-price`); if (price) price.textContent = formatUsd(total); const equivalent = byId(`vm-billing-${code}-equivalent`); if (equivalent) equivalent.textContent = Number.isFinite(total) ? t('deploy.summary.cycle_equivalent_monthly', { price: formatUsd(total / definition.divisor), }) : '—'; }); return selectedCode ? cycles[selectedCode] || null : null; } function deploymentTemplates() { const offerId = String(selectedSaleOffer()?.id ?? ''); if (!offerId) return []; return state.templates.filter(item => Array.isArray(item?.offer_ids) && item.offer_ids.some(id => String(id) === offerId)); } function syncDeploymentPricing() { const offer = selectedSaleOffer(); const option = byId('vm-automatic-backup-option'); const checkbox = byId('vm-automatic-backup'); const help = byId('vm-automatic-backup-help'); const backupAvailable = Boolean(offer); if (checkbox) { checkbox.disabled = !backupAvailable || state.mutationBusy; if (!backupAvailable) checkbox.checked = false; } option?.classList.toggle('is-disabled', !backupAvailable || state.mutationBusy); if (help) { help.textContent = offer ? t('deploy.backup.help_available') : t('deploy.backup.help_unavailable'); } const summary = byId('vm-order-summary'); const empty = byId('vm-order-summary-empty'); if (!offer) { syncDeploymentBillingCycles(null, false); if (summary) summary.hidden = true; if (empty) empty.hidden = false; if (byId('create-submit')) byId('create-submit').textContent = t('deploy.submit.invoice'); return; } const backupSelected = backupAvailable && checkbox?.checked === true; const billingCycle = syncDeploymentBillingCycles(offer, backupSelected); if (!billingCycle) { if (summary) summary.hidden = true; if (empty) empty.hidden = false; if (byId('create-submit')) byId('create-submit').textContent = t('deploy.submit.invoice'); return; } const instancePrice = billingCycle.price; const backupPrice = billingCycle.backupPrice; const total = Math.max(0, Number.isFinite(instancePrice) ? instancePrice : 0) + (backupSelected && Number.isFinite(backupPrice) ? Math.max(0, backupPrice) : 0); if (byId('vm-order-instance-price')) byId('vm-order-instance-price').textContent = formatUsd(instancePrice); if (byId('vm-order-backup-price')) byId('vm-order-backup-price').textContent = formatUsd(backupPrice); if (byId('vm-order-backup-row')) byId('vm-order-backup-row').hidden = !backupSelected; if (byId('vm-order-total-price')) byId('vm-order-total-price').textContent = formatUsd(total); if (byId('vm-order-service-period')) byId('vm-order-service-period').textContent = t('deploy.summary.cycle_days', { days: billingCycle.days }); if (byId('vm-order-renewal-price')) byId('vm-order-renewal-price').textContent = t('deploy.summary.cycle_price', { price: formatUsd(total), cycle: t(DEPLOY_BILLING_CYCLES[billingCycle.code].labelKey), }); if (summary) summary.hidden = false; if (empty) empty.hidden = true; if (byId('create-submit')) byId('create-submit').textContent = t('deploy.submit.invoice_amount', { price: formatUsd(total) }); } function applyDeploymentSource() { const snapshotKey = state.deployCloudSnapshotKey; const source = byId('vm-cloud-snapshot-source'); const templateField = byId('vm-template-field'); const authFields = byId('vm-cloud-fields'); const template = byId('vm-template'); const password = byId('vm-root-password'); if (byId('vm-cloud-snapshot-key')) byId('vm-cloud-snapshot-key').value = snapshotKey; if (source) source.hidden = !snapshotKey; if (templateField) templateField.hidden = Boolean(snapshotKey); if (authFields) authFields.hidden = Boolean(snapshotKey); if (template) { template.disabled = Boolean(snapshotKey) || !deploymentTemplates().some(item => item?.id); } if (password) password.disabled = Boolean(snapshotKey); const sourceTitle = byId('deploy-source-title'); if (sourceTitle?.firstChild) { sourceTitle.firstChild.nodeValue = snapshotKey ? t('deploy.source.snapshot') : t('deploy.source.template'); } if (byId('vm-cloud-snapshot-source-name') && snapshotKey) { const name = state.deployCloudSnapshotName || `${t('deploy.source.snapshot_default')} ${snapshotKey.slice(0, 8)}`; byId('vm-cloud-snapshot-source-name').textContent = t('deploy.source.snapshot_description', { name }); } } function initializeDeploymentOptions(bootstrap = null) { const snapshot = bootstrap?.cloud_snapshot; const key = String(snapshot?.snapshot_key ?? snapshot?.key ?? ''); state.deployCloudSnapshotKey = /^[a-f0-9]{32}$/.test(key) ? key : ''; state.deployCloudSnapshotName = state.deployCloudSnapshotKey ? String(snapshot?.name || '').trim().slice(0, 64) : ''; const checkbox = byId('vm-automatic-backup'); if (checkbox && checkbox.dataset.bound !== 'true') { checkbox.dataset.bound = 'true'; checkbox.addEventListener('change', () => { showError('create-error', ''); syncDeploymentPricing(); updateCreateAvailability(); }); } const billingCycles = byId('vm-billing-cycles'); if (billingCycles && billingCycles.dataset.bound !== 'true') { billingCycles.dataset.bound = 'true'; billingCycles.addEventListener('change', event => { const input = event.target.closest('input[name="billing_cycle"]'); if (!input || !DEPLOY_BILLING_CYCLES[input.value]) return; state.deployBillingCycle = input.value; showError('create-error', ''); updateCreateAvailability(); }); } applyDeploymentSource(); syncDeploymentPricing(); } function updateCreateAvailability() { const offer = selectedSaleOffer(); const selectedTemplate = String(byId('vm-template')?.value || ''); const validTemplate = deploymentTemplates().some(item => String(item?.id) === selectedTemplate); const validMedia = Boolean(state.deployCloudSnapshotKey || validTemplate); const validBillingCycle = Boolean(offerBillingCycles(offer)[state.deployBillingCycle]); if (byId('create-submit')) byId('create-submit').disabled = state.mutationBusy || !isOfferSellable(offer) || !validMedia || !validBillingCycle; syncDeploymentPricing(); } function strongPassword(value) { return !value || (value.length >= 12 && value.length <= 128 && /^[\x21-\x7e]+$/.test(value) && /[A-Z]/.test(value) && /[a-z]/.test(value) && /[0-9]/.test(value) && /[^A-Za-z0-9]/.test(value)); } function formatUsd(value) { const amount = Number(value); if (!Number.isFinite(amount) || amount < 0) return '$— USD'; return `$${amount.toFixed(2)} USD`; } function formatMemoryGiB(memoryMib) { const amount = Number(memoryMib); if (!Number.isFinite(amount) || amount < 0) return '— GB'; return `${i18n.number(amount / 1024, { maximumFractionDigits: 1 })} GB`; } function formatTrafficTiB(trafficTiB) { const amount = Number(trafficTiB); if (!Number.isFinite(amount) || amount < 0) return '—'; if (amount === 0) return t('deploy.offer.unlimited'); return `${amount.toFixed(10).replace(/\.?0+$/, '')} TB`; } function resetInstallChoices() { state.resourceController?.abort(); state.resourceController = null; state.resources = null; state.templates = []; const templateInput = byId('vm-template'); const templateCatalog = byId('vm-template-catalog'); templateInput.value = ''; templateInput.disabled = true; templateCatalog.removeAttribute('aria-busy'); templateCatalog.replaceChildren(); byId('vm-name').disabled = true; byId('vm-root-password').disabled = true; setDeploymentStepEnabled('vm-source-step', false); setDeploymentStepEnabled('vm-config-step', false); updateCreateAvailability(); } function renderRegionPicker() { const container = byId('vm-region-picker'); const cards = saleRegions().map(region => { const button = makeElement('button', 'region-option'); button.type = 'button'; button.dataset.regionId = region.id; button.setAttribute('aria-pressed', String(state.selectedRegionId === region.id)); button.setAttribute('aria-label', t('deploy.region.select', { name: region.name })); button.append(makeElement('span', 'region-flag', flagForCountry(region.countryCode)), makeElement('strong', '', region.name)); button.addEventListener('click', () => void selectRegion(region.id)); return button; }); if (!cards.length) cards.push(makeElement('p', 'template-catalog-empty', t('deploy.region.empty'))); container.replaceChildren(...cards); byId('vm-region').value = state.selectedRegionId; } function renderLinePicker() { const container = byId('vm-line-picker'); if (!container) return; const cards = saleLines().map(line => { const button = makeElement('button', 'line-option'); button.type = 'button'; button.dataset.lineId = line.id; button.setAttribute('aria-pressed', String(state.selectedLineId === line.id)); button.setAttribute('aria-label', t('deploy.line.select', { name: line.name })); button.append(makeElement('strong', '', line.name)); button.addEventListener('click', () => void selectLine(line.id)); return button; }); if (!cards.length) cards.push(makeElement('p', 'template-catalog-empty', t('deploy.line.empty'))); container.replaceChildren(...cards); } function renderOfferPicker() { const container = byId('vm-offer-picker'); const offerInput = byId('vm-offer'); let selectedOfferId = offerInput.value; const offers = saleOffers(); if (!offers.length) { container.replaceChildren(makeElement('p', 'template-catalog-empty', t('deploy.offer.empty'))); return; } if (!offers.some(offer => String(offer.id) === selectedOfferId && isOfferSellable(offer))) { const defaultOffer = offers.find(isOfferSellable); offerInput.value = defaultOffer ? String(defaultOffer.id) : ''; selectedOfferId = offerInput.value; } const header = makeElement('div', 'offer-table-head'); [t('deploy.offer.name'), t('deploy.offer.cpu'), 'Memory', 'Nvme', 'Traffic'] .forEach(label => header.append(makeElement('span', '', label))); const rows = offers.map(offer => { const button = makeElement('button', 'offer-option'); const memory = formatMemoryGiB(offer.memory_mib); const traffic = formatTrafficTiB(offer.traffic_tib); const sellable = isOfferSellable(offer); const name = makeElement('strong', 'offer-option-name', offer.name); if (!sellable) name.append(makeElement('span', 'offer-option-status', t('deploy.offer.sold_out'))); button.type = 'button'; button.dataset.offerId = String(offer.id); button.classList.toggle('is-sold-out', !sellable); button.disabled = !sellable; button.setAttribute('aria-disabled', String(!sellable)); button.setAttribute('aria-pressed', String(sellable && selectedOfferId === String(offer.id))); button.setAttribute('aria-label', t( sellable ? 'deploy.offer.select' : 'deploy.offer.unavailable', { name: offer.name, cpu: offer.cpu_cores, memory, disk: offer.disk_gib, traffic } )); button.append( name, makeElement('span', 'offer-option-value', `${offer.cpu_cores} vCPU`), makeElement('span', 'offer-option-value', memory), makeElement('span', 'offer-option-value', `${offer.disk_gib} GB`), makeElement('span', 'offer-option-value', traffic), ); if (sellable) button.addEventListener('click', () => void selectOffer(String(offer.id))); return button; }); container.replaceChildren(header, ...rows); } async function selectRegion(regionId) { if (state.mutationBusy) return; const normalized = String(regionId || ''); if (!saleRegions().some(region => region.id === normalized)) return; if (state.selectedRegionId === normalized) return; state.selectedRegionId = normalized; state.selectedLineId = defaultSaleLine(saleLines(normalized))?.id || ''; byId('vm-region').value = state.selectedRegionId; byId('vm-line').value = state.selectedLineId; byId('vm-offer').value = ''; if (byId('vm-automatic-backup')) byId('vm-automatic-backup').checked = false; renderRegionPicker(); renderLinePicker(); renderOfferPicker(); renderTemplateCatalog('vm-template'); setDeploymentStepEnabled('vm-line-step', state.linesEnabled); setDeploymentStepEnabled('vm-offer-step', Boolean(state.selectedLineId)); showError('create-error', ''); updateCreateAvailability(); } async function selectLine(lineId) { if (state.mutationBusy) return; const line = saleLines().find(item => item.id === String(lineId)); if (!line || state.selectedLineId === line.id) return; state.selectedLineId = line.id; byId('vm-line').value = line.id; byId('vm-offer').value = ''; if (byId('vm-automatic-backup')) byId('vm-automatic-backup').checked = false; byId('vm-line-picker')?.querySelectorAll('.line-option').forEach(button => { button.setAttribute('aria-pressed', String(button.dataset.lineId === line.id)); }); renderOfferPicker(); renderTemplateCatalog('vm-template'); setDeploymentStepEnabled('vm-offer-step', true); showError('create-error', ''); updateCreateAvailability(); } async function selectOffer(offerId) { if (state.mutationBusy) return; const offer = saleOffers().find(item => String(item.id) === String(offerId)); if (!isOfferSellable(offer)) return; byId('vm-offer').value = String(offer.id); byId('vm-offer-picker').querySelectorAll('.offer-option').forEach(button => { button.setAttribute('aria-pressed', String(button.dataset.offerId === String(offer.id))); }); renderTemplateCatalog('vm-template'); showError('create-error', ''); updateCreateAvailability(); } async function openCreate(bootstrap = null) { state.view = 'create'; state.selectedVmId = null; showError('create-error', ''); byId('vm-offer').value = String(bootstrap?.default_offer_id || ''); if (bootstrap && Array.isArray(bootstrap.offers) && Array.isArray(bootstrap.regions) && Array.isArray(bootstrap.lines) && Array.isArray(bootstrap.templates)) { applySaleCatalog(bootstrap); initializeDeploymentOptions(bootstrap); state.templates = bootstrapItems(bootstrap, 'templates', 'cloud_templates'); state.templateCatalogUnavailable = bootstrap.catalog_unavailable === true; state.sshKeys = bootstrapItems(bootstrap, 'ssh_keys', 'keys'); state.resources = { templates: state.templates }; state.selectedKeys.create = ''; renderRegionPicker(); renderLinePicker(); renderOfferPicker(); renderTemplateCatalog('vm-template'); renderKeyCards('create'); byId('vm-template').disabled = !deploymentTemplates().some(item => item?.id); byId('vm-name').disabled = false; byId('vm-root-password').disabled = false; applyDeploymentSource(); setDeploymentStepEnabled('vm-line-step', state.linesEnabled && Boolean(state.selectedRegionId)); setDeploymentStepEnabled('vm-offer-step', Boolean(state.selectedLineId)); setDeploymentStepEnabled('vm-source-step', true); setDeploymentStepEnabled('vm-config-step', true); updateCreateAvailability(); return; } initializeDeploymentOptions(bootstrap); state.regions = []; state.lines = []; state.offers = []; state.linesEnabled = false; state.selectedRegionId = ''; state.selectedLineId = ''; byId('vm-region').value = ''; byId('vm-line').value = ''; setDeploymentStepEnabled('vm-line-step', false); setDeploymentStepEnabled('vm-offer-step', false); resetInstallChoices(); const results = await Promise.allSettled([ api('/api/v1/catalog').then(catalog => { applySaleCatalog(catalog); renderRegionPicker(); renderLinePicker(); renderOfferPicker(); renderTemplateCatalog('vm-template'); setDeploymentStepEnabled('vm-line-step', state.linesEnabled && Boolean(state.selectedRegionId)); setDeploymentStepEnabled('vm-offer-step', Boolean(state.selectedLineId)); updateCreateAvailability(); }), loadKeys(), loadGlobalTemplates(), ]); const failure = results.find(result => result.status === 'rejected'); if (failure) showError('create-error', t('deploy.error.load')); } async function loadGlobalTemplates() { state.resourceController?.abort(); const controller = new AbortController(); state.resourceController = controller; renderTemplateCatalogStatus('vm-template', t('deploy.template.loading'), true); setDeploymentStepEnabled('vm-source-step', true); try { const resources = await api('/api/v1/resources', { signal: controller.signal }); if (controller !== state.resourceController) return; state.resources = resources; state.templateCatalogUnavailable = false; state.templates = items(resources.templates || resources.cloud_templates); renderTemplateCatalog('vm-template'); byId('vm-template').disabled = !deploymentTemplates().some(item => item?.id); byId('vm-name').disabled = false; byId('vm-root-password').disabled = false; applyDeploymentSource(); setDeploymentStepEnabled('vm-source-step', true); setDeploymentStepEnabled('vm-config-step', true); updateCreateAvailability(); } catch (error) { if (controller === state.resourceController && error.name !== 'AbortError') { renderTemplateCatalogStatus('vm-template', t('deploy.template.load_failed')); showError('create-error', t('deploy.template.load_failed')); } throw error; } finally { if (controller === state.resourceController) { state.resourceController = null; } } } function provisionInvoiceStorageKey() { return `${PROVISION_INVOICE_STORAGE_PREFIX}${state.userId || 'unknown'}`; } async function provisionInvoiceFingerprint(body) { if (!globalThis.crypto?.subtle) throw new Error(t('deploy.error.crypto')); const canonical = {}; for (const key of Object.keys(body).sort()) canonical[key] = body[key]; const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(canonical))); return Array.from(new Uint8Array(digest), value => value.toString(16).padStart(2, '0')).join(''); } async function pendingProvisionInvoiceKey(fingerprint) { if (state.provisionIdempotency && state.provisionFingerprint === fingerprint) return state.provisionIdempotency; let saved = null; try { saved = JSON.parse(sessionStorage.getItem(provisionInvoiceStorageKey()) || 'null'); } catch {} let key = saved && saved.fingerprint === fingerprint ? String(saved.key || '') : ''; if (!/^[A-Za-z0-9_.-]{16,128}$/.test(key)) key = crypto.randomUUID(); state.provisionIdempotency = key; state.provisionFingerprint = fingerprint; try { sessionStorage.setItem(provisionInvoiceStorageKey(), JSON.stringify({ key, fingerprint })); } catch {} return key; } function clearPendingProvisionInvoiceKey() { state.provisionIdempotency = ''; state.provisionFingerprint = ''; try { sessionStorage.removeItem(provisionInvoiceStorageKey()); } catch {} } async function existingProvisionInvoice(key) { try { return await api(`/api/v1/invoices/by-request/${encodeURIComponent(key)}`); } catch (error) { if (error.status === 404) return null; throw error; } } async function buy(event) { event.preventDefault(); if (state.mutationBusy) return; const password = byId('vm-root-password').value; if (!state.deployCloudSnapshotKey && !strongPassword(password)) return showError('create-error', t('deploy.error.password')); if (!state.deployCloudSnapshotKey && !byId('vm-template').value) return showError('create-error', t('deploy.error.template_required')); if (!byId('vm-offer').value) return showError('create-error', t('deploy.error.offer_required')); const selectedOffer = saleOffers().find(offer => String(offer.id) === byId('vm-offer').value); if (!selectedOffer) return showError('create-error', t('deploy.error.offer_mismatch')); if (!isOfferSellable(selectedOffer)) return showError('create-error', t('deploy.error.offer_sold_out')); if (!offerBillingCycles(selectedOffer)[state.deployBillingCycle]) return showError('create-error', t('deploy.error.billing_cycle_required')); state.mutationBusy = true; const formBody = byId('create-form')?.querySelector('.workspace-form-body'); if (formBody) { formBody.inert = true; formBody.setAttribute('aria-busy', 'true'); } byId('create-submit').disabled = true; showError('create-error', ''); const body = { offer_id: Number(byId('vm-offer').value), name: byId('vm-name').value.trim(), source: state.deployCloudSnapshotKey ? 'deployment_snapshot' : 'cloud', billing_cycle: state.deployBillingCycle, automatic_backup: byId('vm-automatic-backup')?.checked === true }; if (state.deployCloudSnapshotKey) body.cloud_snapshot_key = state.deployCloudSnapshotKey; else body.template_id = byId('vm-template').value; if (!state.deployCloudSnapshotKey && state.selectedKeys.create) body.guest_ssh_key_id = state.selectedKeys.create; if (!state.deployCloudSnapshotKey && password) body.root_password = password; try { const fingerprint = await provisionInvoiceFingerprint(body); const invoiceIdempotency = await pendingProvisionInvoiceKey(fingerprint); body.idempotency_key = invoiceIdempotency; const recovered = await existingProvisionInvoice(invoiceIdempotency); const result = recovered || await api('/api/v1/invoices', { method: 'POST', body }); const invoiceId = result?.invoice?.id; if (!invoiceId) throw new Error(t('deploy.error.invoice_missing')); clearPendingProvisionInvoiceKey(); byId('vm-root-password').value = ''; navigate(`${CLOUD_PATHS.invoices}/${encodeURIComponent(String(invoiceId))}`); } catch (error) { // A timeout or 409 can mean the first request committed but its response // was lost. Reconcile by the same durable key before reporting failure. try { const invoiceIdempotency = state.provisionIdempotency; const recovered = invoiceIdempotency ? await existingProvisionInvoice(invoiceIdempotency) : null; if (recovered) { clearPendingProvisionInvoiceKey(); byId('vm-root-password').value = ''; const invoiceId = recovered?.invoice?.id; if (!invoiceId) throw new Error(t('deploy.error.recovered_invoice_missing')); navigate(`${CLOUD_PATHS.invoices}/${encodeURIComponent(String(invoiceId))}`); return; } } catch {} showError('create-error', t('deploy.error.reconcile')); } finally { delete body.root_password; state.mutationBusy = false; if (formBody) { formBody.inert = false; formBody.removeAttribute('aria-busy'); } updateCreateAvailability(); } } function clearReinstallPasswordCard(dismissed = false) { state.reinstallPassword = ''; if (dismissed) state.reinstallPasswordDismissed = true; const card = byId('reinstall-password-card'); if (!card) return; card.hidden = true; const value = byId('reinstall-password-card-value'); if (value) value.textContent = ''; } function showReinstallPasswordCard(password, generated = true) { if (state.reinstallPasswordDismissed || typeof password !== 'string' || password === '') return false; const card = byId('reinstall-password-card'); const value = byId('reinstall-password-card-value'); if (!card || !value) return false; state.reinstallPassword = password; state.reinstallPasswordDismissed = false; value.textContent = password; text('reinstall-password-card-title', generated ? t('reinstall.card.accepted_title') : t('reinstall.card.password_received_title')); text('reinstall-password-card-message', generated ? t('reinstall.card.generated_message') : t('reinstall.card.provided_message')); text('reinstall-password-card-note', t('reinstall.card.pending_note')); card.hidden = false; card.focus({ preventScroll: true }); return true; } async function loadReinstallCredential(vm) { if (state.reinstallPassword || state.reinstallPasswordDismissed || !vm) return; try { const result = await api(`${vmPath(vm)}/credential`, { method: 'POST' }); showReinstallPasswordCard(result?.password, false); } catch { toast(t('reinstall.credential_unavailable'), 'warning', t('reinstall.credential_notice_title')); } } function syncReinstallControls(vm = selectedVm()) { const allowed = vm?.can_operate === true; const fields = byId('reinstall-fields'); const submit = byId('reinstall-submit'); if (fields) { fields.inert = !allowed; if (allowed) fields.removeAttribute('aria-disabled'); else fields.setAttribute('aria-disabled', 'true'); } if (submit) submit.disabled = !allowed; return allowed; } function trackReinstallJob(vm, result) { observeAcceptedTask(result, { title: t('reinstall.task_title') }, { onUpdate: () => text('reinstall-phase', t('reinstall.progress.running')), onTerminal: task => { void (async () => { byId('reinstall-progress').hidden = true; const refreshed = await loadVm(vm.api_id); syncReinstallControls(refreshed || selectedVm()); if (taskSucceededWithoutRecovery(task)) { await loadReinstallCredential(refreshed || vm); if (state.reinstallPassword) text('reinstall-password-card-note', t('reinstall.card.success_note')); return; } const message = taskFailureMessage(task, t('reinstall.task_failed')); showError('reinstall-error', message); if (state.reinstallPassword) { if (task.effect_resolution === 'applied') { text('reinstall-password-card-note', t('reinstall.card.applied_note')); } else if (task.effect_resolution === 'not_applied') { text('reinstall-password-card-note', t('reinstall.card.not_applied_note')); } else { text('reinstall-password-card-note', task.effect_may_have_applied || task.safe_to_resubmit === false ? t('reinstall.card.locked_note') : t('reinstall.card.retry_note')); } } toast(message, 'error', t('reinstall.task_failure_title')); })(); }, onStop: reason => { if (reason === 'pagehide') return; void (async () => { byId('reinstall-progress').hidden = true; const refreshed = await loadVm(vm.api_id); syncReinstallControls(refreshed || selectedVm()); showError('reinstall-error', t('reinstall.progress.observer_stopped')); })(); }, }); } async function openReinstall(vm, bootstrap = null) { state.view = 'reinstall'; state.reinstallPasswordDismissed = false; clearReinstallPasswordCard(); byId('reinstall-confirm-name').value = ''; byId('reinstall-root-password').value = ''; byId('reinstall-template').value = ''; showError('reinstall-error', ''); byId('reinstall-progress').hidden = true; byId('reinstall-result').hidden = true; byId('reinstall-fields').hidden = false; const currentName = String(vm.name ?? ''); const nameValue = byId('reinstall-confirm-name-value'); const nameInput = byId('reinstall-confirm-name'); const copyName = byId('reinstall-copy-name'); if (nameValue) nameValue.textContent = currentName || t('reinstall.value.not_recorded'); const syncNameConfirmation = () => { const matches = currentName !== '' && nameInput?.value === currentName; const hasInput = Boolean(nameInput?.value); nameInput?.classList.toggle('is-match', matches); nameInput?.classList.toggle('is-mismatch', hasInput && !matches); }; if (nameInput) nameInput.oninput = syncNameConfirmation; if (copyName) { copyName.disabled = !currentName; copyName.onclick = async () => { if (!currentName) return; try { await copyText(currentName); } catch { toast(t('reinstall.copy_failed'), 'error'); } }; } const passwordCardClose = byId('reinstall-password-card-close'); const passwordCardSaved = byId('reinstall-password-card-saved'); const passwordCardCopy = byId('reinstall-password-card-copy'); if (passwordCardClose) passwordCardClose.onclick = () => clearReinstallPasswordCard(true); if (passwordCardSaved) passwordCardSaved.onclick = () => clearReinstallPasswordCard(true); if (passwordCardCopy) { passwordCardCopy.onclick = async () => { if (!state.reinstallPassword) return; try { await copyText(state.reinstallPassword); } catch { toast(t('reinstall.copy_failed'), 'error'); } }; } syncNameConfirmation(); if (!vm?.can_operate) { byId('reinstall-fields').inert = true; byId('reinstall-fields').setAttribute('aria-disabled', 'true'); byId('reinstall-submit').disabled = true; showError('reinstall-error', t('reinstall.unavailable.error')); return; } byId('reinstall-fields').inert = false; byId('reinstall-fields').removeAttribute('aria-disabled'); byId('reinstall-submit').disabled = false; if (bootstrap && Array.isArray(bootstrap.templates)) { state.templates = bootstrapItems(bootstrap, 'templates', 'cloud_templates'); state.templateCatalogUnavailable = bootstrap.catalog_unavailable === true; state.sshKeys = bootstrapItems(bootstrap, 'ssh_keys', 'keys'); state.selectedKeys.reinstall = ''; renderTemplateCatalog('reinstall-template'); renderKeyCards('reinstall'); return; } try { const resources = await api(`/api/v1/resources?vm_id=${encodeURIComponent(vm.api_id)}`); state.templates = items(resources.templates || resources.cloud_templates); renderTemplateCatalog('reinstall-template'); await loadKeys(); } catch { showError('reinstall-error', t('reinstall.error.catalog_load')); } } async function reinstall(event) { event.preventDefault(); const vm = selectedVm(); if (!vm || state.mutationBusy) return; if (byId('reinstall-confirm-name').value !== vm.name) return showError('reinstall-error', t('reinstall.error.confirm_name')); const password = byId('reinstall-root-password').value; if (!strongPassword(password)) return showError('reinstall-error', t('reinstall.error.password_invalid')); const template = byId('reinstall-template').value; if (!template) return showError('reinstall-error', t('reinstall.error.template_required')); state.mutationBusy = true; byId('reinstall-submit').disabled = true; const body = { template_id: template, confirmation_name: vm.name }; if (state.selectedKeys.reinstall) body.ssh_key_id = state.selectedKeys.reinstall; if (password) body.root_password = password; let submitted = false; try { const result = await api(`${vmPath(vm)}/reinstall`, { method: 'POST', body, expectedStatus: 202, requireTaskReceipt: true, }); submitted = true; showReinstallPasswordCard(password, false); toast(t('reinstall.accepted'), 'success', t('reinstall.task_title')); byId('reinstall-root-password').value = ''; byId('reinstall-progress').hidden = false; text('reinstall-phase', t('reinstall.progress.accepted')); byId('reinstall-fields').inert = false; byId('reinstall-fields').removeAttribute('aria-disabled'); trackReinstallJob(vm, result); } catch (error) { showError('reinstall-error', error?.mutationMayHaveApplied ? t('reinstall.error.submit_unknown') : t('reinstall.error.submit_failed')); const refreshed = await loadVm(vm.api_id); syncReinstallControls(refreshed || selectedVm()); } finally { delete body.root_password; state.mutationBusy = false; if (!submitted) byId('reinstall-progress').hidden = true; } } function closeConsole() { state.consoleToken++; state.rfb?.disconnect(); state.rfb = null; if (byId('console-modal')) byId('console-modal').hidden = true; if (byId('console-password-form')) byId('console-password-form').hidden = true; if (byId('console-password')) byId('console-password').value = ''; if (byId('console-cad')) byId('console-cad').disabled = true; } async function openConsole(vm) { if (!vm?.can_operate) return toast(t('instance_detail.power.unavailable'), 'error'); closeConsole(); const token = ++state.consoleToken; byId('console-modal').hidden = false; text('console-title', t('instance_detail.console.window_title', { name: vm.name })); text('console-status', t('instance_detail.console.requesting')); const placeholder = byId('console-placeholder'); placeholder.hidden = false; try { const [ticket, module] = await Promise.all([ api(`${vmPath(vm)}/console-ticket`, { method: 'POST' }), import('/cloud/vendor/novnc/core/rfb.js'), ]); if (token !== state.consoleToken) return; const url = new URL(ticket.websocket_path, location.href); if (url.origin !== location.origin || url.pathname !== '/engine-console' || url.search || url.hash || typeof ticket.ticket !== 'string' || !/^[A-Za-z0-9_-]+$/.test(ticket.ticket)) { throw new Error(t('instance_detail.console.invalid_ticket')); } url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'; const rfb = new module.default(byId('console-stage'), url.href, { shared: true, wsProtocols: ['cloud-ticket.' + ticket.ticket], }); state.rfb = rfb; rfb.scaleViewport = true; rfb.resizeSession = false; placeholder.hidden = true; rfb.addEventListener('connect', () => { if (state.rfb !== rfb) return; text('console-status', t('instance_detail.console.connected')); byId('console-cad').disabled = false; }); rfb.addEventListener('disconnect', event => { if (state.rfb !== rfb) return; text('console-status', event.detail?.clean ? t('instance_detail.console.closed') : t('instance_detail.console.interrupted')); byId('console-cad').disabled = true; }); rfb.addEventListener('credentialsrequired', () => { if (state.rfb !== rfb) return; byId('console-password-form').hidden = false; byId('console-password').focus(); text('console-status', t('instance_detail.console.password_prompt')); }); } catch { if (token === state.consoleToken) { text('console-status', t('instance_detail.console.failed')); placeholder.hidden = false; } } } function stateCategory(value) { const normalized = String(value || "unknown").toLowerCase().replace(/[_\s-]+/g, ""); if (normalized === "running" || normalized === "blocked") return "running"; if (["shutoff", "stopped", "crashed"].includes(normalized)) return "stopped"; return "other"; } function stateLabel(value) { const normalized = String(value || "unknown").toLowerCase().replace(/[_\s-]+/g, ""); const labels = { running: 'running', blocked: 'running', shutoff: 'stopped', stopped: 'stopped', shutdown: 'shutting_down', crashed: 'crashed', paused: 'paused', pmsuspended: 'suspended', nostate: 'awaiting_sync', unknown: 'awaiting_sync', }; const key = labels[normalized] || 'awaiting_sync'; return t(`${state.view === 'detail' ? 'instance_detail' : 'instances'}.state.${key}`); } function detailStateDisplay(vm) { const transition = powerTransition(vm); if (transition) { const labels = { start: 'instance_detail.state.starting', shutdown: 'instance_detail.state.shutting_down', reinstall: 'instance_detail.state.reinstalling', upgrade: 'instance_detail.state.upgrading', locked: 'instance_detail.state.reconciling', }; return { label: t(labels[transition] || 'instance_detail.state.operating'), category: 'other', note: '', noteClass: '', }; } if (servicePaused(vm)) { return { label: t('instance_detail.state.paused'), category: 'other', note: '', noteClass: '' }; } const sync = String(vm?.state_sync_status || '').toLowerCase(); if (['unavailable', 'offline', 'host_offline', 'host_unreachable'].includes(sync)) { return { label: t('instance_detail.state.sync_unavailable'), category: 'other', note: '', noteClass: 'offline' }; } const normalized = String(vm?.state || '').toLowerCase().replace(/[_\s-]+/g, ''); if (['', 'unknown', 'nostate'].includes(normalized) || ['pending', 'never'].includes(sync)) { const key = ['creating', 'provisioning', 'deploying'].includes(String(vm?.instance_status || '')) ? 'instance_detail.state.deploying' : 'instance_detail.state.awaiting_sync'; return { label: t(key), category: 'other', note: '', noteClass: '' }; } const fresh = vm?.state_fresh === true || sync === 'fresh'; return { label: stateLabel(vm.state), category: stateCategory(vm.state), note: fresh ? '' : t('instance_detail.state.sync_pending'), noteClass: fresh ? '' : 'stale', }; } function diskLabel(vm) { if (Array.isArray(vm.disks) && vm.disks.length) { const size = vm.disks.reduce((sum, disk) => { const capacity = Number(disk.capacity_gib ?? disk.size_gib ?? 0); return sum + (Number.isFinite(capacity) && capacity > 0 ? capacity : 0); }, 0); if (size > 0) return `${Math.round(size * 100) / 100} GiB`; } if (Number.isFinite(Number(vm.disk_gib)) && Number(vm.disk_gib) > 0) return `${vm.disk_gib} GiB`; return "—"; } function vmSystemInfo(vm) { const detail = state.view === 'detail'; const unavailable = t(detail ? 'instance_detail.value.unrecognized' : 'instances.value.unrecognized'); if (vm.os_source === "iso") return { label: t(detail ? 'instance_detail.system.install_image' : 'instances.system.iso'), value: String(vm.install_iso || unavailable), }; if (vm.os_source === "cloud_template") return { label: t(detail ? 'instance_detail.system.cloud_image' : 'instances.system.template'), value: String(vm.os_name || unavailable), }; return { label: t(detail ? 'instance_detail.info.system' : 'instances.system.other'), value: String(vm.os_name || unavailable), }; } function vmRegion(vm) { return String(vm.region || "").trim() || t(state.view === 'detail' ? 'instance_detail.value.not_set' : 'instances.value.not_set'); } function vmIp(vm, family = 4) { const unavailable = t(state.view === 'detail' ? 'instance_detail.value.not_available' : 'instances.value.not_available'); if (vm?.public_network_valid !== true) return unavailable; return String(family === 6 ? vm.public_ipv6 : vm.public_ipv4).trim() || unavailable; } function vmCreatedAt(vm) { const value = typeof vm.created_at === "string" ? vm.created_at.trim() : ""; if (!value) return t('instance_detail.value.not_recorded'); const date = new Date(value); if (!Number.isFinite(date.getTime())) return t('instance_detail.value.not_recorded'); return i18n.date(date.getTime()); } function vmCreatedAgo(vm, now = Date.now()) { const value = typeof vm.created_at === "string" ? vm.created_at.trim() : ""; if (!value) return t('instance_detail.value.not_recorded'); const created = Date.parse(value); if (!Number.isFinite(created)) return t('instance_detail.value.not_recorded'); const elapsed = Math.max(0, now - created); const minute = 60 * 1000; const hour = 60 * minute; const day = 24 * hour; const month = 30 * day; if (elapsed < minute) return t('instance_detail.created.just_now'); if (elapsed < hour) return t('instance_detail.created.minutes_ago', { count: Math.floor(elapsed / minute) }); if (elapsed < day) return t('instance_detail.created.hours_ago', { count: Math.floor(elapsed / hour) }); if (elapsed < month) return t('instance_detail.created.days_ago', { count: Math.floor(elapsed / day) }); return t('instance_detail.created.months_ago', { count: Math.floor(elapsed / month) }); } function makeCell(row, className = "") { const cell = document.createElement("td"); if (className) cell.className = className; row.append(cell); return cell; } function makeElement(tag, className, content) { const element = document.createElement(tag); if (className) element.className = className; if (content !== undefined) element.textContent = String(content); return element; } function makeCopyIconButton(value, label) { const button = makeElement("button", "vm-copy-icon"); button.type = "button"; const copyLabel = t('instances.copy.value', { label }); button.title = copyLabel; button.setAttribute("aria-label", copyLabel); const icon = document.createElementNS("http://www.w3.org/2000/svg", "svg"); icon.setAttribute("viewBox", "0 0 24 24"); icon.setAttribute("aria-hidden", "true"); const back = document.createElementNS("http://www.w3.org/2000/svg", "rect"); for (const [name, attribute] of Object.entries({ x: "8", y: "8", width: "12", height: "12", rx: "2" })) { back.setAttribute(name, attribute); } const front = document.createElementNS("http://www.w3.org/2000/svg", "path"); front.setAttribute("d", "M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"); icon.append(back, front); button.append(icon); button.addEventListener("click", async () => { try { await copyText(value); } catch { toast(t('instances.error.copy_short'), "error"); } }); return button; } function actionButton(label, handler, options = {}) { const button = makeElement("button", `row-button ${options.variant || ""}`, label); button.type = "button"; button.disabled = Boolean(options.disabled); if (options.key) button.dataset.vmAction = options.key; if (options.title) button.title = options.title; button.addEventListener("click", handler); return button; } function renderVMs(connectionError = false) { const all = state.vms; const runningCount = all.filter((vm) => stateCategory(vm.state) === "running").length; const stoppedCount = all.filter((vm) => stateCategory(vm.state) === "stopped").length; text("stat-total", String(all.length)); text("stat-running", String(runningCount)); text("stat-stopped", String(stoppedCount)); const query = byId("search-input").value.trim().toLocaleLowerCase(); const filter = byId("state-filter").value; const filtered = all.filter((vm) => { const matchesText = !query || [vm.name, vm.uuid, vm.public_ipv4, vm.public_ipv6, vm.region, vm.os_name, vm.install_iso] .some((value) => String(value || "").toLocaleLowerCase().includes(query)); return matchesText && (filter === "all" || stateCategory(vm.state) === filter); }); text("inventory-count", filtered.length !== all.length ? t('instances.list.count_filtered', { filtered: filtered.length, page_count: filtered.length, total: all.length, }) : t('instances.list.count', { page_count: filtered.length, total: all.length })); const tbody = byId("vm-table-body"); const focusedVmId = document.activeElement?.classList.contains("vm-name-link") ? document.activeElement.dataset.vmUuid : null; tbody.replaceChildren(); const empty = byId("empty-state"); empty.hidden = filtered.length !== 0; if (!filtered.length) { if (connectionError) { text("empty-title", t('instances.empty.failed.title')); text("empty-description", t('instances.empty.failed.body')); } else if (all.length) { text("empty-title", t('instances.empty.filtered.title')); text("empty-description", t('instances.empty.filtered.body')); } else { text("empty-title", t('instances.empty.none.title')); text("empty-description", t('instances.empty.none.body')); } return; } for (const vm of filtered) { const uuid = String(vm.uuid || ""); const invalidNetwork = vm?.network_status === 'configuration_invalid'; const category = invalidNetwork ? 'other' : stateCategory(vm.state); const row = document.createElement("tr"); const identity = makeElement("div", "vm-identity"); identity.append(makeElement("div", "vm-icon", "▣")); const identityText = makeElement("div"); const nameLink = makeElement("a", "vm-name-link", vm.name || t('instances.value.unnamed')); nameLink.href = vmPagePath(vm.api_id); nameLink.dataset.vmUuid = uuid; nameLink.setAttribute("aria-label", t('instances.manage.aria', { name: vm.name || uuid || t('instances.value.unnamed'), })); identityText.append(nameLink); const uuidRow = makeElement("span", "vm-uuid-row"); const uuidText = makeElement("span", "vm-id", uuid || t('instances.value.uuid_unknown')); if (uuid) uuidText.title = uuid; uuidRow.append(uuidText); if (uuid) uuidRow.append(makeCopyIconButton(uuid, "UUID")); identityText.append(uuidRow); identity.append(identityText); const identityCell = makeCell(row); identityCell.dataset.label = t('instances.column.instance'); identityCell.append(identity); const stateCell = makeCell(row); stateCell.dataset.label = t('instances.column.status'); stateCell.append(makeElement("span", `state-pill ${category}`, invalidNetwork ? t('instances.state.network_invalid') : stateLabel(vm.state))); const regionCell = makeCell(row); regionCell.dataset.label = t('instances.column.region'); regionCell.append(makeElement("span", "vm-metadata", vmRegion(vm))); const system = vmSystemInfo(vm); const systemCell = makeCell(row); systemCell.dataset.label = system.label; systemCell.append(makeElement("span", "vm-metadata", system.value)); const ipCell = makeCell(row); ipCell.dataset.label = t('instances.column.address'); const addresses = makeElement("div", "vm-public-addresses"); for (const [family, label] of [[4, t('instances.address.ipv4')]]) { const ip = vmIp(vm, family); const ipRow = makeElement("span", "vm-ip-copy-row"); ipRow.append(makeElement("span", "vm-metadata vm-ip", ip)); if (ip !== t('instances.value.not_available')) ipRow.append(makeCopyIconButton(ip, label)); addresses.append(ipRow); } ipCell.append(addresses); const spec = makeElement("div", "vm-spec"); spec.append(makeElement("strong", "", `${vm.vcpu ?? "—"} vCPU · ${vm.memory_mib ?? "—"} MiB`)); spec.append(makeElement("small", "", t('instances.spec.compute'))); const specCell = makeCell(row); specCell.dataset.label = t('instances.column.spec'); specCell.append(spec); const diskCell = makeCell(row); diskCell.dataset.label = t('instances.column.disk'); diskCell.append(makeElement("span", "vm-spec", diskLabel(vm))); tbody.append(row); } if (focusedVmId) { const replacement = Array.from(tbody.querySelectorAll(".vm-name-link")) .find((button) => button.dataset.vmUuid === focusedVmId); replacement?.focus({ preventScroll: true }); } } const VM_METRICS_RANGE_SECONDS = { "1h": 3600, "24h": 86400, "7d": 604800, "30d": 2592000 }; const VM_METRIC_CHARTS = [ { id: "cpu", titleKey: "instance_detail.metrics.cpu", unit: "percent", series: [{ key: "cpu_percent", color: "#0f9eaa" }] }, { id: "memory", titleKey: "instance_detail.metrics.memory", unit: "memory", series: [{ key: "memory_used_mib", color: "#4781cf" }, { key: "memory_total_mib", color: "#a4b7d7", dash: "6 5" }] }, { id: "disk", titleKey: "instance_detail.metrics.disk", unit: "rate", series: [{ key: "disk_read_bps", color: "#477dc9" }, { key: "disk_write_bps", color: "#e59c46" }] }, { id: "network", titleKey: "instance_detail.metrics.network", unit: "rate", series: [{ key: "network_rx_bps", color: "#17a685" }, { key: "network_tx_bps", color: "#926ed0" }] }, ]; let metricsLoopActive = false; function metricViewVisible() { return state.view === "detail" && state.detailTab === "performance" && Boolean(state.selectedVmId) && !document.hidden && !byId("dashboard-view").hidden && !byId("vm-workspace").hidden && !byId("vm-detail-view").hidden; } function stopVmMetrics() { metricsLoopActive = false; if (state.metricsPollTimer) window.clearTimeout(state.metricsPollTimer); state.metricsPollTimer = null; if (state.metricsResizeTimer) window.clearTimeout(state.metricsResizeTimer); state.metricsResizeTimer = null; state.metricsRequest?.controller.abort(); state.metricsRequest = null; } async function runVmMetricsLoop() { if (!metricsLoopActive || !metricViewVisible()) return; await loadVmMetrics(); if (!metricsLoopActive || !metricViewVisible() || state.metricsPollTimer) return; state.metricsPollTimer = window.setTimeout(() => { state.metricsPollTimer = null; void runVmMetricsLoop(); }, 60000); } function startVmMetrics() { if (!metricViewVisible() || metricsLoopActive) return; metricsLoopActive = true; void runVmMetricsLoop(); } function setVmMetricsStatus(message, warning = false) { const status = byId("vm-metrics-status"); status.textContent = message; status.classList.toggle("warning", warning); } function clearVmMetrics(message) { state.metricsPayload = null; setVmMetricsStatus(message); for (const chart of VM_METRIC_CHARTS) { text(`vm-metric-${chart.id}-summary`, "—"); byId(`vm-metric-${chart.id}-plot`).replaceChildren(makeElement("p", "vm-metric-empty", message)); } } async function loadVmMetrics() { if (!metricViewVisible()) return; const vmId = state.selectedVmId; const range = state.metricsRange; const previous = state.metricsRequest; if (previous?.vmId === vmId && previous.range === range) return; previous?.controller.abort(); const request = { vmId, range, controller: new AbortController() }; state.metricsRequest = request; setVmMetricsStatus(t('instance_detail.metrics.updating')); try { const payload = await api(`${vmPath()}/metrics?range=${encodeURIComponent(range)}`, { signal: request.controller.signal, }); if (request !== state.metricsRequest || !metricViewVisible()) return; if (!Array.isArray(payload?.points)) { throw new Error(t('instance_detail.metrics.load_failed')); } renderVmMetrics(payload); } catch { if (request !== state.metricsRequest || request.controller.signal.aborted || !metricViewVisible()) return; setVmMetricsStatus(t('instance_detail.metrics.load_failed'), true); } finally { if (request === state.metricsRequest) state.metricsRequest = null; } } function metricNumber(value) { return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; } function formatMetricRate(value) { if (value === null) return t('instance_detail.metrics.no_stat'); const units = ["B/s", "KB/s", "MB/s", "GB/s", "TB/s"]; let amount = value; let index = 0; while (amount >= 1000 && index < units.length - 1) { amount /= 1000; index += 1; } return `${amount.toFixed(index === 0 ? (amount < 1 && amount > 0 ? 2 : 0) : amount < 10 ? 2 : 1)} ${units[index]}`; } function formatMetricMemory(value) { if (value === null) return t('instance_detail.metrics.no_stat'); return value >= 1024 ? `${(value / 1024).toFixed(value < 10240 ? 2 : 1)} GiB` : `${Math.round(value)} MiB`; } function formatMetricValue(value, unit) { if (value === null) return t('instance_detail.metrics.no_stat'); if (unit === "percent") return `${value.toFixed(1)}%`; if (unit === "memory") return formatMetricMemory(value); return formatMetricRate(value); } function formatMetricTime(timestamp) { return i18n.date(timestamp * 1000); } function metricSummary(chart, points) { const latest = [...points].reverse().find((point) => chart.series.some((series) => metricNumber(point[series.key]) !== null)); if (!latest) return t('instance_detail.metrics.no_stat'); const value = (key) => metricNumber(latest[key]); if (chart.id === "cpu") return formatMetricValue(value("cpu_percent"), "percent"); if (chart.id === "memory") return t('instance_detail.metrics.summary_memory', { used: formatMetricMemory(value("memory_used_mib")), total: formatMetricMemory(value("memory_total_mib")), }); if (chart.id === "disk") return t('instance_detail.metrics.summary_disk', { read: formatMetricRate(value("disk_read_bps")), write: formatMetricRate(value("disk_write_bps")), }); return t('instance_detail.metrics.summary_network', { receive: formatMetricRate(value("network_rx_bps")), send: formatMetricRate(value("network_tx_bps")), }); } function metricChartEmptyText(chart) { if (chart.id === "memory") return t('instance_detail.metrics.no_memory'); if (chart.id === "disk" || chart.id === "network") return t('instance_detail.metrics.no_rate'); return t('instance_detail.metrics.no_cpu'); } function metricNiceMax(value) { if (value <= 0) return 1; const base = 10 ** Math.floor(Math.log10(value)); for (const step of [1, 1.5, 2, 2.5, 5, 10]) { if (value <= step * base) return step * base; } return 10 * base; } function metricSvgElement(tag, attributes = {}) { const element = document.createElementNS("http://www.w3.org/2000/svg", tag); for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, String(value)); return element; } function drawMetricChart(chart, points, start, end, intervalSeconds) { const plot = byId(`vm-metric-${chart.id}-plot`); const summary = metricSummary(chart, points); text(`vm-metric-${chart.id}-summary`, summary); const hasData = points.some((point) => chart.series.some((series) => metricNumber(point[series.key]) !== null)); if (!hasData) { plot.replaceChildren(makeElement("p", "vm-metric-empty", metricChartEmptyText(chart))); return; } const values = points.flatMap((point) => chart.series.map((series) => metricNumber(point[series.key]))).filter((value) => value !== null); const maximum = chart.unit === "percent" ? Math.max(100, metricNiceMax(Math.max(...values))) : metricNiceMax(Math.max(...values)); // A fixed 640px viewBox shrinks axis text to ~4px inside a phone card. const width = Math.max(240, Math.floor(plot.clientWidth || 640)); const height = Math.max(180, Math.floor(plot.clientHeight || 216)); const left = 64; const right = 18; const top = 14; const bottom = 37; const plotWidth = width - left - right; const plotHeight = height - top - bottom; const x = (timestamp) => left + Math.max(0, Math.min(1, (timestamp - start) / (end - start))) * plotWidth; const y = (value) => top + (1 - Math.min(value, maximum) / maximum) * plotHeight; const svg = metricSvgElement("svg", { viewBox: `0 0 ${width} ${height}`, role: "img", "aria-label": t('instance_detail.metrics.chart_aria', { title: t(chart.titleKey), range: byId("vm-metrics-range").selectedOptions[0]?.textContent || t('instance_detail.metrics.current_range'), summary, }), }); for (const fraction of [1, 0.5, 0]) { const lineY = top + (1 - fraction) * plotHeight; svg.append(metricSvgElement("line", { x1: left, x2: width - right, y1: lineY, y2: lineY, class: "vm-metric-gridline" })); const label = metricSvgElement("text", { x: left - 8, y: lineY + 4, "text-anchor": "end", class: "vm-metric-axis-label" }); label.textContent = formatMetricValue(fraction * maximum, chart.unit); svg.append(label); } for (const [fraction, anchor] of [[0, "start"], [0.5, "middle"], [1, "end"]]) { const label = metricSvgElement("text", { x: left + fraction * plotWidth, y: height - 8, "text-anchor": anchor, class: "vm-metric-axis-label" }); label.textContent = formatMetricTime(start + fraction * (end - start)); svg.append(label); } const maxGap = intervalSeconds * 2.5; for (const series of chart.series) { const segments = []; let segment = []; for (const point of points) { const value = metricNumber(point[series.key]); if (value === null) { if (segment.length) segments.push(segment); segment = []; continue; } if (segment.length && point.timestamp - segment[segment.length - 1].timestamp > maxGap) { segments.push(segment); segment = []; } segment.push({ timestamp: point.timestamp, value }); } if (segment.length) segments.push(segment); for (const group of segments) { if (group.length > 1) { const path = metricSvgElement("path", { d: group.map((point, index) => `${index ? "L" : "M"}${x(point.timestamp).toFixed(2)} ${y(point.value).toFixed(2)}`).join(" "), fill: "none", stroke: series.color, "stroke-width": 2.6, "stroke-linecap": "round", "stroke-linejoin": "round", ...(series.dash ? { "stroke-dasharray": series.dash } : {}), }); svg.append(path); } const last = group[group.length - 1]; svg.append(metricSvgElement("circle", { cx: x(last.timestamp), cy: y(last.value), r: group.length === 1 ? 3.8 : 2.8, fill: series.color })); } } plot.replaceChildren(svg); } function renderVmMetrics(payload) { state.metricsPayload = payload; const intervalSeconds = Math.max(1, Number(payload.interval_seconds) || 60); const rangeSeconds = VM_METRICS_RANGE_SECONDS[state.metricsRange]; const now = Math.floor(Date.now() / 1000); const points = payload.points .filter((point) => Number.isFinite(Number(point?.timestamp)) && Number(point.timestamp) >= now - rangeSeconds - intervalSeconds && Number(point.timestamp) <= now + intervalSeconds) .map((point) => ({ ...point, timestamp: Number(point.timestamp) })) .sort((a, b) => a.timestamp - b.timestamp); const end = Math.max(now, points.length ? points[points.length - 1].timestamp : now); const start = end - rangeSeconds; const visiblePoints = points.filter((point) => point.timestamp >= start && point.timestamp <= end); for (const chart of VM_METRIC_CHARTS) drawMetricChart(chart, visiblePoints, start, end, intervalSeconds); if (!visiblePoints.length) { setVmMetricsStatus(t('instance_detail.metrics.no_samples'), true); return; } const latest = visiblePoints[visiblePoints.length - 1].timestamp; // Bucket width grows for long ranges; freshness still follows the 60s // collector cadence, not the downsampling bucket width. const stale = end - latest > 60 * 2.5; setVmMetricsStatus(t('instance_detail.metrics.status', { count: visiblePoints.length, freshness: t(stale ? 'instance_detail.metrics.history' : 'instance_detail.metrics.latest'), time: formatMetricTime(latest), suffix: stale ? t('instance_detail.metrics.stale_suffix') : '', }), stale); } function trafficDailyViewVisible() { return state.view === "detail" && state.detailTab === "performance" && Boolean(state.selectedVmId) && !document.hidden && !byId("dashboard-view").hidden && !byId("vm-workspace").hidden && !byId("vm-detail-view").hidden; } function stopVmTrafficDaily() { state.trafficDailyRequest?.controller.abort(); state.trafficDailyRequest = null; if (state.trafficDailyResizeTimer) window.clearTimeout(state.trafficDailyResizeTimer); state.trafficDailyResizeTimer = null; } function setVmTrafficDailyStatus(message, warning = false) { const status = byId("vm-traffic-daily-status"); status.textContent = message; status.classList.toggle("warning", warning); } function clearVmTrafficDaily(message) { stopVmTrafficDaily(); state.trafficDailyPayload = null; state.trafficDailyVmId = ""; state.trafficDailyLoadedAt = 0; setVmTrafficDailyStatus(message); byId("vm-traffic-daily-plot").replaceChildren(makeElement("p", "vm-metric-empty", message)); } function trafficDailyItems(payload) { if (Array.isArray(payload)) return payload; for (const value of [payload?.points, payload?.days, payload?.items, payload?.daily, payload?.data?.points, payload?.data?.days, payload?.data]) { if (Array.isArray(value)) return value; } return null; } function trafficDailyDate(point) { const value = point?.date ?? point?.day ?? point?.bucket_date ?? point?.observed_date ?? point?.day_start ?? point?.timestamp ?? point?.time; const dateText = typeof value === "string" ? value.trim() : ""; if (/^\d{4}-\d{2}-\d{2}$/.test(dateText)) { return { timestamp: Date.parse(`${dateText}T00:00:00Z`), label: dateText }; } const timestamp = serviceTimestamp(value); if (timestamp === null) return null; const date = new Date(timestamp); return { timestamp, label: `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}-${String(date.getUTCDate()).padStart(2, "0")}` }; } function normalizeTrafficDailyPoints(payload) { const values = trafficDailyItems(payload); if (values === null) throw new Error(t('instance_detail.traffic.daily_invalid')); const points = []; for (const point of values) { const date = trafficDailyDate(point); if (!date) continue; const download = firstNumber(point?.download_bytes, point?.rx_bytes, point?.traffic_download_bytes, point?.download, point?.rx); const upload = firstNumber(point?.upload_bytes, point?.tx_bytes, point?.traffic_upload_bytes, point?.upload, point?.tx); points.push({ ...date, download, upload }); } return points.sort((a, b) => a.timestamp - b.timestamp).slice(-30); } function trafficDailyShortDate(point) { return point.label.slice(5).replace("-", "/"); } function drawVmTrafficDaily(payload) { const plot = byId("vm-traffic-daily-plot"); const points = normalizeTrafficDailyPoints(payload); if (!points.length) { const message = t('instance_detail.traffic.daily_empty'); plot.replaceChildren(makeElement("p", "vm-metric-empty", message)); setVmTrafficDailyStatus(message, true); return; } const values = points.flatMap(point => [point.download, point.upload]).filter(value => value !== null); if (!values.length) { const message = t('instance_detail.traffic.daily_no_samples'); plot.replaceChildren(makeElement("p", "vm-metric-empty", message)); setVmTrafficDailyStatus(message, true); return; } const maximum = metricNiceMax(Math.max(...values)); const width = Math.max(300, Math.floor(plot.clientWidth || 800)); const height = Math.max(220, Math.floor(plot.clientHeight || 290)); const left = 68; const right = 18; const top = 18; const bottom = 38; const plotWidth = width - left - right; const plotHeight = height - top - bottom; const groupWidth = plotWidth / points.length; const barWidth = Math.max(2, Math.min(12, groupWidth * .32)); const y = (value) => top + (1 - Math.min(value, maximum) / maximum) * plotHeight; const totalDownload = points.reduce((sum, point) => sum + (point.download ?? 0), 0); const totalUpload = points.reduce((sum, point) => sum + (point.upload ?? 0), 0); const sampledDays = points.filter(point => point.download !== null || point.upload !== null).length; const svg = metricSvgElement("svg", { viewBox: `0 0 ${width} ${height}`, role: "img", "aria-label": t('instance_detail.traffic.daily_aria', { days: points.length, download: formatBytes(totalDownload), upload: formatBytes(totalUpload), }), }); for (const fraction of [1, .5, 0]) { const lineY = top + (1 - fraction) * plotHeight; svg.append(metricSvgElement("line", { x1: left, x2: width - right, y1: lineY, y2: lineY, class: "vm-metric-gridline" })); const label = metricSvgElement("text", { x: left - 8, y: lineY + 4, "text-anchor": "end", class: "vm-metric-axis-label" }); label.textContent = formatBytes(fraction * maximum); svg.append(label); } points.forEach((point, index) => { const center = left + (index + .5) * groupWidth; for (const [value, className, offset] of [[point.download, "download", -barWidth], [point.upload, "upload", 0]]) { if (value === null) continue; const topY = y(value); const bar = metricSvgElement("rect", { x: center + offset, y: topY, width: barWidth, height: Math.max(1, top + plotHeight - topY), rx: Math.min(2, barWidth / 3), class: `vm-traffic-daily-bar ${className}`, }); const title = metricSvgElement("title"); title.textContent = t('instance_detail.traffic.daily_bar', { date: point.label, direction: t(className === "download" ? 'instance_detail.traffic.download' : 'instance_detail.traffic.upload'), value: formatBytes(value), }); bar.append(title); svg.append(bar); } }); const labelIndexes = [...new Set([0, Math.floor((points.length - 1) / 2), points.length - 1])]; for (const index of labelIndexes) { const anchor = index === 0 ? "start" : index === points.length - 1 ? "end" : "middle"; const label = metricSvgElement("text", { x: left + (index + .5) * groupWidth, y: height - 8, "text-anchor": anchor, class: "vm-metric-axis-label" }); label.textContent = trafficDailyShortDate(points[index]); svg.append(label); } plot.replaceChildren(svg); setVmTrafficDailyStatus(t('instance_detail.traffic.daily_summary', { days: points.length, sampled: sampledDays, download: formatBytes(totalDownload), upload: formatBytes(totalUpload), })); } async function loadVmTrafficDaily(force = false) { if (!trafficDailyViewVisible()) return; const vmId = state.selectedVmId; if (!force && state.trafficDailyPayload && state.trafficDailyVmId === vmId && Date.now() - state.trafficDailyLoadedAt < 60000) return; if (state.trafficDailyRequest?.vmId === vmId) return; state.trafficDailyRequest?.controller.abort(); const request = { vmId, controller: new AbortController() }; state.trafficDailyRequest = request; setVmTrafficDailyStatus(t('instance_detail.traffic.daily_loading')); try { const payload = await api(`${vmPath()}/traffic/daily?days=30`, { signal: request.controller.signal }); if (request !== state.trafficDailyRequest || !trafficDailyViewVisible()) return; state.trafficDailyPayload = payload; state.trafficDailyVmId = vmId; state.trafficDailyLoadedAt = Date.now(); drawVmTrafficDaily(payload); } catch { if (request !== state.trafficDailyRequest || request.controller.signal.aborted || !trafficDailyViewVisible()) return; setVmTrafficDailyStatus(t('instance_detail.traffic.daily_failed'), true); if (!state.trafficDailyPayload || state.trafficDailyVmId !== vmId) { byId("vm-traffic-daily-plot").replaceChildren(makeElement("p", "vm-metric-empty", t('instance_detail.traffic.daily_failed'))); } } finally { if (request === state.trafficDailyRequest) state.trafficDailyRequest = null; } } function startVmTrafficDaily() { if (!trafficDailyViewVisible()) return; if (state.trafficDailyPayload && state.trafficDailyVmId === state.selectedVmId) drawVmTrafficDaily(state.trafficDailyPayload); void loadVmTrafficDaily(); } const TEMPLATE_FAMILY_NAMES = { almalinux: "AlmaLinux", debian: "Debian", centos: "CentOS Stream", centosstream: "CentOS Stream", ubuntu: "Ubuntu", }; const TEMPLATE_ICON_PATHS = { AlmaLinux: "/cloud/almalinux-icon.svg", Debian: "/cloud/debian-icon.svg", "CentOS Stream": "/cloud/centos-icon.svg", Ubuntu: "/cloud/ubuntu-icon.svg", }; const TEMPLATE_FAMILY_ORDER = new Map([ ["AlmaLinux", 0], ["Debian", 1], ["CentOS Stream", 2], ["Ubuntu", 3], ]); function compareTemplateVersions(left, right) { const leftParts = String(left || "0").split(".").map((part) => Number(part) || 0); const rightParts = String(right || "0").split(".").map((part) => Number(part) || 0); const length = Math.max(leftParts.length, rightParts.length); for (let index = 0; index < length; index += 1) { const difference = (leftParts[index] || 0) - (rightParts[index] || 0); if (difference) return difference; } return 0; } function templateSystem(item) { const id = String(item?.id || ""); const familyKey = String(item?.os_family || "").trim().toLowerCase().replace(/[\s_-]+/g, ""); const namedFamily = Object.prototype.hasOwnProperty.call(TEMPLATE_FAMILY_NAMES, familyKey) ? TEMPLATE_FAMILY_NAMES[familyKey] : ""; const idMatch = /^(alma|debian|ubuntu|centosstream)([0-9]{1,4})-/.exec(id); const idFamily = ({ alma: "AlmaLinux", debian: "Debian", ubuntu: "Ubuntu", centosstream: "CentOS Stream" })[idMatch?.[1]] || ""; const rawIdVersion = idMatch?.[2] || ""; const idVersion = idMatch?.[1] === "ubuntu" && rawIdVersion.length === 4 ? `${rawIdVersion.slice(0, 2)}.${rawIdVersion.slice(2)}` : rawIdVersion; const family = namedFamily || idFamily || t('common.template.other_system'); const providedVersion = String(item?.os_version || ""); const version = /^[0-9]+(?:\.[0-9]+){0,2}$/.test(providedVersion) ? providedVersion : idVersion; return { family, version }; } function templateIcon(family, className) { const logoPath = TEMPLATE_ICON_PATHS[family]; const icon = makeElement("span", `${className}${logoPath ? " system" : ""}`); icon.setAttribute("aria-hidden", "true"); if (logoPath) { const logo = makeElement("img", "template-system-logo"); logo.src = logoPath; logo.alt = ""; icon.append(logo); } else { icon.textContent = "◈"; } return icon; } function renderTemplateCatalogStatus(inputId, message, busy = false) { const input = byId(inputId); const container = byId(inputId === "vm-template" ? "vm-template-catalog" : "reinstall-template-catalog"); if (!input || !container) return; input.value = ""; input.disabled = true; container.setAttribute("aria-busy", String(busy)); const status = makeElement("p", "template-catalog-status", message); status.setAttribute("role", "status"); container.replaceChildren(status); } function closeTemplateVersionMenus(except = null) { document.querySelectorAll(".template-family-card[open]").forEach((card) => { if (card !== except) card.open = false; }); } function bindTemplateVersionMenu(card, container) { card.addEventListener("toggle", () => { const deployment = container.id === 'vm-template-catalog'; const family = String(card.dataset.family || t('common.template.system_image')); const summary = card.querySelector("summary"); const selection = card.querySelector(".template-family-selection"); if (!card.open) { const selectedName = String(selection?.title || ""); summary?.setAttribute("aria-label", deployment ? t(selectedName ? 'deploy.template.family_change' : 'deploy.template.family_expand', selectedName ? { family, name: selectedName } : { family }) : (selectedName ? t('reinstall.template.family_change', { family, name: selectedName }) : t('reinstall.template.family_expand', { family }))); return; } summary?.setAttribute("aria-label", deployment ? t('deploy.template.family_collapse', { family }) : t('reinstall.template.family_collapse', { family })); container.querySelectorAll(".template-family-card[open]").forEach((other) => { if (other !== card) other.open = false; }); requestAnimationFrame(() => { if (!card.open) return; const option = card.querySelector('.template-version-option[aria-pressed="true"]') || card.querySelector(".template-version-option"); option?.focus({ preventScroll: true }); }); }); } function updateTemplateFamilySelection(card, selectedName = "", selectedVersion = "") { const deployment = card.closest('#vm-template-catalog') !== null; const family = String(card.dataset.family || t('common.template.system_image')); const summary = card.querySelector("summary"); const label = card.querySelector(".template-family-selection"); const selected = Boolean(selectedName); const fallbackVersion = String(selectedName).startsWith(family) ? String(selectedName).slice(family.length).replace(/^[-_\s]+/, "") : String(selectedName); const versionLabel = String(selectedVersion || fallbackVersion).trim(); card.classList.toggle("has-selection", selected); if (label) { label.textContent = selected ? versionLabel : ""; label.title = selected ? selectedName : ""; } summary?.setAttribute("aria-label", deployment ? t(selected ? 'deploy.template.family_change' : 'deploy.template.family_expand', selected ? { family, name: selectedName } : { family }) : (selected ? t('reinstall.template.family_change', { family, name: selectedName }) : t('reinstall.template.family_expand', { family }))); } function renderTemplateCatalog(inputId) { const input = byId(inputId); const container = byId(inputId === "vm-template" ? "vm-template-catalog" : "reinstall-template-catalog"); container.removeAttribute("aria-busy"); const opened = new Set(Array.from(container.querySelectorAll("details[open]"), (detail) => detail.dataset.family)); const groups = new Map(); const catalogTemplates = inputId === "vm-template" ? deploymentTemplates() : state.templates; for (const item of catalogTemplates) { if (!item?.id) continue; const { family, version } = templateSystem(item); if (!groups.has(family)) groups.set(family, []); groups.get(family).push({ item, version }); } if (!groups.size) { input.value = ""; const noOffer = inputId === "vm-template" && !selectedSaleOffer(); container.replaceChildren(makeElement("p", "template-catalog-empty", inputId === "vm-template" ? (state.templateCatalogUnavailable ? t('deploy.template.catalog_unavailable') : noOffer ? t('deploy.template.offer_first') : t('deploy.template.no_match')) : state.templateCatalogUnavailable ? t('reinstall.template.catalog_unavailable') : state.admin ? t('reinstall.template.admin_empty') : t('reinstall.template.empty'))); input.disabled = true; return; } if (!catalogTemplates.some((item) => String(item.id) === input.value)) input.value = ""; input.disabled = false; const cards = []; const orderedGroups = Array.from(groups.entries()).sort(([left], [right]) => (TEMPLATE_FAMILY_ORDER.get(left) ?? 100) - (TEMPLATE_FAMILY_ORDER.get(right) ?? 100) || left.localeCompare(right, i18n.locale)); for (const [family, entries] of orderedGroups) { entries.sort((a, b) => compareTemplateVersions(b.version, a.version) || String(a.item.name || "").localeCompare(String(b.item.name || ""), i18n.locale)); const card = makeElement("details", "template-family-card"); card.dataset.family = family; card.setAttribute("name", `${inputId}-family`); card.open = opened.has(family); bindTemplateVersionMenu(card, container); const summary = makeElement("summary", "template-family-summary"); const selectedMark = makeElement("span", "template-family-selected-mark", "✓"); selectedMark.setAttribute("aria-hidden", "true"); const icon = templateIcon(family, "template-family-icon"); const selection = makeElement("span", "template-family-selection"); selection.setAttribute("aria-hidden", "true"); const arrow = makeElement("span", "template-family-arrow"); arrow.setAttribute("aria-hidden", "true"); const footer = makeElement("span", "template-family-footer"); footer.append(selection, arrow); summary.append(selectedMark, icon, makeElement("strong", "", family), footer); const versions = makeElement("div", "template-versions"); versions.setAttribute("role", "group"); versions.setAttribute("aria-label", inputId === 'vm-template' ? t('deploy.template.versions', { family }) : t('reinstall.template.versions', { family })); for (const { item, version } of entries) { const id = String(item.id); const name = String(item.name || id); const option = makeElement("button", "template-version-option"); option.type = "button"; option.dataset.templateId = id; option.setAttribute("aria-pressed", String(input.value === id)); option.setAttribute("aria-label", inputId === 'vm-template' ? t('deploy.template.select', { name }) : t('reinstall.template.select', { name })); option.append(makeElement("strong", "", name)); option.addEventListener("click", () => { input.value = id; container.querySelectorAll(".template-version-option").forEach((button) => { button.setAttribute("aria-pressed", String(button.dataset.templateId === id)); }); container.querySelectorAll(".template-family-card").forEach((familyCard) => { updateTemplateFamilySelection(familyCard, familyCard === card ? name : "", familyCard === card ? version : ""); }); card.open = false; summary.focus({ preventScroll: true }); if (inputId === "vm-template") { showError("create-error", ""); updateCreateAvailability(); } else showError("reinstall-error", ""); }); versions.append(option); } card.append(summary, versions); const selectedEntry = entries.find(({ item }) => String(item.id) === input.value); updateTemplateFamilySelection(card, selectedEntry ? String(selectedEntry.item.name || selectedEntry.item.id) : "", selectedEntry?.version || ""); cards.push(card); } container.replaceChildren(...cards); } document.addEventListener("click", (event) => { if (!(event.target instanceof Element) || !event.target.closest(".template-family-card")) { closeTemplateVersionMenus(); } }); document.addEventListener("focusin", (event) => { const openCard = document.querySelector(".template-family-card[open]"); if (!openCard || (event.target instanceof Element && openCard.contains(event.target))) return; closeTemplateVersionMenus(); }); document.addEventListener("keydown", (event) => { if (event.key !== "Escape") return; const openCard = document.querySelector(".template-family-card[open]"); if (!openCard) return; closeTemplateVersionMenus(); openCard.querySelector("summary")?.focus({ preventScroll: true }); }); async function initializeSession(view, bootstrapUser = null) { state.view = view; if (bootstrapUser && typeof bootstrapUser === 'object') { if (bootstrapUser.authenticated === false) { location.assign('/auth/login'); return false; } applyCloudUser(bootstrapUser); return true; } const session = await api('/api/v1/session'); if (session.authenticated === false) { location.assign('/auth/login'); return false; } applyCloudUser(session); return true; } async function selectVmByApiId(apiId, bootstrapVm = null) { if (bootstrapVm && typeof bootstrapVm === 'object') { const vm = normalizeVm(bootstrapVm); if (!vm.api_id || String(vm.api_id) !== String(apiId || '')) { throw new Error(vmPageText('instance_detail.error.vm_data_invalid', 'reinstall.error.vm_data_invalid')); } state.vms = [vm]; state.selectedVmId = vm.uuid; return vm; } const vm = await loadVm(apiId, true); if (!vm) throw new Error(vmPageText('instance_detail.error.vm_unavailable', 'reinstall.error.vm_unavailable')); return vm; } function bindPageCleanup() { window.addEventListener('pagehide', () => { clearCredential(); clearReinstallPasswordCard(); stopVmMetrics(); stopVmTrafficDaily(); closeConsole(); state.resourceController?.abort(); vmStatusGeneration += 1; vmStatusRequest?.controller.abort(); vmStatusRequest = null; for (const observer of activeTaskObservers) observer.stop('pagehide'); activeTaskObservers.clear(); }); } export { CLOUD_PATHS, VM_DETAIL_TABS, api, bindPageCleanup, buy, byId, clearCredential, clearVmMetrics, clearVmTrafficDaily, closeConsole, copyText, credential, drawVmTrafficDaily, hydrateVmDetailBootstrap, initializeSession, loadGlobalTemplates, loadKeys, loadVmMetrics, loadVmTrafficDaily, loadVm, loadVmStatus, loadVms, navigate, openCreate, openReinstall, reinstall, readBootstrap, renderVMs, renderVmDetail, renderVmMetrics, selectVmByApiId, selectedVm, setVmDetailTab, showError, state, stopVmMetrics, stopVmTrafficDaily, toast, trafficDailyViewVisible, vmIp, vmPagePath, };