yichong-canva2 2.1.0 → 2.2.0

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/README.md CHANGED
@@ -2,12 +2,14 @@
2
2
 
3
3
  使用一个 `YiChongCanvaProvider` 管理登录、订阅和额度,通过 `useYiChongCanva()` 直接调用后端接口。
4
4
 
5
+ `2.2.0` 新增账户请求超时、有限重试与自动飞书告警,公开 `accountError` 供 Footer 展示失败及重试;上报切换到最新指定的 webhook。
6
+
5
7
  `2.1.0` 新增 `onUploadProgress` 和导出的 `UploadProgress` 类型,补齐视频目录参数,恢复消费数量原值透传,并将上传命名对齐旧随机算法与 MIME 后缀回退。上传继续复用 `ai.imgkits.com` 的四个 Cloudflare R2 接口,分片公开地址兼容旧响应,无需新增、迁移或部署后端接口。
6
8
 
7
9
  ## 使用
8
10
 
9
11
  ```sh
10
- npm install yichong-canva2@2.1.0
12
+ npm install yichong-canva2@2.2.0
11
13
  ```
12
14
 
13
15
  `1.2.0` 新增文本审核、三个消费接口,以及 Cloudflare R2 单次和分片上传;继续复用原有 Provider。
@@ -471,9 +473,23 @@ const prediction = await client.getPrediction(
471
473
 
472
474
  取消只终止当前 HTTP 等待,不会取消已经创建的后端任务或撤销已提交的消费。创建、查询、文本审核和底层签名的默认请求超时为 60 秒,包含读取响应正文的时间;内容提取和大模型 `chat` 为 360 秒,消费为 30 秒,单次 PUT 上传为 120 秒,分片上传整体为 30 分钟。
473
475
 
476
+ ## 账户故障处理(2.2.0)
477
+
478
+ 继续使用一个 `YiChongCanvaProvider`,无需额外的上报 Provider 或 Footer 上报包装。账户模块会自动报告最终失败,业务 API 的错误仍在业务 catch 中按需显式调用 `client.reportError`。
479
+
480
+ - Canva token、身份验证、canvaid-login、passport 和 status 每步最多 10 秒(含响应正文)。首次登录及其重试共享 30 秒预算;`retry` 仍决定额外尝试次数,但不能突破总预算。
481
+ - 登录最终失败后 `loginStatus` 变为 `error`,Footer 停止圆圈并保留原 `Connect account` 重试按钮。`client.manualLogin()` 开始新一轮;取消旧请求和计时器,迟到响应不再更新状态。
482
+ - `client.refreshUserStatus()` 最多两次尝试,共享 30 秒;失败仍返回旧快照以兼容已有调用,同时设置 `client.accountError`。未登录时只返回当前快照,不抢占登录。返回快照不等于刷新成功,也不能据此认定消费成功。
483
+ - 支付轮询保留原快慢间隔和默认五分钟 TTL;连续三次网络/服务器故障提前结束,确定的响应/业务错误直接结束。健康的状态未变化、正常 TTL 或主动停止不告警;收尾补刷真实失败仍报告。补刷最多 10 秒并取消超时请求。
484
+ - `accountError` 为只读诊断快照或 `null`,包含 `operation`(login/refresh/poll)、`stage`、`code`、可用的 HTTP `status`、安全诊断 `message`、阶段尝试数 `attempts`、耗时 `elapsedMs` 和不带查询参数的 `api`。应用应根据状态显示本地化文案,不直接展示技术诊断。开始重试或成功后清除。
485
+ - Provider 按应用、接口、错误类型五分钟去重。自动报告不等待发送完成,发送失败不影响界面、不递归上报;卸载、主动取消、旧流程被替换都不告警。无需全局异常监听。
486
+ - 上报复用 `https://report.imgkits.com` 的现有转发协议,目标采用最新指定的 webhook,并携带应用/工具包版本。SDK 只收集必要的诊断字段,不发送 JWT、passport、查询参数或原始服务端正文。完全断网时不能保证告警送达。
487
+
488
+ 脚手架 Footer 只读取状态、展示新增失败提示和调用已有重试方法,不自行发送账户报告。正常七种额度文案、样式和布局保持原样。已有应用需要升级 SDK,并同步 Footer 的错误展示分支;更新脚手架不会自动改写旧应用。
489
+
474
490
  ## 错误上报
475
491
 
476
- 继续使用同一个 Provider,业务代码直接调用 `client.reportError`。`error` 接受 Error、ApiError、字符串或其他被抛出的值。Provider 自动补充产品渠道、应用 ID、应用版本及可用的用户 ID。工具包内置现有 Worker 地址和固定上报令牌,机器人固定为 `ROBOT_MONITOR`,应用无需新增配置或修改后端。
492
+ 继续使用同一个 Provider,业务代码直接调用 `client.reportError`。`error` 接受 Error、ApiError、字符串或其他被抛出的值。Provider 自动补充产品渠道、应用 ID、应用版本及可用的用户 ID。工具包内置现有 Worker 地址和固定上报令牌,通过 Worker 原有 `robot` 字段指定最新约定的飞书 webhook(业务应用无需再配置),应用无需新增配置或修改后端。
477
493
 
478
494
  固定令牌会随 npm 包和应用浏览器产物公开,不能视为保密凭据。此请求不向 Worker 发送用户 JWT 或 passport;这类值会从诊断正文中移除。上报可在 Provider 登录前调用,尚未获得的用户 ID 标为 unknown。
479
495
 
@@ -519,7 +535,7 @@ function GenerateButton() {
519
535
 
520
536
  `source` 默认 `"ui"`,支持 `ui/api/runtime/promise/react/upload/host_sdk`;`stage` 是可选的业务阶段(最多 128 字符)。`api` 可填 `{ method, url, status, request_id, response_code }`,`context` 是小型诊断对象。ApiError 自动提取 code、status、data.request_id,不发送完整 data。message 最多 2000 字符,stack 最多 3000;context 截断长字符串、数量和深度,移除常见凭据及 base64 文件。整体内容过大时抛出 `invalid_request`。应用仍应只传诊断所需信息,例如模型名、任务 ID 和处理阶段,避免传原始用户输入或文件。
521
537
 
522
- 成功原样返回 Worker 的 `{ success: true, data, ... }`。`data.status="ignored"` 表示旧 Worker 过滤了噪声,可能附带 reason/country;其他成功结果已经确认飞书业务码为 0。HTTP 成功但飞书业务码非 0 仍抛出 ApiError;上报的错误码为 reporting_failed、invalid_response、network_error、timeout 或 aborted 等,保留 HTTP 状态及可读取的 Retry-After,不回显上游内部错误正文。没有自动捕获全局错误、React 错误或 API 失败,由业务显式调用。
538
+ 成功原样返回 Worker 的 `{ success: true, data, ... }`。`data.status="ignored"` 表示旧 Worker 过滤了噪声,可能附带 reason/country;其他成功结果已经确认飞书业务码为 0。HTTP 成功但飞书业务码非 0 仍抛出 ApiError;上报的错误码为 reporting_failed、invalid_response、network_error、timeout 或 aborted 等,保留 HTTP 状态及可读取的 Retry-After,不回显上游内部错误正文。不安装全局或 React 错误监听。账户登录、刷新和支付检查的最终失败由 Provider 自动上报;其它业务 API 的失败仍由业务显式调用。
523
539
 
524
540
  默认超时 10 秒,支持第二参数 `{ signal, timeoutMs }`,只请求一次。沿用 Worker 的噪声过滤规则,本次不新增服务端限流或网关转发。上报失败不要再次上报自身异常;缺少 Provider 时抛出 provider_missing。`apiBaseUrl` 不影响上报地址,调用方不能覆盖机器人、地址或令牌。
525
541
 
@@ -2,6 +2,7 @@ import { ApiError } from "./error.js";
2
2
  import { isNonemptyString, invalid, readJson, isObject, backendError } from "./request.js";
3
3
  import { reportingPayload } from "./reporting_payload.js";
4
4
  import { withRequest } from "./transport.js";
5
+ const reportRobot = "https://open.feishu.cn/open-apis/bot/v2/hook/c32b7f2a-d17a-478f-8a42-c9226b0a7e11";
5
6
  const reportUrl = "https://report.imgkits.com";
6
7
  const reportToken = "base64:MsUJo+qAhIVGPx52r1mbxCYn5YbWtCx8FQ7pTaHEvRo=";
7
8
  function createErrorReportingApi(getContext) {
@@ -12,13 +13,14 @@ function createErrorReportingApi(getContext) {
12
13
  if (!isNonemptyString(context.productName) || context.productName.length > 64 || !isNonemptyString(context.appId) || context.appId.length > 64 || !Number.isFinite(context.version) || String(context.version).length > 64) {
13
14
  invalid("Error reporting requires the Provider productName, appId and version.");
14
15
  }
15
- const secrets = [reportToken, context.userStatus.jwt, (_a = context.userStatus.profile) == null ? void 0 : _a.token, (_b = context.userStatus.drive) == null ? void 0 : _b.fresh_token, context.passport].filter((value) => typeof value === "string" && value.length > 0);
16
+ const secrets = [reportToken, reportRobot, context.userStatus.jwt, (_a = context.userStatus.profile) == null ? void 0 : _a.token, (_b = context.userStatus.drive) == null ? void 0 : _b.fresh_token, context.passport].filter((value) => typeof value === "string" && value.length > 0);
16
17
  const details = {
17
18
  time: (/* @__PURE__ */ new Date()).toISOString(),
18
19
  app_channel: context.productName,
19
20
  platform: "canva_addon",
20
21
  app_id: context.appId,
21
22
  app_version: String(context.version),
23
+ sdk_version: "2.2.0",
22
24
  user_id: ((_c = context.userStatus.profile) == null ? void 0 : _c.id) ?? "unknown",
23
25
  platform_uid: context.userStatus.userId ?? "unknown",
24
26
  ...reportingPayload(params, secrets)
@@ -28,7 +30,7 @@ function createErrorReportingApi(getContext) {
28
30
  if (secret.length >= 4) message = message.split(secret).join("[redacted]");
29
31
  }
30
32
  message = message.replace(/</g, "<").replace(/>/g, ">");
31
- const body = JSON.stringify({ robot: "ROBOT_MONITOR", title: "Canva 应用错误", titleColor: "red", message });
33
+ const body = JSON.stringify({ robot: reportRobot, title: "Canva 应用错误", titleColor: "red", message });
32
34
  if (new TextEncoder().encode(body).length > 16384) invalid("Error report is too large; provide a smaller context.");
33
35
  return withRequest({ ...options, timeoutMs: (options == null ? void 0 : options.timeoutMs) ?? 1e4 }, async (signal) => {
34
36
  const response = await fetch(reportUrl, {
@@ -0,0 +1,69 @@
1
+ import { ApiError } from "../api/error.js";
2
+ import { throwIfAborted, withRequest } from "../api/transport.js";
3
+ class AccountRequestError extends ApiError {
4
+ constructor(message, code, stage, api) {
5
+ super(message, code, api == null ? void 0 : api.status);
6
+ this.stage = stage;
7
+ this.api = api;
8
+ this.name = "AccountRequestError";
9
+ }
10
+ }
11
+ async function accountStep(stage, options, work, api) {
12
+ var _a;
13
+ (_a = options.onStep) == null ? void 0 : _a.call(options, stage, api);
14
+ try {
15
+ return await withRequest({ signal: options.signal, timeoutMs: 1e4 }, work);
16
+ } catch (error) {
17
+ if (error instanceof AccountRequestError) throw error;
18
+ const code = error instanceof ApiError ? error.code : "network_error";
19
+ throw new AccountRequestError(code === "timeout" ? "Account request timed out." : "Account request failed.", code, stage, api);
20
+ }
21
+ }
22
+ function retryableAccountError(error) {
23
+ return error instanceof ApiError && (error.code === "timeout" || error.code === "network_error" || error.status === 408 || error.status === 429 || error.status != null && error.status >= 500);
24
+ }
25
+ function accountDelay(ms, signal) {
26
+ throwIfAborted(signal);
27
+ return new Promise((resolve, reject) => {
28
+ const cleanup = () => {
29
+ clearTimeout(timer);
30
+ signal.removeEventListener("abort", cancel);
31
+ };
32
+ const cancel = () => {
33
+ cleanup();
34
+ reject(new ApiError("Request canceled.", "aborted"));
35
+ };
36
+ const timer = setTimeout(() => {
37
+ cleanup();
38
+ resolve();
39
+ }, ms);
40
+ signal.addEventListener("abort", cancel, { once: true });
41
+ });
42
+ }
43
+ function createAccountReporter(report) {
44
+ const sent = /* @__PURE__ */ new Map();
45
+ return (error, appKey) => {
46
+ var _a;
47
+ if (error.code === "aborted") return;
48
+ const now = Date.now();
49
+ for (const [key2, time] of sent) if (now - time >= 3e5) sent.delete(key2);
50
+ const key = [appKey, ((_a = error.api) == null ? void 0 : _a.url) ?? error.stage, error.status, error.code].join("|");
51
+ if (sent.has(key)) return;
52
+ sent.set(key, now);
53
+ void report({
54
+ error: new ApiError(error.message, error.code, error.status),
55
+ source: error.stage === "canva_token" ? "host_sdk" : "api",
56
+ stage: `account.${error.operation}.${error.stage}`,
57
+ api: error.api,
58
+ context: { attempts: error.attempts, elapsed_ms: error.elapsedMs }
59
+ }).catch(() => {
60
+ });
61
+ };
62
+ }
63
+ export {
64
+ AccountRequestError,
65
+ accountDelay,
66
+ accountStep,
67
+ createAccountReporter,
68
+ retryableAccountError
69
+ };
@@ -28,6 +28,7 @@ const YiChongCanvaContext = React.createContext(
28
28
  updateCredits: () => {
29
29
  },
30
30
  loginStatus: "idle",
31
+ accountError: null,
31
32
  manualLogin: () => {
32
33
  },
33
34
  createSpecifyPrediction: async () => {
@@ -1,24 +1,26 @@
1
- import requestUrl from "./request.js";
1
+ import { accountRequest } from "./request.js";
2
+ import { isObject } from "../../../api/request.js";
3
+ import { throwIfAborted } from "../../../api/transport.js";
2
4
  const headers = {
3
5
  "Content-Type": "application/json"
4
6
  };
5
7
  const baseUrl = "https://usa.imgkits.com/";
6
- function getUserIds(token, appId, context) {
8
+ function getUserIds(token, appId, context, options = {}) {
7
9
  const queryString = new URLSearchParams({
8
10
  canva_user_token: token,
9
11
  appid: appId
10
12
  }).toString();
11
13
  const url = `https://canva.livepolls.app/getUserIdByAppid?${queryString}`;
12
- return requestUrl({
14
+ return accountRequest({
13
15
  url,
14
16
  method: "GET",
15
17
  headers,
16
18
  redirect: "follow"
17
- }, context);
19
+ }, context, "canva_identity", options, (body) => isObject(body.verified) && typeof body.verified.userId === "string" && !!body.verified.userId);
18
20
  }
19
- function handleUserLoginByCanvaId(userId, productName, context) {
21
+ function handleUserLoginByCanvaId(userId, productName, context, options = {}) {
20
22
  const url = baseUrl + productName + "/api/user/canvaid-login";
21
- return requestUrl({
23
+ return accountRequest({
22
24
  url,
23
25
  method: "POST",
24
26
  headers,
@@ -26,9 +28,10 @@ function handleUserLoginByCanvaId(userId, productName, context) {
26
28
  canva_id: userId
27
29
  }),
28
30
  redirect: "follow"
29
- }, context);
31
+ }, context, "canvaid_login", options, (body) => body.ok === 0 || body.code === 0 || body.success === true);
30
32
  }
31
- function getPassport(userId, productName, context) {
33
+ function getPassport(userId, productName, context, options = {}) {
34
+ if (options.signal) throwIfAborted(options.signal);
32
35
  const passport = localStorage.getItem(userId + "_passport");
33
36
  if (passport) {
34
37
  return Promise.resolve({
@@ -41,7 +44,7 @@ function getPassport(userId, productName, context) {
41
44
  if (productName === "imgkits") {
42
45
  url = baseUrl + "/api/user/canva-passport";
43
46
  }
44
- return requestUrl({
47
+ return accountRequest({
45
48
  url,
46
49
  method: "POST",
47
50
  headers,
@@ -49,23 +52,24 @@ function getPassport(userId, productName, context) {
49
52
  canva_id: userId
50
53
  }),
51
54
  redirect: "follow"
52
- }, context).then((res) => {
55
+ }, context, "canva_passport", options, (body) => isObject(body.data) && typeof body.data.passport === "string" && !!body.data.passport).then((res) => {
56
+ if (options.signal) throwIfAborted(options.signal);
53
57
  localStorage.setItem(userId + "_passport", res.data.passport);
54
58
  return res;
55
59
  });
56
60
  }
57
- function getUserStatusByPassport(passport, productName, context) {
61
+ function getUserStatusByPassport(passport, productName, context, options = {}) {
58
62
  const header = {
59
63
  "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
60
64
  "X-Access-Ticket": passport
61
65
  };
62
66
  const url = baseUrl + productName + "/api/user/status";
63
- return requestUrl({
67
+ return accountRequest({
64
68
  url,
65
69
  method: "POST",
66
70
  headers: header,
67
71
  redirect: "follow"
68
- }, context);
72
+ }, context, "status", options, (body) => isObject(body.data));
69
73
  }
70
74
  const apis = {
71
75
  getUserIds,
@@ -1,5 +1,33 @@
1
- import { addContextQuery, language } from "../../../api/request.js";
2
- const requestUrl = (option, context) => {
1
+ import { addContextQuery, language, isObject } from "../../../api/request.js";
2
+ import { accountStep, AccountRequestError } from "../../account.js";
3
+ function accountRequest(option, context, stage, options = {}, validate) {
4
+ const { url, ...init } = option;
5
+ const target = new URL(url);
6
+ const api = { url: target.origin + target.pathname, method: init.method ?? "GET" };
7
+ addContextQuery(target, context);
8
+ const headers = new Headers(init.headers);
9
+ headers.set("Accept-Language", language(context.getLocale));
10
+ return accountStep(stage, options, async (signal) => {
11
+ const response = await fetch(target.toString(), { ...init, headers, signal });
12
+ const metadata = { ...api, status: response.status, request_id: response.headers.get("x-request-id") ?? void 0 };
13
+ if (!response.ok) throw new AccountRequestError("Account service returned an HTTP error.", "http_error", stage, metadata);
14
+ let body;
15
+ try {
16
+ body = await response.json();
17
+ } catch {
18
+ throw new AccountRequestError("Account service returned invalid JSON.", "invalid_response", stage, metadata);
19
+ }
20
+ if (!isObject(body)) throw new AccountRequestError("Account service returned invalid data.", "invalid_response", stage, metadata);
21
+ const failedCode = [body.ok, body.code].find((value) => value !== void 0 && value !== 0 && value !== "0");
22
+ if (body.success === false || failedCode !== void 0) {
23
+ const code = typeof failedCode === "string" || typeof failedCode === "number" ? failedCode : "account_rejected";
24
+ throw new AccountRequestError("Account service rejected the request.", code, stage, { ...metadata, response_code: code });
25
+ }
26
+ if (validate && !validate(body)) throw new AccountRequestError("Account service returned incomplete data.", "invalid_response", stage, metadata);
27
+ return body;
28
+ }, api);
29
+ }
30
+ function requestUrl(option, context) {
3
31
  const { url, ...init } = option;
4
32
  const target = new URL(url);
5
33
  if (context) {
@@ -8,8 +36,9 @@ const requestUrl = (option, context) => {
8
36
  headers.set("Accept-Language", language(context.getLocale));
9
37
  init.headers = headers;
10
38
  }
11
- return fetch(target.toString(), init).then((res) => res.json());
12
- };
39
+ return fetch(target.toString(), init).then((response) => response.json());
40
+ }
13
41
  export {
42
+ accountRequest,
14
43
  requestUrl as default
15
44
  };
@@ -1,5 +1,9 @@
1
1
  import { auth } from "@canva/user";
2
2
  import apis from "./apis/index.js";
3
+ import { isObject } from "../../api/request.js";
4
+ import { ApiError } from "../../api/error.js";
5
+ import { withRequest, throwIfAborted } from "../../api/transport.js";
6
+ import { AccountRequestError, retryableAccountError, accountDelay, accountStep } from "../account.js";
3
7
  function accountContext(productName, userId, getContext) {
4
8
  const context = getContext == null ? void 0 : getContext();
5
9
  const current = context == null ? void 0 : context.userStatus;
@@ -10,35 +14,32 @@ function accountContext(productName, userId, getContext) {
10
14
  };
11
15
  }
12
16
  auth.initOauth();
13
- async function handleLogin({
14
- appId,
15
- productName,
16
- onPassport,
17
- getRequestContext
18
- }) {
19
- try {
20
- let userId = window.userId;
21
- console.log("userId", userId);
22
- if (!userId) {
23
- const token = await auth.getCanvaUserToken();
24
- window.g_canva_token = token;
25
- const userIdResult = await apis.getUserIds(token, appId, accountContext(productName, userId, getRequestContext));
26
- userId = userIdResult.verified.userId;
27
- window.userId = userId;
28
- await apis.handleUserLoginByCanvaId(userId, productName, accountContext(productName, userId, getRequestContext));
29
- }
30
- const userStatus = await getUserProfile({
31
- userId,
32
- productName,
33
- onPassport,
34
- getRequestContext
35
- });
36
- window.g_token = userStatus.jwt || "";
37
- userStatus.userId = userId;
38
- return userStatus;
39
- } catch (e) {
40
- throw new Error("login failed");
17
+ async function handleLogin({ appId, productName, onPassport, getRequestContext, signal, onStep }) {
18
+ const options = { signal, onStep };
19
+ let userId = window.userId;
20
+ if (!userId) {
21
+ const token = await accountStep("canva_token", options, () => auth.getCanvaUserToken());
22
+ if (signal) throwIfAborted(signal);
23
+ window.g_canva_token = token;
24
+ const identity = await apis.getUserIds(token, appId, accountContext(productName, userId, getRequestContext), options);
25
+ userId = identity.verified.userId;
26
+ await apis.handleUserLoginByCanvaId(userId, productName, accountContext(productName, userId, getRequestContext), options);
27
+ if (signal) throwIfAborted(signal);
28
+ window.userId = userId;
41
29
  }
30
+ const userStatus = await getUserProfile({
31
+ userId,
32
+ productName,
33
+ onPassport,
34
+ getRequestContext,
35
+ ...options,
36
+ maxCount: 1
37
+ });
38
+ if (signal) throwIfAborted(signal);
39
+ if (!userStatus) throw new AccountRequestError("Account request canceled.", "aborted", "status");
40
+ window.g_token = userStatus.jwt || "";
41
+ userStatus.userId = userId;
42
+ return userStatus;
42
43
  }
43
44
  function takeSubscribeBaseline(userStatus) {
44
45
  const sub = userStatus == null ? void 0 : userStatus.subscription;
@@ -81,7 +82,7 @@ function isSubscribeChanged(current, baseline) {
81
82
  return false;
82
83
  }
83
84
  async function getUserProfile({
84
- maxCount = 50,
85
+ maxCount = 2,
85
86
  interval,
86
87
  maxDurationMs,
87
88
  productName,
@@ -93,87 +94,94 @@ async function getUserProfile({
93
94
  isChanged,
94
95
  onStop,
95
96
  onPassport,
96
- getRequestContext
97
+ getRequestContext,
98
+ signal,
99
+ onStep
97
100
  }) {
98
- var _a, _b;
99
- let count = 0;
100
- const startedAt = Date.now();
101
- let latestProfile;
102
- const requestContext = () => {
103
- const context = accountContext(productName, userId, getRequestContext);
104
- return { ...context, userStatus: { ...context.userStatus, profile: latestProfile ?? context.userStatus.profile } };
105
- };
106
- let passportResult = await apis.getPassport(userId, productName, requestContext());
107
- let passport = (_a = passportResult.data) == null ? void 0 : _a.passport;
108
- let isStop = false;
109
- let cancelSleep = null;
110
- let snapshot = baseline ?? null;
101
+ const controller = new AbortController();
102
+ let stopped = false;
103
+ const cancel = () => controller.abort();
104
+ if (signal == null ? void 0 : signal.aborted) controller.abort();
105
+ signal == null ? void 0 : signal.addEventListener("abort", cancel, { once: true });
111
106
  onStop == null ? void 0 : onStop(() => {
112
- isStop = true;
113
- count = maxCount;
114
- cancelSleep == null ? void 0 : cancelSleep();
107
+ stopped = true;
108
+ controller.abort();
115
109
  });
116
- const expired = () => count >= maxCount || maxDurationMs != null && Date.now() - startedAt >= maxDurationMs;
117
- while (!expired()) {
118
- console.log("poll", count);
119
- let userStatus;
120
- try {
121
- userStatus = await (await apis.getUserStatusByPassport(passport, productName, requestContext())).data;
122
- } catch (e) {
123
- userStatus = void 0;
124
- }
125
- if (userStatus == null ? void 0 : userStatus.profile) {
126
- latestProfile = userStatus.profile;
127
- if (typeof passport === "string" && passport) onPassport == null ? void 0 : onPassport(passport, userId, userStatus.profile.id);
128
- if (!isSubscribe) {
129
- successCallback == null ? void 0 : successCallback(userStatus);
130
- return userStatus;
131
- }
132
- if (!snapshot) {
133
- snapshot = takeSubscribeBaseline(userStatus);
134
- } else {
135
- const changed = isChanged ? isChanged(userStatus, snapshot) : isSubscribeChanged(userStatus, snapshot);
136
- if (changed) {
137
- console.log("subscribe success");
138
- successCallback == null ? void 0 : successCallback(userStatus);
139
- return userStatus;
110
+ let lastError;
111
+ let lastStage = "canva_passport";
112
+ let lastApi;
113
+ try {
114
+ return await withRequest({ signal: controller.signal, timeoutMs: maxDurationMs ?? (isSubscribe ? 3e5 : 3e4) }, async (requestSignal) => {
115
+ const options = { signal: requestSignal, onStep: (stage, api) => {
116
+ lastStage = stage;
117
+ lastApi = api;
118
+ onStep == null ? void 0 : onStep(stage, api);
119
+ } };
120
+ let latestProfile;
121
+ const requestContext = () => {
122
+ const context = accountContext(productName, userId, getRequestContext);
123
+ return { ...context, userStatus: { ...context.userStatus, profile: latestProfile ?? context.userStatus.profile } };
124
+ };
125
+ let passport = (await apis.getPassport(userId, productName, requestContext(), options)).data.passport;
126
+ let snapshot = baseline ?? null;
127
+ let consecutiveFailures = 0;
128
+ let renewedPassport = false;
129
+ for (let count = 0; count < maxCount; count++) {
130
+ throwIfAborted(requestSignal);
131
+ try {
132
+ let userStatus;
133
+ try {
134
+ userStatus = (await apis.getUserStatusByPassport(passport, productName, requestContext(), options)).data;
135
+ } catch (error) {
136
+ if (!(error instanceof ApiError && error.status === 401) || renewedPassport) throw error;
137
+ userStatus = {};
138
+ }
139
+ throwIfAborted(requestSignal);
140
+ if (!userStatus.profile && !renewedPassport) {
141
+ renewedPassport = true;
142
+ localStorage.removeItem(userId + "_passport");
143
+ passport = (await apis.getPassport(userId, productName, requestContext(), options)).data.passport;
144
+ userStatus = (await apis.getUserStatusByPassport(passport, productName, requestContext(), options)).data;
145
+ throwIfAborted(requestSignal);
146
+ }
147
+ if (!isObject(userStatus.profile) || typeof userStatus.profile.id !== "string" || !userStatus.profile.id || !isObject(userStatus.profile.usage_limits)) {
148
+ throw new AccountRequestError("Account status is missing a profile.", "invalid_response", "status", lastApi);
149
+ }
150
+ latestProfile = userStatus.profile;
151
+ onPassport == null ? void 0 : onPassport(passport, userId, userStatus.profile.id);
152
+ consecutiveFailures = 0;
153
+ lastError = void 0;
154
+ if (!isSubscribe) {
155
+ successCallback == null ? void 0 : successCallback(userStatus);
156
+ return userStatus;
157
+ }
158
+ if (!snapshot) snapshot = takeSubscribeBaseline(userStatus);
159
+ else if (isChanged ? isChanged(userStatus, snapshot) : isSubscribeChanged(userStatus, snapshot)) {
160
+ successCallback == null ? void 0 : successCallback(userStatus);
161
+ return userStatus;
162
+ }
163
+ } catch (error) {
164
+ throwIfAborted(requestSignal);
165
+ lastError = error;
166
+ consecutiveFailures++;
167
+ if (!retryableAccountError(error) || count + 1 >= maxCount || isSubscribe && consecutiveFailures >= 3) throw error;
140
168
  }
169
+ if (count + 1 < maxCount) await accountDelay(typeof interval === "function" ? interval() : interval ?? 3e3, requestSignal);
141
170
  }
142
- } else if (userStatus) {
143
- localStorage.removeItem(userId + "_passport");
144
- try {
145
- passportResult = await apis.getPassport(userId, productName, requestContext());
146
- passport = (_b = passportResult.data) == null ? void 0 : _b.passport;
147
- } catch (e) {
148
- }
149
- }
150
- count++;
151
- if (isStop || expired()) {
152
- break;
153
- }
154
- let ms = typeof interval === "function" ? interval() : interval ?? 3e3;
155
- if (maxDurationMs != null) {
156
- ms = Math.min(ms, Math.max(maxDurationMs - (Date.now() - startedAt), 0));
157
- }
158
- await sleep(ms, (cancel) => {
159
- cancelSleep = cancel;
171
+ if (isSubscribe && !lastError) return void 0;
172
+ throw lastError ?? new AccountRequestError("Account status is unavailable.", "invalid_response", "status", lastApi);
160
173
  });
161
- cancelSleep = null;
162
- }
163
- if (isStop) {
164
- return;
174
+ } catch (error) {
175
+ if (stopped) return void 0;
176
+ if (error instanceof ApiError && error.code === "timeout" && !(error instanceof AccountRequestError)) {
177
+ if (isSubscribe && !lastError) return void 0;
178
+ error = lastError ?? new AccountRequestError("Account request timed out.", "timeout", lastStage, lastApi);
179
+ }
180
+ if (!(error instanceof ApiError && error.code === "aborted")) failCallback == null ? void 0 : failCallback();
181
+ throw error;
182
+ } finally {
183
+ signal == null ? void 0 : signal.removeEventListener("abort", cancel);
165
184
  }
166
- failCallback == null ? void 0 : failCallback();
167
- throw new Error("get user profile error");
168
- }
169
- function sleep(ms = 3e3, onCancel) {
170
- return new Promise((resolve) => {
171
- const id = setTimeout(resolve, ms);
172
- onCancel == null ? void 0 : onCancel(() => {
173
- clearTimeout(id);
174
- resolve();
175
- });
176
- });
177
185
  }
178
186
  export {
179
187
  computeAvailableLimit,
@@ -1,6 +1,6 @@
1
1
  import { jsx } from "react/jsx-runtime";
2
2
  import { useState, useRef, useEffect } from "react";
3
- import { handleLogin, takeSubscribeBaseline, getUserProfile } from "./login/login.js";
3
+ import { getUserProfile, takeSubscribeBaseline, handleLogin } from "./login/login.js";
4
4
  import { YiChongCanvaContext } from "./context.js";
5
5
  import _ from "lodash";
6
6
  import { getAppVersion } from "./version.js";
@@ -11,6 +11,9 @@ import { createChatApi } from "../api/chat.js";
11
11
  import { createUsageApi } from "../api/usage.js";
12
12
  import { createUploadApi } from "../api/uploads.js";
13
13
  import { createErrorReportingApi } from "../api/reporting.js";
14
+ import { ApiError } from "../api/error.js";
15
+ import { withRequest, throwIfAborted } from "../api/transport.js";
16
+ import { createAccountReporter, AccountRequestError, retryableAccountError, accountDelay } from "./account.js";
14
17
  import { language, addContextQuery } from "../api/request.js";
15
18
  function reduceFreeTimes(baseUrl, passport, cnt, context) {
16
19
  const header = {
@@ -76,6 +79,11 @@ const YiChongCanvaProvider = ({
76
79
  const stopCurrentPolling = useRef(null);
77
80
  const sessionStopRef = useRef(null);
78
81
  const [loginStatus, setLoginStatus] = useState("idle");
82
+ const [accountError, setAccountError] = useState(null);
83
+ const accountRunRef = useRef(null);
84
+ const loginPendingRef = useRef(false);
85
+ const mountedRef = useRef(true);
86
+ const identityScopeRef = useRef(`${appId}|${productName}`);
79
87
  const userStatusRef = useRef({});
80
88
  const apiConfigRef = useRef({ apiBaseUrl, contentBaseUrl, chatBaseUrl, baseUrl, uploadBaseUrl, productName, appId, version, getLocale });
81
89
  apiConfigRef.current = { apiBaseUrl, contentBaseUrl, chatBaseUrl, baseUrl, uploadBaseUrl, productName, appId, version, getLocale };
@@ -151,115 +159,146 @@ const YiChongCanvaProvider = ({
151
159
  var _a;
152
160
  return ((_a = userStatus.profile) == null ? void 0 : _a.usage_limits.free_limit) === -1;
153
161
  };
154
- const login = (tryCount = 0) => {
162
+ const [reportAccountFailure] = useState(() => createAccountReporter(errorReportingApi.reportError));
163
+ const beginAccountRun = (operation) => {
164
+ var _a, _b;
165
+ (_a = sessionStopRef.current) == null ? void 0 : _a.call(sessionStopRef, false);
166
+ (_b = accountRunRef.current) == null ? void 0 : _b.controller.abort();
167
+ const run = {
168
+ operation,
169
+ controller: new AbortController(),
170
+ startedAt: Date.now(),
171
+ attempts: 0,
172
+ stage: operation === "login" ? "canva_token" : "status",
173
+ appKey: `${appId}|${productName}`
174
+ };
175
+ accountRunRef.current = run;
176
+ setAccountError(null);
177
+ return run;
178
+ };
179
+ const isCurrentRun = (run) => mountedRef.current && accountRunRef.current === run && !run.controller.signal.aborted && run.appKey === `${apiConfigRef.current.appId}|${apiConfigRef.current.productName}`;
180
+ const requestOptions = (run) => ({
181
+ signal: run.controller.signal,
182
+ onStep: (stage, api) => {
183
+ run.stage = stage;
184
+ run.api = api;
185
+ run.attempts++;
186
+ }
187
+ });
188
+ const failAccountRun = (run, error) => {
189
+ if (!isCurrentRun(run) || error instanceof ApiError && error.code === "aborted") return;
190
+ const failure = {
191
+ operation: run.operation,
192
+ stage: error instanceof AccountRequestError ? error.stage : run.stage,
193
+ code: error instanceof ApiError ? error.code : "account_error",
194
+ status: error instanceof ApiError ? error.status : void 0,
195
+ // 使用 SDK 生成的诊断文本;未知异常不直接发送任意异常对象/原始后端正文。
196
+ message: error instanceof ApiError ? error.message : "Account operation failed.",
197
+ attempts: run.attempts,
198
+ elapsedMs: Date.now() - run.startedAt,
199
+ api: error instanceof AccountRequestError ? error.api : run.api
200
+ };
201
+ setAccountError(failure);
202
+ reportAccountFailure(failure, run.appKey);
203
+ };
204
+ const login = (extraRetries = retry) => {
205
+ const run = beginAccountRun("login");
206
+ loginPendingRef.current = true;
155
207
  setLoginStatus("loading");
156
- handleLogin({
157
- appId,
158
- productName,
159
- onPassport,
160
- getRequestContext: getApiContext
161
- }).then((userStatus2) => {
162
- setLoginStatus("success");
163
- updateUserStatus(userStatus2);
164
- onUpdateUserStatus == null ? void 0 : onUpdateUserStatus(userStatus2);
165
- window.userId = userStatus2.userId || "";
166
- window.pollUserSubscribe = pollUserStatus.current = (options) => {
167
- var _a;
168
- const {
169
- fastIntervalMs = 5e3,
170
- fastPhaseMs = 3e4,
171
- slowIntervalMs = 15e3,
172
- sessionTtlMs = 3e5
173
- } = options || {};
174
- setHasClickedUpgrade(true);
175
- (_a = sessionStopRef.current) == null ? void 0 : _a.call(sessionStopRef, false);
176
- return new Promise((resolve) => {
177
- const userId = (window == null ? void 0 : window.userId) || "";
178
- const baseline = takeSubscribeBaseline(userStatusRef.current);
179
- const sessionStart = Date.now();
180
- console.log("checkout session start", baseline);
181
- let stopInner = null;
182
- let settled = false;
183
- const finish = (u) => {
184
- if (settled) return;
185
- settled = true;
186
- if (stopCurrentPolling.current === exposedStop) {
187
- stopCurrentPolling.current = null;
188
- }
189
- if (sessionStopRef.current === myStop) {
190
- sessionStopRef.current = null;
191
- }
192
- resolve(u);
193
- };
194
- const finalizeWithRefresh = () => {
195
- if (settled) return;
196
- Promise.race([
197
- refreshUserStatus(),
198
- new Promise(
199
- (r) => setTimeout(() => r(userStatusRef.current), 1e4)
200
- )
201
- ]).catch(() => userStatusRef.current).then((u) => finish(u || userStatusRef.current));
202
- };
203
- const myStop = (withRefresh) => {
204
- stopInner == null ? void 0 : stopInner();
205
- if (stopCurrentPolling.current === exposedStop) {
206
- stopCurrentPolling.current = null;
207
- }
208
- if (sessionStopRef.current === myStop) {
209
- sessionStopRef.current = null;
210
- }
211
- if (withRefresh) {
212
- finalizeWithRefresh();
213
- } else {
214
- finish(userStatusRef.current);
215
- }
216
- };
217
- const exposedStop = () => myStop(true);
218
- stopCurrentPolling.current = exposedStop;
219
- sessionStopRef.current = myStop;
220
- getUserProfile({
208
+ pollUserStatus.current = null;
209
+ void withRequest({ signal: run.controller.signal, timeoutMs: 3e4 }, async (signal) => {
210
+ for (let attempt = 0; ; attempt++) {
211
+ try {
212
+ return await handleLogin({
213
+ appId,
221
214
  productName,
222
- userId,
223
215
  onPassport,
224
216
  getRequestContext: getApiContext,
225
- isSubscribe: true,
226
- baseline,
227
- // 会话时长由 sessionTtlMs 主导;次数上限只作双保险
228
- maxCount: 1e4,
229
- maxDurationMs: sessionTtlMs,
230
- // 快阶段过后降频
231
- interval: () => Date.now() - sessionStart < fastPhaseMs ? fastIntervalMs : slowIntervalMs,
232
- onStop: (fn) => {
233
- stopInner = fn;
234
- },
235
- successCallback(u) {
236
- u.userId = userId;
237
- updateUserStatus(u);
238
- finish(u);
239
- onUpdateUserStatus == null ? void 0 : onUpdateUserStatus(u);
240
- }
241
- }).catch(() => {
242
- console.log("checkout session ttl reached");
243
- finalizeWithRefresh();
244
- }).finally(() => {
245
- if (stopCurrentPolling.current === exposedStop) {
246
- stopCurrentPolling.current = null;
247
- }
248
- if (sessionStopRef.current === myStop) {
249
- sessionStopRef.current = null;
250
- }
217
+ ...requestOptions(run),
218
+ signal
251
219
  });
252
- });
253
- };
254
- }).catch(() => {
255
- setLoginStatus("error");
256
- if (tryCount < retry) {
257
- setTimeout(() => {
258
- login(tryCount + 1);
259
- }, 3e3);
220
+ } catch (error) {
221
+ throwIfAborted(signal);
222
+ if (attempt >= extraRetries || !retryableAccountError(error)) throw error;
223
+ await accountDelay(3e3, signal);
224
+ }
260
225
  }
226
+ }).then((userStatus2) => {
227
+ if (!isCurrentRun(run)) return;
228
+ loginPendingRef.current = false;
229
+ setLoginStatus("success");
230
+ setAccountError(null);
231
+ updateUserStatus(userStatus2);
232
+ window.userId = userStatus2.userId || "";
233
+ window.pollUserSubscribe = pollUserStatus.current = startPolling;
234
+ onUpdateUserStatus == null ? void 0 : onUpdateUserStatus(userStatus2);
235
+ }).catch((error) => {
236
+ if (!isCurrentRun(run)) return;
237
+ loginPendingRef.current = false;
238
+ setLoginStatus("error");
239
+ failAccountRun(run, error);
261
240
  });
262
241
  };
242
+ function startPolling(options) {
243
+ const { fastIntervalMs = 5e3, fastPhaseMs = 3e4, slowIntervalMs = 15e3, sessionTtlMs = 3e5 } = options || {};
244
+ const run = beginAccountRun("poll");
245
+ setHasClickedUpgrade(true);
246
+ const userId = userStatusRef.current.userId || window.userId || "";
247
+ const baseline = takeSubscribeBaseline(userStatusRef.current);
248
+ return new Promise((resolve) => {
249
+ let settled = false;
250
+ let finishing = false;
251
+ const finish = (user) => {
252
+ if (settled) return;
253
+ settled = true;
254
+ if (stopCurrentPolling.current === exposedStop) stopCurrentPolling.current = null;
255
+ if (sessionStopRef.current === stop) sessionStopRef.current = null;
256
+ resolve(user);
257
+ };
258
+ const stop = (withRefresh) => {
259
+ if (settled || finishing) return;
260
+ run.controller.abort();
261
+ if (!withRefresh) {
262
+ finish(userStatusRef.current);
263
+ return;
264
+ }
265
+ finishing = true;
266
+ if (sessionStopRef.current === stop) sessionStopRef.current = null;
267
+ if (stopCurrentPolling.current === exposedStop) stopCurrentPolling.current = null;
268
+ void refreshUserStatus(1e4).then(finish);
269
+ };
270
+ const exposedStop = () => stop(true);
271
+ sessionStopRef.current = stop;
272
+ stopCurrentPolling.current = exposedStop;
273
+ void getUserProfile({
274
+ productName,
275
+ userId,
276
+ onPassport,
277
+ getRequestContext: getApiContext,
278
+ ...requestOptions(run),
279
+ isSubscribe: true,
280
+ baseline,
281
+ maxCount: 1e4,
282
+ maxDurationMs: sessionTtlMs,
283
+ interval: () => Date.now() - run.startedAt < fastPhaseMs ? fastIntervalMs : slowIntervalMs
284
+ }).then((user) => {
285
+ if (!isCurrentRun(run) || settled || finishing) return;
286
+ if (!user) {
287
+ stop(true);
288
+ return;
289
+ }
290
+ user.userId = userId;
291
+ setAccountError(null);
292
+ updateUserStatus(user);
293
+ finish(user);
294
+ onUpdateUserStatus == null ? void 0 : onUpdateUserStatus(user);
295
+ }).catch((error) => {
296
+ if (finishing) return;
297
+ failAccountRun(run, error);
298
+ finish(userStatusRef.current);
299
+ });
300
+ });
301
+ }
263
302
  useEffect(() => {
264
303
  if (!version && !productName && !baseUrl && !appId) {
265
304
  throw new Error("version, productName, baseUrl, appId is required");
@@ -336,10 +375,27 @@ const YiChongCanvaProvider = ({
336
375
  updateUserStatus({});
337
376
  }, [test]);
338
377
  useEffect(() => {
339
- if (autoLogin) {
340
- login();
378
+ mountedRef.current = true;
379
+ const scope = `${appId}|${productName}`;
380
+ if (identityScopeRef.current !== scope) {
381
+ identityScopeRef.current = scope;
382
+ window.userId = "";
383
+ passportRef.current = null;
384
+ userStatusRef.current = {};
385
+ setUserStatus({});
386
+ pollUserStatus.current = null;
341
387
  }
342
- }, [autoLogin]);
388
+ if (autoLogin) login();
389
+ else setLoginStatus("idle");
390
+ return () => {
391
+ var _a, _b;
392
+ mountedRef.current = false;
393
+ loginPendingRef.current = false;
394
+ (_a = sessionStopRef.current) == null ? void 0 : _a.call(sessionStopRef, false);
395
+ (_b = accountRunRef.current) == null ? void 0 : _b.controller.abort();
396
+ accountRunRef.current = null;
397
+ };
398
+ }, [autoLogin, appId, productName]);
343
399
  const initCredits = () => {
344
400
  var _a, _b;
345
401
  if (!userStatus.subscription || !userStatus.profile) {
@@ -448,24 +504,34 @@ const YiChongCanvaProvider = ({
448
504
  }
449
505
  return "Premium";
450
506
  };
451
- function refreshUserStatus() {
452
- return new Promise((resolve) => {
453
- getUserProfile({
454
- productName,
455
- userId: (window == null ? void 0 : window.userId) || "",
456
- onPassport,
457
- getRequestContext: getApiContext,
458
- maxCount: 2,
459
- successCallback(userStatus2) {
460
- userStatus2.userId = (window == null ? void 0 : window.userId) || "";
461
- updateUserStatus(userStatus2);
462
- onUpdateUserStatus == null ? void 0 : onUpdateUserStatus(userStatus2);
463
- resolve(userStatus2);
464
- }
465
- }).catch(() => {
466
- resolve(userStatusRef.current);
467
- });
507
+ function refreshUserStatus(timeoutMs = 3e4) {
508
+ if (loginPendingRef.current || !userStatusRef.current.userId || !userStatusRef.current.profile) return Promise.resolve(userStatusRef.current);
509
+ const existing = accountRunRef.current;
510
+ if ((existing == null ? void 0 : existing.operation) === "refresh" && existing.promise && isCurrentRun(existing)) return existing.promise;
511
+ const run = beginAccountRun("refresh");
512
+ const userId = userStatusRef.current.userId || window.userId || "";
513
+ run.promise = getUserProfile({
514
+ productName,
515
+ userId,
516
+ onPassport,
517
+ getRequestContext: getApiContext,
518
+ ...requestOptions(run),
519
+ maxCount: 2,
520
+ maxDurationMs: timeoutMs
521
+ }).then((user) => {
522
+ if (!user || !isCurrentRun(run)) return userStatusRef.current;
523
+ user.userId = userId;
524
+ setAccountError(null);
525
+ updateUserStatus(user);
526
+ onUpdateUserStatus == null ? void 0 : onUpdateUserStatus(user);
527
+ return user;
528
+ }).catch((error) => {
529
+ failAccountRun(run, error);
530
+ return userStatusRef.current;
531
+ }).finally(() => {
532
+ run.promise = void 0;
468
533
  });
534
+ return run.promise;
469
535
  }
470
536
  useEffect(() => {
471
537
  initCredits();
@@ -639,12 +705,13 @@ const YiChongCanvaProvider = ({
639
705
  },
640
706
  getPricingLink,
641
707
  updateTestMode,
642
- refreshUserStatus,
708
+ refreshUserStatus: () => refreshUserStatus(),
643
709
  hasClickedUpgrade,
644
710
  setHasClickedUpgrade: (v) => {
645
711
  setHasClickedUpgrade(v);
646
712
  },
647
713
  loginStatus,
714
+ accountError,
648
715
  updateCredits,
649
716
  stopCurrentPolling: () => {
650
717
  var _a;
@@ -655,8 +722,7 @@ const YiChongCanvaProvider = ({
655
722
  return false;
656
723
  },
657
724
  manualLogin: (_retry = 1) => {
658
- retry = _retry;
659
- login(0);
725
+ login(_retry);
660
726
  }
661
727
  },
662
728
  children
@@ -9,7 +9,7 @@ export interface ReportingContext extends Pick<ApiContext, "userStatus" | "produ
9
9
  }
10
10
  /**
11
11
  * 绑定显式错误上报能力:整理诊断信息,交由现有 Worker 转发到指定飞书机器人。
12
- * 返回 Worker 的确认结果,不安装全局异常监听,也不在其他 API 失败时自动上报或重试。
12
+ * 返回 Worker 的确认结果,不安装全局异常监听,也不在业务 API 失败时自动上报或重试;账户模块的最终失败由 Provider 调用。
13
13
  * 登录失败本身也需要诊断,因此允许账号尚未就绪,用 unknown 标记缺失身份。
14
14
  * 上报失败仍会抛出 ApiError,应用应单独捕获,避免它覆盖原来的业务异常。
15
15
  */
@@ -0,0 +1,36 @@
1
+ import { ApiError } from '../api/error';
2
+ import { ReportErrorParams } from '../api/types';
3
+ export type AccountStage = "canva_token" | "canva_identity" | "canvaid_login" | "canva_passport" | "status";
4
+ export type AccountOperation = "login" | "refresh" | "poll";
5
+ type AccountApi = NonNullable<ReportErrorParams["api"]>;
6
+ /** 账户加载的安全诊断快照;界面按 operation 选择本地化文案,不直接展示服务器正文。 */
7
+ export interface AccountError {
8
+ operation: AccountOperation;
9
+ stage: AccountStage;
10
+ code: string | number;
11
+ status?: number;
12
+ message: string;
13
+ attempts: number;
14
+ elapsedMs: number;
15
+ api?: AccountApi;
16
+ }
17
+ /** 仅在账户模块内部传递取消信号和当前步骤,不增加应用侧配置。 */
18
+ export interface AccountRequestOptions {
19
+ signal?: AbortSignal;
20
+ onStep?: (stage: AccountStage, api?: AccountApi) => void;
21
+ }
22
+ /** 保留接口、状态码与业务码;不携带响应正文、凭据、查询参数或用户输入。 */
23
+ export declare class AccountRequestError extends ApiError {
24
+ readonly stage: AccountStage;
25
+ readonly api?: AccountApi | undefined;
26
+ constructor(message: string, code: string | number, stage: AccountStage, api?: AccountApi | undefined);
27
+ }
28
+ /** 每个账户步骤最多 10 秒;SDK token 不支持取消,也必须结束等待且忽略它的迟到结果。 */
29
+ export declare function accountStep<T>(stage: AccountStage, options: AccountRequestOptions, work: (signal: AbortSignal) => Promise<T>, api?: AccountApi): Promise<T>;
30
+ /** 网络、限流与服务端错误允许有限重试;确定的客户端错误和主动取消不重试。 */
31
+ export declare function retryableAccountError(error: unknown): boolean;
32
+ /** 取消时立即清理重试计时器;不用嵌套 setTimeout 启动脱离原流程的新登录。 */
33
+ export declare function accountDelay(ms: number, signal: AbortSignal): Promise<void>;
34
+ /** 每个 Provider 持有一份去重表。只上报账户最终失败,不因渲染、重试或上报失败递归告警。 */
35
+ export declare function createAccountReporter(report: (params: ReportErrorParams) => Promise<unknown>): (error: AccountError, appKey: string) => void;
36
+ export {};
@@ -1,4 +1,5 @@
1
1
  import { default as React } from 'react';
2
+ import { AccountError } from './account';
2
3
  import { ChatApi, ContentExtractionApi, ErrorReportingApi, PredictionApi, TextModerationApi, UploadApi, UsageApi } from '../api/types';
3
4
  import { canUseError, CheckoutSessionOptions, TestMode, UserStatus } from './interface';
4
5
  /**
@@ -41,10 +42,10 @@ export interface YiChongCanvaContextType extends PredictionApi, TextModerationAp
41
42
  * 结账会话(checkout session)。
42
43
  * - 打开外部定价页(getPricingLink)后调用;无参调用使用默认参数(快 5s×30s → 慢 15s,TTL 5 分钟)
43
44
  * - 成功判定相对「打开定价页前」的基线:出现/变更 subscription.detail、free_cnt 增加、可用额度增加
44
- * - TTL 在轮次之间检查;到期或 stopCurrentPolling() 后补拉一次 status,再 resolve(补刷最多等待 10 秒)
45
+ * - TTL 会取消在途请求;到期或 stopCurrentPolling() 后补拉一次 status,再 resolve(补刷最多 10 秒)
45
46
  * - resolve 表示会话结束,可能只是超时或手动停止,不能据此认定支付成功;应检查返回账户状态
46
47
  * - 用户回到 Canva 侧栏(focus / visibilitychange)不会停止会话
47
- * - 再次调用会先停止上一轮调度;已发出的 HTTP 请求不会因此取消
48
+ * - 再次调用会取消上一轮在途请求,旧响应不再更新状态;连续三次故障提前结束并写入 accountError
48
49
  * - 登录完成前调用返回 undefined(不是 Promise)
49
50
  */
50
51
  pollUserStatus: (options?: CheckoutSessionOptions) => Promise<UserStatus> | undefined;
@@ -52,18 +53,20 @@ export interface YiChongCanvaContextType extends PredictionApi, TextModerationAp
52
53
  getPricingLink: () => string;
53
54
  /** 切换本地模拟订阅数据;此方法自身不限制环境。初始挂载会按 NODE_ENV 重设测试模式。 */
54
55
  updateTestMode: (m: TestMode) => void;
55
- /** 拉取账户状态,最多尝试 2 次;成功更新状态并回调,失败 resolve 当前内存状态,不 reject。 */
56
+ /** 拉取账户状态,最多尝试 2 次,共享 30 秒预算;失败 resolve 旧快照并写入 accountError、自动上报。 */
56
57
  refreshUserStatus: () => Promise<UserStatus>;
57
58
  /** 是否启动过升级检查;pollUserStatus 会设为 true,轮询结束不会自动恢复 false。 */
58
59
  hasClickedUpgrade: boolean;
59
60
  /** 仅修改升级提示的本地状态,不打开定价页,也不启动或停止轮询。 */
60
61
  setHasClickedUpgrade: (v: boolean) => void;
61
- /** 停止当前结账调度并安排补刷:有会话返回 true,否则 false;该返回值不等待补刷,不取消在途请求。 */
62
+ /** 停止当前结账调度并安排补刷:有会话返回 true,否则 false;该返回值不等待补刷,会取消在途请求。 */
62
63
  stopCurrentPolling: () => boolean;
63
64
  /** 仅覆盖本地 credits;不更新 userStatus 或服务器,后续账户状态派生可能覆盖此值。 */
64
65
  updateCredits: (credits: number) => void;
65
- /** idle=尚未启动;loading=登录中;success=已取得 profile;error=本次失败(仍可能有待执行的重试)。 */
66
+ /** idle=尚未启动;loading=登录中;success=已取得 profile;error=本次登录已结束且失败。 */
66
67
  loginStatus: "success" | "error" | "loading" | "idle";
68
+ /** 最近一次账户登录/刷新/支付检查失败;开始重试或成功后清除。自动上报不依赖 Footer 挂载。 */
69
+ accountError: AccountError | null;
67
70
  /** 手动启动登录,参数是失败后的重试次数(默认 1,另有首次请求);通过状态而非 Promise 获取结果。 */
68
71
  manualLogin: (_retry?: number) => void;
69
72
  }
@@ -3,3 +3,4 @@ export type { YiChongCanvaProviderProps } from './privider';
3
3
  export * from './interface';
4
4
  export * from './context';
5
5
  export * from './use_canva';
6
+ export type { AccountError, AccountStage, AccountOperation } from './account';
@@ -1,3 +1,5 @@
1
+ import { AccountRequestOptions } from '../../account';
2
+ import { UserStatus } from '../../interface';
1
3
  import { CommonRequestContext } from '../../../api/request';
2
4
  /**
3
5
  * 将 Canva 身份 token 和应用 ID 交给验证服务,读取 verified.userId。
@@ -7,14 +9,18 @@ import { CommonRequestContext } from '../../../api/request';
7
9
  * @param context 登录阶段已知的通用参数和当前语言;身份未验证前可能没有 uid/platform_uid。
8
10
  * @returns 验证服务的原始 JSON,结构校验由调用方读取 verified.userId 时体现。
9
11
  */
10
- declare function getUserIds(token: string, appId: string, context: CommonRequestContext): Promise<any>;
12
+ declare function getUserIds(token: string, appId: string, context: CommonRequestContext, options?: AccountRequestOptions): Promise<{
13
+ verified: {
14
+ userId: string;
15
+ };
16
+ }>;
11
17
  /**
12
18
  * 用已验证的 Canva ID 登录产品对应的账户;接口可能建立该应用的账户关系。
13
19
  * @param userId Canva 用户 ID,写入请求体 canva_id。
14
20
  * @param productName 后端渠道路径片段,必须与应用登记值一致。
15
- * @returns 账户服务原始 JSON;此处不会把响应转成新的 ApiResponse/ApiError 约定。
21
+ * @returns 账户服务原始 JSON;保留响应形状;HTTP/业务错误保留安全的 AccountRequestError 诊断。
16
22
  */
17
- declare function handleUserLoginByCanvaId(userId: string, productName: string, context: CommonRequestContext): Promise<any>;
23
+ declare function handleUserLoginByCanvaId(userId: string, productName: string, context: CommonRequestContext, options?: AccountRequestOptions): Promise<Record<string, unknown>>;
18
24
  /**
19
25
  * 获取账户服务 passport,供 status 和消费请求的 X-Access-Ticket 使用。
20
26
  * 优先读取 localStorage 缓存;缓存键历史上只包含 Canva userId,不包含 productName。
@@ -23,13 +29,19 @@ declare function handleUserLoginByCanvaId(userId: string, productName: string, c
23
29
  * imgkits 使用不带产品前缀的历史路径,其余产品使用产品前缀。
24
30
  * @returns 命中缓存时仅返回 { data: { passport } };网络请求时返回原始 JSON 并缓存 passport。
25
31
  */
26
- declare function getPassport(userId: string, productName: string, context: CommonRequestContext): Promise<any>;
32
+ declare function getPassport(userId: string, productName: string, context: CommonRequestContext, options?: AccountRequestOptions): Promise<{
33
+ data: {
34
+ passport: string;
35
+ };
36
+ }>;
27
37
  /**
28
38
  * 以账户 passport 读取产品状态,响应 data 包含 profile、subscription 和 AI 请求用的 jwt。
29
39
  * @param passport 账户票据;不是 Canva token,也不是 status 响应中的 jwt。
30
40
  * @returns 账户服务原始 JSON;轮询层负责判断 data.profile 是否已就绪。
31
41
  */
32
- declare function getUserStatusByPassport(passport: string, productName: string, context: CommonRequestContext): Promise<any>;
42
+ declare function getUserStatusByPassport(passport: string, productName: string, context: CommonRequestContext, options?: AccountRequestOptions): Promise<{
43
+ data: UserStatus;
44
+ }>;
33
45
  declare const apis: {
34
46
  getUserIds: typeof getUserIds;
35
47
  handleUserLoginByCanvaId: typeof handleUserLoginByCanvaId;
@@ -1,13 +1,14 @@
1
1
  import { CommonRequestContext } from '../../../api/request';
2
+ import { AccountStage, AccountRequestOptions } from '../../account';
2
3
  /**
3
- * 登录/账户旧协议的轻量请求层,与新 API 的 postApi 错误处理约定分开保留。
4
- * 提供 context 时补充通用查询参数和 Accept-Language;不会自行添加 JWT 或 passport,凭据由调用方传入。
5
- *
6
- * @param option 完整 URL 和 fetch 选项;可由调用方传 signal,但此层不会创建超时或自动重试。
7
- * @returns res.json() 的原始结果。HTTP 非 2xx 也会尝试解析,不检查 success/code;
8
- * 网络错误或 JSON 解析失败直接 reject,交给登录轮询层处理,不转换成 ApiError。
4
+ * 账户请求保留旧接口的响应形状,但检查 HTTP、JSON 和 ok/code/success。
5
+ * 每次请求含读取正文最多 10 秒,接收整个登录/刷新流程的取消信号。
6
+ * validate 是各接口的必要字段校验;诊断只记录 origin/path,绝不记录 token 查询参数或响应正文。
9
7
  */
10
- declare const requestUrl: (option: RequestInit & {
8
+ export declare function accountRequest<T>(option: RequestInit & {
11
9
  url: string;
12
- }, context?: CommonRequestContext) => Promise<any>;
13
- export default requestUrl;
10
+ }, context: CommonRequestContext, stage: AccountStage, options?: AccountRequestOptions, validate?: (body: Record<string, unknown>) => boolean): Promise<T>;
11
+ /** 远程版本查询仍沿用旧响应协议;账户登录使用上面的有界 accountRequest。 */
12
+ export default function requestUrl(option: RequestInit & {
13
+ url: string;
14
+ }, context?: CommonRequestContext): Promise<any>;
@@ -1,13 +1,12 @@
1
1
  import { UserStatus } from './../interface';
2
+ import { AccountRequestOptions } from '../account';
2
3
  import { CommonRequestContext } from '../../api/request';
3
4
  /**
4
- * Canva token → Canva userId → 应用账户登录 → passport/status,最终返回完整账户快照。
5
- * window.userId 已存在时沿用历史缓存,跳过 token 验证及 canvaid-login,直接读取账户状态。
6
- *
7
- * 成功后写入 window.g_token 兼容字段;passport 经内部回调交给 Provider,不混入公开 userStatus。
8
- * 登录过程中任何异常都会转换成普通 Error("login failed"),此层不会保留原始接口错误详情。
5
+ * Canva token → 平台身份 → 产品账户 → passport/status。
6
+ * 单步超时由 accountStep 处理,整个登录及重试的 30 秒预算由 Provider 管理。
7
+ * 保留具体错误;只在产品登录成功后缓存 userId,失败重试不能跳过尚未成功的 canvaid-login。
9
8
  */
10
- export declare function handleLogin({ appId, productName, onPassport, getRequestContext, }: LoginProps): Promise<UserStatus>;
9
+ export declare function handleLogin({ appId, productName, onPassport, getRequestContext, signal, onStep }: LoginProps): Promise<UserStatus>;
11
10
  /**
12
11
  * 订阅比较基线:打开定价页「之前」的用户状态快照。
13
12
  * 由 Provider 在会话开始时用当时的 userStatus 生成(takeSubscribeBaseline),
@@ -46,31 +45,18 @@ export declare function computeAvailableLimit(userStatus: UserStatus): number |
46
45
  */
47
46
  export declare function isSubscribeChanged(current: UserStatus, baseline: SubscribeBaseline): boolean;
48
47
  /**
49
- * 拉取 / 轮询用户信息。
50
- *
51
- * 两种模式(isSubscribe 区分):
52
- * - isSubscribe = false(handleLogin / refreshUserStatus):拿到带 profile 的
53
- * userStatus 立刻调用 successCallback 并返回,无需等待订阅变化。
54
- * - isSubscribe = true(结账会话):相对 baseline 检测订阅/额度变化,变了才成功。
55
- * 未传 baseline 时保持旧语义:用第一轮成功响应拍快照(但 detail 快照 bug 已修)。
56
- *
57
- * 结束方式:
58
- * 1. 成功:successCallback + return userStatus
59
- * 2. 手动停止(onStop 交出的函数被调用):打断 sleep,退出循环后 return undefined;
60
- * 已发出的请求仍可能先满足成功条件并返回账户状态
61
- * 3. maxCount 次数耗尽或 maxDurationMs 到期:failCallback + throw
62
- *
63
- * 时长/停止条件在请求之间检查,不取消在途 fetch。首次申请 passport 在轮询 try/catch 之外,
64
- * 它若失败会直接 reject;status 请求失败则消耗一轮后继续尝试,直到次数或时长预算耗尽。
48
+ * 普通读取默认最多两次;支付轮询仍按订阅基线判断,连续三次网络/服务端错误即结束。
49
+ * 一次无 profile 的响应允许刷新 passport 后再读一次;不把任意服务器故障当作票据失效。
50
+ * 总预算覆盖 passport、status、等待和响应体读取;主动停止/健康的支付 TTL 到期正常返回 undefined。
65
51
  */
66
- export declare function getUserProfile({ maxCount, interval, maxDurationMs, productName, userId, successCallback, failCallback, isSubscribe, baseline, isChanged, onStop, onPassport, getRequestContext, }: UserProfileProps): Promise<UserStatus | undefined>;
52
+ export declare function getUserProfile({ maxCount, interval, maxDurationMs, productName, userId, successCallback, failCallback, isSubscribe, baseline, isChanged, onStop, onPassport, getRequestContext, signal, onStep, }: UserProfileProps): Promise<UserStatus | undefined>;
67
53
  /** 内部账户读取/支付轮询配置;应用通常通过 client.refreshUserStatus 或 pollUserStatus 使用。 */
68
- export interface UserProfileProps {
69
- /** status 尝试次数上限,默认 50;passport 请求另行发生,不包含在此计数内。 */
54
+ export interface UserProfileProps extends AccountRequestOptions {
55
+ /** status 尝试次数上限,默认 2;passport 请求另行发生,不包含在此计数内。 */
70
56
  maxCount?: number;
71
57
  /** 两轮 status 之间的等待毫秒数,默认 3000;函数形式在每轮计算,用于支付快慢阶段切换。 */
72
58
  interval?: number | (() => number);
73
- /** 从函数开始计算的轮询预算;默认仅受 maxCount 限制,不会打断已发出的 HTTP 请求。 */
59
+ /** 从函数开始计算的轮询预算;默认读取 30 秒、支付检查 5 分钟;到时取消在途请求。 */
74
60
  maxDurationMs?: number;
75
61
  /** 后端登记的产品渠道,用于账户接口路径和请求上下文。 */
76
62
  productName: string;
@@ -86,7 +72,7 @@ export interface UserProfileProps {
86
72
  baseline?: SubscribeBaseline;
87
73
  /** 订阅模式的自定义结束判定;省略时使用 isSubscribeChanged。 */
88
74
  isChanged?: (current: UserStatus, baseline: SubscribeBaseline) => boolean;
89
- /** 取得停止调度函数;能立即唤醒 sleep,但不会取消 status/passport 网络请求。 */
75
+ /** 取得停止调度函数;立即取消等待和 status/passport 网络请求。 */
90
76
  onStop?: (fn: () => void) => void;
91
77
  /** status 具有 profile 后传出已验证可用的账户票据、Canva ID 和系统 ID,供 Provider 私有缓存。 */
92
78
  onPassport?: (passport: string, userId: string, uid: string) => void;
@@ -94,7 +80,7 @@ export interface UserProfileProps {
94
80
  getRequestContext?: () => CommonRequestContext;
95
81
  }
96
82
  /** 内部登录参数;callback 和 requestConfig 为保留字段,当前 handleLogin 不读取它们。 */
97
- export interface LoginProps {
83
+ export interface LoginProps extends AccountRequestOptions {
98
84
  /** 历史兼容声明;当前登录结果由 Promise 返回,此回调不被调用。 */
99
85
  callback?: (state: LoginState) => void;
100
86
  /** Canva 应用 ID,用于 token 验证。 */
@@ -35,7 +35,7 @@ export interface YiChongCanvaProviderProps {
35
35
  mode?: Mode;
36
36
  /** server_credits 模式下订阅用户余额计算的总额度,默认 1;不是后端月限额的覆盖配置。 */
37
37
  maxAvailablePoints?: number;
38
- /** 自动登录失败后的额外重试次数,默认 3;首次请求不计入,重试间隔 3 秒。 */
38
+ /** 自动登录失败后的额外重试次数,默认 3;首次请求不计入,重试间隔 3 秒,整个登录受 30 秒总上限约束。 */
39
39
  retry?: number;
40
40
  }
41
41
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yichong-canva2",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",