yichong-canva2 2.6.0 → 2.7.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,6 +2,8 @@
2
2
 
3
3
  使用一个 `YiChongCanvaProvider` 管理登录、订阅和额度,通过 `useYiChongCanva()` 直接调用后端接口。
4
4
 
5
+ **2.7.0(2026-10-27)**:配合后端 msg 分级,新增 `getDisplayMessage`、`getBackendErrorCode`、`isPolicyBlocked`,`ApiError` 增加 `errorCode`、`traceId`、`displayable`;新通道按后端 `error_code` 推断错误码和是否预期内。已有字段含义不变。见下文「错误文案(2.7.0 起)」。另外新增 `client.pricingUnit`:计量单位按渠道和界面语言从定价语言包读取,见「计量单位(2.7.0 起)」。
6
+
5
7
  **2.6.0**:新增行为与错误上报的**新通道**(schema `canva.v1`),**默认关闭**,升级后行为与 2.5.1 相同。开启后在旧 GET 统计、飞书错误上报之外额外发一份到 `telemetry.imgkits.com`;旧通道的请求内容、返回值和抛错行为不变。新增 `client.track`、`reportUsage` 的可选字段 `flow` / `timings` / `error`、`use()` 的可选第 4 个参数 `{ operationId }`,以及 `StageError`、`toErrorCode`、`createStageTimer`。见下文「新通道(2.6.0 起)」。
6
8
 
7
9
  **2.5.1**:只补类型、不改行为。`userStatus.profile` 增加后端 status 已返回的 `review?: boolean`(审核开关:true 审核期、false 正常运行、缺失为旧账户)、`canva_id?`、`created_at?`、`nextUsageResetTime?`。支付链接是否可点由应用按 `review === false || canAcceptPayments` 决定,SDK 不据此改变任何行为。
