dsh-sub2api 0.0.0-stage → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/config.js ADDED
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Plugin configuration: defaults plus a tolerant reader.
3
+ *
4
+ * The loader may hand `apply()` either plain values or volatile references
5
+ * (`{ get() }`), depending on how the row was written. Everything here reads
6
+ * through {@link field} so both shapes work, and so a settings-page write is
7
+ * visible on the next read without re-applying the plugin.
8
+ * @module dsh-sub2api/config
9
+ */
10
+
11
+ import { join } from "node:path";
12
+ import { homedir } from "node:os";
13
+ import { API_KEY_REF, KEY_NAME, MODELS_CACHE_FILE } from "./constants.js";
14
+ import { normalizeBaseUrl } from "./util.js";
15
+
16
+ /**
17
+ * Read one configuration field, unwrapping a volatile reference when present.
18
+ * @template T
19
+ * @param {any} config raw or volatile configuration
20
+ * @param {string} key field name
21
+ * @param {T} fallback value used when the field is absent or blank
22
+ * @returns {T}
23
+ */
24
+ export function field(config, key, fallback) {
25
+ let value = config?.[key];
26
+ if (value !== null && typeof value === "object" && typeof value.get === "function") {
27
+ value = value.get();
28
+ }
29
+ if (value === undefined || value === null || value === "") return fallback;
30
+ return value;
31
+ }
32
+
33
+ /**
34
+ * Resolve the raw configuration into the facts the rest of the plugin uses.
35
+ * @param {any} config configuration handed to `apply()`
36
+ * @returns {{
37
+ * apiBase: string,
38
+ * payBase: string,
39
+ * apiKeyEnv: string,
40
+ * groupId: number | undefined,
41
+ * keyName: string,
42
+ * requestTimeoutMs: number,
43
+ * streamIdleTimeoutMs: number,
44
+ * modelsCachePath: string,
45
+ * showSidebarQuota: boolean,
46
+ * visibleModels: string[],
47
+ * contextWindow: number | undefined,
48
+ * autoProvision: boolean,
49
+ * announceToAgent: boolean,
50
+ * }}
51
+ */
52
+ export function resolveConfig(config) {
53
+ const dshHome = process.env.DSH_HOME ?? join(homedir(), ".dsh");
54
+ const configuredKeyName = String(field(config, "keyName", "")).trim();
55
+
56
+ return {
57
+ apiBase: normalizeBaseUrl(field(config, "apiBase", "https://sub.pscly.cc")),
58
+ payBase: normalizeBaseUrl(field(config, "payBase", "https://pay.pscly.cc")),
59
+ apiKeyEnv: String(field(config, "apiKeyEnv", API_KEY_REF)),
60
+ groupId: toPositiveInt(field(config, "groupId", undefined)),
61
+ keyName: configuredKeyName === "" ? KEY_NAME : configuredKeyName,
62
+ requestTimeoutMs: toPositiveInt(field(config, "requestTimeoutMs", 300000)),
63
+ streamIdleTimeoutMs: toPositiveInt(field(config, "streamIdleTimeoutMs", 300000)),
64
+ modelsCachePath: String(
65
+ field(config, "modelsCachePath", join(dshHome, MODELS_CACHE_FILE)),
66
+ ),
67
+ showSidebarQuota: field(config, "showSidebarQuota", false) === true,
68
+ visibleModels: toStringArray(field(config, "visibleModels", [])),
69
+ contextWindow: toPositiveInt(field(config, "contextWindow", undefined)),
70
+ autoProvision: field(config, "autoProvision", true) !== false,
71
+ announceToAgent: field(config, "announceToAgent", true) !== false,
72
+ };
73
+ }
74
+
75
+ /** Coerce to a positive integer, or undefined when it is not one. */
76
+ function toPositiveInt(value) {
77
+ const n = typeof value === "number" ? value : Number(value);
78
+ if (!Number.isFinite(n) || n <= 0) return undefined;
79
+ return Math.trunc(n);
80
+ }
81
+
82
+ /** Coerce to a list of non-empty strings. */
83
+ function toStringArray(value) {
84
+ if (!Array.isArray(value)) return [];
85
+ return value.map((item) => String(item ?? "").trim()).filter((item) => item !== "");
86
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Stable identifiers shared by the host plugin, its HTTP routes and the browser panel.
3
+ * @module dsh-sub2api/constants
4
+ */
5
+
6
+ /** Cordis plugin name (the `name` export hosts log and address). */
7
+ export const PLUGIN_NAME = "llm-sub2api";
8
+
9
+ /** The single provider route this plugin owns. */
10
+ export const PROVIDER = "sub2api";
11
+
12
+ /** Settings namespace the Models page associates with this provider. */
13
+ export const SETTINGS_NS = "llm-sub2api";
14
+
15
+ /** Credential reference that holds the sub2api API key. */
16
+ export const API_KEY_REF = "SUB2API_API_KEY";
17
+
18
+ /** Credential reference that holds an optional saved account password. */
19
+ export const PASSWORD_REF = "SUB2API_PASSWORD";
20
+
21
+ /** Credential record scope/id holding the login session (tokens + user snapshot). */
22
+ export const SESSION_SCOPE = "llm-sub2api";
23
+ export const SESSION_ID = "session";
24
+
25
+ /** Name of the API key this plugin creates on the user's behalf. */
26
+ export const KEY_NAME = "dsh";
27
+
28
+ /** Prefix every browser-facing route lives under. */
29
+ export const ROUTE_PREFIX = "/api/sub2api";
30
+
31
+ /** Default model catalog cache file name under $DSH_HOME. */
32
+ export const MODELS_CACHE_FILE = "sub2api-models.json";
33
+
34
+ /** How long a discovered catalog stays fresh before a background refresh. */
35
+ export const CATALOG_TTL_MS = 10 * 60 * 1000;
36
+
37
+ /** Refresh the access token this long before it expires. */
38
+ export const TOKEN_REFRESH_LEAD_MS = 60 * 1000;
39
+
40
+ /** Default page size when listing API keys. */
41
+ export const KEY_PAGE_SIZE = 100;
42
+
43
+ /** Model id fragments that mark an image-capable model when the endpoint says nothing. */
44
+ export const VISION_HINTS = [
45
+ "gpt-4o",
46
+ "gpt-4.1",
47
+ "gpt-5",
48
+ "o3",
49
+ "o4",
50
+ "claude-3",
51
+ "claude-4",
52
+ "claude-sonnet",
53
+ "claude-opus",
54
+ "gemini",
55
+ "vision",
56
+ "vl",
57
+ "-v-",
58
+ "qwen-vl",
59
+ "glm-4v",
60
+ "pixtral",
61
+ "llava",
62
+ "internvl",
63
+ "step-1v",
64
+ ];
package/lib/index.js ADDED
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Host entry: compose the provider route, the panel's HTTP surface and the
3
+ * agent-facing tools.
4
+ *
5
+ * Registration order matters. The provider directory entry is what makes the
6
+ * Models page render a card for this namespace; the adapter is what makes the
7
+ * route answer; the routes are what the browser panel talks to. All three are
8
+ * installed inside `ctx.effect` so a reload disposes them together.
9
+ * @module dsh-sub2api
10
+ */
11
+
12
+ import { PROVIDER, PLUGIN_NAME, SETTINGS_NS } from "./constants.js";
13
+ import { resolveConfig } from "./config.js";
14
+ import { Sub2ApiAdapter } from "./adapter.js";
15
+ import { makeRoutes } from "./routes.js";
16
+ import { Sub2ApiApi } from "./sub2api/api.js";
17
+ import { ModelCatalog } from "./sub2api/catalog.js";
18
+ import { SessionStore } from "./sub2api/session.js";
19
+
20
+ export { Config } from "./schema.js";
21
+
22
+ /** Stable Cordis plugin name. */
23
+ export const name = PLUGIN_NAME;
24
+
25
+ /** Services required before anything can mount. */
26
+ export const inject = ["llm"];
27
+
28
+ /** Order of the announcement section within the tool-guidance band. */
29
+ const SECTION_ORDER = 172;
30
+
31
+ const GUIDANCE =
32
+ "本机已安装 dsh-sub2api 插件:它把 sub2api(sub.pscly.cc)中转站接入 DSH。用户在 设置 → Sub2API 用一个邮箱和密码完成登录或注册,插件会自动在该账号下创建名为 dsh 的 API 密钥、写入本机凭据库,并同步上游模型目录,模型随后出现在模型选择器的 Sub2API 分组里。余额、订阅进度与充值入口也在同一面板;充值走 pay.pscly.cc,点「去支付」会在新标签页打开。可用命令 /sub2api 查看状态。用户提到「sub2api / 中转站 / 我的网关 / 余额充值」时即指本插件。";
33
+
34
+ /**
35
+ * Mount the provider, panel routes and tools.
36
+ * @param {any} ctx host context
37
+ * @param {any} rawConfig configuration row from the composition patch
38
+ */
39
+ export function apply(ctx, rawConfig = {}) {
40
+ const logger = {
41
+ info: (message) => safeLog(ctx, "info", message),
42
+ warn: (message) => safeLog(ctx, "warn", message),
43
+ };
44
+
45
+ /** Read the configuration fresh: the settings page may rewrite it in place. */
46
+ const cfg = () => resolveConfig(rawConfig);
47
+
48
+ const api = new Sub2ApiApi({
49
+ apiBase: () => cfg().apiBase,
50
+ timeoutMs: () => cfg().requestTimeoutMs,
51
+ });
52
+
53
+ const session = new SessionStore({
54
+ credentials: () => optional(ctx, "credentials"),
55
+ api,
56
+ apiKeyEnv: () => cfg().apiKeyEnv,
57
+ });
58
+
59
+ const catalog = new ModelCatalog({
60
+ api,
61
+ cachePath: () => cfg().modelsCachePath,
62
+ visibleModels: () => cfg().visibleModels,
63
+ contextWindow: () => cfg().contextWindow,
64
+ apiKey: () => session.apiKey(),
65
+ logger,
66
+ });
67
+
68
+ const adapter = new Sub2ApiAdapter({
69
+ ctx,
70
+ catalog,
71
+ apiBase: () => cfg().apiBase,
72
+ apiKeyEnv: () => cfg().apiKeyEnv,
73
+ timeoutMs: () => cfg().requestTimeoutMs,
74
+ idleTimeoutMs: () => cfg().streamIdleTimeoutMs,
75
+ logger,
76
+ });
77
+
78
+ const deps = { api, session, catalog, adapter, cfg, logger };
79
+
80
+ // 1) Provider directory + adapter. The directory entry is what the Models
81
+ // page turns into a card for this namespace.
82
+ ctx.effect(() => {
83
+ const providers = ctx.llm.registerConfigurableProviders([
84
+ {
85
+ provider: PROVIDER,
86
+ displayName: "Sub2API",
87
+ settingsNs: SETTINGS_NS,
88
+ settingsPath: [],
89
+ },
90
+ ]);
91
+ const adapters = ctx.llm.registerAdapter([PROVIDER], adapter);
92
+ return () => {
93
+ adapters?.();
94
+ providers?.();
95
+ };
96
+ }, "sub2api: provider");
97
+
98
+ // 2) Model discovery for the Models page's probe button.
99
+ ctx.effect(() => {
100
+ if (typeof ctx.llm.registerModelDiscovery !== "function") return () => {};
101
+ const dispose = ctx.llm.registerModelDiscovery(SETTINGS_NS, async (request, signal) => {
102
+ // A draft probe carries its own one-shot key and endpoint; a configured
103
+ // route falls back to the stored credential and this plugin's apiBase.
104
+ const key = request?.apiKey ?? (await session.apiKey());
105
+ if (!key) return [];
106
+ const payload = await api.gatewayModels(key, signal, request?.baseURL);
107
+ const { normalizeModels } = await import("./sub2api/catalog.js");
108
+ return normalizeModels(payload).map((model) => ({
109
+ id: model.id,
110
+ ...(model.name === undefined ? {} : { name: model.name }),
111
+ ...(model.contextWindow === undefined ? {} : { contextWindow: model.contextWindow }),
112
+ ...(model.maxTokens === undefined ? {} : { maxTokens: model.maxTokens }),
113
+ ...(model.vision === true ? { inputModalities: ["text", "image"] } : {}),
114
+ }));
115
+ });
116
+ return () => dispose?.();
117
+ }, "sub2api: discovery");
118
+
119
+ // 3) Browser routes.
120
+ ctx.effect(() => {
121
+ const webServer = optional(ctx, "webServer");
122
+ if (webServer === undefined || typeof webServer.register !== "function") return () => {};
123
+ const routes = makeRoutes({
124
+ ...deps,
125
+ cfg,
126
+ hostname: () => "dsh",
127
+ refreshCatalog: (key) => catalog.refresh(key),
128
+ });
129
+ const disposers = routes.map((route) => webServer.register(route));
130
+ return () => disposers.forEach((dispose) => dispose?.());
131
+ }, "sub2api: routes");
132
+
133
+ // 4) Agent tools: read-only status so the model can answer "how much is left".
134
+ // Imported lazily: a deployment without @deepseek-ai/dsh-tools still gets
135
+ // the provider and the panel, just no tools.
136
+ ctx.effect(() => {
137
+ let cancelled = false;
138
+ let disposers = [];
139
+ void import("./tools.js")
140
+ .then((module) => {
141
+ if (cancelled) return;
142
+ const tools = optional(ctx, "tools");
143
+ if (tools === undefined || typeof tools.register !== "function") return;
144
+ disposers = module
145
+ .buildTools({ api, session, catalog, cfg })
146
+ .map((tool) => tools.register(tool));
147
+ })
148
+ .catch((error) => logger.warn(`[sub2api] 工具未注册:${describe(error)}`));
149
+ return () => {
150
+ cancelled = true;
151
+ disposers.forEach((dispose) => dispose?.());
152
+ };
153
+ }, "sub2api: tools");
154
+
155
+ // 5) Warm the catalog so the first picker open is not empty.
156
+ ctx.effect(() => {
157
+ void catalog.load().then(() => catalog.ensureFresh()).catch(() => {});
158
+ return () => {};
159
+ }, "sub2api: warm");
160
+
161
+ // 6) Agent guidance, so the model knows the panel exists.
162
+ ctx.effect(() => {
163
+ if (cfg().announceToAgent !== true) return () => {};
164
+ const systemPrompt = optional(ctx, "systemPrompt");
165
+ if (systemPrompt === undefined || typeof systemPrompt.section !== "function") return () => {};
166
+ return systemPrompt.section({
167
+ name: "plugin:sub2api",
168
+ order: SECTION_ORDER,
169
+ text: GUIDANCE,
170
+ });
171
+ }, "sub2api: guidance");
172
+ }
173
+
174
+ /** A short message for a failed dynamic import. */
175
+ function describe(error) {
176
+ return error instanceof Error ? error.message : String(error);
177
+ }
178
+
179
+ /** Read an optional host service without letting its absence throw. */
180
+ function optional(ctx, serviceName) {
181
+ try {
182
+ return ctx.get?.(serviceName);
183
+ } catch {
184
+ return undefined;
185
+ }
186
+ }
187
+
188
+ /** Log through the host logger when it exists, and never let logging break a mount. */
189
+ function safeLog(ctx, level, message) {
190
+ try {
191
+ const logger = ctx.logger;
192
+ if (typeof logger?.[level] === "function") logger[level](message);
193
+ else if (level === "warn") console.warn(message);
194
+ } catch {
195
+ // A logger failure must not affect the plugin.
196
+ }
197
+ }
package/lib/pay.js ADDED
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Recharge hand-off to the pay centre.
3
+ *
4
+ * The pay centre is a separate Laravel service. It only renders the embedded
5
+ * recharge form when the caller proves who the user is: a `user_id` plus a
6
+ * sub2api access token, which it validates by calling
7
+ * `GET {sub2api}/api/v1/user/profile`. A bare link therefore answers 403 — that
8
+ * is the whole reason this module exists instead of the settings page simply
9
+ * opening a URL.
10
+ *
11
+ * Two levels are offered:
12
+ * - {@link buildRechargeLink}: hand the user a signed-in URL and let the pay
13
+ * page collect the amount. No CSRF handling, no local state.
14
+ * - {@link createRechargeOrder}: pick the amount here, then walk the CSRF
15
+ * handshake (`GET` for the cookie, `X-XSRF-TOKEN` on the `POST`) so the user
16
+ * lands directly on the checkout page and the panel knows the order number
17
+ * to poll.
18
+ * @module dsh-sub2api/pay
19
+ */
20
+
21
+ import { Sub2ApiError } from "./util.js";
22
+
23
+ const EMBEDDED_PATH = "/embedded/sub-recharge";
24
+
25
+ /**
26
+ * The URL that makes the embedded recharge page work.
27
+ * @param {object} deps
28
+ * @param {string} deps.payBase
29
+ * @param {number|string} deps.userId
30
+ * @param {string} deps.token sub2api access token
31
+ * @param {"light"|"dark"} [deps.theme]
32
+ * @param {string} [deps.lang]
33
+ * @param {string} [deps.srcHost]
34
+ * @param {string} [deps.srcUrl]
35
+ * @returns {string}
36
+ */
37
+ export function buildRechargeLink(deps) {
38
+ const url = new URL(`${deps.payBase}${EMBEDDED_PATH}`);
39
+ url.searchParams.set("user_id", String(deps.userId));
40
+ url.searchParams.set("token", deps.token);
41
+ url.searchParams.set("ui_mode", "embedded");
42
+ url.searchParams.set("lang", deps.lang ?? "zh");
43
+ url.searchParams.set("theme", deps.theme ?? "light");
44
+ if (deps.srcHost) url.searchParams.set("src_host", deps.srcHost);
45
+ if (deps.srcUrl) url.searchParams.set("src_url", deps.srcUrl);
46
+ return url.toString();
47
+ }
48
+
49
+ /**
50
+ * Create an order for a chosen amount and return the checkout URL.
51
+ *
52
+ * The pay centre is a server-rendered form guarded by Laravel's CSRF check, so
53
+ * the handshake is: `GET` the form (which also validates the token and returns
54
+ * 403 when it is stale), keep the cookies, then `POST` the amount back with
55
+ * `X-XSRF-TOKEN`. `redirect: "manual"` exposes the `Location` header instead of
56
+ * silently following it.
57
+ *
58
+ * @param {object} deps
59
+ * @param {string} deps.payBase
60
+ * @param {number|string} deps.userId
61
+ * @param {string} deps.token
62
+ * @param {number} deps.amountYuan positive, two decimals at most
63
+ * @param {string} [deps.srcUrl] where the pay page sends the user back
64
+ * @param {"light"|"dark"} [deps.theme]
65
+ * @param {number} [deps.timeoutMs]
66
+ * @param {typeof fetch} [deps.fetchImpl]
67
+ * @returns {Promise<{checkoutUrl: string, orderNo: string, expires: number, checkoutToken: string}>}
68
+ */
69
+ export async function createRechargeOrder(deps) {
70
+ const fetchImpl = deps.fetchImpl ?? fetch;
71
+ const timeoutMs = deps.timeoutMs ?? 20000;
72
+ const amountYuan = Number(deps.amountYuan);
73
+
74
+ if (!Number.isFinite(amountYuan) || amountYuan <= 0) {
75
+ throw new Sub2ApiError("请输入大于 0 的充值金额", { code: "invalid_amount" });
76
+ }
77
+ if (amountYuan > 100000) {
78
+ throw new Sub2ApiError("单笔充值金额过大", { code: "invalid_amount" });
79
+ }
80
+
81
+ const link = buildRechargeLink({
82
+ payBase: deps.payBase,
83
+ userId: deps.userId,
84
+ token: deps.token,
85
+ theme: deps.theme,
86
+ srcUrl: deps.srcUrl,
87
+ });
88
+
89
+ // 1) The form page: it both validates the token and hands out the CSRF cookie.
90
+ const form = await call(fetchImpl, link, { method: "GET", timeoutMs });
91
+ if (!form.ok) {
92
+ throw new Sub2ApiError(await payFailureMessage(form, "打开充值页失败"), {
93
+ status: form.status,
94
+ code: "pay_rejected",
95
+ });
96
+ }
97
+
98
+ const cookies = form.headers.getSetCookie?.() ?? [];
99
+ const cookieHeader = cookies.map((entry) => entry.split(";")[0]).join("; ");
100
+ const xsrfRaw = cookies.find((entry) => entry.startsWith("XSRF-TOKEN="));
101
+ if (!xsrfRaw) {
102
+ throw new Sub2ApiError("充值页没有下发 CSRF 凭证", { code: "pay_no_csrf" });
103
+ }
104
+ const xsrf = decodeURIComponent(xsrfRaw.split(";")[0].slice("XSRF-TOKEN=".length));
105
+
106
+ // 2) The order: same endpoint, form-encoded, manual redirect.
107
+ const body = new URLSearchParams({
108
+ user_id: String(deps.userId),
109
+ token: deps.token,
110
+ amount_yuan: amountYuan.toFixed(2),
111
+ ui_mode: "embedded",
112
+ lang: "zh",
113
+ theme: deps.theme ?? "light",
114
+ });
115
+ if (deps.srcUrl) body.set("src_url", deps.srcUrl);
116
+
117
+ const created = await call(fetchImpl, `${deps.payBase}${EMBEDDED_PATH}`, {
118
+ method: "POST",
119
+ timeoutMs,
120
+ headers: {
121
+ "Content-Type": "application/x-www-form-urlencoded",
122
+ "X-XSRF-TOKEN": xsrf,
123
+ ...(cookieHeader === "" ? {} : { Cookie: cookieHeader }),
124
+ },
125
+ body: body.toString(),
126
+ redirect: "manual",
127
+ });
128
+
129
+ const location = created.headers.get("location");
130
+ if (!location) {
131
+ throw new Sub2ApiError(await payFailureMessage(created, "生成充值订单失败"), {
132
+ status: created.status,
133
+ code: "pay_no_order",
134
+ });
135
+ }
136
+
137
+ const checkout = new URL(location, deps.payBase);
138
+ const orderNo = checkout.pathname.split("/").filter(Boolean).pop() ?? "";
139
+ if (orderNo === "") {
140
+ throw new Sub2ApiError("充值页返回的订单地址无法解析", { code: "pay_bad_order" });
141
+ }
142
+
143
+ return {
144
+ checkoutUrl: checkout.toString(),
145
+ orderNo,
146
+ expires: Number(checkout.searchParams.get("expires")) || 0,
147
+ checkoutToken: checkout.searchParams.get("token") ?? "",
148
+ };
149
+ }
150
+
151
+ /**
152
+ * Read one order's progress. The pay centre signs this URL too, so the caller
153
+ * must pass back the `expires`/`token` pair it received at creation.
154
+ * @param {object} deps
155
+ * @param {string} deps.payBase
156
+ * @param {string} deps.orderNo
157
+ * @param {number} deps.expires
158
+ * @param {string} deps.checkoutToken
159
+ * @param {number} [deps.timeoutMs]
160
+ * @param {typeof fetch} [deps.fetchImpl]
161
+ * @returns {Promise<{status?: string, delivery_status?: string, is_expired?: boolean, message?: string, notice?: string}>}
162
+ */
163
+ export async function fetchOrderStatus(deps) {
164
+ const url = new URL(`${deps.payBase}/checkout/${encodeURIComponent(deps.orderNo)}/status`);
165
+ url.searchParams.set("expires", String(deps.expires));
166
+ url.searchParams.set("token", deps.checkoutToken);
167
+
168
+ const response = await call(deps.fetchImpl ?? fetch, url.toString(), {
169
+ method: "GET",
170
+ timeoutMs: deps.timeoutMs ?? 15000,
171
+ headers: { Accept: "application/json" },
172
+ });
173
+
174
+ if (!response.ok) {
175
+ throw new Sub2ApiError(`查询订单状态失败(HTTP ${response.status})`, {
176
+ status: response.status,
177
+ code: "pay_status_failed",
178
+ });
179
+ }
180
+
181
+ const payload = await response.json().catch(() => undefined);
182
+ const data = payload && typeof payload === "object" && "data" in payload ? payload.data : payload;
183
+ return data && typeof data === "object" ? data : {};
184
+ }
185
+
186
+ /**
187
+ * Turn the pay centre's status payload into the one line a user should read.
188
+ * @param {{status?: string, delivery_status?: string, is_expired?: boolean, message?: string, notice?: string}} data
189
+ * @returns {{tone: "pending"|"progress"|"done"|"error", text: string, detail?: string}}
190
+ */
191
+ export function describeOrderStatus(data) {
192
+ const status = String(data?.status ?? "").toLowerCase();
193
+ const delivery = String(data?.delivery_status ?? "").toLowerCase();
194
+
195
+ if (data?.is_expired === true || status === "expired") {
196
+ return { tone: "error", text: "订单已过期,请重新发起", detail: data?.notice ?? undefined };
197
+ }
198
+ if (status === "rejected") {
199
+ return { tone: "error", text: "订单未通过", detail: data?.notice ?? "请联系客服" };
200
+ }
201
+ if (status === "approved" && delivery === "succeeded") {
202
+ return { tone: "done", text: "已到账", detail: data?.notice ?? "余额已更新" };
203
+ }
204
+ if (status === "approved") {
205
+ return { tone: "progress", text: "已确认收款,正在入账", detail: data?.message ?? undefined };
206
+ }
207
+ if (status === "pending" && data?.payment_notified_at) {
208
+ return { tone: "progress", text: "已提交支付通知,正在确认到账", detail: data?.message ?? undefined };
209
+ }
210
+ return { tone: "pending", text: "等待付款", detail: data?.message ?? undefined };
211
+ }
212
+
213
+ /** One fetch with a deadline, normalized into a Response. */
214
+ async function call(fetchImpl, url, init) {
215
+ const { timeoutMs = 20000, ...rest } = init;
216
+ try {
217
+ return await fetchImpl(url, { ...rest, signal: AbortSignal.timeout(Math.max(1, timeoutMs)) });
218
+ } catch (error) {
219
+ throw new Sub2ApiError(`支付服务不可达:${error instanceof Error ? error.message : String(error)}`, {
220
+ code: "pay_unreachable",
221
+ cause: error,
222
+ });
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Extract a human-readable reason from a pay-centre error page. The service
228
+ * answers HTML (Laravel's error view), so the visible text is the only clue.
229
+ */
230
+ async function payFailureMessage(response, fallback) {
231
+ const text = await response.text().catch(() => "");
232
+ const visible = text
233
+ .replace(/<script[\s\S]*?<\/script>/gi, " ")
234
+ .replace(/<style[\s\S]*?<\/style>/gi, " ")
235
+ .replace(/<[^>]+>/g, " ")
236
+ .replace(/\s+/g, " ")
237
+ .trim();
238
+ const known = visible.match(/(缺少 Sub2API 用户上下文|Sub2API 用户校验失败[^ ]*|Sub2API 用户身份不匹配)/);
239
+ if (known) return known[0];
240
+ if (response.status === 403) return `${fallback}:登录状态已失效(403)`;
241
+ if (response.status === 419) return `${fallback}:支付页会话过期(419)`;
242
+ return `${fallback}(HTTP ${response.status})`;
243
+ }