yichong-canva2 2.4.0 → 2.5.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.5.0 本地待发布**:消费不再自动重试,`use()` 返回可核对的 `UseResult`;账户与审核缓存按身份隔离。新增显式轮询 `waitForPrediction`、取消请求 `cancelPrediction`、结果地址/取消识别工具,以及 `uploadFile({ retention: "day30" })`。这轮尚未发布到 npm,验证新能力请构建后 `npm pack`,或使用脚手架 `--sdk-path`。
6
+
5
7
  **2.4.0 新增**:`client.reportUsage` 和 Provider 公共行为统计,兼容旧 GET 接口;另新增语音合成 `client.createTextToSpeech`、`client.getTextToSpeechResult`。下面的行为统计与 TTS 示例要求 `2.4.0` 或更高版本,`2.3.0` 不包含。
6
8
 
7
9
  `2.3.0` 新增 `client.createVtt` 和 `client.getVttStatus`,统一调用音视频转录接口,并沿用 Provider 身份、通用参数、超时与取消支持。
@@ -13,7 +15,7 @@
13
15
  ## 使用
14
16
 
15
17
  ```sh
16
- npm install yichong-canva2@2.3.0
18
+ npm install yichong-canva2@^2.4.0
17
19
  ```
18
20
 
19
21
  `1.2.0` 新增文本审核、三个消费接口,以及 Cloudflare R2 单次和分片上传;继续复用原有 Provider。
