yichong-canva2 1.1.28 → 1.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
@@ -1,9 +1,15 @@
1
1
  # yichong-canva2
2
2
 
3
- 使用一个 `YiChongCanvaProvider` 管理登录、订阅和额度,通过 `useYiChongCanva()` 调用后端同名接口。
3
+ 使用一个 `YiChongCanvaProvider` 管理登录、订阅和额度,通过 `useYiChongCanva()` 直接调用后端接口。
4
4
 
5
5
  ## 使用
6
6
 
7
+ ```sh
8
+ npm install yichong-canva2@1.2.0
9
+ ```
10
+
11
+ `1.2.0` 新增文本审核、三个消费接口,以及 Cloudflare R2 单次和分片上传;继续复用原有 Provider。
12
+
7
13
  ```tsx
8
14
  import { useState } from "react";
9
15
  import { YiChongCanvaProvider, useYiChongCanva } from "yichong-canva2";
@@ -26,15 +32,21 @@ function GenerateButton() {
26
32
  const [error, setError] = useState("");
27
33
  const [status, setStatus] = useState("");
28
34
  const [busy, setBusy] = useState(false);
35
+ const [prompt, setPrompt] = useState("a cat");
29
36
 
30
37
  async function generate() {
31
38
  setError("");
32
39
  setBusy(true);
33
40
  try {
41
+ const moderation = await client.textCheck({ text: prompt });
42
+ if (moderation.data.allowed !== true) {
43
+ setError(moderation.msg);
44
+ return;
45
+ }
34
46
  const created = await client.createSpecifyPrediction({
35
47
  owner: "openai",
36
48
  name: "gpt-image-2",
37
- input: { prompt: "a cat" },
49
+ input: { prompt },
38
50
  });
39
51
  const prediction = await client.getPrediction({ id: created.data });
40
52
  setStatus(prediction.data.status);
@@ -50,6 +62,7 @@ function GenerateButton() {
50
62
  }
51
63
 
52
64
  return <>
65
+ <textarea value={prompt} disabled={busy} onChange={event => setPrompt(event.target.value)} />
53
66
  <button disabled={client.loginStatus !== "success" || busy} onClick={() => void generate()}>Generate</button>
54
67
  {status && <p>{status}</p>}
55
68
  {error && <p role="alert">{error}</p>}
@@ -59,6 +72,8 @@ function GenerateButton() {
59
72
 
60
73
  `baseUrl` 沿用原有账户扣费接口的地址。AI 请求默认使用 `https://api.imgkits.com`,可以通过可选的 `apiBaseUrl` 指定测试地址。
61
74
 
75
+ 文件签名服务默认使用 `https://ai.imgkits.com`,可通过 Provider 的 `uploadBaseUrl` 指定测试服务;上传后的公开域名由签名响应的 `endpointBaseUrl` 决定。
76
+
62
77
  语言默认在每次请求时读取 `document.documentElement.lang` 或浏览器语言;应用有自己的国际化状态时,在 Provider 上传 `getLocale={() => currentLocale}`。
63
78
 
64
79
  ## 后端接口