@@ -687,6 +689,51 @@ const prediction = await client.getPrediction(
687
689
 
688
690
  取消只终止当前 HTTP 等待,不会取消已经创建的后端任务或撤销已提交的消费。创建、查询、文本审核和底层签名的默认请求超时为 60 秒,包含读取响应正文的时间;内容提取和大模型 `chat` 为 360 秒,消费为 30 秒,单次 PUT 上传为 120 秒,分片上传整体为 30 分钟。
689
691
 
692
+ ## 错误文案(2.7.0 起)
693
+
694
+ 后端对 `createSpecifyPrediction`、`getPrediction` 做了 msg 分级:失败时的 `msg`、任务的 `error_msg` / `error` 都是按 `Accept-Language` 翻译好的用户文案,原文挪到 `debug_msg` / `raw_*`(约定见仓库 `docs/前后端约定-错误文案msg分级.md`)。界面取文案只用 `getDisplayMessage`,取不到再显示应用自己的翻译文案:
695
+
696
+ ```ts
697
+ import { getDisplayMessage, isPolicyBlocked } from "yichong-canva2";
698
+
699
+ function describeFailure(error: unknown): string {
700
+ return getDisplayMessage(error) // 后端分级后的用户文案
701
+ || (isPolicyBlocked(error) ? policyText // 内容违规:换图 / 换样式
702
+ : fallbackText); // 应用自己的翻译兜底
703
+ }
704
+ ```
705
+
706
+ | 字段 / 函数 | 含义 |
707
+ | --- | --- |
708
+ | `ApiError.displayable` | message 能原样展示时为 true。创建失败看响应是否带 `debug_msg`,任务失败看任务是否带 `error_code`;其它接口、SDK 本地错误恒为 false |
709
+ | `ApiError.errorCode` | 后端 `error_code`(snake_case),逻辑判断只看它 |
710
+ | `ApiError.traceId` | 后端 `trace_id`(创建接口),新通道放进 `request_id` |
711
+ | `getDisplayMessage(error)` | 可展示的后端文案,没有返回 `""`;会顺着 `StageError` / `Error.cause` 找,最多 5 层 |
712
+ | `getBackendErrorCode(error)` | 后端 `error_code`,没有返回 `undefined` |
713
+ | `isPolicyBlocked(error)` | 后端判定内容违规(`content_policy_violation`),或 `StageError` 的 code 为 `POLICY_BLOCKED` |
714
+
715
+ - 不再需要维护「SDK 本地错误码清单」,也不要再用正则匹配 `E005`。
716
+ - 新通道:后端 `content_policy_violation` 记为 `POLICY_BLOCKED`(`generate_blocked`,不告警);`image_unavailable`、`invalid_input`、`too_many_concurrent_tasks`、`image_preprocessing_failed`、`no_output` 记为预期内。
717
+ - `code`、`userMessage` 含义不变:创建失败的 `code` 仍是后端数字 `1`,任务失败仍是 `prediction_failed`。
718
+ - 后端没打开分级时 `displayable` 一律为 false,应用显示自己的兜底文案。
719
+
720
+ ## 计量单位(2.7.0 起)
721
+
722
+ `client.pricingUnit` 是定价语言包里的计量单位,和定价页用同一份文件:改了定价单位,用户下次打开应用就生效,不用前端发版。
723
+
724
+ ```ts
725
+ const { pricingUnit } = useYiChongCanva();
726
+ // { unitNoun: "Quiz", unitNounPlural: "Quizze", locale: "de" },读取中或拿不到时为 null
727
+ const unitNoun = pricingUnit?.unitNoun ?? appConfig.unitConfig.unitNoun;
728
+ ```
729
+
730
+ - 地址:`https://project.deletetweets.ai/yichong_pricing_language/<productName>/<语言>.json` 的 `config.unit` / `config.plural_unit`。
731
+ - 语言:取界面语言的主语言(`zh-TW` → `zh`,`pt-BR` → `pt`),没有语言包再退到 `en`;换语言时重新读取,期间保留上一份单位,换渠道时旧单位作废。
732
+ - 每次打开都用 `cache: "no-cache"` 带 ETag 校验,没变时只回 304;单次 10 秒超时,不阻塞登录。
733
+ - 404、断网、超时、格式不对(非字符串、超过 40 字符、含 `<>{}`)都只得到 `null`,不抛错、不上报:部分渠道本来就没有定价语言包,应用退回 `config.ts` 的 `unitConfig`。
734
+ - 复数沿用「1 用单数,其余用复数」;语言包没有 `plural_unit` 时复数等于单数。
735
+ - 也导出了 `loadPricingUnit(productName, locale, signal?)`,供不用 Provider 的场景使用。
736
+
690
737
  ## 账户故障处理(2.2.0)
691
738
 
692
739
  继续使用一个 `YiChongCanvaProvider`,无需额外的上报 Provider 或 Footer 上报包装。账户模块会自动报告最终失败,业务 API 的错误仍在业务 catch 中按需显式调用 `client.reportError`。
package/dist/api/error.js CHANGED
@@ -3,7 +3,7 @@ class ApiError extends Error {
3
3
  * @param message 可展示的错误说明。
4
4
  * @param code 后端业务码或 SDK 标识,例如 invalid_request、timeout、network_error。
5
5
  * @param status 已取得的 HTTP 状态;请求发出前的错误等情况通常没有此值。
6
- * @param details 可选诊断数据和 Retry-After 秒数;仅提供信息,不触发重试。
6
+ * @param details 可选诊断数据、Retry-After 秒数和后端分级信息;仅提供信息,不触发重试。
7
7
  */
8
8
  constructor(message, code, status, details) {
9
9
  super(message);
@@ -13,12 +13,38 @@ class ApiError extends Error {
13
13
  this.userMessage = message;
14
14
  this.data = details == null ? void 0 : details.data;
15
15
  this.retryAfter = details == null ? void 0 : details.retryAfter;
16
+ this.errorCode = typeof (details == null ? void 0 : details.errorCode) === "string" && errorCodePattern.test(details.errorCode) ? details.errorCode : void 0;
17
+ this.traceId = typeof (details == null ? void 0 : details.traceId) === "string" && details.traceId.trim() ? details.traceId.trim().slice(0, 128) : void 0;
18
+ this.displayable = (details == null ? void 0 : details.displayable) === true && message.trim().length > 0;
16
19
  }
17
20
  }
21
+ const errorCodePattern = /^[a-z][a-z0-9_]{1,63}$/;
22
+ const MAX_CAUSE_DEPTH = 5;
23
+ function findInChain(error, pick) {
24
+ let current = error;
25
+ for (let depth = 0; depth <= MAX_CAUSE_DEPTH && current !== null && typeof current === "object"; depth++) {
26
+ const found = pick(current);
27
+ if (found !== void 0) return found;
28
+ current = current.cause;
29
+ }
30
+ return void 0;
31
+ }
32
+ function getDisplayMessage(error) {
33
+ return findInChain(error, (value) => value instanceof ApiError && value.displayable ? value.message.trim() : void 0) ?? "";
34
+ }
35
+ function getBackendErrorCode(error) {
36
+ return findInChain(error, (value) => value instanceof ApiError ? value.errorCode : void 0);
37
+ }
38
+ function isPolicyBlocked(error) {
39
+ return findInChain(error, (value) => value instanceof ApiError && value.errorCode === "content_policy_violation" || !(value instanceof ApiError) && value.code === "POLICY_BLOCKED" ? true : void 0) === true;
40
+ }
18
41
  function isAbortError(error) {
19
42
  return error instanceof ApiError ? error.code === "aborted" : error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
20
43
  }
21
44
  export {
22
45
  ApiError,
23
- isAbortError
46
+ getBackendErrorCode,
47
+ getDisplayMessage,
48
+ isAbortError,
49
+ isPolicyBlocked
24
50
  };
@@ -124,8 +124,13 @@ function createPredictionApi(getContext) {
124
124
  }
125
125
  if (task) {
126
126
  if (["failed", "canceled", "aborted"].includes(task.status)) {
127
- const message = [task.error_msg, task.error].find(isNonemptyString) || "Generation failed.";
128
- throw new ApiError(message, "prediction_failed", void 0, { data: { id: task.id, status: task.status } });
127
+ const message = [task.error_msg, task.error].find(isNonemptyString);
128
+ const errorCode = isNonemptyString(task.error_code) ? task.error_code : void 0;
129
+ throw new ApiError(message || "Generation failed.", "prediction_failed", void 0, {
130
+ data: { id: task.id, status: task.status, ...errorCode ? { error_code: errorCode } : {} },
131
+ errorCode,
132
+ displayable: errorCode !== void 0 && message !== void 0
133
+ });
129
134
  }
130
135
  if (task.status === "succeeded" || allowEarlyOutput && getPredictionOutputUrl(task.output)) return task;
131
136
  }
@@ -24,7 +24,7 @@ function createErrorReportingApi(getContext) {
24
24
  platform: "canva_addon",
25
25
  app_id: context.appId,
26
26
  app_version: String(context.version),
27
- sdk_version: "2.6.0",
27
+ sdk_version: "2.7.0",
28
28
  user_id: ((_d = context.userStatus.profile) == null ? void 0 : _d.id) ?? "unknown",
29
29
  platform_uid: context.userStatus.userId ?? "unknown",
30
30
  ...reportingPayload(params, secrets)
@@ -77,15 +77,20 @@ async function readJson(response) {
77
77
  throw new ApiError("Backend returned an invalid JSON response.", response.ok ? "invalid_response" : "http_error", response.status);
78
78
  }
79
79
  }
80
- function backendError(response, payload, fallbackCode) {
81
- const message = isObject(payload) && isNonemptyString(payload.msg) ? payload.msg : isObject(payload) && isNonemptyString(payload.message) ? payload.message : "Backend request failed.";
80
+ function backendError(response, payload, fallbackCode, options = {}) {
81
+ const hasMsg = isObject(payload) && isNonemptyString(payload.msg);
82
+ const message = hasMsg ? payload.msg : isObject(payload) && isNonemptyString(payload.message) ? payload.message : "Backend request failed.";
82
83
  const code = isObject(payload) && (typeof payload.code === "string" || typeof payload.code === "number") ? payload.code : fallbackCode;
83
84
  const retryAfter = response.headers.get("Retry-After");
84
85
  return new ApiError(message, code, response.status, {
85
86
  data: isObject(payload) && isObject(payload.data) ? payload.data : void 0,
86
- retryAfter: retryAfter !== null && /^\d+$/.test(retryAfter) && Number.isSafeInteger(Number(retryAfter)) ? Number(retryAfter) : void 0
87
+ retryAfter: retryAfter !== null && /^\d+$/.test(retryAfter) && Number.isSafeInteger(Number(retryAfter)) ? Number(retryAfter) : void 0,
88
+ errorCode: isObject(payload) ? payload.error_code : void 0,
89
+ traceId: isObject(payload) ? payload.trace_id : void 0,
90
+ displayable: options.tiered === true && hasMsg && isObject(payload) && typeof payload.debug_msg === "string"
87
91
  });
88
92
  }
93
+ const tieredMethods = /* @__PURE__ */ new Set(["createSpecifyPrediction"]);
89
94
  async function postApi(context, method, params, options = {}) {
90
95
  return withRequest(options, async (signal) => {
91
96
  var _a;
@@ -114,14 +119,15 @@ async function postApi(context, method, params, options = {}) {
114
119
  redirect: "error"
115
120
  });
116
121
  const payload = await readJson(response);
117
- if (!response.ok) throw backendError(response, payload, "http_error");
122
+ const tiered = tieredMethods.has(method);
123
+ if (!response.ok) throw backendError(response, payload, "http_error", { tiered });
118
124
  if (method === "cancelPrediction" && isObject(payload) && payload.code === void 0) {
119
125
  return payload;
120
126
  }
121
127
  if (!isObject(payload) || typeof payload.code !== "number" && typeof payload.code !== "string") {
122
128
  throw new ApiError("Backend returned an invalid response envelope.", "invalid_response", response.status);
123
129
  }
124
- if (payload.code !== 0) throw backendError(response, payload, "http_error");
130
+ if (payload.code !== 0) throw backendError(response, payload, "http_error", { tiered });
125
131
  if (typeof payload.msg !== "string" || !Object.prototype.hasOwnProperty.call(payload, "data")) {
126
132
  throw new ApiError("Backend returned an invalid response envelope.", "invalid_response", response.status);
127
133
  }
@@ -115,7 +115,7 @@ function createTelemetry(getContext) {
115
115
  event_id: newId(),
116
116
  occurred_at: (/* @__PURE__ */ new Date()).toISOString(),
117
117
  seq: ++seq,
118
- app: { id: context.appId, channel: context.productName, version: String(context.version), sdk: "2.6.0" },
118
+ app: { id: context.appId, channel: context.productName, version: String(context.version), sdk: "2.7.0" },
119
119
  user: { id: context.userId && idPattern.test(context.userId) ? context.userId : null, plan: context.plan },
120
120
  session: { id: context.sessionId, locale: context.locale },
121
121
  env,
@@ -64,7 +64,18 @@ function cleanTimings(input) {
64
64
  function cleanDuration(value) {
65
65
  return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= MAX_DURATION ? Math.round(value) : void 0;
66
66
  }
67
- const expectedCodes = /* @__PURE__ */ new Set(["ABORTED", "POLICY_BLOCKED", "NOT_FOUND", "USER_OFFLINE", "PERMISSION_DENIED"]);
67
+ const expectedCodes = /* @__PURE__ */ new Set([
68
+ "ABORTED",
69
+ "POLICY_BLOCKED",
70
+ "NOT_FOUND",
71
+ "USER_OFFLINE",
72
+ "PERMISSION_DENIED",
73
+ "IMAGE_UNAVAILABLE",
74
+ "INVALID_INPUT",
75
+ "TOO_MANY_CONCURRENT_TASKS",
76
+ "IMAGE_PREPROCESSING_FAILED",
77
+ "NO_OUTPUT"
78
+ ]);
68
79
  function cleanError(input, secrets) {
69
80
  var _a;
70
81
  const stage = isReportStage(input.stage) ? input.stage : "unknown";
@@ -83,7 +94,7 @@ function cleanError(input, secrets) {
83
94
  if (cause instanceof ApiError) {
84
95
  if (cause.status !== void 0) payload.http_status = cause.status;
85
96
  if (typeof cause.code === "number") payload.backend_code = String(cause.code);
86
- const requestId = (_a = cause.data) == null ? void 0 : _a.request_id;
97
+ const requestId = cause.traceId ?? ((_a = cause.data) == null ? void 0 : _a.request_id);
87
98
  if (typeof requestId === "string") payload.request_id = usageReportingText(requestId, 128, secrets);
88
99
  }
89
100
  return payload;
@@ -38,6 +38,9 @@ class StageError extends Error {
38
38
  function toErrorCode(error, stage) {
39
39
  if (error instanceof StageError) return error.code;
40
40
  if (isAbortError(error)) return "ABORTED";
41
+ if (error instanceof ApiError && error.errorCode) {
42
+ return error.errorCode === "content_policy_violation" ? "POLICY_BLOCKED" : error.errorCode.toUpperCase();
43
+ }
41
44
  const code = error instanceof ApiError ? error.code : error !== null && typeof error === "object" && "code" in error ? error.code : void 0;
42
45
  if (typeof code === "string" && /^[a-z][a-z0-9_]{1,63}$/.test(code)) return code.toUpperCase();
43
46
  if (typeof code === "string" && errorCodePattern.test(code)) return code;
package/dist/index.js CHANGED
@@ -1,19 +1,25 @@
1
1
  import { YiChongCanvaProvider } from "./login/privider.js";
2
2
  import { YiChongCanvaContext } from "./login/context.js";
3
3
  import { useYiChongCanva } from "./login/use_canva.js";
4
- import { ApiError, isAbortError } from "./api/error.js";
4
+ import { PRICING_LANGUAGE_BASE_URL, loadPricingUnit } from "./login/pricing_unit.js";
5
+ import { ApiError, getBackendErrorCode, getDisplayMessage, isAbortError, isPolicyBlocked } from "./api/error.js";
5
6
  import { getPredictionOutputUrl } from "./api/predictions.js";
6
7
  import { REPORT_STAGES, StageError, createStageTimer, isReportStage, toErrorCode } from "./api/telemetry/stage.js";
7
8
  export {
8
9
  ApiError,
10
+ PRICING_LANGUAGE_BASE_URL,
9
11
  REPORT_STAGES,
10
12
  StageError,
11
13
  YiChongCanvaContext,
12
14
  YiChongCanvaProvider,
13
15
  createStageTimer,
16
+ getBackendErrorCode,
17
+ getDisplayMessage,
14
18
  getPredictionOutputUrl,
15
19
  isAbortError,
20
+ isPolicyBlocked,
16
21
  isReportStage,
22
+ loadPricingUnit,
17
23
  toErrorCode,
18
24
  useYiChongCanva
19
25
  };
@@ -34,6 +34,7 @@ const YiChongCanvaContext = React.createContext(
34
34
  },
35
35
  loginStatus: "idle",
36
36
  accountError: null,
37
+ pricingUnit: null,
37
38
  manualLogin: () => {
38
39
  },
39
40
  createSpecifyPrediction: async () => {
@@ -0,0 +1,48 @@
1
+ import { withRequest } from "../api/transport.js";
2
+ const PRICING_LANGUAGE_BASE_URL = "https://project.deletetweets.ai/yichong_pricing_language";
3
+ const channelPattern = /^[a-z0-9_]{1,64}$/;
4
+ const languagePattern = /^[a-z]{2,3}$/;
5
+ const TIMEOUT_MS = 1e4;
6
+ const MAX_UNIT_LENGTH = 40;
7
+ function cleanUnit(value) {
8
+ if (typeof value !== "string") return void 0;
9
+ const text = value.trim();
10
+ return text && text.length <= MAX_UNIT_LENGTH && !/[<>{}]/.test(text) ? text : void 0;
11
+ }
12
+ async function fetchUnit(channel, lang, signal) {
13
+ return withRequest({ signal, timeoutMs: TIMEOUT_MS }, async (requestSignal) => {
14
+ const response = await fetch(`${PRICING_LANGUAGE_BASE_URL}/${channel}/${lang}.json`, {
15
+ cache: "no-cache",
16
+ credentials: "omit",
17
+ redirect: "error",
18
+ signal: requestSignal
19
+ });
20
+ if (!response.ok) return null;
21
+ const body = await response.json().catch(() => null);
22
+ const config = body !== null && typeof body === "object" ? body.config : void 0;
23
+ const fields = config !== null && typeof config === "object" ? config : {};
24
+ const unitNoun = cleanUnit(fields.unit);
25
+ if (!unitNoun) return null;
26
+ return { unitNoun, unitNounPlural: cleanUnit(fields.plural_unit) ?? unitNoun, locale: lang };
27
+ });
28
+ }
29
+ async function loadPricingUnit(channel, locale, signal) {
30
+ var _a;
31
+ if (!channelPattern.test(channel)) return null;
32
+ const primary = ((_a = locale.split("-")[0]) == null ? void 0 : _a.toLowerCase()) ?? "";
33
+ const candidates = languagePattern.test(primary) && primary !== "en" ? [primary, "en"] : ["en"];
34
+ for (const lang of candidates) {
35
+ if (signal == null ? void 0 : signal.aborted) return null;
36
+ try {
37
+ const unit = await fetchUnit(channel, lang, signal);
38
+ if (unit) return unit;
39
+ } catch {
40
+ if (signal == null ? void 0 : signal.aborted) return null;
41
+ }
42
+ }
43
+ return null;
44
+ }
45
+ export {
46
+ PRICING_LANGUAGE_BASE_URL,
47
+ loadPricingUnit
48
+ };
@@ -22,6 +22,7 @@ import { readCache, writeCache, versionCacheKey, testCacheKey } from "./cache.js
22
22
  import { ApiError } from "../api/error.js";
23
23
  import { withRequest, throwIfAborted } from "../api/transport.js";
24
24
  import { createAccountReporter, AccountRequestError, retryableAccountError, accountDelay } from "./account.js";
25
+ import { loadPricingUnit } from "./pricing_unit.js";
25
26
  let usageIdSequence = 0;
26
27
  function usageId() {
27
28
  try {
@@ -78,6 +79,8 @@ const YiChongCanvaProvider = ({
78
79
  const sessionStopRef = useRef(null);
79
80
  const [loginStatus, setLoginStatus] = useState("idle");
80
81
  const [accountError, setAccountError] = useState(null);
82
+ const [pricingUnit, setPricingUnit] = useState(null);
83
+ const pricingLocale = language(getLocale);
81
84
  const accountRunRef = useRef(null);
82
85
  const loginPendingRef = useRef(false);
83
86
  const mountedRef = useRef(true);
@@ -770,6 +773,13 @@ const YiChongCanvaProvider = ({
770
773
  return creditsRef.current;
771
774
  }
772
775
  };
776
+ useEffect(() => {
777
+ const controller = new AbortController();
778
+ void loadPricingUnit(productName, pricingLocale, controller.signal).then((unit) => {
779
+ if (!controller.signal.aborted) setPricingUnit({ productName, unit });
780
+ });
781
+ return () => controller.abort();
782
+ }, [productName, pricingLocale]);
773
783
  const getMonthlyUsageLimit = () => {
774
784
  const { profile } = userStatusRef.current;
775
785
  const { usage_limits } = profile || {};
@@ -824,6 +834,8 @@ const YiChongCanvaProvider = ({
824
834
  },
825
835
  loginStatus,
826
836
  accountError,
837
+ // 换语言期间先保留上一份单位,避免闪回 config.ts 的英文;换渠道时旧单位作废。
838
+ pricingUnit: (pricingUnit == null ? void 0 : pricingUnit.productName) === productName ? pricingUnit.unit : null,
827
839
  updateCredits,
828
840
  stopCurrentPolling: () => {
829
841
  var _a;
@@ -13,16 +13,40 @@ export declare class ApiError extends Error {
13
13
  readonly data?: Record<string, unknown>;
14
14
  /** Retry-After 响应头的秒数;工具包不会自动重试。 */
15
15
  readonly retryAfter?: number;
16
+ /** 后端 error_code(snake_case):创建失败取响应顶层,任务失败取任务对象。2.7.0 起。 */
17
+ readonly errorCode?: string;
18
+ /** 后端 trace_id,目前只有创建接口返回。2.7.0 起。 */
19
+ readonly traceId?: string;
20
+ /**
21
+ * message 是后端分级后的用户文案、可以原样展示时为 true(见 docs/前后端约定-错误文案msg分级.md)。
22
+ * SDK 本地错误、约定范围外的接口、后端尚未打开分级时恒为 false。界面取文案用 getDisplayMessage。2.7.0 起。
23
+ */
24
+ readonly displayable: boolean;
16
25
  /**
17
26
  * @param message 可展示的错误说明。
18
27
  * @param code 后端业务码或 SDK 标识,例如 invalid_request、timeout、network_error。
19
28
  * @param status 已取得的 HTTP 状态;请求发出前的错误等情况通常没有此值。
20
- * @param details 可选诊断数据和 Retry-After 秒数;仅提供信息,不触发重试。
29
+ * @param details 可选诊断数据、Retry-After 秒数和后端分级信息;仅提供信息,不触发重试。
21
30
  */
22
31
  constructor(message: string, code: string | number, status?: number | undefined, details?: {
23
32
  data?: Record<string, unknown>;
24
33
  retryAfter?: number;
34
+ errorCode?: unknown;
35
+ traceId?: unknown;
36
+ displayable?: boolean;
25
37
  });
26
38
  }
39
+ /**
40
+ * 能原样展示给用户的后端文案;没有时返回 "",由应用显示自己的翻译兜底。
41
+ * 只认 displayable 的 ApiError:SDK 本地英文错误、服务商原文、未分级的 msg 都返回 ""。
42
+ */
43
+ export declare function getDisplayMessage(error: unknown): string;
44
+ /** 后端 error_code;没有时返回 undefined。应用做逻辑判断只看它,不匹配文案。 */
45
+ export declare function getBackendErrorCode(error: unknown): string | undefined;
46
+ /**
47
+ * 内容违规:后端 error_code 为 content_policy_violation,或 StageError 的 code 为 POLICY_BLOCKED。
48
+ * StageError 定义在 telemetry/stage.ts 且依赖本文件,这里按 code 字段判断,避免循环依赖。
49
+ */
50
+ export declare function isPolicyBlocked(error: unknown): boolean;
27
51
  /** 仅识别主动取消;普通 DOMException(例如 SecurityError)或后端任务失败不应被静默忽略。 */
28
52
  export declare function isAbortError(error: unknown): boolean;
@@ -3,7 +3,7 @@
3
3
  * 实现工厂保持内部使用,业务通过 Provider 的 client 调用方法,共享登录身份和配置。
4
4
  * 参数、返回值及方法的 JSDoc 定义在 types.ts,会随声明文件发布供编辑器提示。
5
5
  */
6
- export { ApiError, isAbortError } from './error';
6
+ export { ApiError, getBackendErrorCode, getDisplayMessage, isAbortError, isPolicyBlocked } from './error';
7
7
  export { getPredictionOutputUrl } from './predictions';
8
8
  export * from './telemetry';
9
9
  export type { ApiRequestOptions, ApiResponse, CancelPredictionResponse, ChatApi, ChatParams, ChatPayload, ChatResult, CreateTextToSpeechParams, CreateTextToSpeechResult, GetTextToSpeechResultParams, TextToSpeechApi, TextToSpeechResult, TextToSpeechTaskState, CreateVttParams, CreateVttResult, GetVttStatusParams, VttApi, VttStatusResult, VttTaskState, CompleteUploadParams, CompleteUploadResponse, ContentExtractParams, ContentExtractResult, ContentExtractionApi, TextCheckParams, CreateSpecifyPredictionParams, ErrorReportingApi, ErrorReportSource, GetPredictionParams, GeneratePresignedUrlParams, GetUploadUrlParams, InitiateUploadParams, InitiateUploadResponse, JsonObject, JsonValue, Prediction, PredictionApi, WaitForPredictionOptions, ReportErrorParams, ReportUsageParams, TelemetryApi, UsageReportingApi, UsageReportingConfig, ReportErrorResult, PresignedUrlResponse, TextModerationApi, TextModerationCategory, TextModerationDecision, TextModerationResult, UploadApi, UploadFileParams, UploadFileResult, UploadedPart, UploadPartUrlResponse, UploadProgress, UsageApi, UsageParams, UsageResponse, } from './types';
@@ -62,10 +62,14 @@ export declare function addContextQuery(url: URL, context: CommonRequestContext)
62
62
  /** 读取完整 JSON 正文;HTML 错误页或损坏 JSON 只产生统一错误,不把原始正文混进异常。 */
63
63
  export declare function readJson(response: Response): Promise<unknown>;
64
64
  /**
65
- * 尽量保留后端 msg / code 以及对象类型的诊断 data,供应用展示或识别业务失败。
65
+ * 尽量保留后端 msg / code / error_code / trace_id 以及对象类型的诊断 data,供应用展示或识别业务失败。
66
66
  * Retry-After 仅接受整数秒并作为提示返回;此处不会安排重试,也不解析 HTTP 日期格式。
67
+ * tiered 表示该接口属于 msg 分级约定(docs/前后端约定-错误文案msg分级.md):响应带 debug_msg 时
68
+ * 说明后端已打开分级、msg 可以原样展示。其它接口的 msg 仍可能是内部代号,displayable 恒为 false。
67
69
  */
68
- export declare function backendError(response: Response, payload: unknown, fallbackCode: string | number): ApiError;
70
+ export declare function backendError(response: Response, payload: unknown, fallbackCode: string | number, options?: {
71
+ tiered?: boolean;
72
+ }): ApiError;
69
73
  /**
70
74
  * AI 接口的公共 POST:注入鉴权、Channel、语言与通用 query,并校验响应包。
71
75
  * 旧 TTS 路由的 JWT 可选,其余保持原有 JWT 要求;账户归属不等于服务端身份验证。
@@ -18,8 +18,9 @@ export declare class StageError extends Error {
18
18
  });
19
19
  }
20
20
  /**
21
- * 按 01 第 5 节的顺序推断错误码:StageError → SDK / Canva 的字符串错误码转大写 → <STAGE>_FAILED → UNKNOWN。
22
- * 数字业务码不当作错误码(放 backend_code),避免后端自由文本进入分组键。
21
+ * 按 01 第 5 节的顺序推断错误码:StageError → 后端 error_code → SDK / Canva 的字符串错误码转大写
22
+ * → <STAGE>_FAILED → UNKNOWN。数字业务码不当作错误码(放 backend_code),避免后端自由文本进入分组键。
23
+ * 后端的 content_policy_violation 记为 POLICY_BLOCKED(generate_blocked,不告警),应用不用再匹配 E005。
23
24
  */
24
25
  export declare function toErrorCode(error: unknown, stage?: ReportStage): string;
25
26
  /**
@@ -133,6 +133,12 @@ export interface Prediction {
133
133
  error?: string | null;
134
134
  /** 部分后端返回的补充错误文案。 */
135
135
  error_msg?: string | null;
136
+ /** 失败任务的统一错误码(msg 分级打开后才有);有它时 error_msg / error 已是用户文案。2.7.0 起。 */
137
+ error_code?: string;
138
+ /** 改写前的 error 原文,只用于排查,不要展示。2.7.0 起。 */
139
+ raw_error?: string | null;
140
+ /** 改写前的 error_msg 原文,只用于排查,不要展示。2.7.0 起。 */
141
+ raw_error_msg?: string | null;
136
142
  /** 后端附加的平台标识。 */
137
143
  $platform?: string;
138
144
  /** 后端附加的模型标识。 */
@@ -1,6 +1,7 @@
1
1
  import { default as React } from 'react';
2
2
  import { AccountError } from './account';
3
3
  import { UseResult } from './consumption';
4
+ import { PricingUnit } from './pricing_unit';
4
5
  import { ChatApi, ContentExtractionApi, ErrorReportingApi, PredictionApi, TelemetryApi, TextModerationApi, TextToSpeechApi, UploadApi, UsageApi, UsageReportingApi, VttApi } from '../api/types';
5
6
  import { canUseError, CheckoutSessionOptions, TestMode, UserStatus } from './interface';
6
7
  /**
@@ -73,6 +74,11 @@ export interface YiChongCanvaContextType extends PredictionApi, TextModerationAp
73
74
  loginStatus: "success" | "error" | "loading" | "idle";
74
75
  /** 最近一次账户登录/刷新/支付检查失败;开始重试或成功后清除。自动上报不依赖 Footer 挂载。 */
75
76
  accountError: AccountError | null;
77
+ /**
78
+ * 2.7.0:定价语言包里的计量单位,按 productName 和界面语言(主语言,没有退 en)读取。
79
+ * 读取中或拿不到时为 null,应用退回 config.ts 的 unitConfig;改定价单位不需要前端发版。
80
+ */
81
+ pricingUnit: PricingUnit | null;
76
82
  /** 手动启动登录,参数是失败后的重试次数(默认 1,另有首次请求);通过状态而非 Promise 获取结果。 */
77
83
  manualLogin: (_retry?: number) => void;
78
84
  }
@@ -5,3 +5,5 @@ export * from './context';
5
5
  export * from './use_canva';
6
6
  export type { AccountError, AccountStage, AccountOperation } from './account';
7
7
  export type { UseResult, UseChannel, UseError, UseSkipReason, ConfirmedUsage } from './consumption';
8
+ export { loadPricingUnit, PRICING_LANGUAGE_BASE_URL } from './pricing_unit';
9
+ export type { PricingUnit } from './pricing_unit';
@@ -0,0 +1,15 @@
1
+ /**
2
+ * 定价语言包里的计量单位(2.7.0 起)。Footer / QuotaAlert 优先用它,拿不到时用应用 config.ts 的 unitConfig。
3
+ * 来源与定价页同一份文件,改了定价单位不用前端发版;locale 是实际取到的语言包(例如 zh、en)。
4
+ */
5
+ export interface PricingUnit {
6
+ unitNoun: string;
7
+ unitNounPlural: string;
8
+ locale: string;
9
+ }
10
+ export declare const PRICING_LANGUAGE_BASE_URL = "https://project.deletetweets.ai/yichong_pricing_language";
11
+ /**
12
+ * 先取界面语言的主语言(zh-TW → zh、pt-BR → pt),没有再退到 en;都拿不到返回 null。
13
+ * 404、断网、超时、格式不对都只返回 null,不抛错、不上报:部分渠道本来就没有定价语言包。
14
+ */
15
+ export declare function loadPricingUnit(channel: string, locale: string, signal?: AbortSignal): Promise<PricingUnit | null>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yichong-canva2",
3
- "version": "2.6.0",
3
+ "version": "2.7.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",