| 1 | import { httpErrorMessage, connectionErrorMessage } from "../error-message.mjs"; |
| 2 | |
| 3 | |
| 4 | |
| 5 | const desktopConnection = location.pathname === "/mobile.html" |
| 6 | ? sessionStorage.getItem("cage-cli-local-connection") : null; |
| 7 | |
| 8 | async function requestAPI(path, { body, signal, keepalive } = {}) { |
| 9 | let response; |
| 10 | try { |
| 11 | response = await fetch(path, { |
| 12 | keepalive, |
| 13 | method: body === undefined ? "GET" : "POST", |
| 14 | credentials: "same-origin", |
| 15 | cache: "no-store", |
| 16 | headers: { ...(desktopConnection ? { "X-Cage-Connection": desktopConnection } : {}), |
| 17 | ...(body === undefined ? {} : { "Content-Type": "application/json" }) }, |
| 18 | body: body === undefined ? undefined : JSON.stringify(body), |
| 19 | signal, |
| 20 | }); |
| 21 | } catch (error) { |
| 22 | if (signal?.aborted) throw error; |
| 23 | throw new Error(connectionErrorMessage(path), { cause: error }); |
| 24 | } |
| 25 | if (!response.ok) { |
| 26 | let message; |
| 27 | if (response.status === 401) message = "连接授权已失效,请从 Cage 重新打开此页面。"; |
| 28 | else if (response.status === 423) message = "Cage 已锁定。请在电脑上解锁,再重新读取。"; |
| 29 | else if ((response.headers.get("Content-Type") || "").startsWith("text/plain")) { |
| 30 | message = (await response.text()).trim().slice(0, 1200); |
| 31 | } |
| 32 | const error = new Error(message || httpErrorMessage(path, response.status)); |
| 33 | error.status = response.status; |
| 34 | throw error; |
| 35 | } |
| 36 | if (response.status === 204) return null; |
| 37 | try { return await response.json(); } |
| 38 | catch (error) { throw new Error("读取会话或画面结果失败:Cage 返回的数据格式无效。请重新读取;持续出现时从电脑上的 Cage 导出诊断包。", { cause: error }); } |
| 39 | } |
| 40 | |
| 41 | export const request = (path, options) => requestAPI("/api/mobile/cli" + path, options); |
| 42 | export const browserRequest = (path, options) => requestAPI("/api/mobile/browser" + path, options); |
| 43 | |
| 44 | export const desktopRequest = (path, options) => requestAPI("/api/mobile/desktop" + path, options); |
| 45 | |
| 46 | export const sessionPath = (id) => "/sessions/" + encodeURIComponent(id); |
| 47 | export const accessDenied = (error) => error.status === 401 || error.status === 423; |