yichong-canva2 1.4.0 → 2.1.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.
@@ -58,6 +58,7 @@ async function initiate(context, params, signal) {
58
58
  contentType: params.contentType
59
59
  }, signal);
60
60
  if (!isNonemptyString(payload.UploadId)) throw new ApiError("Backend did not return UploadId.", "invalid_response");
61
+ if (payload.endpointBaseUrl !== void 0) httpsUrl(payload.endpointBaseUrl, true);
61
62
  return payload;
62
63
  }
63
64
  async function partUrl(context, params, signal) {
@@ -89,6 +90,7 @@ async function complete(context, params, signal) {
89
90
  parts
90
91
  }, signal);
91
92
  if (!isNonemptyString(payload.ETag)) throw new ApiError("Backend did not confirm multipart completion with ETag.", "invalid_response");
93
+ if (payload.endpointBaseUrl !== void 0) httpsUrl(payload.endpointBaseUrl, true);
92
94
  return payload;
93
95
  }
94
96
  function httpsUrl(value, publicBase = false) {
@@ -98,7 +100,7 @@ function httpsUrl(value, publicBase = false) {
98
100
  } catch {
99
101
  throw new ApiError("Backend returned an invalid upload URL.", "invalid_response");
100
102
  }
101
- if (url.protocol !== "https:" || url.username || url.password || url.hash || publicBase && url.search) {
103
+ if (url.protocol !== "https:" || url.username || url.password || url.hash || publicBase && /[?#]/.test(url.href)) {
102
104
  throw new ApiError("Upload URLs must be HTTPS without credentials or fragments.", "invalid_response");
103
105
  }
104
106
  return url;
@@ -133,13 +135,97 @@ async function presign(context, params, signal) {
133
135
  if (payload.endpointBaseUrl !== void 0) httpsUrl(payload.endpointBaseUrl, true);
134
136
  return payload;
135
137
  }
138
+ function putWithProgress(url, file, contentType, signal, onProgress, check) {
139
+ if (typeof XMLHttpRequest === "undefined") {
140
+ throw new ApiError("Upload progress requires a browser with XMLHttpRequest.", "unsupported_environment");
141
+ }
142
+ return new Promise((resolve, reject) => {
143
+ const xhr = new XMLHttpRequest();
144
+ let settled = false;
145
+ const cleanup = () => {
146
+ signal.removeEventListener("abort", onAbort);
147
+ xhr.upload.removeEventListener("progress", progress);
148
+ xhr.removeEventListener("load", loaded);
149
+ xhr.removeEventListener("error", failed);
150
+ xhr.removeEventListener("abort", canceled);
151
+ xhr.removeEventListener("timeout", timedOut);
152
+ };
153
+ const finish = (error) => {
154
+ if (settled) return;
155
+ settled = true;
156
+ cleanup();
157
+ if (error !== void 0) reject(error);
158
+ else resolve();
159
+ };
160
+ const onAbort = () => {
161
+ finish(new ApiError("Request canceled.", "aborted"));
162
+ xhr.abort();
163
+ };
164
+ const progress = (event) => {
165
+ if (settled) return;
166
+ try {
167
+ check();
168
+ onProgress({ loaded: event.loaded, ...event.lengthComputable ? { total: event.total } : {} });
169
+ } catch (error) {
170
+ finish(error);
171
+ xhr.abort();
172
+ }
173
+ };
174
+ const loaded = () => {
175
+ if (settled) return;
176
+ try {
177
+ check();
178
+ if (xhr.status < 200 || xhr.status >= 300) {
179
+ throw new ApiError(`File upload failed (HTTP ${xhr.status}).`, "upload_failed", xhr.status);
180
+ }
181
+ finish();
182
+ } catch (error) {
183
+ finish(error);
184
+ }
185
+ };
186
+ const failed = () => finish(new ApiError("Unable to connect to the upload service.", "network_error"));
187
+ const canceled = () => finish(new ApiError("Request canceled.", "aborted"));
188
+ const timedOut = () => finish(new ApiError("Request timed out.", "timeout"));
189
+ try {
190
+ check();
191
+ xhr.open("PUT", url, true);
192
+ xhr.withCredentials = false;
193
+ xhr.setRequestHeader("Content-Type", contentType);
194
+ xhr.upload.addEventListener("progress", progress);
195
+ xhr.addEventListener("load", loaded);
196
+ xhr.addEventListener("error", failed);
197
+ xhr.addEventListener("abort", canceled);
198
+ xhr.addEventListener("timeout", timedOut);
199
+ signal.addEventListener("abort", onAbort, { once: true });
200
+ check();
201
+ xhr.send(file);
202
+ } catch (error) {
203
+ finish(error);
204
+ }
205
+ });
206
+ }
207
+ function randomString(len = 32) {
208
+ const chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
209
+ let pwd = "";
210
+ for (let i = 0; i < len; i++) {
211
+ pwd += chars.charAt(Math.floor(Math.random() * chars.length));
212
+ }
213
+ return pwd;
214
+ }
215
+ function getFileType(file, fileName) {
216
+ const name = fileName || ("name" in file && typeof file.name === "string" ? file.name : "");
217
+ if (name) {
218
+ const dotIndex = name.lastIndexOf(".");
219
+ if (dotIndex !== -1) return name.slice(dotIndex + 1).toLowerCase();
220
+ }
221
+ const slashIndex = file.type.lastIndexOf("/");
222
+ return slashIndex !== -1 ? file.type.slice(slashIndex + 1).toLowerCase() : "";
223
+ }
136
224
  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";
225
+ const extension = getFileType(file, fileName) || "bin";
140
226
  const now = /* @__PURE__ */ new Date();
141
227
  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}`);
228
+ return objectName(`temp_${productName}_${day}_${randomString(32)}.${extension}`);
143
229
  }
144
230
  function createUploadApi(getContext) {
145
231
  return {
@@ -149,10 +235,11 @@ function createUploadApi(getContext) {
149
235
  completeUpload: (params, options = {}) => withRequest(options, (signal) => complete(getContext(), params, signal)),
150
236
  async uploadFile(params, options = {}) {
151
237
  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))) {
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))) {
153
239
  invalid("uploadFile requires a nonempty file within the R2 object size limit and valid upload parameters.");
154
240
  }
155
241
  const file = params.file;
242
+ const onUploadProgress = params.onUploadProgress;
156
243
  const multipart = params.multipart === true || file.size >= multipartThreshold;
157
244
  const context = getContext();
158
245
  const key = params.objectName === void 0 ? fileObjectName(file, params.fileName, context.productName) : objectName(params.objectName);
@@ -168,10 +255,17 @@ function createUploadApi(getContext) {
168
255
  };
169
256
  return withRequest({ ...options, timeoutMs: options.timeoutMs ?? (multipart ? 30 * 6e4 : 12e4) }, async (signal) => {
170
257
  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);
258
+ let base;
174
259
  const contentType = file.type || "application/octet-stream";
260
+ const progress = (value) => {
261
+ check(signal);
262
+ try {
263
+ onUploadProgress == null ? void 0 : onUploadProgress(value);
264
+ } catch {
265
+ throw new ApiError("Upload progress callback failed.", "upload_progress_failed");
266
+ }
267
+ check(signal);
268
+ };
175
269
  const put = async (url, body) => {
176
270
  check(signal);
177
271
  const response = await fetch(url, {
@@ -189,7 +283,11 @@ function createUploadApi(getContext) {
189
283
  if (multipart) {
190
284
  const session = await initiate(context, { objectName: key, bucketName: bucket, contentType }, signal);
191
285
  check(signal);
286
+ const publicBase = session.endpointBaseUrl === void 0 ? (await presign(context, { objectName: key, bucketName: bucket }, signal)).endpointBaseUrl : session.endpointBaseUrl;
287
+ check(signal);
288
+ base = httpsUrl(publicBase, true).href.replace(/\/+$/, "");
192
289
  const partSize = Math.max(5 * MiB, Math.ceil(file.size / maxParts / MiB) * MiB);
290
+ const partCount = Math.ceil(file.size / partSize);
193
291
  const parts = [];
194
292
  for (let start = 0; start < file.size; start += partSize) {
195
293
  check(signal);
@@ -201,12 +299,24 @@ function createUploadApi(getContext) {
201
299
  throw new ApiError("R2 did not expose ETag. Configure the bucket CORS ExposeHeaders to include ETag.", "missing_etag", response.status);
202
300
  }
203
301
  parts.push({ ETag: etag, PartNumber: number });
302
+ progress({ loaded: parts.length, total: partCount });
204
303
  }
205
304
  check(signal);
206
- await complete(context, { objectName: key, bucketName: bucket, uploadId: session.UploadId, parts }, signal);
305
+ const completed = await complete(context, { objectName: key, bucketName: bucket, uploadId: session.UploadId, parts }, signal);
207
306
  check(signal);
307
+ if (completed.endpointBaseUrl !== void 0) {
308
+ base = httpsUrl(completed.endpointBaseUrl, true).href.replace(/\/+$/, "");
309
+ }
208
310
  } else {
209
- await put(signed.url, file);
311
+ const signed = await presign(context, { objectName: key, bucketName: bucket }, signal);
312
+ base = httpsUrl(signed.endpointBaseUrl, true).href.replace(/\/+$/, "");
313
+ check(signal);
314
+ if (onUploadProgress) {
315
+ await putWithProgress(signed.url, file, contentType, signal, progress, () => check(signal));
316
+ check(signal);
317
+ } else {
318
+ await put(signed.url, file);
319
+ }
210
320
  }
211
321
  return { url: `${base}/${key.split("/").map(encodeURIComponent).join("/")}`, key, endpointBaseUrl: base };
212
322
  });
package/dist/api/usage.js CHANGED
@@ -8,13 +8,12 @@ const paths = {
8
8
  };
9
9
  function createUsageApi(getContext) {
10
10
  const post = async (method, params, options = {}) => {
11
- const digits = method === "addFreeUsageCnt" ? 1 : 2;
12
11
  if (!isObject(params) || typeof params.cnt !== "number" || !Number.isFinite(params.cnt) || params.cnt <= 0 || Object.keys(params).some((key) => key !== "cnt")) {
13
12
  invalid(`${method} requires a positive cnt number.`);
14
13
  }
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.`);
14
+ const maximumCnt = Number.MAX_SAFE_INTEGER / (method === "addFreeUsageCnt" ? 10 : 100);
15
+ if (params.cnt > maximumCnt) {
16
+ invalid(`${method} requires cnt within the safe numeric range.`);
18
17
  }
19
18
  return withRequest({ ...options, timeoutMs: options.timeoutMs ?? 3e4 }, async (signal) => {
20
19
  var _a;
@@ -42,6 +42,9 @@ const YiChongCanvaContext = React.createContext(
42
42
  contentExtract: async () => {
43
43
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
44
44
  },
45
+ chat: async () => {
46
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
47
+ },
45
48
  reportError: async () => {
46
49
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
47
50
  },
@@ -7,6 +7,7 @@ import { getAppVersion } from "./version.js";
7
7
  import { createPredictionApi } from "../api/predictions.js";
8
8
  import { createTextModerationApi } from "../api/moderation.js";
9
9
  import { createContentExtractionApi } from "../api/content.js";
10
+ import { createChatApi } from "../api/chat.js";
10
11
  import { createUsageApi } from "../api/usage.js";
11
12
  import { createUploadApi } from "../api/uploads.js";
12
13
  import { createErrorReportingApi } from "../api/reporting.js";
@@ -55,6 +56,7 @@ const YiChongCanvaProvider = ({
55
56
  baseUrl,
56
57
  apiBaseUrl = "https://api.imgkits.com",
57
58
  contentBaseUrl = "https://ai.imgkits.com",
59
+ chatBaseUrl = "https://ai.imgkits.com",
58
60
  uploadBaseUrl = "https://ai.imgkits.com",
59
61
  getLocale,
60
62
  autoLogin = true,
@@ -75,8 +77,8 @@ const YiChongCanvaProvider = ({
75
77
  const sessionStopRef = useRef(null);
76
78
  const [loginStatus, setLoginStatus] = useState("idle");
77
79
  const userStatusRef = useRef({});
78
- const apiConfigRef = useRef({ apiBaseUrl, contentBaseUrl, baseUrl, uploadBaseUrl, productName, appId, version, getLocale });
79
- apiConfigRef.current = { apiBaseUrl, contentBaseUrl, baseUrl, uploadBaseUrl, productName, appId, version, getLocale };
80
+ const apiConfigRef = useRef({ apiBaseUrl, contentBaseUrl, chatBaseUrl, baseUrl, uploadBaseUrl, productName, appId, version, getLocale });
81
+ apiConfigRef.current = { apiBaseUrl, contentBaseUrl, chatBaseUrl, baseUrl, uploadBaseUrl, productName, appId, version, getLocale };
80
82
  const passportRef = useRef(null);
81
83
  const onPassport = (passport, userId, uid) => {
82
84
  passportRef.current = { passport, userId, uid, productName };
@@ -91,6 +93,10 @@ const YiChongCanvaProvider = ({
91
93
  ...getApiContext(),
92
94
  apiBaseUrl: apiConfigRef.current.contentBaseUrl
93
95
  })));
96
+ const [chatApi] = useState(() => createChatApi(() => ({
97
+ ...getApiContext(),
98
+ apiBaseUrl: apiConfigRef.current.chatBaseUrl
99
+ })));
94
100
  const [usageApi] = useState(() => createUsageApi(() => {
95
101
  var _a;
96
102
  const context = getApiContext();
@@ -611,6 +617,7 @@ const YiChongCanvaProvider = ({
611
617
  ...predictionApi,
612
618
  ...textModerationApi,
613
619
  ...contentExtractionApi,
620
+ ...chatApi,
614
621
  ...usageApi,
615
622
  ...uploadApi,
616
623
  ...errorReportingApi,
@@ -0,0 +1,9 @@
1
+ import { ApiContext } from './request';
2
+ import { ChatApi } from './types';
3
+ /**
4
+ * 将同步大模型接口绑定到 Provider;应用通过 client.chat() 调用,不需另建 API 包装层。
5
+ * getContext 在每次调用时读取当前账号、语言和服务地址,避免工厂创建时锁住旧 JWT。
6
+ * 返回后端原始响应包,完整文本位于 data.result;这里只发起一次请求,不轮询、重试或扣费。
7
+ * 消息语义、模型选择与回退由后端处理;传入 model 并不代表后端一定使用该模型。
8
+ */
9
+ export declare function createChatApi(getContext: () => ApiContext): ChatApi;
@@ -1,4 +1,8 @@
1
1
  import { ApiContext } from './request';
2
2
  import { ContentExtractionApi } from './types';
3
- /** 内部绑定函数;对外只通过现有 Provider / hook 使用。 */
3
+ /**
4
+ * 绑定文件、视频和网页内容提取接口;接收可访问的 URL,不负责先上传本地文件。
5
+ * 每次调用从 Provider 获取当前身份;返回完整响应包,提取文本位于 data.content。
6
+ * 提取期间只等待一次同步请求,不轮询、不自动重试,也不自动调用 Chat 或消费接口。
7
+ */
4
8
  export declare function createContentExtractionApi(getContext: () => ApiContext): ContentExtractionApi;
@@ -1,12 +1,24 @@
1
- /** message / userMessage 保留服务端翻译后的 msg,供应用展示。 */
1
+ /**
2
+ * 具名后端 API 统一使用的异常,可用 instanceof ApiError 区分。
3
+ * 多数后端接口保留有效的 msg/message;上报 Worker 失败、本地校验、网络和取消使用统一文案。
4
+ * code 用于业务分支,status 仅表示可用的 HTTP 状态;不要从文案中解析错误类型。
5
+ * 例如 aborted 可按主动取消处理,account_not_ready 表示账号凭据尚未就绪。
6
+ */
2
7
  export declare class ApiError extends Error {
3
8
  readonly code: string | number;
4
9
  readonly status?: number | undefined;
10
+ /** 与 Error.message 相同,可用于界面展示;不保证所有本地错误文案已经本地化。 */
5
11
  readonly userMessage: string;
6
- /** 后端错误 data 原样保留,例如 error_code / request_id / retryable。 */
12
+ /** 经公共后端错误处理器读取的对象型 data,如 error_code/request_id;部分接口不返回此字段。 */
7
13
  readonly data?: Record<string, unknown>;
8
14
  /** Retry-After 响应头的秒数;工具包不会自动重试。 */
9
15
  readonly retryAfter?: number;
16
+ /**
17
+ * @param message 可展示的错误说明。
18
+ * @param code 后端业务码或 SDK 标识,例如 invalid_request、timeout、network_error。
19
+ * @param status 已取得的 HTTP 状态;请求发出前的错误等情况通常没有此值。
20
+ * @param details 可选诊断数据和 Retry-After 秒数;仅提供信息,不触发重试。
21
+ */
10
22
  constructor(message: string, code: string | number, status?: number | undefined, details?: {
11
23
  data?: Record<string, unknown>;
12
24
  retryAfter?: number;
@@ -1,2 +1,7 @@
1
+ /**
2
+ * 后端 API 的公共类型与异常出口。
3
+ * 实现工厂保持内部使用,业务通过 Provider 的 client 调用方法,共享登录身份和配置。
4
+ * 参数、返回值及方法的 JSDoc 定义在 types.ts,会随声明文件发布供编辑器提示。
5
+ */
1
6
  export { ApiError } from './error';
2
- export type { ApiRequestOptions, ApiResponse, CompleteUploadParams, CompleteUploadResponse, ContentExtractParams, ContentExtractResult, ContentExtractionApi, TextCheckParams, CreateSpecifyPredictionParams, ErrorReportingApi, ErrorReportSource, GetPredictionParams, GeneratePresignedUrlParams, GetUploadUrlParams, InitiateUploadParams, InitiateUploadResponse, JsonObject, JsonValue, Prediction, PredictionApi, ReportErrorParams, ReportErrorResult, PresignedUrlResponse, TextModerationApi, TextModerationCategory, TextModerationDecision, TextModerationResult, UploadApi, UploadFileParams, UploadFileResult, UploadedPart, UploadPartUrlResponse, UsageApi, UsageParams, UsageResponse, } from './types';
7
+ export type { ApiRequestOptions, ApiResponse, ChatApi, ChatParams, ChatPayload, ChatResult, CompleteUploadParams, CompleteUploadResponse, ContentExtractParams, ContentExtractResult, ContentExtractionApi, TextCheckParams, CreateSpecifyPredictionParams, ErrorReportingApi, ErrorReportSource, GetPredictionParams, GeneratePresignedUrlParams, GetUploadUrlParams, InitiateUploadParams, InitiateUploadResponse, JsonObject, JsonValue, Prediction, PredictionApi, ReportErrorParams, ReportErrorResult, PresignedUrlResponse, TextModerationApi, TextModerationCategory, TextModerationDecision, TextModerationResult, UploadApi, UploadFileParams, UploadFileResult, UploadedPart, UploadPartUrlResponse, UploadProgress, UsageApi, UsageParams, UsageResponse, } from './types';
@@ -1,4 +1,8 @@
1
1
  import { ApiContext } from './request';
2
2
  import { TextModerationApi } from './types';
3
- /** 内部绑定函数;对外只通过现有 Provider / hook 使用。 */
3
+ /**
4
+ * 绑定文本审核能力,对外名为 client.textCheck(),后端仍使用 public 审核路由。
5
+ * 返回含 allowed / decision / categories 的原始响应;应用应根据结果控制后续业务。
6
+ * 本方法不会自动发起生成或扣费,审核请求本身也不会被 SDK 自动重试。
7
+ */
4
8
  export declare function createTextModerationApi(getContext: () => ApiContext): TextModerationApi;
@@ -1,4 +1,8 @@
1
1
  import { ApiContext } from './request';
2
2
  import { PredictionApi } from './types';
3
- /** 内部绑定函数;对外只通过现有 Provider / hook 使用。 */
3
+ /**
4
+ * 将后端同名的任务创建/查询接口绑定到 Provider,保留参数名与原始响应结构。
5
+ * 创建仅返回任务 ID,查询仅取得一次状态;轮询间隔、取消业务与结果展示由应用编排。
6
+ * 两种调用都只发送一次请求,不自动重试、审核输入或记录消费,避免重复创建/扣费。
7
+ */
4
8
  export declare function createPredictionApi(getContext: () => ApiContext): PredictionApi;
@@ -1,9 +1,16 @@
1
1
  import { ApiContext } from './request';
2
2
  import { ErrorReportingApi } from './types';
3
+ /** 上报的应用/账号归属由 Provider 注入;passport 只参与脱敏,不会作为上报认证票据。 */
3
4
  export interface ReportingContext extends Pick<ApiContext, "userStatus" | "productName"> {
4
5
  appId: string;
5
6
  version: number;
6
7
  /** 只用于从诊断内容中移除当前账户凭据。 */
7
8
  passport?: string;
8
9
  }
10
+ /**
11
+ * 绑定显式错误上报能力:整理诊断信息,交由现有 Worker 转发到指定飞书机器人。
12
+ * 返回 Worker 的确认结果,不安装全局异常监听,也不在其他 API 失败时自动上报或重试。
13
+ * 登录失败本身也需要诊断,因此允许账号尚未就绪,用 unknown 标记缺失身份。
14
+ * 上报失败仍会抛出 ApiError,应用应单独捕获,避免它覆盖原来的业务异常。
15
+ */
9
16
  export declare function createErrorReportingApi(getContext: () => ReportingContext): ErrorReportingApi;
@@ -1,3 +1,8 @@
1
1
  import { JsonObject, ReportErrorParams } from './types';
2
- /** 只整理诊断信息;不读取 window/localStorage,不发送请求,不修改原错误。 */
2
+ /**
3
+ * 将 Error、字符串或其他异常值转换为体积受限的 JSON 诊断信息,供 reporting.ts 发送。
4
+ * 不读取 window/localStorage、不发送请求、不修改原错误;已知凭据由调用层显式传入。
5
+ * 按字段名、常见凭据文本和已知值做尽力脱敏,并限制深度、项数及文本长度。
6
+ * 任意业务文本仍可能包含个人信息,调用方应主动挑选 context,不能把此处当作全面匿名化。
7
+ */
3
8
  export declare function reportingPayload(params: ReportErrorParams, secrets?: readonly string[]): JsonObject;
@@ -1,12 +1,17 @@
1
1
  import { UserStatus } from '../login/interface';
2
2
  import { ApiError } from './error';
3
3
  import { ApiRequestOptions, ApiResponse, JsonObject } from './types';
4
- /** 内部读取 Provider 的当前状态,不从 window / localStorage 读取 API 凭据。 */
4
+ /**
5
+ * 各服务共用的调用上下文,由 Provider 在调用时提供当前快照。
6
+ * 身份来自已完成的登录流程,不从 window / localStorage 搜索或猜测 API 凭据。
7
+ * query 中的归属信息不是认证本身;各服务仍须使用其对应的认证协议。
8
+ */
5
9
  export interface CommonRequestContext {
6
10
  userStatus: UserStatus;
7
11
  productName: string;
8
12
  getLocale?: () => string;
9
13
  }
14
+ /** AI 网关上下文;具体能力可由 Provider 指向独立服务地址,但共用这里的请求协议。 */
10
15
  export interface ApiContext extends CommonRequestContext {
11
16
  apiBaseUrl: string;
12
17
  }
@@ -15,18 +20,52 @@ declare const apiPaths: {
15
20
  readonly getPrediction: "/replicate/getPrediction";
16
21
  readonly textCheck: "/api/public/text-moderation/check";
17
22
  readonly contentExtract: "/api/content-extract";
23
+ readonly chat: "/api/chat";
18
24
  };
25
+ /** 粗筛非空、非数组对象;是否属于普通 JSON 对象由 validateJson 进一步判断。 */
19
26
  export declare function isObject(value: unknown): value is Record<string, unknown>;
27
+ /** 仅判断是否含有效字符,不修改返回给后端的原始字符串及其首尾空白。 */
20
28
  export declare function isNonemptyString(value: unknown): value is string;
29
+ /** 统一标记本地参数错误,调用方可通过 code 区分它与网络或后端业务错误。 */
21
30
  export declare function invalid(message: string): never;
22
- /** 防止 stringify 悄悄删掉 undefined / 函数,或把 NaN / Infinity 转成 null。 */
31
+ /**
32
+ * 递归验证枚举到的参数值,防止 stringify 悄悄丢掉 undefined / 函数,或将非有限数改成 null。
33
+ * 只接受普通对象/数组等 JSON 值,拒绝 Date、类实例及循环引用,不执行自定义序列化逻辑。
34
+ * ancestors 只跟踪当前递归路径:同一对象被多个字段引用可以通过,真正的祖先回环才拒绝。
35
+ */
23
36
  export declare function validateJson(value: unknown, ancestors?: Set<object>): void;
37
+ /**
38
+ * 语言优先取 Provider 的实时回调,其次文档、浏览器,最后使用 en。
39
+ * 将区域标记规范化为 Accept-Language 可用值;若收到语言列表,仅使用第一项。
40
+ * 这里只生成请求头,浏览器请求不额外添加 accept_language 查询参数。
41
+ */
24
42
  export declare function language(getLocale?: () => string): string;
25
43
  /** 每次请求读取当前运行环境的 IANA 时区,环境不支持时使用 UTC。 */
26
44
  export declare function timezone(): string;
45
+ /**
46
+ * 在服务基地址的已有路径后追加固定接口路径,兼容反向代理前缀。
47
+ * 拒绝凭据、查询串和片段,避免混入历史身份参数或让同一个配置产生不明确的请求目标。
48
+ * 允许 HTTP 用于本地服务;带身份的正式部署应使用可信任的 HTTPS 基地址。
49
+ */
27
50
  export declare function endpoint(baseUrl: string, path: string): URL;
51
+ /**
52
+ * 写入后端通用参数:系统 uid、Canva platform_uid、平台、产品渠道及运行环境时区。
53
+ * uid 对应 profile.id,platform_uid 对应 Canva userId;缺失身份不伪造为空字符串。
54
+ * 本函数会修改传入 URL;语言单独放在请求头,是否必须已登录由各服务调用处判断。
55
+ */
28
56
  export declare function addContextQuery(url: URL, context: CommonRequestContext): void;
57
+ /** 读取完整 JSON 正文;HTML 错误页或损坏 JSON 只产生统一错误,不把原始正文混进异常。 */
29
58
  export declare function readJson(response: Response): Promise<unknown>;
59
+ /**
60
+ * 尽量保留后端 msg / code 以及对象类型的诊断 data,供应用展示或识别业务失败。
61
+ * Retry-After 仅接受整数秒并作为提示返回;此处不会安排重试,也不解析 HTTP 日期格式。
62
+ */
30
63
  export declare function backendError(response: Response, payload: unknown, fallbackCode: string | number): ApiError;
64
+ /**
65
+ * AI 接口的公共 POST:注入 Bearer JWT、Channel、语言与通用 query,并校验响应包。
66
+ * 返回后端的 { code, msg, data },不提取/重命名 data;具体 API 再验证自己的业务数据。
67
+ * 只执行一次请求,超时/取消涵盖读取响应正文;credentials: omit 不依赖浏览器 Cookie。
68
+ * 禁止重定向,避免认证头被带往配置以外的跳转目标。
69
+ */
31
70
  export declare function postApi<T>(context: ApiContext, method: keyof typeof apiPaths, params: JsonObject, options?: ApiRequestOptions): Promise<ApiResponse<T>>;
32
71
  export {};
@@ -1,4 +1,10 @@
1
1
  import { ApiRequestOptions } from './types';
2
- /** 一次操作共用超时和取消信号,包含响应正文;不重试任何请求。 */
2
+ /**
3
+ * 为一次完整操作提供统一的超时与取消边界,默认等待 60 秒;具体 API 可覆盖默认值。
4
+ * work 必须将接收到的 signal 传给内部请求,并在此回调内完成所需响应正文的读取。
5
+ * 多步上传也可共用同一个预算,超时不会因为开始下一个步骤而重置。
6
+ * 只执行一次 work,不做重试;取消客户端等待无法保证撤销后端已经接受的操作。
7
+ */
3
8
  export declare function withRequest<T>(options: ApiRequestOptions, work: (signal: AbortSignal) => Promise<T>): Promise<T>;
9
+ /** 多步操作在阶段交界处主动检查,避免取消后继续发起下一次签名、上传或合并请求。 */
4
10
  export declare function throwIfAborted(signal: AbortSignal): void;