| 1 | import { reportDiagnostic } from "./diagnostics.mjs"; |
| 2 | import { httpErrorMessage, connectionErrorMessage, operationName, nativeFailureMessage } from "./error-message.mjs"; |
| 3 | import { assertConnection, connectionHeaders, getClientContext, isProjectSharesPath } from "./client-context.mjs"; |
| 4 | import { installAgentNativeConsumer } from "./agent-native.js"; |
| 5 | let sessionRenewal; |
| 6 | class WorkbenchUnreachable extends Error {} |
| 7 | async function responseError(response, path, method = "GET") { |
| 8 | const error = new Error( |
| 9 | httpErrorMessage(path, response.status, await response.text(), response.headers.get("Content-Type") || "", method), |
| 10 | ); |
| 11 | error.status = response.status; |
| 12 | error.recovery = response.headers.get("X-Cage-Recovery") || ""; |
| 13 | return error; |
| 14 | } |
| 15 | async function renewSession() { |
| 16 | if (!sessionRenewal) { |
| 17 | sessionRenewal = (async () => { |
| 18 | const { url } = await native("refreshSession"); |
| 19 | const entry = new URL(url); |
| 20 | if (entry.origin !== location.origin) { |
| 21 | await native("reconnect"); |
| 22 | throw new Error("工作台地址已更新,连接恢复后请重试刚才的操作。"); |
| 23 | } |
| 24 | const response = await fetch("/api/session", { |
| 25 | method: "POST", |
| 26 | headers: { "Content-Type": "application/json" }, |
| 27 | body: JSON.stringify({ token: entry.hash.slice(1) }), |
| 28 | }); |
| 29 | if (!response.ok) throw await responseError(response, "/session"); |
| 30 | })().finally(() => { |
| 31 | sessionRenewal = null; |
| 32 | }); |
| 33 | } |
| 34 | return sessionRenewal; |
| 35 | } |
| 36 | export async function api(path, body, method, headers = {}, { signal } = {}) { |
| 37 | const connection = getClientContext().connection_id; |
| 38 | const options = { |
| 39 | method: method || (body === undefined ? "GET" : "POST"), |
| 40 | headers: { ...connectionHeaders(path), ...(body === undefined ? {} : { "Content-Type": "application/json" }), ...headers }, |
| 41 | body: body === undefined ? undefined : JSON.stringify(body), |
| 42 | signal, |
| 43 | }; |
| 44 | const send = async () => { |
| 45 | try { return await fetch("/api" + path, options); } |
| 46 | catch (error) { |
| 47 | if (signal?.aborted) throw signal.reason; |
| 48 | reportDiagnostic("frontend", error); |
| 49 | const message = connectionErrorMessage(path, options.method); |
| 50 | if (error instanceof TypeError) throw new WorkbenchUnreachable(message, { cause: error }); |
| 51 | throw new Error(message, { cause: error }); |
| 52 | } |
| 53 | }; |
| 54 | let response = await send(); |
| 55 | |
| 56 | |
| 57 | if (response.status === 401 && path !== "/session" && nativeAvailable()) { |
| 58 | await renewSession(); |
| 59 | response = await send(); |
| 60 | } |
| 61 | if (response.status === 423 && !path.startsWith("/client/")) window.dispatchEvent(new Event("cage-account-locked")); |
| 62 | if (!response.ok) throw await responseError(response, path, options.method); |
| 63 | let value; |
| 64 | try { value = await response.json(); } |
| 65 | catch (error) { reportDiagnostic("frontend", error); throw new Error(`${operationName(path, options.method)}失败:后台返回的结果格式无效。请重新连接;仍出现时在设置中导出诊断包。`, { cause: error }); } |
| 66 | if (path !== "/session" && !path.startsWith("/agent/native") && (!path.startsWith("/client/") || isProjectSharesPath(path))) assertConnection(connection); |
| 67 | return value; |
| 68 | } |
| 69 | export async function uploadFile(path, file, { signal, onProgress } = {}) { |
| 70 | const headers = connectionHeaders(path); |
| 71 | const connection = getClientContext().connection_id; |
| 72 | const send = () => new Promise((resolve, reject) => { |
| 73 | if (signal?.aborted) { reject(new DOMException("上传已取消", "AbortError")); return; } |
| 74 | const request = new XMLHttpRequest(); |
| 75 | const abort = () => request.abort(); |
| 76 | const cleanup = () => signal?.removeEventListener("abort", abort); |
| 77 | request.open("POST", "/api" + path); |
| 78 | request.setRequestHeader("Content-Type", "application/octet-stream"); |
| 79 | for (const [name, value] of Object.entries(headers)) request.setRequestHeader(name, value); |
| 80 | request.upload.onprogress = event => onProgress?.(event.loaded, event.total || file.size); |
| 81 | request.onerror = () => { cleanup(); reject(new Error("上传文件失败:与 Cage 后台的连接中断。请恢复连接后核对目标是否已收到文件,再重新选择文件。")); }; |
| 82 | request.onabort = () => { cleanup(); reject(new DOMException("上传已取消", "AbortError")); }; |
| 83 | request.onload = () => { |
| 84 | cleanup(); |
| 85 | if (request.status === 423) window.dispatchEvent(new Event("cage-account-locked")); |
| 86 | if (request.status !== 200) { |
| 87 | const error = new Error(httpErrorMessage(path, request.status, request.responseText, request.getResponseHeader("Content-Type") || "")); |
| 88 | error.status = request.status; reject(error); return; |
| 89 | } |
| 90 | try { assertConnection(connection); } |
| 91 | catch (error) { reject(error); return; } |
| 92 | try { resolve(JSON.parse(request.responseText)); } |
| 93 | catch { reject(new Error("上传文件后未收到有效确认。请先核对目标是否已收到文件,避免重复上传;仍失败时导出诊断包。")); } |
| 94 | }; |
| 95 | signal?.addEventListener("abort", abort, { once: true }); |
| 96 | request.send(file); |
| 97 | }); |
| 98 | try { return await send(); } |
| 99 | catch (error) { |
| 100 | if (error.status !== 401 || !nativeAvailable() || signal?.aborted) throw error; |
| 101 | await renewSession(); |
| 102 | return send(); |
| 103 | } |
| 104 | } |
| 105 | const nativeBridge = () => |
| 106 | window.cageNativeBridge || window.webkit?.messageHandlers?.cage; |
| 107 | export const nativeAvailable = () => Boolean(nativeBridge()); |
| 108 | const lostLocalView = (context) => |
| 109 | context.desktop_gateway && context.mode === "local" && |
| 110 | context.connection?.state === "failed" && context.connection.error_code === "connection_lost"; |
| 111 | |
| 112 | async function suspendBeforeQuit(context) { |
| 113 | if (context.mode !== "local" || context.client_only || lostLocalView(context)) return; |
| 114 | try { |
| 115 | await api("/account/suspend", {}); |
| 116 | } catch (error) { |
| 117 | if (error.status === 423) return; |
| 118 | |
| 119 | if (context.desktop_gateway && [409, 502].includes(error.status)) { |
| 120 | const latest = await api("/client/context"); |
| 121 | if (latest.connection_id === context.connection_id && lostLocalView(latest)) return; |
| 122 | } |
| 123 | throw error; |
| 124 | } |
| 125 | } |
| 126 | export async function native(action, extra = {}) { |
| 127 | const context = getClientContext(); |
| 128 | const connection = context.connection_id; |
| 129 | if (action === "quitNow") { |
| 130 | try { await suspendBeforeQuit(context); } |
| 131 | catch (error) { if (!(error instanceof WorkbenchUnreachable)) throw error; } |
| 132 | assertConnection(connection); |
| 133 | } |
| 134 | try { |
| 135 | const result = await nativeBridge().postMessage({ action, ...extra, connection_id: connection }); |
| 136 | assertConnection(connection); |
| 137 | return result; |
| 138 | } |
| 139 | catch (error) { |
| 140 | reportDiagnostic("frontend", error); |
| 141 | const original = error?.message || String(error); |
| 142 | const message = nativeFailureMessage(action, original); |
| 143 | if (message === original) throw error; |
| 144 | throw new Error(message, { cause: error }); |
| 145 | } |
| 146 | } |
| 147 | export const readClipboard = () => |
| 148 | nativeAvailable() ? native("clipboardRead") : navigator.clipboard.readText(); |
| 149 | export const writeClipboard = (text) => |
| 150 | nativeAvailable() |
| 151 | ? native("clipboardWrite", { text }) |
| 152 | : navigator.clipboard.writeText(text); |
| 153 | export function normalizeURL(text) { |
| 154 | const value = text.trim(); |
| 155 | if (!value || value === "about:blank") return "about:blank"; |
| 156 | if (/^https?:\/\//i.test(value)) return new URL(value).href; |
| 157 | if (/^[a-z][a-z\d+.-]*:/i.test(value) && !/^localhost:\d+/i.test(value)) |
| 158 | throw new Error("地址仅支持 http 或 https"); |
| 159 | if ( |
| 160 | !/\s/.test(value) && |
| 161 | (value.includes(".") || /^localhost(?::\d+)?(?:\/|$)/i.test(value)) |
| 162 | ) |
| 163 | return new URL( |
| 164 | (/^localhost|^127\./.test(value) ? "http://" : "https://") + value, |
| 165 | ).href; |
| 166 | return "https://www.google.com/search?q=" + encodeURIComponent(value); |
| 167 | } |
| 168 | |
| 169 | installAgentNativeConsumer({ api, native, nativeAvailable, getContext: getClientContext }); |