@@ -67,13 +82,161 @@ function GenerateButton() {
67
82
  | --- | --- | --- |
68
83
  | `client.createSpecifyPrediction({ owner, name, input })` | `POST /replicate/createSpecifyPrediction` | `{ code: 0, msg: "ok", data: "任务 ID" }` |
69
84
  | `client.getPrediction({ id })` | `POST /replicate/getPrediction` | `{ code: 0, msg: "ok", data: { id, status, output, ... } }` |
85
+ | `client.textCheck({ text, scene? })` | `POST /api/public/text-moderation/check` | `{ code: 0, msg: "展示文案", data: { allowed, decision, categories, ... } }` |
86
+ | `client.reduceFreeCnt({ cnt })` | `POST {baseUrl}/api/user/reduce-free-cnt` | `{ ok: 0, msg: "success" }` |
87
+ | `client.addMonthlyUsage({ cnt })` | `POST {baseUrl}/api/user/add-monthly-usage` | `{ ok: 0, msg: "success" }` |
88
+ | `client.addFreeUsageCnt({ cnt })` | `POST {baseUrl}/api/user/add-free-usage-cnt` | `{ ok: 0, msg: "success" }` |
89
+ | `client.generatePresignedUrl({ objectName, bucketName? })` | `POST {uploadBaseUrl}/api/generate-presigned-url` | `{ success: true, url, endpointBaseUrl?, ... }` |
90
+ | `client.initiateUpload({ objectName, bucketName?, contentType? })` | `POST {uploadBaseUrl}/upload/initiate-upload` | `{ UploadId, Bucket?, Key?, ... }` |
91
+ | `client.getUploadUrl({ objectName, uploadId, partNumber, bucketName? })` | `POST {uploadBaseUrl}/upload/get-upload-url` | `{ url, ... }` |
92
+ | `client.completeUpload({ objectName, uploadId, parts, bucketName? })` | `POST {uploadBaseUrl}/upload/complete-upload` | `{ ETag, Bucket?, Key?, Location?, ... }` |
93
+ | `client.uploadFile({ file, ... })` | 自动单次 PUT 或初始化 → 分片签名 / PUT → 合并 | `{ url: "公开资源地址", key, endpointBaseUrl }` |
94
+
95
+ Provider 自动注入自有后端请求 query 中的 `uid`、`platform_uid`、`platform=canva_addon`、`app_channel`,以及 `Accept-Language`。AI 接口还携带 `Authorization: Bearer <jwt>`、`Channel: ai`;消费接口使用 `X-Access-Ticket`、`X-Access-Channel`;签名接口使用 `Channel: node-nauth`。R2 PUT 原样使用签名 URL,只携带文件的 `Content-Type`。创建请求中的 `user_id` 使用系统用户 ID(`userStatus.profile.id`)。公共审核只要求有效的业务 JWT;`uid` 和 `platform_uid` 在账户状态包含这些值时才附带,审核身份由后端验签确定。调用方无需维护这些字段。
96
+
97
+ 当前创建接口支持普通的 `owner/name/input` 合同;视频 `schema_v2` 等高级参数后续接入。模型参数按 JSON 原样发送,不改写 prompt 或供应商。创建、查询和文本审核只发送一次请求,不自动轮询、重试、额外扣费或插入 Canva 设计。消费由应用显式调用具名方法。原有登录、额度和结账会话方法继续由同一个 hook 提供。
98
+
99
+ ## 消费接口
100
+
101
+ 三个具名方法复用 Provider 登录流程已获得的 passport,只提交指定的数量,原样返回账户服务的 `{ ok: 0, msg, ... }`。后端拒绝、非法响应、HTTP 失败、超时或取消会抛出 `ApiError`;`error.code` 保留后端的失败 `ok` 值。
102
+
103
+ | 方法 | 用途 | cnt 精度 |
104
+ | --- | --- | --- |
105
+ | `reduceFreeCnt` | 扣减免费次数 / 积分余额 `free_cnt` | 最多两位小数 |
106
+ | `addMonthlyUsage` | 累计订阅月用量 `monthly_usage_cnt` | 最多两位小数 |
107
+ | `addFreeUsageCnt` | 累计服务端计量模式的 `free_usage_cnt` | 最多一位小数 |
108
+
109
+ `cnt` 必须是有限的正数,并满足后端精度。应用按自己的计价规则、账户类型和剩余额度选择接口;方法不会自动选择套餐或拆分月额度与积分。下面是已确认本次消费应扣 `free_cnt` 时的组件示例:
110
+
111
+ ```tsx
112
+ function ConfirmUsageButton() {
113
+ const client = useYiChongCanva();
114
+ const [busy, setBusy] = useState(false);
115
+ const [error, setError] = useState("");
116
+
117
+ async function confirmUsage() {
118
+ if (busy) return;
119
+ setBusy(true);
120
+ setError("");
121
+ try {
122
+ await client.reduceFreeCnt({ cnt: 1 });
123
+ await client.refreshUserStatus();
124
+ } catch (error) {
125
+ setError(error instanceof Error ? error.message : "消费未确认");
126
+ } finally {
127
+ setBusy(false);
128
+ }
129
+ }
70
130
 
71
- Provider 自动注入 query 中的 `uid`、`platform_uid`、`platform=canva_addon`、`app_channel`,以及请求头 `Authorization: Bearer <jwt>`、`Channel: ai`、`Accept-Language`。创建请求中的 `user_id` 使用系统用户 ID(`userStatus.profile.id`)。调用方无需维护这些字段。
131
+ return <>
132
+ <button disabled={busy || client.loginStatus !== "success"} onClick={() => void confirmUsage()}>
133
+ 确认消费
134
+ </button>
135
+ {error && <p role="alert">{error}</p>}
136
+ </>;
137
+ }
138
+ ```
139
+
140
+ 月用量和服务端免费用量分别使用 `await client.addMonthlyUsage({ cnt: 1 })`、`await client.addFreeUsageCnt({ cnt: 1 })`,每次只调用业务所需的接口。确认后按需调用 `refreshUserStatus()` 更新显示;消费方法不会乐观修改余额,也不自动发起账户刷新。
141
+
142
+ 默认消费超时为 30 秒,无自动重试。请求已发出后,超时、网络错误或取消不能证明服务端没有扣费;不要因此直接重放消费。后端未提供此接口的任务去重键,重复调用会再次记账。原有 `use()` 保留兼容,同一次消费不要同时调用 `use()` 和具名方法。
143
+
144
+ ## Cloudflare R2 文件上传
72
145
 
73
- 当前创建接口支持普通的 `owner/name/input` 合同;视频 `schema_v2` 等高级参数后续接入。模型参数按 JSON 原样发送,不改写 prompt 或供应商。两种方法都只发送一次请求,不自动轮询、重试创建、扣费或插入 Canva 设计。原有登录、额度和结账会话方法继续由同一个 hook 提供。
146
+ `uploadFile({ file })` 自动完成上传:小于 100 MiB 使用单次 PUT,达到 100 MiB 使用分片。调用方式和返回值相同;也可传 `multipart: true` 让小文件使用分片,省略或 false 时按大小自动选择。它支持非空的 File / Blob,默认生成 `temp_<产品渠道>_<日期>_<随机值>.<扩展名>` 对象名,bucket 默认 `video`。可传 `objectName` 和 `bucketName` 指定存储位置;Blob 可通过 `fileName` 指定扩展名。
147
+
148
+ 业务组件仍放在同一个 Provider 内:
149
+
150
+ ```tsx
151
+ import { useEffect, useRef, useState } from "react";
152
+ import { useYiChongCanva } from "yichong-canva2";
153
+
154
+ function FileUploadPanel() {
155
+ const client = useYiChongCanva();
156
+ const [busy, setBusy] = useState(false);
157
+ const [url, setUrl] = useState("");
158
+ const [error, setError] = useState("");
159
+
160
+ const controllerRef = useRef<AbortController | null>(null);
161
+ useEffect(() => () => controllerRef.current?.abort(), []);
162
+
163
+ async function upload(file: File) {
164
+ if (controllerRef.current) return;
165
+ const controller = new AbortController();
166
+ controllerRef.current = controller;
167
+ setBusy(true);
168
+ setUrl("");
169
+ setError("");
170
+ try {
171
+ const uploaded = await client.uploadFile(
172
+ { file }, // 大文件自动分片,无需自己切片。
173
+ { signal: controller.signal },
174
+ );
175
+ setUrl(uploaded.url);
176
+ // 可以将 uploaded.url 放进 createSpecifyPrediction 的 input。
177
+ } catch (error) {
178
+ setError(error instanceof Error ? error.message : "上传失败");
179
+ } finally {
180
+ controllerRef.current = null;
181
+ setBusy(false);
182
+ }
183
+ }
184
+
185
+ return <>
186
+ <input
187
+ type="file"
188
+ disabled={busy || client.loginStatus !== "success"}
189
+ onChange={event => {
190
+ const file = event.target.files?.[0];
191
+ if (file) void upload(file);
192
+ }}
193
+ />
194
+ <button disabled={!busy} onClick={() => controllerRef.current?.abort()}>取消上传</button>
195
+ {url && <a href={url} target="_blank" rel="noreferrer">查看上传文件</a>}
196
+ {error && <p role="alert">{error}</p>}
197
+ </>;
198
+ }
199
+ ```
200
+
201
+ `generatePresignedUrl({ objectName, bucketName? })` 提供底层签名接口,返回后端原始结构;它本身不上传文件。一键上传必须取得合法的 `endpointBaseUrl` 才 PUT,避免把临时签名地址当成公开资源地址。旧响应仅返回签名 URL 时,底层方法仍可读取。
202
+
203
+ 上传的整个流程共用一次超时和取消信号。单次 PUT 默认 120 秒,分片默认 30 分钟;可在第二个参数传 `{ signal, timeoutMs }` 调整。取消或账户、产品渠道变化后不再发起下一片或合并;合并请求已发出时,取消等待不能保证服务端没有完成。工具包不自动重试或续传。
204
+
205
+ 分片顺序上传,默认每片 5 MiB,超大文件自动增大片大小以保持不超过 10000 片;最后一片可以更小。按 [R2 当前限制](https://developers.cloudflare.com/r2/platform/limits/) 校验文件大小(最多 5 TiB − 5 GiB)和对象名(最多 1024 个 UTF-8 字节),不将整份文件读入内存。
206
+
207
+ 浏览器必须能读取每片 PUT 的 `ETag`。R2 bucket 的 CORS 要允许应用来源、`PUT` 和 `Content-Type`,并设置 `ExposeHeaders: ["ETag"]`,参见 [Cloudflare CORS 文档](https://developers.cloudflare.com/r2/buckets/cors/)。读取不到 ETag 时抛出 `code="missing_etag"`,停止上传,不会合并。
208
+
209
+ 三个底层方法 `initiateUpload`、`getUploadUrl`、`completeUpload` 保留后端原始响应,使用上表中的参数,默认每次超时 60 秒。初始化结果的 `UploadId` 大写,下一步参数使用 `uploadId`;合并的 `parts` 必须按编号升序排列,每项使用后端要求的 `{ ETag, PartNumber }`,ETag 的引号原样保留。手动上传时由应用切片、PUT 和收集 ETag;一般业务直接使用 `uploadFile` 即可。
210
+
211
+ 当前后端没有终止分片会话的接口,取消只停止客户端流程,已上传分片需由 bucket 的生命周期规则清理。[R2 官方文档](https://developers.cloudflare.com/r2/objects/upload-objects/) 说明默认会在 7 天后清理未完成会话,实际以当前 bucket 配置为准。
212
+
213
+ ## 文本审核
214
+
215
+ `client.textCheck` 封装后端的公共文本审核接口,复用现有 Provider,无需另外配置令牌。请求发送到用户 JWT 公共入口。
216
+
217
+ ```ts
218
+ const result = await client.textCheck(
219
+ { text: userInput, scene: "default" },
220
+ { timeoutMs: 30_000 },
221
+ );
222
+
223
+ if (result.data.allowed === true) {
224
+ // 可以继续后续操作;保留原始 decision,但不重复计算审核阈值。
225
+ } else {
226
+ // 在应用的提示组件中展示 result.msg。
227
+ }
228
+ ```
229
+
230
+ 应用只在 `data.allowed === true` 时继续。后端当前统一 `pass/review` 放行、`block` 拒绝;三种审核结果都可以是 HTTP 200 / `code=0`,它只表示审核执行成功。`msg`、`request_id`、`decision`、分类分数、`policy_version`、`model`、`duration_ms` 和附加字段原样保留。工具包严格验证 `allowed` 等响应字段,缺失或类型错误时抛出 `ApiError`。
231
+
232
+ `text` 必须非空,并同时满足最多 1024 个 Unicode 字符、1024 个 UTF-8 字节,例如 1024 个 ASCII 字符、341 个常见汉字或 256 个四字节 emoji。原文包含的空白会保留,不截断或拆片。`scene` 可省略,目前仅支持 `"default"`。本地非法参数抛出 `code="invalid_request"`,不会发送请求。
233
+
234
+ 审核不会自动创建生成任务。上面的完整示例由应用显式先审核 prompt,再调用 `createSpecifyPrediction`;直接调用创建接口也不会隐式触发审核。
74
235
 
75
236
  HTTP 失败、后端 `code` 非 `0`、网络错误、无效响应、超时和取消都会抛出导出的 `ApiError`。服务端返回的 `msg` 保留在 `error.message` / `error.userMessage`,应用应在错误组件中直接展示。`code=0` 且 `data.status="failed"` 表示任务执行失败,查询方法会保留任务信息,应用应处理 `error_msg` / `error`。
76
237
 
238
+ 审核的技术错误也抛出 `ApiError`,不能当作审核通过。`error.status` / `error.code` 保留 HTTP 状态和后端 code;错误对象中的 `error.data` 保留后端 `error_code`、`request_id`、`retryable`、`allowed` 等字段。429 返回的 `Retry-After` 秒数保留在 `error.retryAfter`,由应用决定重试时机。
239
+
77
240
  ```ts
78
241
  const controller = new AbortController();
79
242
  const prediction = await client.getPrediction(
@@ -82,7 +245,7 @@ const prediction = await client.getPrediction(
82
245
  );
83
246
  ```
84
247
 
85
- 取消只终止当前 HTTP 等待,不会取消已经创建的后端任务。默认请求超时为 60 秒,包含读取响应正文的时间。
248
+ 取消只终止当前 HTTP 等待,不会取消已经创建的后端任务或撤销已提交的消费。创建、查询、文本审核和底层签名的默认请求超时为 60 秒,包含读取响应正文的时间;消费为 30 秒,一键上传为 120 秒。
86
249
 
87
250
  ## 开发
88
251
 
@@ -93,6 +256,6 @@ npm run lint
93
256
  npm test
94
257
  ```
95
258
 
96
- `npm test` 构建后使用 Node 测试真实产物,覆盖请求合同、错误、超时、取消,以及 Provider 登录/刷新后的凭据共享。测试替换 Canva 宿主和网络请求,不调用真实模型。
259
+ `npm test` 构建后使用 Node 测试真实产物,覆盖请求合同、消费数量精度、签名与 PUT 的凭据边界、错误、超时、取消,以及 Provider 登录/刷新后的凭据共享。测试替换 Canva 宿主和网络请求,不调用真实模型、记账或上传资源。
97
260
 
98
261
  源码在 `packages/`,构建输出在 `dist/`。`npm run lint` 检查新增 API 模块和测试;全包类型由 `lint:types` 检查。原包的旧 Provider 实现暂时保留。
package/dist/api/error.js CHANGED
@@ -1,10 +1,12 @@
1
1
  class ApiError extends Error {
2
- constructor(message, code, status) {
2
+ constructor(message, code, status, details) {
3
3
  super(message);
4
4
  this.code = code;
5
5
  this.status = status;
6
6
  this.name = "ApiError";
7
7
  this.userMessage = message;
8
+ this.data = details == null ? void 0 : details.data;
9
+ this.retryAfter = details == null ? void 0 : details.retryAfter;
8
10
  }
9
11
  }
10
12
  export {
@@ -0,0 +1,32 @@
1
+ import { ApiError } from "./error.js";
2
+ import { isObject, isNonemptyString, invalid, postApi } from "./request.js";
3
+ function isDecision(value) {
4
+ return value === "pass" || value === "review" || value === "block";
5
+ }
6
+ function isResult(value) {
7
+ return isObject(value) && typeof value.allowed === "boolean" && isDecision(value.decision) && isNonemptyString(value.request_id) && isNonemptyString(value.scene) && isNonemptyString(value.policy_version) && isNonemptyString(value.model) && typeof value.duration_ms === "number" && Number.isFinite(value.duration_ms) && value.duration_ms >= 0 && Array.isArray(value.flagged_categories) && value.flagged_categories.every(isNonemptyString) && isObject(value.categories) && Object.values(value.categories).every((category) => isObject(category) && typeof category.score === "number" && Number.isFinite(category.score) && category.score >= 0 && category.score <= 1 && isDecision(category.decision));
8
+ }
9
+ function createTextModerationApi(getContext) {
10
+ return {
11
+ async textCheck(params, options) {
12
+ if (!isObject(params) || !isNonemptyString(params.text) || params.scene !== void 0 && params.scene !== "default" || Object.keys(params).some((key) => key !== "text" && key !== "scene")) {
13
+ invalid("textCheck requires nonempty text and an optional default scene.");
14
+ }
15
+ if (/[\uD800-\uDFFF]/u.test(params.text)) invalid("text must contain valid Unicode characters.");
16
+ if ([...params.text].length > 1024 || new TextEncoder().encode(params.text).length > 1024) {
17
+ invalid("text must not exceed 1024 Unicode characters or 1024 UTF-8 bytes.");
18
+ }
19
+ const response = await postApi(getContext(), "textCheck", {
20
+ text: params.text,
21
+ ...params.scene === void 0 ? {} : { scene: params.scene }
22
+ }, options);
23
+ if (!isResult(response.data)) {
24
+ throw new ApiError("Backend returned invalid text moderation information.", "invalid_response");
25
+ }
26
+ return response;
27
+ }
28
+ };
29
+ }
30
+ export {
31
+ createTextModerationApi
32
+ };
@@ -1,4 +1,10 @@
1
1
  import { ApiError } from "./error.js";
2
+ import { withRequest } from "./transport.js";
3
+ const apiPaths = {
4
+ createSpecifyPrediction: "/replicate/createSpecifyPrediction",
5
+ getPrediction: "/replicate/getPrediction",
6
+ textCheck: "/api/public/text-moderation/check"
7
+ };
2
8
  function isObject(value) {
3
9
  return value !== null && typeof value === "object" && !Array.isArray(value);
4
10
  }
@@ -27,100 +33,87 @@ function language(getLocale) {
27
33
  return "en";
28
34
  }
29
35
  }
30
- async function postApi(context, method, params, options = {}) {
31
- var _a, _b, _c, _d, _e;
32
- const timeoutMs = options.timeoutMs ?? 6e4;
33
- if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) {
34
- invalid("timeoutMs must be a positive integer in milliseconds.");
35
- }
36
- if ((_a = options.signal) == null ? void 0 : _a.aborted) throw new ApiError("Request canceled.", "aborted");
37
- const { userStatus, productName, apiBaseUrl } = context;
38
- const uid = (_b = userStatus.profile) == null ? void 0 : _b.id;
39
- if (!isNonemptyString(uid) || !isNonemptyString(userStatus.userId) || !isNonemptyString(userStatus.jwt)) {
40
- throw new ApiError("Sign in before calling prediction APIs.", "account_not_ready");
41
- }
42
- if (!isNonemptyString(productName)) invalid("productName is required.");
36
+ function endpoint(baseUrl, path) {
43
37
  let url;
44
38
  try {
45
- url = new URL(apiBaseUrl);
39
+ url = new URL(baseUrl);
46
40
  } catch {
47
- invalid("apiBaseUrl must be an absolute HTTP(S) URL.");
41
+ invalid("The service base URL must be an absolute HTTP(S) URL.");
48
42
  }
49
43
  if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
50
- invalid("apiBaseUrl must be HTTP(S) without credentials, query or fragment.");
44
+ invalid("The service base URL must be HTTP(S) without credentials, query or fragment.");
51
45
  }
52
- url.pathname = `${url.pathname.replace(/\/+$/, "")}/replicate/${method}`;
53
- url.searchParams.set("uid", uid);
54
- url.searchParams.set("platform_uid", userStatus.userId);
46
+ url.pathname = `${url.pathname.replace(/\/+$/, "")}${path}`;
47
+ return url;
48
+ }
49
+ function addContextQuery(url, context) {
50
+ if (!isNonemptyString(context.productName)) invalid("productName is required.");
51
+ const { profile, userId } = context.userStatus;
52
+ if (isNonemptyString(profile == null ? void 0 : profile.id)) url.searchParams.set("uid", profile.id);
53
+ if (isNonemptyString(userId)) url.searchParams.set("platform_uid", userId);
55
54
  url.searchParams.set("platform", "canva_addon");
56
- url.searchParams.set("app_channel", productName);
57
- const headers = {
58
- "Content-Type": "application/json",
59
- "Accept-Language": language(context.getLocale),
60
- Authorization: `Bearer ${userStatus.jwt}`,
61
- Channel: "ai"
62
- };
63
- const body = JSON.stringify(method === "createSpecifyPrediction" ? { ...params, user_id: uid } : params);
64
- const controller = new AbortController();
65
- let timedOut = false;
66
- let rejectCanceled;
67
- const canceled = new Promise((_, reject) => {
68
- rejectCanceled = reject;
69
- });
70
- const cancel = () => {
71
- controller.abort();
72
- rejectCanceled(new ApiError(timedOut ? "Request timed out." : "Request canceled.", timedOut ? "timeout" : "aborted"));
73
- };
74
- (_c = options.signal) == null ? void 0 : _c.addEventListener("abort", cancel, { once: true });
75
- const timer = setTimeout(() => {
76
- timedOut = true;
77
- cancel();
78
- }, timeoutMs);
55
+ url.searchParams.set("app_channel", context.productName);
56
+ }
57
+ async function readJson(response) {
79
58
  try {
80
- return await Promise.race([
81
- (async () => {
82
- const response = await fetch(url.toString(), {
83
- method: "POST",
84
- headers,
85
- body,
86
- signal: controller.signal,
87
- credentials: "omit",
88
- redirect: "error"
89
- });
90
- let payload;
91
- try {
92
- payload = await response.json();
93
- } catch {
94
- throw new ApiError("Backend returned an invalid JSON response.", response.ok ? "invalid_response" : "http_error", response.status);
95
- }
96
- const message = isObject(payload) && isNonemptyString(payload.msg) ? payload.msg : "Backend request failed.";
97
- const code = isObject(payload) && (typeof payload.code === "string" || typeof payload.code === "number") ? payload.code : "http_error";
98
- if (!response.ok) throw new ApiError(message, code, response.status);
99
- if (!isObject(payload) || typeof payload.code !== "number" && typeof payload.code !== "string") {
100
- throw new ApiError("Backend returned an invalid response envelope.", "invalid_response", response.status);
101
- }
102
- if (payload.code !== 0) throw new ApiError(message, payload.code, response.status);
103
- if (typeof payload.msg !== "string" || !Object.prototype.hasOwnProperty.call(payload, "data")) {
104
- throw new ApiError("Backend returned an invalid response envelope.", "invalid_response", response.status);
105
- }
106
- return payload;
107
- })(),
108
- canceled
109
- ]);
110
- } catch (error) {
111
- if (timedOut) throw new ApiError("Request timed out.", "timeout");
112
- if ((_d = options.signal) == null ? void 0 : _d.aborted) throw new ApiError("Request canceled.", "aborted");
113
- if (error instanceof ApiError) throw error;
114
- throw new ApiError("Unable to connect to the backend.", "network_error");
115
- } finally {
116
- clearTimeout(timer);
117
- (_e = options.signal) == null ? void 0 : _e.removeEventListener("abort", cancel);
59
+ return await response.json();
60
+ } catch {
61
+ throw new ApiError("Backend returned an invalid JSON response.", response.ok ? "invalid_response" : "http_error", response.status);
118
62
  }
119
63
  }
64
+ function backendError(response, payload, fallbackCode) {
65
+ const message = isObject(payload) && isNonemptyString(payload.msg) ? payload.msg : isObject(payload) && isNonemptyString(payload.message) ? payload.message : "Backend request failed.";
66
+ const code = isObject(payload) && (typeof payload.code === "string" || typeof payload.code === "number") ? payload.code : fallbackCode;
67
+ const retryAfter = response.headers.get("Retry-After");
68
+ return new ApiError(message, code, response.status, {
69
+ data: isObject(payload) && isObject(payload.data) ? payload.data : void 0,
70
+ retryAfter: retryAfter !== null && /^\d+$/.test(retryAfter) && Number.isSafeInteger(Number(retryAfter)) ? Number(retryAfter) : void 0
71
+ });
72
+ }
73
+ async function postApi(context, method, params, options = {}) {
74
+ return withRequest(options, async (signal) => {
75
+ var _a;
76
+ const { userStatus, apiBaseUrl } = context;
77
+ const uid = (_a = userStatus.profile) == null ? void 0 : _a.id;
78
+ if (!isNonemptyString(userStatus.jwt) || method !== "textCheck" && (!isNonemptyString(uid) || !isNonemptyString(userStatus.userId))) {
79
+ throw new ApiError("Wait for the Provider account credentials before calling backend APIs.", "account_not_ready");
80
+ }
81
+ const url = endpoint(apiBaseUrl, apiPaths[method]);
82
+ addContextQuery(url, context);
83
+ const response = await fetch(url.toString(), {
84
+ method: "POST",
85
+ headers: {
86
+ "Content-Type": "application/json",
87
+ "Accept-Language": language(context.getLocale),
88
+ Authorization: `Bearer ${userStatus.jwt}`,
89
+ Channel: "ai"
90
+ },
91
+ body: JSON.stringify(method === "createSpecifyPrediction" ? { ...params, user_id: uid } : params),
92
+ signal,
93
+ credentials: "omit",
94
+ redirect: "error"
95
+ });
96
+ const payload = await readJson(response);
97
+ if (!response.ok) throw backendError(response, payload, "http_error");
98
+ if (!isObject(payload) || typeof payload.code !== "number" && typeof payload.code !== "string") {
99
+ throw new ApiError("Backend returned an invalid response envelope.", "invalid_response", response.status);
100
+ }
101
+ if (payload.code !== 0) throw backendError(response, payload, "http_error");
102
+ if (typeof payload.msg !== "string" || !Object.prototype.hasOwnProperty.call(payload, "data")) {
103
+ throw new ApiError("Backend returned an invalid response envelope.", "invalid_response", response.status);
104
+ }
105
+ return payload;
106
+ });
107
+ }
120
108
  export {
109
+ addContextQuery,
110
+ backendError,
111
+ endpoint,
121
112
  invalid,
122
113
  isNonemptyString,
123
114
  isObject,
115
+ language,
124
116
  postApi,
117
+ readJson,
125
118
  validateJson
126
119
  };
@@ -0,0 +1,42 @@
1
+ import { ApiError } from "./error.js";
2
+ async function withRequest(options, work) {
3
+ var _a, _b, _c, _d;
4
+ const timeoutMs = options.timeoutMs ?? 6e4;
5
+ if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) {
6
+ throw new ApiError("timeoutMs must be a positive integer in milliseconds.", "invalid_request");
7
+ }
8
+ if ((_a = options.signal) == null ? void 0 : _a.aborted) throw new ApiError("Request canceled.", "aborted");
9
+ const controller = new AbortController();
10
+ let timedOut = false;
11
+ let rejectCanceled;
12
+ const canceled = new Promise((_, reject) => {
13
+ rejectCanceled = reject;
14
+ });
15
+ const cancel = () => {
16
+ controller.abort();
17
+ rejectCanceled(new ApiError(timedOut ? "Request timed out." : "Request canceled.", timedOut ? "timeout" : "aborted"));
18
+ };
19
+ (_b = options.signal) == null ? void 0 : _b.addEventListener("abort", cancel, { once: true });
20
+ const timer = setTimeout(() => {
21
+ timedOut = true;
22
+ cancel();
23
+ }, timeoutMs);
24
+ try {
25
+ return await Promise.race([work(controller.signal), canceled]);
26
+ } catch (error) {
27
+ if (timedOut) throw new ApiError("Request timed out.", "timeout");
28
+ if ((_c = options.signal) == null ? void 0 : _c.aborted) throw new ApiError("Request canceled.", "aborted");
29
+ if (error instanceof ApiError) throw error;
30
+ throw new ApiError("Unable to connect to the backend.", "network_error");
31
+ } finally {
32
+ clearTimeout(timer);
33
+ (_d = options.signal) == null ? void 0 : _d.removeEventListener("abort", cancel);
34
+ }
35
+ }
36
+ function throwIfAborted(signal) {
37
+ if (signal.aborted) throw new ApiError("Request canceled.", "aborted");
38
+ }
39
+ export {
40
+ throwIfAborted,
41
+ withRequest
42
+ };
@@ -0,0 +1,218 @@
1
+ import { ApiError } from "./error.js";
2
+ import { isObject, isNonemptyString, invalid, endpoint, addContextQuery, language, readJson, backendError } from "./request.js";
3
+ import { withRequest, throwIfAborted } from "./transport.js";
4
+ const MiB = 1024 * 1024;
5
+ const multipartThreshold = 100 * MiB;
6
+ const maxParts = 1e4;
7
+ const maxFileSize = 5 * 1024 ** 4 - 5 * 1024 ** 3;
8
+ function objectName(value) {
9
+ if (!isNonemptyString(value) || value.includes("\\") || /[\uD800-\uDFFF]/u.test(value) || new TextEncoder().encode(value).length > 1024 || value.split("/").some((part) => !part || part === "." || part === "..")) {
10
+ invalid("objectName must contain a nonempty object key without unsafe path segments.");
11
+ }
12
+ return value;
13
+ }
14
+ function validateParams(params, allowed, method) {
15
+ if (!isObject(params) || Object.keys(params).some((key) => !allowed.includes(key))) {
16
+ invalid(`${method} received invalid parameters.`);
17
+ }
18
+ }
19
+ function uploadId(value) {
20
+ if (!isNonemptyString(value)) invalid("uploadId must be a nonempty string.");
21
+ return value;
22
+ }
23
+ function partNumber(value) {
24
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > maxParts) {
25
+ invalid("partNumber must be an integer between 1 and 10000.");
26
+ }
27
+ return value;
28
+ }
29
+ async function multipartPost(context, path, body, signal) {
30
+ const url = endpoint(context.uploadBaseUrl, path);
31
+ addContextQuery(url, context);
32
+ const response = await fetch(url.toString(), {
33
+ method: "POST",
34
+ credentials: "omit",
35
+ redirect: "error",
36
+ signal,
37
+ headers: { "Content-Type": "application/json", Channel: "node-nauth", "Accept-Language": language(context.getLocale) },
38
+ body: JSON.stringify(body)
39
+ });
40
+ const payload = await readJson(response);
41
+ throwIfAborted(signal);
42
+ if (!response.ok || isObject(payload) && (payload.error !== void 0 || payload.Error !== void 0)) {
43
+ const details = isObject(payload) && isNonemptyString(payload.error) ? { ...payload, msg: payload.error } : payload;
44
+ throw backendError(response, details, "multipart_failed");
45
+ }
46
+ if (!isObject(payload)) throw new ApiError("Backend returned an invalid multipart response.", "invalid_response", response.status);
47
+ if (payload.Key !== void 0 && payload.Key !== body.objectName || payload.Bucket !== void 0 && payload.Bucket !== body.bucketName) {
48
+ throw new ApiError("Backend returned a different upload object or bucket.", "invalid_response", response.status);
49
+ }
50
+ return payload;
51
+ }
52
+ async function initiate(context, params, signal) {
53
+ validateParams(params, ["objectName", "bucketName", "contentType"], "initiateUpload");
54
+ if (params.contentType !== void 0 && !isNonemptyString(params.contentType)) invalid("contentType must be a nonempty string.");
55
+ const payload = await multipartPost(context, "/upload/initiate-upload", {
56
+ objectName: objectName(params.objectName),
57
+ bucketName: bucketName(params.bucketName),
58
+ contentType: params.contentType
59
+ }, signal);
60
+ if (!isNonemptyString(payload.UploadId)) throw new ApiError("Backend did not return UploadId.", "invalid_response");
61
+ return payload;
62
+ }
63
+ async function partUrl(context, params, signal) {
64
+ validateParams(params, ["objectName", "bucketName", "uploadId", "partNumber"], "getUploadUrl");
65
+ const payload = await multipartPost(context, "/upload/get-upload-url", {
66
+ objectName: objectName(params.objectName),
67
+ bucketName: bucketName(params.bucketName),
68
+ uploadId: uploadId(params.uploadId),
69
+ partNumber: partNumber(params.partNumber)
70
+ }, signal);
71
+ httpsUrl(payload.url);
72
+ return payload;
73
+ }
74
+ async function complete(context, params, signal) {
75
+ validateParams(params, ["objectName", "bucketName", "uploadId", "parts"], "completeUpload");
76
+ if (!Array.isArray(params.parts) || !params.parts.length || params.parts.length > maxParts) invalid("parts must contain 1 to 10000 uploaded parts.");
77
+ let previous = 0;
78
+ const parts = Array.from(params.parts, (part) => {
79
+ validateParams(part, ["ETag", "PartNumber"], "completeUpload part");
80
+ const number = partNumber(part.PartNumber);
81
+ if (number <= previous || !isNonemptyString(part.ETag)) invalid("parts must have ETag and unique, ascending PartNumber values.");
82
+ previous = number;
83
+ return { ETag: part.ETag, PartNumber: number };
84
+ });
85
+ const payload = await multipartPost(context, "/upload/complete-upload", {
86
+ objectName: objectName(params.objectName),
87
+ bucketName: bucketName(params.bucketName),
88
+ uploadId: uploadId(params.uploadId),
89
+ parts
90
+ }, signal);
91
+ if (!isNonemptyString(payload.ETag)) throw new ApiError("Backend did not confirm multipart completion with ETag.", "invalid_response");
92
+ return payload;
93
+ }
94
+ function httpsUrl(value, publicBase = false) {
95
+ let url;
96
+ try {
97
+ url = new URL(typeof value === "string" ? value : "");
98
+ } catch {
99
+ throw new ApiError("Backend returned an invalid upload URL.", "invalid_response");
100
+ }
101
+ if (url.protocol !== "https:" || url.username || url.password || url.hash || publicBase && url.search) {
102
+ throw new ApiError("Upload URLs must be HTTPS without credentials or fragments.", "invalid_response");
103
+ }
104
+ return url;
105
+ }
106
+ function bucketName(value) {
107
+ if (value === void 0) return "video";
108
+ if (!isNonemptyString(value)) invalid("bucketName must be a nonempty string.");
109
+ return value;
110
+ }
111
+ async function presign(context, params, signal) {
112
+ if (!isObject(params) || Object.keys(params).some((key) => key !== "objectName" && key !== "bucketName")) {
113
+ invalid("generatePresignedUrl requires objectName and an optional bucketName.");
114
+ }
115
+ const body = { objectName: objectName(params.objectName), bucketName: bucketName(params.bucketName) };
116
+ const url = endpoint(context.uploadBaseUrl, "/api/generate-presigned-url");
117
+ addContextQuery(url, context);
118
+ const response = await fetch(url.toString(), {
119
+ method: "POST",
120
+ credentials: "omit",
121
+ redirect: "error",
122
+ signal,
123
+ headers: { "Content-Type": "application/json", Channel: "node-nauth", "Accept-Language": language(context.getLocale) },
124
+ body: JSON.stringify(body)
125
+ });
126
+ const payload = await readJson(response);
127
+ throwIfAborted(signal);
128
+ if (!response.ok || isObject(payload) && payload.success === false) throw backendError(response, payload, "presign_failed");
129
+ if (!isObject(payload) || payload.success !== true || !isNonemptyString(payload.url)) {
130
+ throw new ApiError("Backend returned an invalid presign response.", "invalid_response", response.status);
131
+ }
132
+ httpsUrl(payload.url);
133
+ if (payload.endpointBaseUrl !== void 0) httpsUrl(payload.endpointBaseUrl, true);
134
+ return payload;
135
+ }
136
+ function fileObjectName(file, fileName, productName) {
137
+ var _a, _b;
138
+ const name = fileName ?? ("name" in file && typeof file.name === "string" ? file.name : "");
139
+ const extension = ((_b = (_a = /\.([a-z0-9]{1,12})$/i.exec(name)) == null ? void 0 : _a[1]) == null ? void 0 : _b.toLowerCase()) ?? { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/gif": "gif", "application/pdf": "pdf", "video/mp4": "mp4", "audio/mpeg": "mp3" }[file.type] ?? "bin";
140
+ const now = /* @__PURE__ */ new Date();
141
+ const day = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
142
+ return objectName(`temp_${productName}_${day}_${crypto.randomUUID()}.${extension}`);
143
+ }
144
+ function createUploadApi(getContext) {
145
+ return {
146
+ generatePresignedUrl: (params, options = {}) => withRequest(options, (signal) => presign(getContext(), params, signal)),
147
+ initiateUpload: (params, options = {}) => withRequest(options, (signal) => initiate(getContext(), params, signal)),
148
+ getUploadUrl: (params, options = {}) => withRequest(options, (signal) => partUrl(getContext(), params, signal)),
149
+ completeUpload: (params, options = {}) => withRequest(options, (signal) => complete(getContext(), params, signal)),
150
+ async uploadFile(params, options = {}) {
151
+ var _a;
152
+ 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" || Object.keys(params).some((key2) => !["file", "fileName", "bucketName", "objectName", "multipart"].includes(key2))) {
153
+ invalid("uploadFile requires a nonempty file within the R2 object size limit and valid upload parameters.");
154
+ }
155
+ const file = params.file;
156
+ const multipart = params.multipart === true || file.size >= multipartThreshold;
157
+ const context = getContext();
158
+ const key = params.objectName === void 0 ? fileObjectName(file, params.fileName, context.productName) : objectName(params.objectName);
159
+ const bucket = bucketName(params.bucketName);
160
+ const owner = JSON.stringify([(_a = context.userStatus.profile) == null ? void 0 : _a.id, context.userStatus.userId, context.productName]);
161
+ const check = (signal) => {
162
+ var _a2;
163
+ throwIfAborted(signal);
164
+ const current = getContext();
165
+ if (JSON.stringify([(_a2 = current.userStatus.profile) == null ? void 0 : _a2.id, current.userStatus.userId, current.productName]) !== owner) {
166
+ throw new ApiError("Account changed during upload.", "account_changed");
167
+ }
168
+ };
169
+ return withRequest({ ...options, timeoutMs: options.timeoutMs ?? (multipart ? 30 * 6e4 : 12e4) }, async (signal) => {
170
+ check(signal);
171
+ const signed = await presign(context, { objectName: key, bucketName: bucket }, signal);
172
+ const base = httpsUrl(signed.endpointBaseUrl, true).href.replace(/\/+$/, "");
173
+ check(signal);
174
+ const contentType = file.type || "application/octet-stream";
175
+ const put = async (url, body) => {
176
+ check(signal);
177
+ const response = await fetch(url, {
178
+ method: "PUT",
179
+ credentials: "omit",
180
+ redirect: "error",
181
+ signal,
182
+ headers: { "Content-Type": contentType },
183
+ body
184
+ });
185
+ check(signal);
186
+ if (!response.ok) throw new ApiError(`File upload failed (HTTP ${response.status}).`, "upload_failed", response.status);
187
+ return response;
188
+ };
189
+ if (multipart) {
190
+ const session = await initiate(context, { objectName: key, bucketName: bucket, contentType }, signal);
191
+ check(signal);
192
+ const partSize = Math.max(5 * MiB, Math.ceil(file.size / maxParts / MiB) * MiB);
193
+ const parts = [];
194
+ for (let start = 0; start < file.size; start += partSize) {
195
+ check(signal);
196
+ const number = parts.length + 1;
197
+ const signedPart = await partUrl(context, { objectName: key, bucketName: bucket, uploadId: session.UploadId, partNumber: number }, signal);
198
+ const response = await put(signedPart.url, file.slice(start, Math.min(start + partSize, file.size), contentType));
199
+ const etag = response.headers.get("ETag");
200
+ if (!isNonemptyString(etag)) {
201
+ throw new ApiError("R2 did not expose ETag. Configure the bucket CORS ExposeHeaders to include ETag.", "missing_etag", response.status);
202
+ }
203
+ parts.push({ ETag: etag, PartNumber: number });
204
+ }
205
+ check(signal);
206
+ await complete(context, { objectName: key, bucketName: bucket, uploadId: session.UploadId, parts }, signal);
207
+ check(signal);
208
+ } else {
209
+ await put(signed.url, file);
210
+ }
211
+ return { url: `${base}/${key.split("/").map(encodeURIComponent).join("/")}`, key, endpointBaseUrl: base };
212
+ });
213
+ }
214
+ };
215
+ }
216
+ export {
217
+ createUploadApi
218
+ };
@@ -0,0 +1,57 @@
1
+ import { ApiError } from "./error.js";
2
+ import { isObject, invalid, isNonemptyString, endpoint, addContextQuery, language, readJson, backendError } from "./request.js";
3
+ import { withRequest } from "./transport.js";
4
+ const paths = {
5
+ reduceFreeCnt: "/api/user/reduce-free-cnt",
6
+ addMonthlyUsage: "/api/user/add-monthly-usage",
7
+ addFreeUsageCnt: "/api/user/add-free-usage-cnt"
8
+ };
9
+ function createUsageApi(getContext) {
10
+ const post = async (method, params, options = {}) => {
11
+ const digits = method === "addFreeUsageCnt" ? 1 : 2;
12
+ if (!isObject(params) || typeof params.cnt !== "number" || !Number.isFinite(params.cnt) || params.cnt <= 0 || Object.keys(params).some((key) => key !== "cnt")) {
13
+ invalid(`${method} requires a positive cnt number.`);
14
+ }
15
+ const scaled = params.cnt * 10 ** digits;
16
+ if (!Number.isSafeInteger(Math.round(scaled)) || Math.round(scaled) <= 0 || Math.abs(scaled - Math.round(scaled)) > 1e-8) {
17
+ invalid(`${method} supports at most ${digits} decimal places.`);
18
+ }
19
+ return withRequest({ ...options, timeoutMs: options.timeoutMs ?? 3e4 }, async (signal) => {
20
+ var _a;
21
+ const context = getContext();
22
+ if (!isNonemptyString(context.passport) || !isNonemptyString((_a = context.userStatus.profile) == null ? void 0 : _a.id) || !isNonemptyString(context.userStatus.userId)) {
23
+ throw new ApiError("Wait for the Provider account credentials before recording usage.", "account_not_ready");
24
+ }
25
+ const url = endpoint(context.baseUrl, paths[method]);
26
+ addContextQuery(url, context);
27
+ const response = await fetch(url.toString(), {
28
+ method: "POST",
29
+ credentials: "omit",
30
+ redirect: "error",
31
+ signal,
32
+ headers: {
33
+ "Content-Type": "application/json",
34
+ "Accept-Language": language(context.getLocale),
35
+ "X-Access-Ticket": context.passport,
36
+ "X-Access-Channel": context.productName
37
+ },
38
+ body: JSON.stringify({ cnt: params.cnt })
39
+ });
40
+ const payload = await readJson(response);
41
+ if (!response.ok) throw backendError(response, payload, isObject(payload) && typeof payload.ok === "number" ? payload.ok : "http_error");
42
+ if (!isObject(payload) || typeof payload.ok !== "number" || !Number.isFinite(payload.ok) || typeof payload.msg !== "string") {
43
+ throw new ApiError("Backend returned an invalid usage response.", "invalid_response", response.status);
44
+ }
45
+ if (payload.ok !== 0) throw backendError(response, payload, payload.ok);
46
+ return payload;
47
+ });
48
+ };
49
+ return {
50
+ reduceFreeCnt: (params, options) => post("reduceFreeCnt", params, options),
51
+ addMonthlyUsage: (params, options) => post("addMonthlyUsage", params, options),
52
+ addFreeUsageCnt: (params, options) => post("addFreeUsageCnt", params, options)
53
+ };
54
+ }
55
+ export {
56
+ createUsageApi
57
+ };
@@ -35,6 +35,33 @@ const YiChongCanvaContext = React.createContext(
35
35
  },
36
36
  getPrediction: async () => {
37
37
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
38
+ },
39
+ textCheck: async () => {
40
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
41
+ },
42
+ reduceFreeCnt: async () => {
43
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
44
+ },
45
+ addMonthlyUsage: async () => {
46
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
47
+ },
48
+ addFreeUsageCnt: async () => {
49
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
50
+ },
51
+ generatePresignedUrl: async () => {
52
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
53
+ },
54
+ initiateUpload: async () => {
55
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
56
+ },
57
+ getUploadUrl: async () => {
58
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
59
+ },
60
+ completeUpload: async () => {
61
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
62
+ },
63
+ uploadFile: async () => {
64
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
38
65
  }
39
66
  }
40
67
  );
@@ -3,7 +3,8 @@ import apis from "./apis/index.js";
3
3
  auth.initOauth();
4
4
  async function handleLogin({
5
5
  appId,
6
- productName
6
+ productName,
7
+ onPassport
7
8
  }) {
8
9
  try {
9
10
  let userId = window.userId;
@@ -18,7 +19,8 @@ async function handleLogin({
18
19
  }
19
20
  const userStatus = await getUserProfile({
20
21
  userId,
21
- productName
22
+ productName,
23
+ onPassport
22
24
  });
23
25
  window.g_token = userStatus.jwt || "";
24
26
  userStatus.userId = userId;
@@ -78,7 +80,8 @@ async function getUserProfile({
78
80
  isSubscribe = false,
79
81
  baseline,
80
82
  isChanged,
81
- onStop
83
+ onStop,
84
+ onPassport
82
85
  }) {
83
86
  var _a, _b;
84
87
  let count = 0;
@@ -103,6 +106,7 @@ async function getUserProfile({
103
106
  userStatus = void 0;
104
107
  }
105
108
  if (userStatus == null ? void 0 : userStatus.profile) {
109
+ if (typeof passport === "string" && passport) onPassport == null ? void 0 : onPassport(passport, userId, userStatus.profile.id);
106
110
  if (!isSubscribe) {
107
111
  successCallback == null ? void 0 : successCallback(userStatus);
108
112
  return userStatus;
@@ -5,6 +5,9 @@ import { YiChongCanvaContext } from "./context.js";
5
5
  import _ from "lodash";
6
6
  import { getAppVersion } from "./version.js";
7
7
  import { createPredictionApi } from "../api/predictions.js";
8
+ import { createTextModerationApi } from "../api/moderation.js";
9
+ import { createUsageApi } from "../api/usage.js";
10
+ import { createUploadApi } from "../api/uploads.js";
8
11
  function reduceFreeTimes(baseUrl, passport, cnt = 1) {
9
12
  const header = {
10
13
  "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
@@ -43,6 +46,7 @@ const YiChongCanvaProvider = ({
43
46
  // freeTimes = 1,
44
47
  baseUrl,
45
48
  apiBaseUrl = "https://api.imgkits.com",
49
+ uploadBaseUrl = "https://ai.imgkits.com",
46
50
  getLocale,
47
51
  autoLogin = true,
48
52
  testMode: _testMode = "noTest",
@@ -62,12 +66,26 @@ const YiChongCanvaProvider = ({
62
66
  const sessionStopRef = useRef(null);
63
67
  const [loginStatus, setLoginStatus] = useState("idle");
64
68
  const userStatusRef = useRef({});
65
- const apiConfigRef = useRef({ apiBaseUrl, productName, getLocale });
66
- apiConfigRef.current = { apiBaseUrl, productName, getLocale };
67
- const [predictionApi] = useState(() => createPredictionApi(() => ({
69
+ const apiConfigRef = useRef({ apiBaseUrl, baseUrl, uploadBaseUrl, productName, getLocale });
70
+ apiConfigRef.current = { apiBaseUrl, baseUrl, uploadBaseUrl, productName, getLocale };
71
+ const passportRef = useRef(null);
72
+ const onPassport = (passport, userId, uid) => {
73
+ passportRef.current = { passport, userId, uid, productName };
74
+ };
75
+ const getApiContext = () => ({
68
76
  ...apiConfigRef.current,
69
77
  userStatus: userStatusRef.current
70
- })));
78
+ });
79
+ const [predictionApi] = useState(() => createPredictionApi(getApiContext));
80
+ const [textModerationApi] = useState(() => createTextModerationApi(getApiContext));
81
+ const [usageApi] = useState(() => createUsageApi(() => {
82
+ var _a;
83
+ const context = getApiContext();
84
+ const credential = passportRef.current;
85
+ const matches = (credential == null ? void 0 : credential.userId) === context.userStatus.userId && (credential == null ? void 0 : credential.uid) === ((_a = context.userStatus.profile) == null ? void 0 : _a.id) && (credential == null ? void 0 : credential.productName) === context.productName;
86
+ return { ...context, passport: matches ? credential == null ? void 0 : credential.passport : void 0 };
87
+ }));
88
+ const [uploadApi] = useState(() => createUploadApi(getApiContext));
71
89
  useEffect(() => {
72
90
  userStatusRef.current = userStatus;
73
91
  }, [userStatus]);
@@ -111,7 +129,8 @@ const YiChongCanvaProvider = ({
111
129
  setLoginStatus("loading");
112
130
  handleLogin({
113
131
  appId,
114
- productName
132
+ productName,
133
+ onPassport
115
134
  }).then((userStatus2) => {
116
135
  setLoginStatus("success");
117
136
  updateUserStatus(userStatus2);
@@ -174,6 +193,7 @@ const YiChongCanvaProvider = ({
174
193
  getUserProfile({
175
194
  productName,
176
195
  userId,
196
+ onPassport,
177
197
  isSubscribe: true,
178
198
  baseline,
179
199
  // 会话时长由 sessionTtlMs 主导;次数上限只作双保险
@@ -405,6 +425,7 @@ const YiChongCanvaProvider = ({
405
425
  getUserProfile({
406
426
  productName,
407
427
  userId: (window == null ? void 0 : window.userId) || "",
428
+ onPassport,
408
429
  maxCount: 2,
409
430
  successCallback(userStatus2) {
410
431
  userStatus2.userId = (window == null ? void 0 : window.userId) || "";
@@ -565,6 +586,9 @@ const YiChongCanvaProvider = ({
565
586
  {
566
587
  value: {
567
588
  ...predictionApi,
589
+ ...textModerationApi,
590
+ ...usageApi,
591
+ ...uploadApi,
568
592
  userStatus,
569
593
  updateUserStatus,
570
594
  handleLogin: login,
@@ -3,5 +3,12 @@ export declare class ApiError extends Error {
3
3
  readonly code: string | number;
4
4
  readonly status?: number | undefined;
5
5
  readonly userMessage: string;
6
- constructor(message: string, code: string | number, status?: number | undefined);
6
+ /** 后端错误 data 原样保留,例如 error_code / request_id / retryable。 */
7
+ readonly data?: Record<string, unknown>;
8
+ /** Retry-After 响应头的秒数;工具包不会自动重试。 */
9
+ readonly retryAfter?: number;
10
+ constructor(message: string, code: string | number, status?: number | undefined, details?: {
11
+ data?: Record<string, unknown>;
12
+ retryAfter?: number;
13
+ });
7
14
  }
@@ -1,2 +1,2 @@
1
1
  export { ApiError } from './error';
2
- export type { ApiRequestOptions, ApiResponse, CreateSpecifyPredictionParams, GetPredictionParams, JsonObject, JsonValue, Prediction, PredictionApi, } from './types';
2
+ export type { ApiRequestOptions, ApiResponse, CompleteUploadParams, CompleteUploadResponse, TextCheckParams, CreateSpecifyPredictionParams, GetPredictionParams, GeneratePresignedUrlParams, GetUploadUrlParams, InitiateUploadParams, InitiateUploadResponse, JsonObject, JsonValue, Prediction, PredictionApi, PresignedUrlResponse, TextModerationApi, TextModerationCategory, TextModerationDecision, TextModerationResult, UploadApi, UploadFileParams, UploadFileResult, UploadedPart, UploadPartUrlResponse, UsageApi, UsageParams, UsageResponse, } from './types';
@@ -0,0 +1,4 @@
1
+ import { ApiContext } from './request';
2
+ import { TextModerationApi } from './types';
3
+ /** 内部绑定函数;对外只通过现有 Provider / hook 使用。 */
4
+ export declare function createTextModerationApi(getContext: () => ApiContext): TextModerationApi;
@@ -1,4 +1,5 @@
1
1
  import { UserStatus } from '../login/interface';
2
+ import { ApiError } from './error';
2
3
  import { ApiRequestOptions, ApiResponse, JsonObject } from './types';
3
4
  /** 内部读取 Provider 的当前状态,不从 window / localStorage 读取 API 凭据。 */
4
5
  export interface ApiContext {
@@ -7,9 +8,20 @@ export interface ApiContext {
7
8
  apiBaseUrl: string;
8
9
  getLocale?: () => string;
9
10
  }
11
+ declare const apiPaths: {
12
+ readonly createSpecifyPrediction: "/replicate/createSpecifyPrediction";
13
+ readonly getPrediction: "/replicate/getPrediction";
14
+ readonly textCheck: "/api/public/text-moderation/check";
15
+ };
10
16
  export declare function isObject(value: unknown): value is Record<string, unknown>;
11
17
  export declare function isNonemptyString(value: unknown): value is string;
12
18
  export declare function invalid(message: string): never;
13
19
  /** 防止 stringify 悄悄删掉 undefined / 函数,或把 NaN / Infinity 转成 null。 */
14
20
  export declare function validateJson(value: unknown, ancestors?: Set<object>): void;
15
- export declare function postApi<T>(context: ApiContext, method: "createSpecifyPrediction" | "getPrediction", params: JsonObject, options?: ApiRequestOptions): Promise<ApiResponse<T>>;
21
+ export declare function language(getLocale?: () => string): string;
22
+ export declare function endpoint(baseUrl: string, path: string): URL;
23
+ export declare function addContextQuery(url: URL, context: ApiContext): void;
24
+ export declare function readJson(response: Response): Promise<unknown>;
25
+ export declare function backendError(response: Response, payload: unknown, fallbackCode: string | number): ApiError;
26
+ export declare function postApi<T>(context: ApiContext, method: keyof typeof apiPaths, params: JsonObject, options?: ApiRequestOptions): Promise<ApiResponse<T>>;
27
+ export {};
@@ -0,0 +1,4 @@
1
+ import { ApiRequestOptions } from './types';
2
+ /** 一次操作共用超时和取消信号,包含响应正文;不重试任何请求。 */
3
+ export declare function withRequest<T>(options: ApiRequestOptions, work: (signal: AbortSignal) => Promise<T>): Promise<T>;
4
+ export declare function throwIfAborted(signal: AbortSignal): void;
@@ -11,6 +11,30 @@ export interface CreateSpecifyPredictionParams {
11
11
  export interface GetPredictionParams {
12
12
  id: string;
13
13
  }
14
+ export interface TextCheckParams {
15
+ /** 完整原文;最多 1024 个 Unicode 字符且最多 1024 个 UTF-8 字节。 */
16
+ text: string;
17
+ /** 省略时由后端使用 default。 */
18
+ scene?: "default";
19
+ }
20
+ export type TextModerationDecision = "pass" | "review" | "block";
21
+ export interface TextModerationCategory {
22
+ score: number;
23
+ decision: TextModerationDecision;
24
+ }
25
+ export interface TextModerationResult {
26
+ request_id: string;
27
+ scene: string;
28
+ decision: TextModerationDecision;
29
+ /** 使用后端的放行结果;只有 allowed === true 时才继续业务操作。 */
30
+ allowed: boolean;
31
+ flagged_categories: string[];
32
+ categories: Record<string, TextModerationCategory>;
33
+ policy_version: string;
34
+ model: string;
35
+ duration_ms: number;
36
+ [key: string]: unknown;
37
+ }
14
38
  /** 保留后端响应结构;HTTP 或 code 非 0 时抛出 ApiError。 */
15
39
  export interface ApiResponse<T> {
16
40
  code: 0;
@@ -41,3 +65,96 @@ export interface PredictionApi {
41
65
  /** 只查询一次;code=0 且 status=failed 仍返回任务信息。 */
42
66
  getPrediction(params: GetPredictionParams, options?: ApiRequestOptions): Promise<ApiResponse<Prediction>>;
43
67
  }
68
+ export interface TextModerationApi {
69
+ /** 调用公共文本审核入口;内容拒绝仍返回 code=0。 */
70
+ textCheck(params: TextCheckParams, options?: ApiRequestOptions): Promise<ApiResponse<TextModerationResult>>;
71
+ }
72
+ export interface UsageParams {
73
+ /** 消费数量;reduceFreeCnt / addMonthlyUsage 最多两位小数,addFreeUsageCnt 最多一位。 */
74
+ cnt: number;
75
+ }
76
+ /** 账户服务使用 ok=0,与 AI 服务的 code=0 合同不同。 */
77
+ export interface UsageResponse {
78
+ ok: 0;
79
+ msg: string;
80
+ [key: string]: unknown;
81
+ }
82
+ export interface UsageApi {
83
+ reduceFreeCnt(params: UsageParams, options?: ApiRequestOptions): Promise<UsageResponse>;
84
+ addMonthlyUsage(params: UsageParams, options?: ApiRequestOptions): Promise<UsageResponse>;
85
+ addFreeUsageCnt(params: UsageParams, options?: ApiRequestOptions): Promise<UsageResponse>;
86
+ }
87
+ export interface GeneratePresignedUrlParams {
88
+ objectName: string;
89
+ /** 默认 video。 */
90
+ bucketName?: string;
91
+ }
92
+ export interface PresignedUrlResponse {
93
+ success: true;
94
+ /** 只用于 PUT,不能追加身份、渠道或其他 query。 */
95
+ url: string;
96
+ /** 一键上传用此字段构造公开资源地址。 */
97
+ endpointBaseUrl?: string;
98
+ message?: string;
99
+ [key: string]: unknown;
100
+ }
101
+ export interface UploadFileParams {
102
+ /** 非空 File / Blob;达到 100 MiB 时自动分片。 */
103
+ file: Blob;
104
+ /** Blob 没有文件名时可显式提供,用于生成对象名的扩展名。 */
105
+ fileName?: string;
106
+ bucketName?: string;
107
+ /** 省略时自动生成 temp_<产品渠道>_<日期>_<随机值>.<扩展名>。 */
108
+ objectName?: string;
109
+ /** true 时小文件也使用分片;省略或 false 时按文件大小选择。 */
110
+ multipart?: boolean;
111
+ }
112
+ export interface InitiateUploadParams extends GeneratePresignedUrlParams {
113
+ contentType?: string;
114
+ }
115
+ /** 保留 S3 原始字段名及附加字段。 */
116
+ export interface InitiateUploadResponse {
117
+ UploadId: string;
118
+ Bucket?: string;
119
+ Key?: string;
120
+ [key: string]: unknown;
121
+ }
122
+ export interface GetUploadUrlParams extends GeneratePresignedUrlParams {
123
+ uploadId: string;
124
+ /** 1 到 10000 的整数。 */
125
+ partNumber: number;
126
+ }
127
+ export interface UploadPartUrlResponse {
128
+ url: string;
129
+ [key: string]: unknown;
130
+ }
131
+ export interface UploadedPart {
132
+ /** 保留 R2 PUT 返回的 ETag,包括引号。 */
133
+ ETag: string;
134
+ PartNumber: number;
135
+ }
136
+ export interface CompleteUploadParams extends GeneratePresignedUrlParams {
137
+ uploadId: string;
138
+ /** 已上传分片,按 PartNumber 升序排列。 */
139
+ parts: UploadedPart[];
140
+ }
141
+ export interface CompleteUploadResponse {
142
+ ETag: string;
143
+ Bucket?: string;
144
+ Key?: string;
145
+ Location?: string;
146
+ [key: string]: unknown;
147
+ }
148
+ export interface UploadFileResult {
149
+ url: string;
150
+ key: string;
151
+ endpointBaseUrl: string;
152
+ }
153
+ export interface UploadApi {
154
+ generatePresignedUrl(params: GeneratePresignedUrlParams, options?: ApiRequestOptions): Promise<PresignedUrlResponse>;
155
+ initiateUpload(params: InitiateUploadParams, options?: ApiRequestOptions): Promise<InitiateUploadResponse>;
156
+ getUploadUrl(params: GetUploadUrlParams, options?: ApiRequestOptions): Promise<UploadPartUrlResponse>;
157
+ completeUpload(params: CompleteUploadParams, options?: ApiRequestOptions): Promise<CompleteUploadResponse>;
158
+ /** 自动完成上传;单次 PUT 默认 120 秒,分片整体默认 30 分钟。合并成功后返回公开 URL。 */
159
+ uploadFile(params: UploadFileParams, options?: ApiRequestOptions): Promise<UploadFileResult>;
160
+ }
@@ -0,0 +1,6 @@
1
+ import { ApiContext } from './request';
2
+ import { UploadApi } from './types';
3
+ export interface UploadContext extends ApiContext {
4
+ uploadBaseUrl: string;
5
+ }
6
+ export declare function createUploadApi(getContext: () => UploadContext): UploadApi;
@@ -0,0 +1,9 @@
1
+ import { ApiContext } from './request';
2
+ import { UsageApi } from './types';
3
+ export interface UsageContext extends ApiContext {
4
+ baseUrl: string;
5
+ /** 只由 Provider 内部提供,绑定当前已验证的账户。 */
6
+ passport?: string;
7
+ }
8
+ /** 只提交调用方指定的消费,不重算套餐、拆分消费或乐观修改余额。 */
9
+ export declare function createUsageApi(getContext: () => UsageContext): UsageApi;
@@ -1,5 +1,5 @@
1
1
  import { default as React } from 'react';
2
- import { PredictionApi } from '../api/types';
2
+ import { PredictionApi, TextModerationApi, UploadApi, UsageApi } from '../api/types';
3
3
  import { canUseError, CheckoutSessionOptions, TestMode, UserStatus } from './interface';
4
4
  /**
5
5
  *
@@ -17,7 +17,7 @@ import { canUseError, CheckoutSessionOptions, TestMode, UserStatus } from './int
17
17
  * @property {() => string} getPricingLink 获取付费链接
18
18
  * @property {() => void} updateTestMode 更新测试模式, 只有在开发环境下有效
19
19
  */
20
- export interface YiChongCanvaContextType extends PredictionApi {
20
+ export interface YiChongCanvaContextType extends PredictionApi, TextModerationApi, UsageApi, UploadApi {
21
21
  userStatus: UserStatus;
22
22
  updateUserStatus: (user: Partial<UserStatus>) => void;
23
23
  handleLogin: () => void;
@@ -1,5 +1,5 @@
1
1
  import { UserStatus } from './../interface';
2
- export declare function handleLogin({ appId, productName, }: LoginProps): Promise<UserStatus>;
2
+ export declare function handleLogin({ appId, productName, onPassport, }: LoginProps): Promise<UserStatus>;
3
3
  /**
4
4
  * 订阅比较基线:打开定价页「之前」的用户状态快照。
5
5
  * 由 Provider 在会话开始时用当时的 userStatus 生成(takeSubscribeBaseline),
@@ -48,7 +48,7 @@ export declare function isSubscribeChanged(current: UserStatus, baseline: Subscr
48
48
  * 2. 手动停止(onStop 交出的函数被调用):打断等待中的 sleep,return undefined(不算失败)
49
49
  * 3. maxCount 次数耗尽或 maxDurationMs 到期:failCallback + throw
50
50
  */
51
- export declare function getUserProfile({ maxCount, interval, maxDurationMs, productName, userId, successCallback, failCallback, isSubscribe, baseline, isChanged, onStop, }: UserProfileProps): Promise<UserStatus | undefined>;
51
+ export declare function getUserProfile({ maxCount, interval, maxDurationMs, productName, userId, successCallback, failCallback, isSubscribe, baseline, isChanged, onStop, onPassport, }: UserProfileProps): Promise<UserStatus | undefined>;
52
52
  export interface UserProfileProps {
53
53
  maxCount?: number;
54
54
  interval?: number | (() => number);
@@ -61,12 +61,14 @@ export interface UserProfileProps {
61
61
  baseline?: SubscribeBaseline;
62
62
  isChanged?: (current: UserStatus, baseline: SubscribeBaseline) => boolean;
63
63
  onStop?: (fn: () => void) => void;
64
+ onPassport?: (passport: string, userId: string, uid: string) => void;
64
65
  }
65
66
  export interface LoginProps {
66
67
  callback?: (state: LoginState) => void;
67
68
  appId: string;
68
69
  productName: string;
69
70
  requestConfig?: UserProfileProps;
71
+ onPassport?: UserProfileProps["onPassport"];
70
72
  }
71
73
  export interface LoginState {
72
74
  status: "finish" | "error" | "start" | "user_id";
@@ -18,6 +18,8 @@ export interface YiChongCanvaProviderProps {
18
18
  baseUrl: string;
19
19
  /** AI 接口地址;baseUrl 仍用于原有账户扣费接口。 */
20
20
  apiBaseUrl?: string;
21
+ /** R2 签名服务根地址,默认 https://ai.imgkits.com。 */
22
+ uploadBaseUrl?: string;
21
23
  /** 每次 API 请求读取当前界面语言,默认使用浏览器语言。 */
22
24
  getLocale?: () => string;
23
25
  autoLogin?: boolean;
@@ -39,4 +41,4 @@ export interface YiChongCanvaProviderProps {
39
41
  * @param {string} params0.mode 测试模式
40
42
  * @returns
41
43
  */
42
- export declare const YiChongCanvaProvider: ({ children, appId, productName, onUpdateUserStatus, baseUrl, apiBaseUrl, getLocale, autoLogin, testMode: _testMode, version, mode, retry, maxAvailablePoints, }: YiChongCanvaProviderProps) => React.JSX.Element;
44
+ export declare const YiChongCanvaProvider: ({ children, appId, productName, onUpdateUserStatus, baseUrl, apiBaseUrl, uploadBaseUrl, getLocale, autoLogin, testMode: _testMode, version, mode, retry, maxAvailablePoints, }: YiChongCanvaProviderProps) => React.JSX.Element;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yichong-canva2",
3
- "version": "1.1.28",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",