@@ -106,6 +108,8 @@ function GenerateButton() {
106
108
  | --- | --- | --- |
107
109
  | `client.createSpecifyPrediction({ owner, name, input })` | `POST /replicate/createSpecifyPrediction` | `{ code: 0, msg: "ok", data: "任务 ID" }` |
108
110
  | `client.getPrediction({ id })` | `POST /replicate/getPrediction` | `{ code: 0, msg: "ok", data: { id, status, output, ... } }` |
111
+ | `client.waitForPrediction({ id }, options?)`(2.5.0) | 显式、有界地重复 getPrediction | `Prediction`,无 data 包装 |
112
+ | `client.cancelPrediction({ id }, options?)`(2.5.0) | `POST /replicate/cancelPrediction` | 后端原样 `Prediction` 或 `ApiResponse<Prediction>` |
109
113
  | `client.textCheck({ text, scene? })` | `POST /api/public/text-moderation/check` | `{ code: 0, msg: "展示文案", data: { allowed, decision, categories, ... } }` |
110
114
  | `client.contentExtract({ type, url })` | `POST {contentBaseUrl}/api/content-extract` | `{ code: 0, msg, data: { content: "提取的原文", ... } }` |
111
115
  | `client.chat({ payload, model?, img_url?, image_url?, image_urls? })` | `POST {chatBaseUrl}/api/chat` | `{ code: 0, msg, data: { result: "模型输出", ... } }` |
@@ -132,6 +136,39 @@ Provider 自动注入自有后端请求 query 中的 `uid`、`platform_uid`、`p
132
136
 
133
137
  创建接口保留普通的 `owner/name/input` 合同,也支持后端现有的 `video_type`、`video_catalog`、`catalog_model_id`、`primary_provider`、`execution_chain`、`provider_requests` 参数;这些视频路由字段按原名和 JSON 结构传递。当 `video_catalog: "schema_v2"` 且 `provider_requests` 非空时,可省略顶层 `input`,由各供应商请求携带输入;普通任务仍须传 `input` 对象。SDK 不改写 prompt、选择供应商或调整执行链。创建、查询和文本审核只发送一次请求,不自动轮询、重试、额外扣费或插入 Canva 设计。消费由应用显式调用具名方法。原有登录、额度和结账会话方法继续由同一个 hook 提供。
134
138
 
139
+ ## 任务轮询、输出与取消(2.5.0 待发布)
140
+
141
+ `getPrediction` 仍只查询一次;业务需要统一轮询时显式调用以下方法,不增加另一层改名的 API 包装:
142
+
143
+ ```ts
144
+ import { getPredictionOutputUrl, isAbortError } from "yichong-canva2";
145
+
146
+ const controller = new AbortController();
147
+ const { data: id } = await client.createSpecifyPrediction(
148
+ { owner: "your-owner", name: "your-model", input: { prompt } },
149
+ { signal: controller.signal },
150
+ );
151
+ try {
152
+ const task = await client.waitForPrediction(
153
+ { id },
154
+ { intervalMs: 3_000, maxPolls: 60, timeoutMs: 180_000, signal: controller.signal },
155
+ );
156
+ const url = getPredictionOutputUrl(task.output);
157
+ if (!url) throw new Error("任务已完成,但没有图片地址");
158
+ // 校验和使用业务结果;消费、插入 Canva 由业务显式触发。
159
+ } catch (error) {
160
+ if (!isAbortError(error)) throw error;
161
+ }
162
+ ```
163
+
164
+ 默认每 3 秒查询一次,最多 60 次,所有请求与间隔共用 180 秒预算。只有 `succeeded` 默认成功;`failed/canceled/aborted` 终态优先,即使附带 URL 也失败。旧 QR 背景这类明确允许先使用输出的场景可传 `allowEarlyOutput: true`。网络错误或单次请求超时最多连续容忍 3 次,每次计入次数;鉴权、HTTP、业务和协议错误直接结束。次数/总预算耗尽抛 `prediction_timeout`,失败终态抛 `prediction_failed`,主动中止抛 `aborted`。
165
+
166
+ `getPredictionOutputUrl` 从字符串、数组和 `{ url }` 递归提取第一个 HTTP(S) 地址,无则返回 `""`;它不判断任务完成。`isAbortError` 只识别名为 `AbortError` 的错误或 SDK 的 `aborted`,不把其它 DOMException 误判为取消。
167
+
168
+ 服务端取消需独立调用 `await client.cancelPrediction({ id })`,不要传已经 abort 的 signal。失败正常抛 `ApiError`;不同供应商不一定支持真正终止执行,成功响应也不保证停止上游计费。本地中止 `waitForPrediction` 不会自动发送取消请求。
169
+
170
+ 社区模型兼容由后端 `external_api` 提交 `0d29626f` 提供,需部署后生效;SDK 仍使用 `createSpecifyPrediction({ owner, name, input })`。按 owner/name 使用最新模型版本,作者更新可能改变效果。参见仓库 `docs/replicate-社区模型不能走createSpecifyPrediction.md`。
171
+
135
172
  ## 消费接口
136
173
 
137
174
  三个具名方法复用 Provider 登录流程已获得的 passport,只提交指定的数量,原样返回账户服务的 `{ ok: 0, msg, ... }`。后端拒绝、非法响应、HTTP 失败、超时或取消会抛出 `ApiError`;`error.code` 保留后端的失败 `ok` 值。
@@ -177,8 +214,30 @@ function ConfirmUsageButton() {
177
214
 
178
215
  默认消费超时为 30 秒,无自动重试。请求已发出后,超时、网络错误或取消不能证明服务端没有扣费;不要因此直接重放消费。后端未提供此接口的任务去重键,重复调用会再次记账。原有 `use()` 保留兼容,同一次消费不要同时调用 `use()` 和具名方法。
179
216
 
217
+ ### 原有 use 的结果(2.5.0 待发布)
218
+
219
+ `const result = await client.use(1)` 返回 `Promise<UseResult>`,始终 resolve;已有不 await 的调用仍可用。根据最新账户状态分配月额度与积分,单个 Provider 内的调用串行处理;切换账户后,旧调用不会更新新账户。保留本地乐观余额更新,因此不能仅看余额判断服务端记账成功。
220
+
221
+ | result.status | 含义 |
222
+ | --- | --- |
223
+ | `charged` | 本次需要上传的消费已确认成功,`charged: true` |
224
+ | `skipped` | `test_mode`、`in_review_test`、`free_unlimited`、`not_upload` 或 `account_changed` |
225
+ | `failed` | 参数、账户未就绪或服务端明确拒绝,`charged: false` |
226
+ | `unknown` | 网络、超时等造成记账结果未知,`charged: null`;不可直接重复消费 |
227
+ | `partial` | 混合消费一部分成功,其余失败、未知或跳过;`charged: true` 只表示部分确认 |
228
+
229
+ `confirmed.monthly` / `confirmed.freeCnt` 给出已确认数量。`force`、`notUpload`、测试模式保留原分支语义。未知或部分成功时先保留生成结果,再核对账户;不要通过再次 `use()` 自动补扣。
230
+
231
+ 2.4.0 的免费消费网络错误可能无限重试;2.5.0 完全取消自动重试。每个消费请求检查 HTTP 和业务 `ok === 0`,各有 30 秒时限;混合消费最多顺序执行两次,月额度失败不继续扣积分。积分请求复用既有消费 API 的 JSON `{ cnt }` 与 `X-Access-Channel`,替代旧 use 的 query cnt。编排层对失败自动上报一次,不等待报告、不让告警失败影响业务。旧 `use()` 的月额度仍使用历史公共账户入口,显式 `addMonthlyUsage` 仍使用产品 `baseUrl`。
232
+
233
+ 版本键使用 `yichong_version_{appId}`;测试信息和测试余额按应用、产品、用户隔离,不再读取没有归属的旧全局键。版本查询失败和切换应用的迟到请求不会污染新账户。
234
+
180
235
  ## Cloudflare R2 文件上传
181
236
 
237
+ 2.5.0 新增 `retention?: "temp" | "day30"`:默认 `temp`,`client.uploadFile({ file, retention: "day30" })` 使用 `day30_` 前缀,其余命名、32 位随机 ID、单次/分片上传流程不变。`retention` 和 `objectName` 互斥,同时传入报参数错误。该参数只决定对象名,不改变后端协议或资源域名。
238
+
239
+ 2026-10-16 的 R2 截图记录中,`temp_` 1 天后删除对象并中止未完成上传,`day30_` 30 天后删除对象(未列出中止上传规则)。真正清理由对应桶的生命周期配置决定,SDK 不保证配置永不变;完整前缀表保存在仓库 `docs/工具包与脚手架-修复优化清单.md` 第 7 节。
240
+
182
241
  `2.1.0` 增加分片公开地址兼容处理和 `onUploadProgress`,继续复用 `ai.imgkits.com` 的现有接口,无需新增或部署后端。这里只接入 Cloudflare R2;`aliyun-fc` 是签名服务的托管平台,与文件存储不同,本次不接入阿里云 OSS,也不改变现有托管平台。
183
242
 
184
243
  `uploadFile({ file })` 自动完成上传:小于 100 MiB 使用单次 PUT,达到 100 MiB 使用分片。调用方式和返回值相同;也可传 `multipart: true` 让小文件使用分片,省略或 false 时按大小自动选择。它支持非空的 File / Blob,默认生成 `temp_{app_channel}_{YYYY-MM-DD}_{32位随机}.{后缀}` 对象名:`app_channel` 对应 Provider 的 `productName`,日期使用浏览器本地日期,随机部分沿用旧应用的 `randomString(32)`:使用 `Math.random()` 从固定字符集 `ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678` 中逐位取值。bucket 默认 `video`。显式传入 `objectName` 时使用指定对象名,不套用默认命名格式;可传 `bucketName` 指定 bucket,Blob 可通过 `fileName` 指定扩展名;未提供文件后缀时沿用旧模板的 MIME subtype 回退(例如 `audio/wav` → `wav`、`video/webm` → `webm`),均缺失才使用 `bin`。
package/dist/api/error.js CHANGED
@@ -15,6 +15,10 @@ class ApiError extends Error {
15
15
  this.retryAfter = details == null ? void 0 : details.retryAfter;
16
16
  }
17
17
  }
18
+ function isAbortError(error) {
19
+ return error instanceof ApiError ? error.code === "aborted" : error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
20
+ }
18
21
  export {
19
- ApiError
22
+ ApiError,
23
+ isAbortError
20
24
  };
@@ -1,7 +1,62 @@
1
1
  import { ApiError } from "./error.js";
2
- import { isObject, isNonemptyString, invalid, postApi, validateJson } from "./request.js";
2
+ import { invalid, isNonemptyString, postApi, isObject, validateJson } from "./request.js";
3
+ import { withRequest, throwIfAborted } from "./transport.js";
4
+ function getPredictionOutputUrl(output) {
5
+ const seen = /* @__PURE__ */ new Set();
6
+ const visit = (value) => {
7
+ if (typeof value === "string") {
8
+ if (!/^https?:\/\//i.test(value)) return "";
9
+ try {
10
+ const url = new URL(value);
11
+ return (url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password ? value : "";
12
+ } catch {
13
+ return "";
14
+ }
15
+ }
16
+ if (value === null || typeof value !== "object" || seen.has(value)) return "";
17
+ seen.add(value);
18
+ if (Array.isArray(value)) {
19
+ for (const item of value) {
20
+ const url = visit(item);
21
+ if (url) return url;
22
+ }
23
+ return "";
24
+ }
25
+ return "url" in value ? visit(value.url) : "";
26
+ };
27
+ return visit(output);
28
+ }
29
+ function validateId(params) {
30
+ if (!isObject(params) || !isNonemptyString(params.id) || Object.keys(params).some((key) => key !== "id")) {
31
+ invalid("A prediction id string is required.");
32
+ }
33
+ }
34
+ function validatePrediction(value) {
35
+ if (!isObject(value) || !isNonemptyString(value.id) || !isNonemptyString(value.status)) {
36
+ throw new ApiError("Query response did not contain prediction information.", "invalid_response");
37
+ }
38
+ }
39
+ function delay(milliseconds, signal) {
40
+ throwIfAborted(signal);
41
+ return new Promise((resolve, reject) => {
42
+ const cancel = () => {
43
+ clearTimeout(timer);
44
+ signal.removeEventListener("abort", cancel);
45
+ reject(new ApiError("Request canceled.", "aborted"));
46
+ };
47
+ const timer = setTimeout(() => {
48
+ signal.removeEventListener("abort", cancel);
49
+ resolve();
50
+ }, milliseconds);
51
+ signal.addEventListener("abort", cancel, { once: true });
52
+ if (signal.aborted) cancel();
53
+ });
54
+ }
55
+ function predictionTimeout() {
56
+ return new ApiError("Generation timed out. Please try again.", "prediction_timeout");
57
+ }
3
58
  function createPredictionApi(getContext) {
4
- return {
59
+ const api = {
5
60
  async createSpecifyPrediction(params, options) {
6
61
  var _a;
7
62
  if (!isObject(params) || !isNonemptyString(params.owner) || !isNonemptyString(params.name)) {
@@ -34,17 +89,59 @@ function createPredictionApi(getContext) {
34
89
  return response;
35
90
  },
36
91
  async getPrediction(params, options) {
37
- if (!isObject(params) || !isNonemptyString(params.id) || Object.keys(params).some((key) => key !== "id")) {
38
- invalid("getPrediction requires an id string.");
39
- }
92
+ validateId(params);
40
93
  const response = await postApi(getContext(), "getPrediction", { id: params.id }, options);
41
- if (!isObject(response.data) || !isNonemptyString(response.data.id) || !isNonemptyString(response.data.status)) {
42
- throw new ApiError("Query response did not contain prediction information.", "invalid_response");
43
- }
94
+ validatePrediction(response.data);
95
+ return response;
96
+ },
97
+ async cancelPrediction(params, options) {
98
+ validateId(params);
99
+ const response = await postApi(getContext(), "cancelPrediction", { id: params.id }, options);
100
+ validatePrediction(response.code !== void 0 ? response.data : response);
44
101
  return response;
102
+ },
103
+ async waitForPrediction(params, options = {}) {
104
+ validateId(params);
105
+ const { intervalMs = 3e3, maxPolls = 60, allowEarlyOutput = false } = options;
106
+ if (!Number.isInteger(intervalMs) || intervalMs < 0 || intervalMs > 2147483647 || !Number.isSafeInteger(maxPolls) || maxPolls < 1 || typeof allowEarlyOutput !== "boolean") {
107
+ invalid("waitForPrediction requires a nonnegative intervalMs, a positive maxPolls and a boolean allowEarlyOutput.");
108
+ }
109
+ let budgetSignal;
110
+ try {
111
+ return await withRequest({ ...options, timeoutMs: options.timeoutMs ?? 18e4 }, async (signal) => {
112
+ budgetSignal = signal;
113
+ let consecutiveErrors = 0;
114
+ for (let attempt = 0; attempt < maxPolls; attempt++) {
115
+ throwIfAborted(signal);
116
+ let task;
117
+ try {
118
+ task = (await api.getPrediction(params, { signal })).data;
119
+ throwIfAborted(signal);
120
+ consecutiveErrors = 0;
121
+ } catch (error) {
122
+ throwIfAborted(signal);
123
+ if (!(error instanceof ApiError) || !["network_error", "timeout"].includes(String(error.code)) || error.status !== void 0 || ++consecutiveErrors >= 3) throw error;
124
+ }
125
+ if (task) {
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 } });
129
+ }
130
+ if (task.status === "succeeded" || allowEarlyOutput && getPredictionOutputUrl(task.output)) return task;
131
+ }
132
+ if (attempt < maxPolls - 1) await delay(intervalMs, signal);
133
+ }
134
+ throw predictionTimeout();
135
+ });
136
+ } catch (error) {
137
+ if (error instanceof ApiError && error.code === "timeout" && (budgetSignal == null ? void 0 : budgetSignal.aborted)) throw predictionTimeout();
138
+ throw error;
139
+ }
45
140
  }
46
141
  };
142
+ return api;
47
143
  }
48
144
  export {
49
- createPredictionApi
145
+ createPredictionApi,
146
+ getPredictionOutputUrl
50
147
  };
@@ -20,7 +20,7 @@ function createErrorReportingApi(getContext) {
20
20
  platform: "canva_addon",
21
21
  app_id: context.appId,
22
22
  app_version: String(context.version),
23
- sdk_version: "2.4.0",
23
+ sdk_version: "2.5.0",
24
24
  user_id: ((_c = context.userStatus.profile) == null ? void 0 : _c.id) ?? "unknown",
25
25
  platform_uid: context.userStatus.userId ?? "unknown",
26
26
  ...reportingPayload(params, secrets)
@@ -3,6 +3,7 @@ import { withRequest } from "./transport.js";
3
3
  const apiPaths = {
4
4
  createSpecifyPrediction: "/replicate/createSpecifyPrediction",
5
5
  getPrediction: "/replicate/getPrediction",
6
+ cancelPrediction: "/replicate/cancelPrediction",
6
7
  textCheck: "/api/public/text-moderation/check",
7
8
  contentExtract: "/api/content-extract",
8
9
  chat: "/api/chat",
@@ -114,6 +115,9 @@ async function postApi(context, method, params, options = {}) {
114
115
  });
115
116
  const payload = await readJson(response);
116
117
  if (!response.ok) throw backendError(response, payload, "http_error");
118
+ if (method === "cancelPrediction" && isObject(payload) && payload.code === void 0) {
119
+ return payload;
120
+ }
117
121
  if (!isObject(payload) || typeof payload.code !== "number" && typeof payload.code !== "string") {
118
122
  throw new ApiError("Backend returned an invalid response envelope.", "invalid_response", response.status);
119
123
  }
@@ -221,11 +221,11 @@ function getFileType(file, fileName) {
221
221
  const slashIndex = file.type.lastIndexOf("/");
222
222
  return slashIndex !== -1 ? file.type.slice(slashIndex + 1).toLowerCase() : "";
223
223
  }
224
- function fileObjectName(file, fileName, productName) {
224
+ function fileObjectName(file, fileName, productName, retention = "temp") {
225
225
  const extension = getFileType(file, fileName) || "bin";
226
226
  const now = /* @__PURE__ */ new Date();
227
227
  const day = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
228
- return objectName(`temp_${productName}_${day}_${randomString(32)}.${extension}`);
228
+ return objectName(`${retention}_${productName}_${day}_${randomString(32)}.${extension}`);
229
229
  }
230
230
  function createUploadApi(getContext) {
231
231
  return {
@@ -235,14 +235,14 @@ function createUploadApi(getContext) {
235
235
  completeUpload: (params, options = {}) => withRequest(options, (signal) => complete(getContext(), params, signal)),
236
236
  async uploadFile(params, options = {}) {
237
237
  var _a;
238
- if (!isObject(params) || !(params.file instanceof Blob) || !Number.isSafeInteger(params.file.size) || params.file.size <= 0 || params.file.size > maxFileSize || params.fileName !== void 0 && !isNonemptyString(params.fileName) || params.multipart !== void 0 && typeof params.multipart !== "boolean" || params.onUploadProgress !== void 0 && typeof params.onUploadProgress !== "function" || Object.keys(params).some((key2) => !["file", "fileName", "bucketName", "objectName", "multipart", "onUploadProgress"].includes(key2))) {
238
+ if (!isObject(params) || !(params.file instanceof Blob) || !Number.isSafeInteger(params.file.size) || params.file.size <= 0 || params.file.size > maxFileSize || params.fileName !== void 0 && !isNonemptyString(params.fileName) || params.multipart !== void 0 && typeof params.multipart !== "boolean" || params.retention !== void 0 && params.retention !== "temp" && params.retention !== "day30" || params.retention !== void 0 && params.objectName !== void 0 || params.onUploadProgress !== void 0 && typeof params.onUploadProgress !== "function" || Object.keys(params).some((key2) => !["file", "fileName", "bucketName", "objectName", "retention", "multipart", "onUploadProgress"].includes(key2))) {
239
239
  invalid("uploadFile requires a nonempty file within the R2 object size limit and valid upload parameters.");
240
240
  }
241
241
  const file = params.file;
242
242
  const onUploadProgress = params.onUploadProgress;
243
243
  const multipart = params.multipart === true || file.size >= multipartThreshold;
244
244
  const context = getContext();
245
- const key = params.objectName === void 0 ? fileObjectName(file, params.fileName, context.productName) : objectName(params.objectName);
245
+ const key = params.objectName === void 0 ? fileObjectName(file, params.fileName, context.productName, params.retention) : objectName(params.objectName);
246
246
  const bucket = bucketName(params.bucketName);
247
247
  const owner = JSON.stringify([(_a = context.userStatus.profile) == null ? void 0 : _a.id, context.userStatus.userId, context.productName]);
248
248
  const check = (signal) => {
package/dist/index.js CHANGED
@@ -1,10 +1,13 @@
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 } from "./api/error.js";
4
+ import { ApiError, isAbortError } from "./api/error.js";
5
+ import { getPredictionOutputUrl } from "./api/predictions.js";
5
6
  export {
6
7
  ApiError,
7
8
  YiChongCanvaContext,
8
9
  YiChongCanvaProvider,
10
+ getPredictionOutputUrl,
11
+ isAbortError,
9
12
  useYiChongCanva
10
13
  };
@@ -0,0 +1,38 @@
1
+ const versionCacheKey = (appId) => `yichong_version_${appId}`;
2
+ function testCacheKey(kind, appId, productName, userId, uid) {
3
+ return `yichong_${kind}_${encodeURIComponent(JSON.stringify([appId, productName, userId ?? "", uid ?? ""]))}`;
4
+ }
5
+ const passportCacheKey = (userId) => `${userId}_passport`;
6
+ const memory = /* @__PURE__ */ new Map();
7
+ function readCache(key) {
8
+ try {
9
+ const value = localStorage.getItem(key);
10
+ if (value === null) memory.delete(key);
11
+ else memory.set(key, value);
12
+ return value;
13
+ } catch {
14
+ return memory.get(key) ?? null;
15
+ }
16
+ }
17
+ function writeCache(key, value) {
18
+ memory.set(key, value);
19
+ try {
20
+ localStorage.setItem(key, value);
21
+ } catch {
22
+ }
23
+ }
24
+ function removeCache(key) {
25
+ memory.delete(key);
26
+ try {
27
+ localStorage.removeItem(key);
28
+ } catch {
29
+ }
30
+ }
31
+ export {
32
+ passportCacheKey,
33
+ readCache,
34
+ removeCache,
35
+ testCacheKey,
36
+ versionCacheKey,
37
+ writeCache
38
+ };
@@ -0,0 +1,94 @@
1
+ import { ApiError } from "../api/error.js";
2
+ const skippedUsage = (reason) => ({
3
+ status: "skipped",
4
+ charged: false,
5
+ reason,
6
+ confirmed: { monthly: 0, freeCnt: 0 }
7
+ });
8
+ function usageFailure(error) {
9
+ const code = error instanceof ApiError ? error.code : "network_error";
10
+ const knownCodes = ["network_error", "timeout", "aborted", "invalid_response", "invalid_request", "account_not_ready", "http_error"];
11
+ return {
12
+ // 后端可能把自由文本放进 code;仅保留数字业务码和 SDK 定义的字符串码。
13
+ code: typeof code === "number" || knownCodes.includes(code) ? code : "backend_rejected",
14
+ message: "Usage recording could not be confirmed.",
15
+ ...error instanceof ApiError && error.status !== void 0 ? { status: error.status } : {}
16
+ };
17
+ }
18
+ function invalidUsageResult() {
19
+ return {
20
+ status: "failed",
21
+ charged: false,
22
+ reason: "invalid_count",
23
+ confirmed: { monthly: 0, freeCnt: 0 },
24
+ error: { code: "invalid_request", message: "cnt must be a positive number within the safe numeric range." }
25
+ };
26
+ }
27
+ function isValidUsageCount(cnt) {
28
+ return typeof cnt === "number" && Number.isFinite(cnt) && cnt > 0 && cnt <= Number.MAX_SAFE_INTEGER / 100;
29
+ }
30
+ async function recordUsage(options) {
31
+ const { monthly, freeCnt, notUpload, api, isCurrent, report } = options;
32
+ const confirmed = { monthly: 0, freeCnt: 0 };
33
+ const channel = monthly > 0 ? freeCnt > 0 ? "monthly_and_free_cnt" : "monthly" : "free_cnt";
34
+ let stage = "use_monthly";
35
+ const skip = (reason) => confirmed.monthly > 0 ? { status: "partial", charged: true, channel: "monthly_and_free_cnt", confirmed, remaining: "skipped", reason } : skippedUsage(reason);
36
+ try {
37
+ if (!isCurrent()) return skip("account_changed");
38
+ if (monthly > 0) {
39
+ await api.addMonthlyUsage({ cnt: monthly });
40
+ confirmed.monthly = monthly;
41
+ }
42
+ if (freeCnt > 0) {
43
+ if (!isCurrent()) return skip("account_changed");
44
+ if (notUpload) return skip("not_upload");
45
+ stage = "reduce_free_cnt";
46
+ await api.reduceFreeCnt({ cnt: freeCnt });
47
+ confirmed.freeCnt = freeCnt;
48
+ }
49
+ return { status: "charged", charged: true, channel, confirmed };
50
+ } catch (error) {
51
+ const failure = usageFailure(error);
52
+ const unknown = ["timeout", "network_error", "aborted", "invalid_response"].includes(String(failure.code)) || failure.status !== void 0 && failure.status >= 500;
53
+ try {
54
+ void Promise.resolve(report({
55
+ error: failure.message,
56
+ source: "api",
57
+ stage,
58
+ context: {
59
+ code: failure.code,
60
+ http_status: failure.status ?? 0,
61
+ monthly_confirmed: confirmed.monthly,
62
+ free_cnt_confirmed: confirmed.freeCnt,
63
+ outcome: unknown ? "unknown" : "failed"
64
+ }
65
+ })).catch(() => {
66
+ });
67
+ } catch {
68
+ }
69
+ if (confirmed.monthly > 0 || confirmed.freeCnt > 0) {
70
+ return {
71
+ status: "partial",
72
+ charged: true,
73
+ channel: "monthly_and_free_cnt",
74
+ confirmed,
75
+ remaining: unknown ? "unknown" : "failed",
76
+ error: failure
77
+ };
78
+ }
79
+ return unknown ? { status: "unknown", charged: null, channel, confirmed, error: failure } : {
80
+ status: "failed",
81
+ charged: false,
82
+ confirmed,
83
+ reason: failure.code === "account_not_ready" ? "account_not_ready" : "request_failed",
84
+ error: failure
85
+ };
86
+ }
87
+ }
88
+ export {
89
+ invalidUsageResult,
90
+ isValidUsageCount,
91
+ recordUsage,
92
+ skippedUsage,
93
+ usageFailure
94
+ };
@@ -11,8 +11,13 @@ const YiChongCanvaContext = React.createContext(
11
11
  getLimitUsage: () => null,
12
12
  getMonthlyUsageLimit: () => null,
13
13
  isSubscribed: false,
14
- use: () => {
15
- },
14
+ use: async () => ({
15
+ status: "failed",
16
+ charged: false,
17
+ reason: "account_not_ready",
18
+ confirmed: { monthly: 0, freeCnt: 0 },
19
+ error: { code: "provider_missing", message: "Wrap your components in YiChongCanvaProvider first." }
20
+ }),
16
21
  canUse: () => false,
17
22
  canUseLimit: () => ({ canUse: false }),
18
23
  isFreeUnlimited: () => false,
@@ -37,6 +42,12 @@ const YiChongCanvaContext = React.createContext(
37
42
  getPrediction: async () => {
38
43
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
39
44
  },
45
+ cancelPrediction: async () => {
46
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
47
+ },
48
+ waitForPrediction: async () => {
49
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
50
+ },
40
51
  textCheck: async () => {
41
52
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
42
53
  },
@@ -1,6 +1,7 @@
1
1
  import { accountRequest } from "./request.js";
2
2
  import { isObject } from "../../../api/request.js";
3
3
  import { throwIfAborted } from "../../../api/transport.js";
4
+ import { readCache, passportCacheKey, writeCache } from "../../cache.js";
4
5
  const headers = {
5
6
  "Content-Type": "application/json"
6
7
  };
@@ -32,7 +33,7 @@ function handleUserLoginByCanvaId(userId, productName, context, options = {}) {
32
33
  }
33
34
  function getPassport(userId, productName, context, options = {}) {
34
35
  if (options.signal) throwIfAborted(options.signal);
35
- const passport = localStorage.getItem(userId + "_passport");
36
+ const passport = readCache(passportCacheKey(userId));
36
37
  if (passport) {
37
38
  return Promise.resolve({
38
39
  data: {
@@ -54,7 +55,7 @@ function getPassport(userId, productName, context, options = {}) {
54
55
  redirect: "follow"
55
56
  }, context, "canva_passport", options, (body) => isObject(body.data) && typeof body.data.passport === "string" && !!body.data.passport).then((res) => {
56
57
  if (options.signal) throwIfAborted(options.signal);
57
- localStorage.setItem(userId + "_passport", res.data.passport);
58
+ writeCache(passportCacheKey(userId), res.data.passport);
58
59
  return res;
59
60
  });
60
61
  }
@@ -27,18 +27,6 @@ function accountRequest(option, context, stage, options = {}, validate) {
27
27
  return body;
28
28
  }, api);
29
29
  }
30
- function requestUrl(option, context) {
31
- const { url, ...init } = option;
32
- const target = new URL(url);
33
- if (context) {
34
- addContextQuery(target, context);
35
- const headers = new Headers(init.headers);
36
- headers.set("Accept-Language", language(context.getLocale));
37
- init.headers = headers;
38
- }
39
- return fetch(target.toString(), init).then((response) => response.json());
40
- }
41
30
  export {
42
- accountRequest,
43
- requestUrl as default
31
+ accountRequest
44
32
  };
@@ -4,6 +4,7 @@ import { isObject } from "../../api/request.js";
4
4
  import { ApiError } from "../../api/error.js";
5
5
  import { withRequest, throwIfAborted } from "../../api/transport.js";
6
6
  import { AccountRequestError, retryableAccountError, accountDelay, accountStep } from "../account.js";
7
+ import { removeCache, passportCacheKey } from "../cache.js";
7
8
  function accountContext(productName, userId, getContext) {
8
9
  const context = getContext == null ? void 0 : getContext();
9
10
  const current = context == null ? void 0 : context.userStatus;
@@ -139,7 +140,7 @@ async function getUserProfile({
139
140
  throwIfAborted(requestSignal);
140
141
  if (!userStatus.profile && !renewedPassport) {
141
142
  renewedPassport = true;
142
- localStorage.removeItem(userId + "_passport");
143
+ removeCache(passportCacheKey(userId));
143
144
  passport = (await apis.getPassport(userId, productName, requestContext(), options)).data.passport;
144
145
  userStatus = (await apis.getUserStatusByPassport(passport, productName, requestContext(), options)).data;
145
146
  throwIfAborted(requestSignal);