yichong-canva2 2.2.0 → 2.4.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,10 @@
2
2
 
3
3
  使用一个 `YiChongCanvaProvider` 管理登录、订阅和额度,通过 `useYiChongCanva()` 直接调用后端接口。
4
4
 
5
+ **2.4.0 新增**:`client.reportUsage` 和 Provider 公共行为统计,兼容旧 GET 接口;另新增语音合成 `client.createTextToSpeech`、`client.getTextToSpeechResult`。下面的行为统计与 TTS 示例要求 `2.4.0` 或更高版本,`2.3.0` 不包含。
6
+
7
+ `2.3.0` 新增 `client.createVtt` 和 `client.getVttStatus`,统一调用音视频转录接口,并沿用 Provider 身份、通用参数、超时与取消支持。
8
+
5
9
  `2.2.0` 新增账户请求超时、有限重试与自动飞书告警,公开 `accountError` 供 Footer 展示失败及重试;上报切换到最新指定的 webhook。
6
10
 
7
11
  `2.1.0` 新增 `onUploadProgress` 和导出的 `UploadProgress` 类型,补齐视频目录参数,恢复消费数量原值透传,并将上传命名对齐旧随机算法与 MIME 后缀回退。上传继续复用 `ai.imgkits.com` 的四个 Cloudflare R2 接口,分片公开地址兼容旧响应,无需新增、迁移或部署后端接口。
@@ -9,7 +13,7 @@
9
13
  ## 使用
10
14
 
11
15
  ```sh
12
- npm install yichong-canva2@2.2.0
16
+ npm install yichong-canva2@2.3.0
13
17
  ```
14
18
 
15
19
  `1.2.0` 新增文本审核、三个消费接口,以及 Cloudflare R2 单次和分片上传;继续复用原有 Provider。
@@ -84,7 +88,7 @@ function GenerateButton() {
84
88
  }
85
89
  ```
86
90
 
87
- `baseUrl` 沿用原有账户扣费接口的地址。预测和文本审核请求默认使用 `https://api.imgkits.com`,可以通过可选的 `apiBaseUrl` 指定测试地址。
91
+ `baseUrl` 沿用原有账户扣费接口的地址。预测、文本审核和音视频转录请求默认使用 `https://api.imgkits.com`,可以通过可选的 `apiBaseUrl` 指定测试地址。
88
92
 
89
93
  文件签名服务默认使用 `https://ai.imgkits.com`,复用下表中的四个现有上传入口,可通过 Provider 的 `uploadBaseUrl` 指定测试服务。公开资源地址由后端响应的 `endpointBaseUrl` 提供:单次 PUT 使用普通签名响应;分片优先使用初始化响应,旧初始化响应缺少该字段时额外读取一次现有普通签名接口的地址信息,合并响应若提供最新地址则优先采用。`uploadBaseUrl` 是接口服务地址,不是公开资源地址。
90
94
 
@@ -92,6 +96,8 @@ function GenerateButton() {
92
96
 
93
97
  大模型 `chat` 同样默认使用 `https://ai.imgkits.com`,无需新增配置。Provider 可选的 `chatBaseUrl` 仅供覆盖大模型测试服务地址,独立于 `apiBaseUrl`、`contentBaseUrl` 和 `uploadBaseUrl`。
94
98
 
99
+ 语音合成 TTS 默认使用 `https://ai.imgkits.com`,Provider 的可选 `ttsBaseUrl` 可覆盖测试服务地址。它独立于预测与转录使用的 `apiBaseUrl`,正常使用不需要新增配置。
100
+
95
101
  语言默认在每次请求时读取 `document.documentElement.lang` 或浏览器语言;应用有自己的国际化状态时,在 Provider 上传 `getLocale={() => currentLocale}`。
96
102
 
97
103
  ## 后端接口
@@ -103,6 +109,11 @@ function GenerateButton() {
103
109
  | `client.textCheck({ text, scene? })` | `POST /api/public/text-moderation/check` | `{ code: 0, msg: "展示文案", data: { allowed, decision, categories, ... } }` |
104
110
  | `client.contentExtract({ type, url })` | `POST {contentBaseUrl}/api/content-extract` | `{ code: 0, msg, data: { content: "提取的原文", ... } }` |
105
111
  | `client.chat({ payload, model?, img_url?, image_url?, image_urls? })` | `POST {chatBaseUrl}/api/chat` | `{ code: 0, msg, data: { result: "模型输出", ... } }` |
112
+ | `client.createVtt({ audio?, video?, ifRender?, email?, env? })` | `POST {apiBaseUrl}/get-vtt/create` | `{ code: 0, msg, data: { jobId, status, status_str, remark } }` |
113
+ | `client.getVttStatus({ jobId })` | `POST {apiBaseUrl}/get-vtt/status` | `{ code: 0, msg, data: { status, status_str, result, remark, final_video_url } }` |
114
+ | `client.createTextToSpeech({ text, voice?, emotion?, speed?, language?, refer_audio?, refer_audio_text? })`(2.4.0 起) | `POST {ttsBaseUrl}/api/text-to-speech/create` | `{ code: 0, msg, data: { jobId, status, status_str, remark } }` |
115
+ | `client.getTextToSpeechResult({ jobId })`(2.4.0 起) | `POST {ttsBaseUrl}/api/text-to-speech/result` | `{ code: 0, msg, data: { jobId, status, status_str, result, remark } }` |
116
+ | `client.reportUsage({ sum_key, title, data? })`(2.4.0 起) | `GET https://log.aibabygenerator.io/api/report` | `Promise<boolean>`;失败不抛错,不阻断业务 |
106
117
  | `client.reportError({ error, source?, stage?, api?, context? })` | `POST https://report.imgkits.com` | Worker 原始 `{ success: true, data: { code: 0, ... } }` 或过滤响应 |
107
118
  | `client.reduceFreeCnt({ cnt })` | `POST {baseUrl}/api/user/reduce-free-cnt` | `{ ok: 0, msg: "success" }` |
108
119
  | `client.addMonthlyUsage({ cnt })` | `POST {baseUrl}/api/user/add-monthly-usage` | `{ ok: 0, msg: "success" }` |
@@ -115,7 +126,7 @@ function GenerateButton() {
115
126
 
116
127
  Provider 自动注入自有后端请求 query 中的 `uid`、`platform_uid`、`platform=canva_addon`、`app_channel`、`timezone`,以及请求头 `Accept-Language`。时区每次请求通过 `Intl.DateTimeFormat().resolvedOptions().timeZone` 读取,如 `Asia/Taipei`;运行环境不支持时使用 `UTC`。浏览器请求不额外发送 `accept_language` 参数。
117
128
 
118
- 这些通用信息覆盖预测、文本审核、内容提取、大模型 `chat`、消费、上传签名和分片管理,以及原有登录、通行证、状态查询、版本配置和 `use` 消费请求。登录开始时不附带未知的用户 ID;拿到 Canva 用户 ID 后附带 `platform_uid`,拿到系统用户 ID 后再附带 `uid`,后续刷新和轮询读取最新语言与时区。调用方无需配置时区或在业务参数中重复填写通用字段。
129
+ 这些通用信息覆盖预测、文本审核、内容提取、大模型 `chat`、音视频转录、语音合成 TTS、消费、上传签名和分片管理,以及原有登录、通行证、状态查询、版本配置和 `use` 消费请求。登录开始时不附带未知的用户 ID;拿到 Canva 用户 ID 后附带 `platform_uid`,拿到系统用户 ID 后再附带 `uid`,后续刷新和轮询读取最新语言与时区。调用方无需配置时区或在业务参数中重复填写通用字段。
119
130
 
120
131
  预测、文本审核、内容提取和大模型 `chat` 还携带 `Authorization: Bearer <jwt>`、`Channel: ai`;具名消费接口使用 `X-Access-Ticket`、`X-Access-Channel`;签名接口使用 `Channel: node-nauth`。R2 PUT 原样使用签名 URL,只携带文件的 `Content-Type`;错误上报 Worker 使用独立协议,身份与渠道信息放在诊断消息中。创建请求中的 `user_id` 使用系统用户 ID(`userStatus.profile.id`)。公共审核只要求有效的业务 JWT;`uid` 和 `platform_uid` 在账户状态包含这些值时才附带,审核身份由后端验签确定。
121
132
 
@@ -436,6 +447,145 @@ try {
436
447
 
437
448
  默认超时 `360_000` 毫秒(6 分钟,包含读取响应正文),是客户端等待预算;后端模型回退可能花费更久,可通过第二参数的 `timeoutMs` 调整。`signal` 只取消客户端等待,不保证停止后端生成。失败沿用 `ApiError`,后端 `msg` 保留在 `error.message` / `error.userMessage`;上例直接展示该信息。内容提取与 chat 各自计算超时,共用取消信号。
438
449
 
450
+ ## 音视频转录
451
+
452
+ 继续使用原来的 `YiChongCanvaProvider`,子组件中直接调用 `client.createVtt()`、`client.getVttStatus()`。创建参数沿用后端的 `audio` / `video`;正文 `userId` 自动使用 Provider 的系统用户 ID(`profile.id`),不是 Canva 的 `userId`。JWT、渠道、平台 ID、语言和时区也由当前 Provider 注入。
453
+
454
+ ```tsx
455
+ import { useState } from 'react';
456
+ import { ApiError, useYiChongCanva } from 'yichong-canva2';
457
+
458
+ // 此组件放在现有 Provider 下。mediaUrl 应是上传后、服务端可访问的音频地址。
459
+ export function TranscriptionPanel({ mediaUrl }: { mediaUrl: string }) {
460
+ const client = useYiChongCanva();
461
+ const [jobId, setJobId] = useState('');
462
+ const [result, setResult] = useState('');
463
+ const [message, setMessage] = useState('');
464
+ const [busy, setBusy] = useState(false);
465
+
466
+ async function run(action: 'create' | 'status') {
467
+ setBusy(true);
468
+ setMessage('');
469
+ try {
470
+ if (action === 'create') {
471
+ setJobId('');
472
+ setResult('');
473
+ // 视频使用 { video: mediaUrl }。本地 File 先单独调用 client.uploadFile()。
474
+ const { data } = await client.createVtt({ audio: mediaUrl });
475
+ if (data.status === -1) throw new Error(data.remark || 'Transcription failed');
476
+ setJobId(data.jobId);
477
+ setMessage('Task ready. Check its status for subtitles.');
478
+ } else {
479
+ const { data } = await client.getVttStatus({ jobId });
480
+ if (data.status === -1) throw new Error(data.remark || 'Transcription failed');
481
+ if (data.status === 10) {
482
+ setResult(data.result ?? ''); // 字幕片段的 JSON 原文;需要数组时自行 JSON.parse。
483
+ setMessage('Completed');
484
+ } else {
485
+ setMessage('Transcription is still in progress.');
486
+ }
487
+ }
488
+ } catch (error) {
489
+ setMessage(error instanceof ApiError ? error.userMessage
490
+ : error instanceof Error ? error.message : 'Request failed');
491
+ } finally {
492
+ setBusy(false);
493
+ }
494
+ }
495
+
496
+ return <>
497
+ <button disabled={busy || !mediaUrl || client.loginStatus !== 'success'}
498
+ onClick={() => void run('create')}>Create transcription</button>
499
+ <button disabled={busy || !jobId || client.loginStatus !== 'success'}
500
+ onClick={() => void run('status')}>Check status</button>
501
+ <p>{message}</p>
502
+ <pre>{result}</pre>
503
+ </>;
504
+ }
505
+ ```
506
+
507
+ `data.result` 当前是字幕片段数组的 JSON 字符串,形如 `[{"start_time":"00:00:00.000","end_time":"00:00:01.500","text":"你好"}]`,并非 WEBVTT 文件文本。SDK 原样返回,字幕文件导出由应用另行处理。
508
+
509
+ 示例用手动查询展示两个原始接口,应用可以在业务流程里安排每 2–5 秒轮询,并设置总时限、在完成/失败/组件卸载时停止。SDK 本身只请求一次;任务状态 `0` 为排队、`2` 为处理中、`10` 为成功、`-1` 为失败。`code=0` 不代表转录已经成功。
510
+
511
+ 可选参数 `ifRender: 0 | 1`、`email`、`env` 原样传给后端;`env: 'pre'` 不立即派发,普通使用应省略。建议只传一个媒体地址,两者都非空时后端优先 `video`,允许另一个字段为空字符串。上传、轮询和消费不由这两个方法自动执行,后端原有用量处理保持不变。
512
+
513
+ 两个方法均默认超时 60 秒,可用第二参数 `{ timeoutMs, signal }` 覆盖或取消等待。取消请求不会取消后台任务,也不会自动重新创建。
514
+
515
+ 服务地址沿用 Provider 的 `apiBaseUrl`,默认 `https://api.imgkits.com`。这是客户端默认值,使用前需要后端部署 `/get-vtt/*` 并确认对应网关转发;这两个方法自 `2.3.0` 起提供。
516
+
517
+ ## 语音合成 TTS(2.4.0 起)
518
+
519
+ 继续使用同一个 `YiChongCanvaProvider`,组件直接调用 `client.createTextToSpeech()` 和 `client.getTextToSpeechResult()`。默认地址分别是 `https://ai.imgkits.com/api/text-to-speech/create` 与 `/api/text-to-speech/result`;需要测试服务时再设置 Provider 的 `ttsBaseUrl`。
520
+
521
+ SDK 要求已有系统用户 ID 和 Canva 平台用户 ID。创建正文中的 `guid` 自动取 `userStatus.profile.id`,不是随机任务 ID,也不是 Canva 用户 ID;调用方不能传 `guid`、`userId`、`app_id` 覆盖身份或计费参数。后端现有实现根据 `guid` 关联用户及用量,不能将它称为 JWT 身份验证;Provider 有有效 JWT 时才发送,缺失时省略 Authorization,不会发送 `Bearer null`。语言、渠道和通用 query 由 Provider 补齐。
522
+
523
+ ```tsx
524
+ import { useState } from 'react';
525
+ import { ApiError, useYiChongCanva } from 'yichong-canva2';
526
+
527
+ // 放在现有 Provider 下。示例手动查询,保留 jobId 以便继续查看同一个任务。
528
+ export function SpeechPanel() {
529
+ const client = useYiChongCanva();
530
+ const [text, setText] = useState('你好,欢迎使用语音合成。');
531
+ const [jobId, setJobId] = useState('');
532
+ const [audioUrl, setAudioUrl] = useState('');
533
+ const [message, setMessage] = useState('');
534
+ const [busy, setBusy] = useState(false);
535
+
536
+ async function run(action: 'create' | 'result') {
537
+ setBusy(true);
538
+ setMessage('');
539
+ try {
540
+ if (action === 'create') {
541
+ setJobId('');
542
+ setAudioUrl('');
543
+ const { data } = await client.createTextToSpeech({
544
+ text,
545
+ voice: 'Arrogant_Miss',
546
+ emotion: 'auto',
547
+ speed: 1,
548
+ });
549
+ if (data.status === -1) throw new Error(data.remark || 'Speech generation failed');
550
+ setJobId(data.jobId);
551
+ setMessage('Task created. Check the result when it is ready.');
552
+ } else {
553
+ const { data } = await client.getTextToSpeechResult({ jobId });
554
+ if (data.status === -1) throw new Error(data.remark || 'Speech generation failed');
555
+ if (data.status === 10) {
556
+ if (!data.result) throw new Error('The completed task did not return audio');
557
+ setAudioUrl(data.result); // 原始音频 URL,不是字幕 JSON,也不是音频文件二进制。
558
+ setMessage('Completed');
559
+ } else {
560
+ setMessage('Speech generation is still waiting or processing.');
561
+ }
562
+ }
563
+ } catch (error) {
564
+ setMessage(error instanceof ApiError ? error.userMessage
565
+ : error instanceof Error ? error.message : 'Request failed');
566
+ } finally {
567
+ setBusy(false);
568
+ }
569
+ }
570
+
571
+ return <>
572
+ <textarea value={text} disabled={busy} onChange={event => setText(event.target.value)} />
573
+ <button disabled={busy || !text.trim() || client.loginStatus !== 'success'}
574
+ onClick={() => void run('create')}>Create speech</button>
575
+ <button disabled={busy || !jobId || client.loginStatus !== 'success'}
576
+ onClick={() => void run('result')}>Check result</button>
577
+ <p>{message}</p>
578
+ {audioUrl && <audio controls src={audioUrl} />}
579
+ </>;
580
+ }
581
+ ```
582
+
583
+ `text` 必需、非空且最多 5000 个 Unicode 字符。`voice`、`emotion`、`speed`、`language`、`refer_audio`、`refer_audio_text` 可选,按后端字段名传递。`speed` 范围为 0.5–2.0,SDK 不自行舍入,省略时后端使用 1.0;未填的音色、情感和语言由后端取默认值。使用参考音频时,`refer_audio` 应是后端可访问的 HTTP(S) URL,参考文本最多 5000 个 Unicode 字符,后端仅在参考音频非空时使用;工具包不会自动上传音频或改写用户文本。
584
+
585
+ 创建返回任务 `jobId`;查询保留 `jobId/status/status_str/remark/result`。状态为 `0` 等待、`2` 处理中、`10` 完成、`-1` 失败。`code=0` 不是生成完成,创建本身也可能返回 `status=-1`,因此创建和查询均要检查任务状态。`result` 是音频 URL 字符串或 `null`,直接用于播放器或后续导入流程,无需 JSON.parse。
586
+
587
+ 默认每次请求超时 60 秒,第二参数支持 `{ timeoutMs, signal }`。SDK 只发送一次请求,不自动重试、轮询、插入 Canva 或再扣一次额度;后端已有自己的 TTS 字符用量处理。需要轮询时,由业务设置总时限,并在完成、失败或组件卸载时停止。取消或超时只停止客户端等待,不保证后台任务取消或未扣费;尤其创建超时后不要直接重放创建请求。
588
+
439
589
  ## 文本审核
440
590
 
441
591
  `client.textCheck` 封装后端的公共文本审核接口,复用现有 Provider,无需另外配置令牌。请求发送到用户 JWT 公共入口。
@@ -551,3 +701,49 @@ npm test
551
701
  `npm test` 构建后使用 Node 测试真实产物,覆盖请求合同、消费数量精度、签名与 PUT 的凭据边界、错误、超时、取消,以及 Provider 登录/刷新后的凭据共享。测试替换 Canva 宿主和网络请求,不调用真实模型、记账或上传资源。
552
702
 
553
703
  源码在 `packages/`,构建输出在 `dist/`。`npm run lint` 检查新增 API 模块和测试;全包类型由 `lint:types` 检查。原包的旧 Provider 实现暂时保留。
704
+
705
+ ## 用户行为统计(2.4.0 起)
706
+
707
+ 保留原有一个 Provider 的用法,行为统计默认开启,不用额外包裹组件。Provider 自动记录 `app_open`、`login_start`、`login_success`、`login_fail`、`account_fail` 和 `account_recovered`;最后一项只有账户发生失败并真实恢复后才发出。普通成功的 status 轮询不逐次上报,避免高频噪声。`client.reportUsage` 的方法引用保持稳定,调用时读取当前用户身份。
708
+
709
+ ```tsx
710
+ <YiChongCanvaProvider
711
+ appId="YOUR_CANVA_APP_ID"
712
+ productName="your_app_channel"
713
+ baseUrl="https://usa.imgkits.com/your_app_channel"
714
+ version={1}
715
+ usageReporting={{
716
+ enabled: true, // 默认 true;false 同时关闭 Provider 公共事件和手动 reportUsage
717
+ // appKey: "your_app_channel_canva", // 默认沿用旧应用 {productName}_canva
718
+ // endpoint: "https://your-report-service.example/api/report", // 可替换完整接口地址
719
+ }}
720
+ >
721
+ <App />
722
+ </YiChongCanvaProvider>
723
+ ```
724
+
725
+ 应用只补自己的关键行为,仍然直接调用同名 API:
726
+
727
+ ```ts
728
+ const client = useYiChongCanva();
729
+ void client.reportUsage({
730
+ sum_key: "generate_success",
731
+ title: "生成成功",
732
+ data: {
733
+ operation_id: operationId,
734
+ duration_ms: 12800,
735
+ result_count: 1,
736
+ model: "your_model",
737
+ },
738
+ });
739
+ ```
740
+
741
+ `operationId` 由业务或脚手架在一次生成开始时创建,串联开始、成功、失败、取消等事件;每次上报由 SDK 单独生成事件 UUID,网络重试复用这个 UUID。Provider 自动补入内存会话 `session_id` 和应用版本 `app_version`(即 Provider 的 `version`),业务不可覆盖同名字段。`user_id` 取当前 `userStatus.profile.id`,登录前省略,仍可上报登录故障。登录、消费、AI 请求不会等待行为统计。
742
+
743
+ 新脚手架自动记录三段式页面进入、处理开始/成功/失败/取消/重试、插入设计和打开套餐页,业务不要重复记录同一公共事件。`createSpecifyPrediction` 返回任务 ID 只表示提交成功;只有最终生成结果已就绪才能报成功,不能在提交后提前报 `generate_success`。实际事件名见生成项目的 `src/app.tsx`、`src/pages/result.tsx`、`src/components/footer.tsx` 和 `AGENTS.md`。
744
+
745
+ 接口与旧应用一致,字段包含 `app_key`、`sum_key`、`title`、`user_id`、`data`、`timestamp`、`uuid`,并继续补公共 query 与 Accept-Language。`data` 保留旧 JSON 双重 URL 编码供统计后台解码。Worker 使用服务端接收时间作为统计 `timestamp`;客户端发生时间保存在 `data.occurred_at`。不发送用户 JWT、passport 或 cookie,也不读取本地存储补身份。
746
+
747
+ 返回值为 `Promise<boolean>`:收到 HTTP 成功确认时为 true;关闭、非法参数、身份 getter/序列化异常、取消、网络等失败均为 false,不向业务抛错、不显示错误、不递归告警。通常 `void client.reportUsage(...)` 即可。默认每次请求 4 秒,网络/超时/429/5xx 最多重试一次,其他 4xx 不重试;第二参数 `{ signal, timeoutMs }` 可取消或缩短等待(1–4000 毫秒,每次)。
748
+
749
+ 只传枚举、计数、耗时、错误码等少量属性,不传提示词、完整 input/output、文件、资源地址、token、stack 或原始异常。SDK 会脱敏敏感字段和值,跳过 getter/toJSON/类实例,最多 3 层、30 个字段、数组 10 项、字符串 256 字符;最终 URL 上限 8192 字符,超长时先移除尾部业务属性。脱敏无法识别任意改名的用户文本,应用仍需只提供必要统计数据。统计失败不影响 Footer 原样式、加载状态或文案。
@@ -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.2.0",
23
+ sdk_version: "2.4.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)
@@ -5,7 +5,11 @@ const apiPaths = {
5
5
  getPrediction: "/replicate/getPrediction",
6
6
  textCheck: "/api/public/text-moderation/check",
7
7
  contentExtract: "/api/content-extract",
8
- chat: "/api/chat"
8
+ chat: "/api/chat",
9
+ createVtt: "/get-vtt/create",
10
+ getVttStatus: "/get-vtt/status",
11
+ createTextToSpeech: "/api/text-to-speech/create",
12
+ getTextToSpeechResult: "/api/text-to-speech/result"
9
13
  };
10
14
  function isObject(value) {
11
15
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -86,21 +90,24 @@ async function postApi(context, method, params, options = {}) {
86
90
  var _a;
87
91
  const { userStatus, apiBaseUrl } = context;
88
92
  const uid = (_a = userStatus.profile) == null ? void 0 : _a.id;
89
- if (!isNonemptyString(userStatus.jwt) || method !== "textCheck" && (!isNonemptyString(uid) || !isNonemptyString(userStatus.userId))) {
93
+ const optionalJwt = method === "createTextToSpeech" || method === "getTextToSpeechResult";
94
+ if (!optionalJwt && !isNonemptyString(userStatus.jwt) || method !== "textCheck" && (!isNonemptyString(uid) || !isNonemptyString(userStatus.userId))) {
90
95
  throw new ApiError("Wait for the Provider account credentials before calling backend APIs.", "account_not_ready");
91
96
  }
92
97
  const url = endpoint(apiBaseUrl, apiPaths[method]);
93
98
  addContextQuery(url, context);
99
+ const attachJwt = !optionalJwt || isNonemptyString(userStatus.jwt) && !["null", "undefined"].includes(userStatus.jwt.trim().toLowerCase());
100
+ const headers = {
101
+ "Content-Type": "application/json",
102
+ "Accept-Language": language(context.getLocale),
103
+ Channel: "ai"
104
+ };
105
+ if (attachJwt) headers.Authorization = `Bearer ${userStatus.jwt}`;
94
106
  const response = await fetch(url.toString(), {
95
107
  method: "POST",
96
- headers: {
97
- "Content-Type": "application/json",
98
- "Accept-Language": language(context.getLocale),
99
- Authorization: `Bearer ${userStatus.jwt}`,
100
- Channel: "ai"
101
- },
102
- // 创建任务还需在正文写入 user_id,始终以 Provider 账号为准。
103
- body: JSON.stringify(method === "createSpecifyPrediction" ? { ...params, user_id: uid } : params),
108
+ headers,
109
+ // 各任务的身份字段不同;正文身份与 query 的 uid 始终使用同一账户快照。
110
+ body: JSON.stringify(method === "createSpecifyPrediction" ? { ...params, user_id: uid } : method === "createVtt" ? { ...params, userId: uid } : method === "createTextToSpeech" ? { ...params, guid: uid } : params),
104
111
  signal,
105
112
  credentials: "omit",
106
113
  redirect: "error"
@@ -0,0 +1,65 @@
1
+ import { ApiError } from "./error.js";
2
+ import { isObject, isNonemptyString, invalid, postApi, validateJson } from "./request.js";
3
+ const createKeys = ["text", "voice", "emotion", "speed", "language", "refer_audio", "refer_audio_text"];
4
+ function validateTextLength(text, field) {
5
+ if ([...text].length > 5e3) invalid(`${field} must not exceed 5000 characters.`);
6
+ }
7
+ function validateReferenceAudio(value) {
8
+ if (value === void 0 || value === "") return;
9
+ if (!isNonemptyString(value)) invalid("refer_audio must be an HTTP(S) URL.");
10
+ let url;
11
+ try {
12
+ url = new URL(value);
13
+ } catch {
14
+ invalid("refer_audio must be an HTTP(S) URL.");
15
+ }
16
+ if (!/^https?:\/\//i.test(value) || !["http:", "https:"].includes(url.protocol) || url.username || url.password) {
17
+ invalid("refer_audio must be an HTTP(S) URL without credentials.");
18
+ }
19
+ }
20
+ function validateTask(data) {
21
+ if (!isObject(data) || !isNonemptyString(data.jobId) || !Number.isInteger(data.status) || typeof data.status_str !== "string" || data.remark !== void 0 && data.remark !== null && typeof data.remark !== "string") {
22
+ throw new ApiError("Backend returned an invalid text-to-speech task.", "invalid_response");
23
+ }
24
+ }
25
+ function createTextToSpeechApi(getContext) {
26
+ return {
27
+ async createTextToSpeech(params, options) {
28
+ if (!isObject(params) || !isNonemptyString(params.text) || Object.keys(params).some((key) => !createKeys.includes(key))) {
29
+ invalid("createTextToSpeech requires text; account identity and billing fields cannot be overridden.");
30
+ }
31
+ validateTextLength(params.text, "text");
32
+ for (const key of ["voice", "emotion", "language", "refer_audio", "refer_audio_text"]) {
33
+ if (params[key] !== void 0 && typeof params[key] !== "string") invalid(`${key} must be a string.`);
34
+ }
35
+ if (params.speed !== void 0 && (typeof params.speed !== "number" || !Number.isFinite(params.speed) || params.speed < 0.5 || params.speed > 2)) {
36
+ invalid("speed must be a number between 0.5 and 2.0.");
37
+ }
38
+ validateReferenceAudio(params.refer_audio);
39
+ if (typeof params.refer_audio_text === "string") validateTextLength(params.refer_audio_text, "refer_audio_text");
40
+ const body = {};
41
+ for (const key of createKeys) {
42
+ const value = params[key];
43
+ if (typeof value === "string" || typeof value === "number") body[key] = value;
44
+ }
45
+ validateJson(body);
46
+ const response = await postApi(getContext(), "createTextToSpeech", body, options);
47
+ validateTask(response.data);
48
+ return response;
49
+ },
50
+ async getTextToSpeechResult(params, options) {
51
+ if (!isObject(params) || !isNonemptyString(params.jobId) || Object.keys(params).some((key) => key !== "jobId")) {
52
+ invalid("getTextToSpeechResult requires a nonempty jobId.");
53
+ }
54
+ const response = await postApi(getContext(), "getTextToSpeechResult", { jobId: params.jobId }, options);
55
+ validateTask(response.data);
56
+ if (response.data.result !== null && typeof response.data.result !== "string") {
57
+ throw new ApiError("Backend returned an invalid text-to-speech result.", "invalid_response");
58
+ }
59
+ return response;
60
+ }
61
+ };
62
+ }
63
+ export {
64
+ createTextToSpeechApi
65
+ };
@@ -0,0 +1,76 @@
1
+ import { ApiError } from "./error.js";
2
+ import { addContextQuery, language } from "./request.js";
3
+ import { withRequest } from "./transport.js";
4
+ import { usageReportingData, usageReportingText } from "./usage_reporting_payload.js";
5
+ function createUsageReportingApi(getContext) {
6
+ return {
7
+ async reportUsage(params, options = {}) {
8
+ var _a, _b, _c, _d, _e;
9
+ try {
10
+ const context = getContext();
11
+ const config = context.usageReporting ?? {};
12
+ if (config.enabled === false || ((_a = options.signal) == null ? void 0 : _a.aborted)) return false;
13
+ if (config.enabled !== void 0 && typeof config.enabled !== "boolean") return false;
14
+ if (!params || typeof params !== "object" || Array.isArray(params) || Object.keys(params).some((key) => !["sum_key", "title", "data"].includes(key)) || typeof params.sum_key !== "string" || !/^[a-zA-Z0-9_.:-]{1,64}$/.test(params.sum_key) || typeof params.title !== "string" || !params.title.trim() || params.data != null && (typeof params.data !== "object" || Array.isArray(params.data))) return false;
15
+ const appKey = config.appKey ?? `${context.productName}_canva`;
16
+ if (typeof appKey !== "string" || !/^[a-zA-Z0-9_.:-]{1,128}$/.test(appKey)) return false;
17
+ const timeoutMs = options.timeoutMs ?? 4e3;
18
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 4e3) return false;
19
+ const url = new URL(config.endpoint ?? "https://log.aibabygenerator.io/api/report");
20
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) || url.username || url.password || url.search || url.hash) return false;
21
+ const secrets = [context.userStatus.jwt, (_b = context.userStatus.profile) == null ? void 0 : _b.token, (_c = context.userStatus.drive) == null ? void 0 : _c.fresh_token, ...context.secrets ?? []].filter((value) => typeof value === "string" && value.length > 0);
22
+ const occurredAt = (/* @__PURE__ */ new Date()).toISOString();
23
+ const base = usageReportingData({ ...context.metadata, occurred_at: occurredAt }, secrets);
24
+ const attributes = usageReportingData(params.data, secrets);
25
+ const data = usageReportingData({ ...base, ...Object.fromEntries(Object.entries(attributes).filter(([key]) => !(key in base))) }, secrets);
26
+ const userId = (_d = context.userStatus.profile) == null ? void 0 : _d.id;
27
+ if (userId !== void 0 && (typeof userId !== "string" || userId.length > 128)) return false;
28
+ const title = usageReportingText(params.title, 128, secrets);
29
+ url.searchParams.set("app_key", appKey);
30
+ url.searchParams.set("sum_key", params.sum_key);
31
+ url.searchParams.set("title", title);
32
+ if (userId) url.searchParams.set("user_id", userId);
33
+ url.searchParams.set("timestamp", String(Date.now()));
34
+ url.searchParams.set("uuid", globalThis.crypto.randomUUID());
35
+ addContextQuery(url, context);
36
+ const headers = { "Accept-Language": language(context.getLocale) };
37
+ const updateData = () => url.searchParams.set("data", encodeURIComponent(JSON.stringify(data)));
38
+ updateData();
39
+ for (const key of Object.keys(data).reverse()) {
40
+ if (url.href.length <= 8192) break;
41
+ if (key === "occurred_at") continue;
42
+ delete data[key];
43
+ updateData();
44
+ }
45
+ if (url.href.length > 8192) return false;
46
+ const requestUrl = url.toString();
47
+ for (let attempt = 0; attempt < 2; attempt++) {
48
+ if ((_e = options.signal) == null ? void 0 : _e.aborted) return false;
49
+ try {
50
+ const response = await withRequest({ signal: options.signal, timeoutMs }, (signal) => fetch(requestUrl, {
51
+ method: "GET",
52
+ headers,
53
+ signal,
54
+ credentials: "omit",
55
+ redirect: "error",
56
+ referrerPolicy: "no-referrer",
57
+ cache: "no-store",
58
+ mode: "cors",
59
+ keepalive: true
60
+ }));
61
+ if (response.ok) return true;
62
+ if (response.status !== 429 && response.status < 500) return false;
63
+ } catch (error) {
64
+ if (!(error instanceof ApiError) || !["network_error", "timeout"].includes(String(error.code))) return false;
65
+ }
66
+ }
67
+ return false;
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
72
+ };
73
+ }
74
+ export {
75
+ createUsageReportingApi
76
+ };
@@ -0,0 +1,44 @@
1
+ const sensitiveKey = /(?:prompt|input|output|content|message|text|file|image|audio|video|url|uri|token|passport|authorization|cookie|password|secret|credential|email|stack|rawerror|requestbody|responsebody)/i;
2
+ const redacted = "[redacted]";
3
+ function usageReportingText(value, maxLength, secrets) {
4
+ let clean = value;
5
+ for (const secret of secrets) {
6
+ if (typeof secret === "string" && secret.length >= 4) clean = clean.split(secret).join(redacted);
7
+ }
8
+ clean = clean.replace(/(?:https?:\/\/|blob:|data:|www\.)[^\s<>"']+/gi, redacted).replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, redacted).replace(/\bBearer\s+\S+/gi, redacted).replace(/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, redacted).replace(/[\u0000-\u001f\u007f]/g, " ");
9
+ return Array.from(clean).slice(0, maxLength).join("");
10
+ }
11
+ function usageReportingData(value, secrets) {
12
+ let fields = 0;
13
+ const seen = /* @__PURE__ */ new Set();
14
+ function clean(input, depth) {
15
+ if (input === null || typeof input === "boolean") return input;
16
+ if (typeof input === "string") return usageReportingText(input, 256, secrets);
17
+ if (typeof input === "number") return Number.isFinite(input) ? input : void 0;
18
+ if (!input || typeof input !== "object" || seen.has(input) || depth > 3) return void 0;
19
+ if (!Array.isArray(input) && Object.getPrototypeOf(input) !== Object.prototype && Object.getPrototypeOf(input) !== null) return void 0;
20
+ seen.add(input);
21
+ try {
22
+ if (Array.isArray(input)) {
23
+ return Object.values(Object.getOwnPropertyDescriptors(input)).slice(0, 10).filter((descriptor) => descriptor.enumerable && "value" in descriptor).map((descriptor) => clean(descriptor.value, depth + 1)).filter((item) => item !== void 0);
24
+ }
25
+ const output = /* @__PURE__ */ Object.create(null);
26
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(input))) {
27
+ if (fields >= 30) break;
28
+ if (!descriptor.enumerable || !("value" in descriptor) || !/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(key)) continue;
29
+ fields++;
30
+ const child = sensitiveKey.test(key.replace(/[_-]/g, "")) ? redacted : clean(descriptor.value, depth + 1);
31
+ if (child !== void 0) output[key] = child;
32
+ }
33
+ return output;
34
+ } finally {
35
+ seen.delete(input);
36
+ }
37
+ }
38
+ const result = clean(value, 0);
39
+ return result && typeof result === "object" && !Array.isArray(result) ? result : {};
40
+ }
41
+ export {
42
+ usageReportingData,
43
+ usageReportingText
44
+ };
@@ -0,0 +1,62 @@
1
+ import { ApiError } from "./error.js";
2
+ import { isObject, isNonemptyString, invalid, postApi } from "./request.js";
3
+ function validateMediaUrl(value) {
4
+ if (value === void 0 || value === "") return;
5
+ if (!isNonemptyString(value)) invalid("audio and video must be HTTP(S) URLs.");
6
+ let url;
7
+ try {
8
+ url = new URL(value);
9
+ } catch {
10
+ invalid("audio and video must be HTTP(S) URLs.");
11
+ }
12
+ if (!/^https?:\/\//i.test(value) || !["https:", "http:"].includes(url.protocol) || url.username || url.password) {
13
+ invalid("audio and video must be HTTP(S) URLs without credentials.");
14
+ }
15
+ }
16
+ function validateStatus(data) {
17
+ if (!isObject(data) || !Number.isInteger(data.status) || typeof data.status_str !== "string") {
18
+ throw new ApiError("Backend returned an invalid transcription status.", "invalid_response");
19
+ }
20
+ }
21
+ function createVttApi(getContext) {
22
+ return {
23
+ async createVtt(params, options) {
24
+ if (!isObject(params) || Object.keys(params).some((key) => !["audio", "video", "ifRender", "email", "env"].includes(key)) || !isNonemptyString(params.audio) && !isNonemptyString(params.video)) {
25
+ invalid("createVtt requires audio or video; userId is supplied by the current account.");
26
+ }
27
+ validateMediaUrl(params.audio);
28
+ validateMediaUrl(params.video);
29
+ if (params.ifRender !== void 0 && params.ifRender !== 0 && params.ifRender !== 1) {
30
+ invalid("ifRender must be 0 or 1.");
31
+ }
32
+ for (const key of ["email", "env"]) {
33
+ if (params[key] !== void 0 && typeof params[key] !== "string") invalid(`${key} must be a string.`);
34
+ }
35
+ const body = {};
36
+ for (const key of ["audio", "video", "ifRender", "email", "env"]) {
37
+ const value = params[key];
38
+ if (typeof value === "string" || typeof value === "number") body[key] = value;
39
+ }
40
+ const response = await postApi(getContext(), "createVtt", body, options);
41
+ validateStatus(response.data);
42
+ if (!isNonemptyString(response.data.jobId)) {
43
+ throw new ApiError("Backend returned an invalid transcription jobId.", "invalid_response");
44
+ }
45
+ return response;
46
+ },
47
+ async getVttStatus(params, options) {
48
+ if (!isObject(params) || !isNonemptyString(params.jobId) || Object.keys(params).some((key) => key !== "jobId")) {
49
+ invalid("getVttStatus requires a nonempty jobId.");
50
+ }
51
+ const response = await postApi(getContext(), "getVttStatus", { jobId: params.jobId }, options);
52
+ validateStatus(response.data);
53
+ if (response.data.result !== null && typeof response.data.result !== "string" || response.data.final_video_url !== null && typeof response.data.final_video_url !== "string") {
54
+ throw new ApiError("Backend returned an invalid transcription result.", "invalid_response");
55
+ }
56
+ return response;
57
+ }
58
+ };
59
+ }
60
+ export {
61
+ createVttApi
62
+ };
@@ -46,9 +46,22 @@ const YiChongCanvaContext = React.createContext(
46
46
  chat: async () => {
47
47
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
48
48
  },
49
+ createVtt: async () => {
50
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
51
+ },
52
+ getVttStatus: async () => {
53
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
54
+ },
55
+ createTextToSpeech: async () => {
56
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
57
+ },
58
+ getTextToSpeechResult: async () => {
59
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
60
+ },
49
61
  reportError: async () => {
50
62
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
51
63
  },
64
+ reportUsage: async () => false,
52
65
  reduceFreeCnt: async () => {
53
66
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
54
67
  },
@@ -8,13 +8,24 @@ import { createPredictionApi } from "../api/predictions.js";
8
8
  import { createTextModerationApi } from "../api/moderation.js";
9
9
  import { createContentExtractionApi } from "../api/content.js";
10
10
  import { createChatApi } from "../api/chat.js";
11
+ import { createVttApi } from "../api/vtt.js";
12
+ import { createTextToSpeechApi } from "../api/tts.js";
11
13
  import { createUsageApi } from "../api/usage.js";
12
14
  import { createUploadApi } from "../api/uploads.js";
13
15
  import { createErrorReportingApi } from "../api/reporting.js";
16
+ import { createUsageReportingApi } from "../api/usage_reporting.js";
14
17
  import { ApiError } from "../api/error.js";
15
18
  import { withRequest, throwIfAborted } from "../api/transport.js";
16
19
  import { createAccountReporter, AccountRequestError, retryableAccountError, accountDelay } from "./account.js";
17
20
  import { language, addContextQuery } from "../api/request.js";
21
+ let usageIdSequence = 0;
22
+ function usageId() {
23
+ try {
24
+ return globalThis.crypto.randomUUID();
25
+ } catch {
26
+ return `usage-${Date.now().toString(36)}-${(++usageIdSequence).toString(36)}-${Math.random().toString(36).slice(2)}`;
27
+ }
28
+ }
18
29
  function reduceFreeTimes(baseUrl, passport, cnt, context) {
19
30
  const header = {
20
31
  "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
@@ -60,8 +71,10 @@ const YiChongCanvaProvider = ({
60
71
  apiBaseUrl = "https://api.imgkits.com",
61
72
  contentBaseUrl = "https://ai.imgkits.com",
62
73
  chatBaseUrl = "https://ai.imgkits.com",
74
+ ttsBaseUrl = "https://ai.imgkits.com",
63
75
  uploadBaseUrl = "https://ai.imgkits.com",
64
76
  getLocale,
77
+ usageReporting,
65
78
  autoLogin = true,
66
79
  testMode: _testMode = "noTest",
67
80
  version = 1,
@@ -84,9 +97,15 @@ const YiChongCanvaProvider = ({
84
97
  const loginPendingRef = useRef(false);
85
98
  const mountedRef = useRef(true);
86
99
  const identityScopeRef = useRef(`${appId}|${productName}`);
100
+ const usageSessionRef = useRef(null);
101
+ const usageScope = `${appId}|${productName}`;
102
+ if (!usageSessionRef.current || usageSessionRef.current.scope !== usageScope) {
103
+ usageSessionRef.current = { scope: usageScope, id: usageId(), opened: false };
104
+ }
105
+ const previousAccountFailureRef = useRef(null);
87
106
  const userStatusRef = useRef({});
88
- const apiConfigRef = useRef({ apiBaseUrl, contentBaseUrl, chatBaseUrl, baseUrl, uploadBaseUrl, productName, appId, version, getLocale });
89
- apiConfigRef.current = { apiBaseUrl, contentBaseUrl, chatBaseUrl, baseUrl, uploadBaseUrl, productName, appId, version, getLocale };
107
+ const apiConfigRef = useRef({ apiBaseUrl, contentBaseUrl, chatBaseUrl, ttsBaseUrl, baseUrl, uploadBaseUrl, productName, appId, version, getLocale, usageReporting });
108
+ apiConfigRef.current = { apiBaseUrl, contentBaseUrl, chatBaseUrl, ttsBaseUrl, baseUrl, uploadBaseUrl, productName, appId, version, getLocale, usageReporting };
90
109
  const passportRef = useRef(null);
91
110
  const onPassport = (passport, userId, uid) => {
92
111
  passportRef.current = { passport, userId, uid, productName };
@@ -97,6 +116,7 @@ const YiChongCanvaProvider = ({
97
116
  });
98
117
  const [predictionApi] = useState(() => createPredictionApi(getApiContext));
99
118
  const [textModerationApi] = useState(() => createTextModerationApi(getApiContext));
119
+ const [vttApi] = useState(() => createVttApi(getApiContext));
100
120
  const [contentExtractionApi] = useState(() => createContentExtractionApi(() => ({
101
121
  ...getApiContext(),
102
122
  apiBaseUrl: apiConfigRef.current.contentBaseUrl
@@ -105,6 +125,10 @@ const YiChongCanvaProvider = ({
105
125
  ...getApiContext(),
106
126
  apiBaseUrl: apiConfigRef.current.chatBaseUrl
107
127
  })));
128
+ const [textToSpeechApi] = useState(() => createTextToSpeechApi(() => ({
129
+ ...getApiContext(),
130
+ apiBaseUrl: apiConfigRef.current.ttsBaseUrl
131
+ })));
108
132
  const [usageApi] = useState(() => createUsageApi(() => {
109
133
  var _a;
110
134
  const context = getApiContext();
@@ -120,6 +144,35 @@ const YiChongCanvaProvider = ({
120
144
  passport: (_a = passportRef.current) == null ? void 0 : _a.passport
121
145
  };
122
146
  }));
147
+ const [usageReportingApi] = useState(() => createUsageReportingApi(() => {
148
+ var _a, _b, _c;
149
+ const context = getApiContext();
150
+ const scope = `${context.appId}|${context.productName}`;
151
+ return {
152
+ ...context,
153
+ // 子组件 effect 可能先于 Provider 的换应用 effect 执行,不能把旧用户算入新应用。
154
+ userStatus: identityScopeRef.current === scope ? context.userStatus : {},
155
+ metadata: { session_id: (_a = usageSessionRef.current) == null ? void 0 : _a.id, app_version: String(context.version), platform: "canva_addon" },
156
+ secrets: [context.userStatus.jwt, (_b = context.userStatus.profile) == null ? void 0 : _b.token, (_c = passportRef.current) == null ? void 0 : _c.passport].filter((value) => !!value)
157
+ };
158
+ }));
159
+ const reportAccountUsage = (sum_key, title, run, data = {}) => {
160
+ void usageReportingApi.reportUsage({ sum_key, title, data: {
161
+ ...data,
162
+ operation_id: run.usageOperationId,
163
+ operation: run.operation,
164
+ duration_ms: Math.max(0, Date.now() - run.startedAt)
165
+ } });
166
+ };
167
+ const reportAccountRecovery = (run) => {
168
+ const previous = previousAccountFailureRef.current;
169
+ if (!previous || previous.scope !== run.appKey) return;
170
+ previousAccountFailureRef.current = null;
171
+ reportAccountUsage("account_recovered", "账户状态恢复", run, {
172
+ previous_operation: previous.operation,
173
+ retry_of: previous.operationId
174
+ });
175
+ };
123
176
  useEffect(() => {
124
177
  userStatusRef.current = userStatus;
125
178
  }, [userStatus]);
@@ -170,7 +223,8 @@ const YiChongCanvaProvider = ({
170
223
  startedAt: Date.now(),
171
224
  attempts: 0,
172
225
  stage: operation === "login" ? "canva_token" : "status",
173
- appKey: `${appId}|${productName}`
226
+ appKey: `${appId}|${productName}`,
227
+ usageOperationId: usageId()
174
228
  };
175
229
  accountRunRef.current = run;
176
230
  setAccountError(null);
@@ -199,6 +253,12 @@ const YiChongCanvaProvider = ({
199
253
  api: error instanceof AccountRequestError ? error.api : run.api
200
254
  };
201
255
  setAccountError(failure);
256
+ previousAccountFailureRef.current = { scope: run.appKey, operation: run.operation, operationId: run.usageOperationId };
257
+ reportAccountUsage(run.operation === "login" ? "login_fail" : "account_fail", "账户操作失败", run, {
258
+ stage: failure.stage,
259
+ error_code: String(failure.code),
260
+ http_status: failure.status
261
+ });
202
262
  reportAccountFailure(failure, run.appKey);
203
263
  };
204
264
  const login = (extraRetries = retry) => {
@@ -206,6 +266,9 @@ const YiChongCanvaProvider = ({
206
266
  loginPendingRef.current = true;
207
267
  setLoginStatus("loading");
208
268
  pollUserStatus.current = null;
269
+ queueMicrotask(() => {
270
+ if (isCurrentRun(run)) reportAccountUsage("login_start", "开始登录", run);
271
+ });
209
272
  void withRequest({ signal: run.controller.signal, timeoutMs: 3e4 }, async (signal) => {
210
273
  for (let attempt = 0; ; attempt++) {
211
274
  try {
@@ -229,6 +292,8 @@ const YiChongCanvaProvider = ({
229
292
  setLoginStatus("success");
230
293
  setAccountError(null);
231
294
  updateUserStatus(userStatus2);
295
+ reportAccountUsage("login_success", "登录成功", run);
296
+ reportAccountRecovery(run);
232
297
  window.userId = userStatus2.userId || "";
233
298
  window.pollUserSubscribe = pollUserStatus.current = startPolling;
234
299
  onUpdateUserStatus == null ? void 0 : onUpdateUserStatus(userStatus2);
@@ -290,6 +355,7 @@ const YiChongCanvaProvider = ({
290
355
  user.userId = userId;
291
356
  setAccountError(null);
292
357
  updateUserStatus(user);
358
+ reportAccountRecovery(run);
293
359
  finish(user);
294
360
  onUpdateUserStatus == null ? void 0 : onUpdateUserStatus(user);
295
361
  }).catch((error) => {
@@ -384,6 +450,12 @@ const YiChongCanvaProvider = ({
384
450
  userStatusRef.current = {};
385
451
  setUserStatus({});
386
452
  pollUserStatus.current = null;
453
+ previousAccountFailureRef.current = null;
454
+ }
455
+ const session = usageSessionRef.current;
456
+ if (!session.opened) {
457
+ session.opened = true;
458
+ void usageReportingApi.reportUsage({ sum_key: "app_open", title: "打开应用" });
387
459
  }
388
460
  if (autoLogin) login();
389
461
  else setLoginStatus("idle");
@@ -523,6 +595,7 @@ const YiChongCanvaProvider = ({
523
595
  user.userId = userId;
524
596
  setAccountError(null);
525
597
  updateUserStatus(user);
598
+ reportAccountRecovery(run);
526
599
  onUpdateUserStatus == null ? void 0 : onUpdateUserStatus(user);
527
600
  return user;
528
601
  }).catch((error) => {
@@ -684,9 +757,12 @@ const YiChongCanvaProvider = ({
684
757
  ...textModerationApi,
685
758
  ...contentExtractionApi,
686
759
  ...chatApi,
760
+ ...vttApi,
761
+ ...textToSpeechApi,
687
762
  ...usageApi,
688
763
  ...uploadApi,
689
764
  ...errorReportingApi,
765
+ ...usageReportingApi,
690
766
  userStatus,
691
767
  updateUserStatus,
692
768
  handleLogin: login,
@@ -4,4 +4,4 @@
4
4
  * 参数、返回值及方法的 JSDoc 定义在 types.ts,会随声明文件发布供编辑器提示。
5
5
  */
6
6
  export { ApiError } from './error';
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';
7
+ export type { ApiRequestOptions, ApiResponse, ChatApi, ChatParams, ChatPayload, ChatResult, CreateTextToSpeechParams, CreateTextToSpeechResult, GetTextToSpeechResultParams, TextToSpeechApi, TextToSpeechResult, TextToSpeechTaskState, CreateVttParams, CreateVttResult, GetVttStatusParams, VttApi, VttStatusResult, VttTaskState, CompleteUploadParams, CompleteUploadResponse, ContentExtractParams, ContentExtractResult, ContentExtractionApi, TextCheckParams, CreateSpecifyPredictionParams, ErrorReportingApi, ErrorReportSource, GetPredictionParams, GeneratePresignedUrlParams, GetUploadUrlParams, InitiateUploadParams, InitiateUploadResponse, JsonObject, JsonValue, Prediction, PredictionApi, ReportErrorParams, ReportUsageParams, UsageReportingApi, UsageReportingConfig, ReportErrorResult, PresignedUrlResponse, TextModerationApi, TextModerationCategory, TextModerationDecision, TextModerationResult, UploadApi, UploadFileParams, UploadFileResult, UploadedPart, UploadPartUrlResponse, UploadProgress, UsageApi, UsageParams, UsageResponse, } from './types';
@@ -21,6 +21,10 @@ declare const apiPaths: {
21
21
  readonly textCheck: "/api/public/text-moderation/check";
22
22
  readonly contentExtract: "/api/content-extract";
23
23
  readonly chat: "/api/chat";
24
+ readonly createVtt: "/get-vtt/create";
25
+ readonly getVttStatus: "/get-vtt/status";
26
+ readonly createTextToSpeech: "/api/text-to-speech/create";
27
+ readonly getTextToSpeechResult: "/api/text-to-speech/result";
24
28
  };
25
29
  /** 粗筛非空、非数组对象;是否属于普通 JSON 对象由 validateJson 进一步判断。 */
26
30
  export declare function isObject(value: unknown): value is Record<string, unknown>;
@@ -62,7 +66,8 @@ export declare function readJson(response: Response): Promise<unknown>;
62
66
  */
63
67
  export declare function backendError(response: Response, payload: unknown, fallbackCode: string | number): ApiError;
64
68
  /**
65
- * AI 接口的公共 POST:注入 Bearer JWT、Channel、语言与通用 query,并校验响应包。
69
+ * AI 接口的公共 POST:注入鉴权、Channel、语言与通用 query,并校验响应包。
70
+ * 旧 TTS 路由的 JWT 可选,其余保持原有 JWT 要求;账户归属不等于服务端身份验证。
66
71
  * 返回后端的 { code, msg, data },不提取/重命名 data;具体 API 再验证自己的业务数据。
67
72
  * 只执行一次请求,超时/取消涵盖读取响应正文;credentials: omit 不依赖浏览器 Cookie。
68
73
  * 禁止重定向,避免认证头被带往配置以外的跳转目标。
@@ -0,0 +1,8 @@
1
+ import { ApiContext } from './request';
2
+ import { TextToSpeechApi } from './types';
3
+ /**
4
+ * 封装现有异步 TTS 创建/查询协议;仅请求一次,不附加轮询、重试或额外消费。
5
+ * guid 由请求层使用当前系统 uid 注入,调用方不能覆盖 guid 或改变计费分支的 app_id。
6
+ * 语音、语言与上游模型的默认选择继续由后端负责;SDK 不维护会过时的语音枚举。
7
+ */
8
+ export declare function createTextToSpeechApi(getContext: () => ApiContext): TextToSpeechApi;
@@ -431,3 +431,158 @@ export interface UploadApi {
431
431
  */
432
432
  uploadFile(params: UploadFileParams, options?: ApiRequestOptions): Promise<UploadFileResult>;
433
433
  }
434
+ /** 音视频转录创建参数;至少传一个媒体 URL,系统 userId 由客户端当前身份自动注入。 */
435
+ export interface CreateVttParams {
436
+ /** 可访问的 HTTP(S) 音频地址;本地文件需先 uploadFile,不能直接传 File/Blob。 */
437
+ audio?: string;
438
+ /** 可访问的视频地址;与 audio 都非空时后端优先使用 video。 */
439
+ video?: string;
440
+ /** 是否请求字幕成片:0 不渲染、1 渲染;省略时沿用后端默认 0。 */
441
+ ifRender?: 0 | 1;
442
+ /** 可选邮箱,原样传给后端;SDK 不从账户信息中猜测或补写。 */
443
+ email?: string;
444
+ /** 原有后端参数;pre 表示创建/复用任务但不立即派发,普通转录应省略。 */
445
+ env?: string;
446
+ }
447
+ /** 使用创建响应中的 data.jobId 查询;也支持旧音频/视频入口创建的同一任务。 */
448
+ export interface GetVttStatusParams {
449
+ jobId: string;
450
+ }
451
+ /** 原始任务状态;code=0 只代表请求成功,任务仍可能失败或正在处理。 */
452
+ export interface VttTaskState {
453
+ /** 常见值:-1 失败、0 排队、2 处理中、10 成功;保留 number 以兼容后端新增状态。 */
454
+ status: number;
455
+ /** 后端状态描述,原样保留。 */
456
+ status_str: string;
457
+ /** 失败原因等信息;排队或成功时可以为空。 */
458
+ remark?: string | null;
459
+ [key: string]: unknown;
460
+ }
461
+ /** 创建响应的 data,不是字幕结果;也可能复用已有任务并返回其当前状态。 */
462
+ export interface CreateVttResult extends VttTaskState {
463
+ jobId: string;
464
+ }
465
+ /** 查询响应的 data;保留原字段,不将 result 重命名或自动下载。 */
466
+ export interface VttStatusResult extends VttTaskState {
467
+ /**
468
+ * 字幕片段数组的 JSON 字符串,字段为 start_time、end_time、text;不是 WEBVTT 文件文本。
469
+ * 尚未完成或失败时允许 null;SDK 原样返回,业务需要片段数组时自行 JSON.parse。
470
+ */
471
+ result: string | null;
472
+ /** 后端字幕成片地址,未生成时允许 null。 */
473
+ final_video_url: string | null;
474
+ }
475
+ /** /get-vtt 通用转录;两种媒体共用创建和查询,不额外包装音频/视频专属方法。 */
476
+ export interface VttApi {
477
+ /**
478
+ * POST /get-vtt/create,默认超时 60 秒,支持 signal 和 timeoutMs。
479
+ * 自动携带当前用户 JWT、通用 query 和正文 userId;不自动上传、重试或轮询。
480
+ * 返回完整 code/msg/data;检查 data.status,不能只凭 code=0 判定任务成功。
481
+ * @example
482
+ * const task = await client.createVtt({ audio: uploaded.url });
483
+ * const jobId = task.data.jobId;
484
+ */
485
+ createVtt(params: CreateVttParams, options?: ApiRequestOptions): Promise<ApiResponse<CreateVttResult>>;
486
+ /**
487
+ * POST /get-vtt/status,默认超时 60 秒;只查询一次,由应用决定轮询间隔和总时限。
488
+ * status=10 时读取 result,status=-1 时展示 remark;取消请求不会取消后台任务。
489
+ * 不额外调用消费接口,后端自身的额度检查与用量记录保持原行为。
490
+ */
491
+ getVttStatus(params: GetVttStatusParams, options?: ApiRequestOptions): Promise<ApiResponse<VttStatusResult>>;
492
+ }
493
+ /** TTS 创建参数;仅保留后端的规范字段,系统 guid 由当前账户自动注入。 */
494
+ export interface CreateTextToSpeechParams {
495
+ /** 待合成文本,1 至 5000 个 Unicode 字符;保留原始空白,不自动裁剪或分段。 */
496
+ text: string;
497
+ /** 后端支持的语音 ID,例如 Arrogant_Miss;省略时由后端默认使用 alloy。 */
498
+ voice?: string;
499
+ /** 情感参数,例如 auto;不固定枚举,由后端及语音供应商判断是否支持。 */
500
+ emotion?: string;
501
+ /** 语速,0.5 至 2.0;省略时由后端使用 1.0,SDK 不自行舍入。 */
502
+ speed?: number;
503
+ /** 语言代码;省略时由后端识别文本语言,不从界面语言推断。 */
504
+ language?: string;
505
+ /** 可访问的 HTTP(S) 参考音频 URL;文件需先上传,不能直接传 File/Blob。 */
506
+ refer_audio?: string;
507
+ /**
508
+ * 参考音频对应的文本,最多 5000 个 Unicode 字符。
509
+ * 后端仅在 refer_audio 非空时使用;超过 5000 会被后端忽略,因此 SDK 提前拒绝超长值。
510
+ */
511
+ refer_audio_text?: string;
512
+ }
513
+ /** 使用创建响应中的 data.jobId 查询,不重复提交文本、语音或用户身份。 */
514
+ export interface GetTextToSpeechResultParams {
515
+ jobId: string;
516
+ }
517
+ /** TTS 任务快照;code=0 只代表接口成功,生成是否完成须检查 status。 */
518
+ export interface TextToSpeechTaskState {
519
+ /** 创建和查询响应都保留后端任务 ID。 */
520
+ jobId: string;
521
+ /** 常见值:-1 失败、0 排队、2 处理中、10 成功;兼容后端新增整数状态。 */
522
+ status: number;
523
+ /** 后端状态描述,例如 waiting、processing、done、fail。 */
524
+ status_str: string;
525
+ /** 任务失败原因,例如余额不足;排队或成功时可以为空。 */
526
+ remark?: string | null;
527
+ [key: string]: unknown;
528
+ }
529
+ /** 创建返回的任务状态;尚不包含音频结果,也可能立即返回 status=-1。 */
530
+ export type CreateTextToSpeechResult = TextToSpeechTaskState;
531
+ /** 查询返回的任务状态与音频结果;SDK 不改名、不下载、不自动插入设计。 */
532
+ export interface TextToSpeechResult extends TextToSpeechTaskState {
533
+ /** 后端生成的音频 URL;排队、处理中或失败时可以为 null 或空字符串。 */
534
+ result: string | null;
535
+ }
536
+ /** 异步文字转语音;保留现有 /api/text-to-speech 路径及 code/msg/data 响应包。 */
537
+ export interface TextToSpeechApi {
538
+ /**
539
+ * POST /api/text-to-speech/create,默认超时 60 秒,支持 signal 和 timeoutMs。
540
+ * 等待当前账户身份就绪,自动注入 guid 和通用 query;有有效 JWT 时附带 Bearer,无 JWT 时省略。
541
+ * 该旧接口本身未强制校验 JWT;query/guid 仅是归属字段,不应理解为服务端鉴权保证。
542
+ * 不接收 app_id/userId/guid 覆盖,不改变后端额度检查和用量记录,也不额外调用消费接口。
543
+ * 不重试、不轮询;超时/中止只停止客户端等待,后端可能已经创建任务。
544
+ * @example
545
+ * const task = await client.createTextToSpeech({ text: "你好", voice: "Arrogant_Miss", emotion: "auto" });
546
+ * const jobId = task.data.jobId;
547
+ */
548
+ createTextToSpeech(params: CreateTextToSpeechParams, options?: ApiRequestOptions): Promise<ApiResponse<CreateTextToSpeechResult>>;
549
+ /**
550
+ * POST /api/text-to-speech/result,默认超时 60 秒;只查询一次,由应用安排轮询及总时限。
551
+ * status=10 时读取 result;status=-1 时展示 remark。失败任务原样返回,不作为接口异常抛出。
552
+ */
553
+ getTextToSpeechResult(params: GetTextToSpeechResultParams, options?: ApiRequestOptions): Promise<ApiResponse<TextToSpeechResult>>;
554
+ }
555
+ /** 行为统计配置;独立于消费记账与飞书错误告警,关闭后不会发出埋点请求。 */
556
+ export interface UsageReportingConfig {
557
+ /** 默认 true;测试、预览或明确退出统计时可关闭。 */
558
+ enabled?: boolean;
559
+ /** 完整 GET 接口地址,默认 https://log.aibabygenerator.io/api/report;不附加固定路径。 */
560
+ endpoint?: string;
561
+ /** 统计后台的应用键;Canva 默认 {productName}_canva,公共客户端默认 {appChannel}_{platform}。 */
562
+ appKey?: string;
563
+ }
564
+ /** 仅传行为和少量统计属性;用户、应用、时间和事件 UUID 由客户端提供。 */
565
+ export interface ReportUsageParams {
566
+ /** 稳定事件名,例如 generate_start / generate_success;最多 64 字符,使用字母、数字、_、-、.、:。 */
567
+ sum_key: string;
568
+ /** 展示在统计后台的固定标题,不放用户输入,最多保留 128 字符。 */
569
+ title: string;
570
+ /**
571
+ * 少量统计属性,例如 operation_id、page、duration_ms、model、error_code。
572
+ * 不传提示词、完整 input、文件、资源地址、token 或异常对象;敏感字段和值会脱敏。
573
+ * 对象最多 3 层、30 个字段,数组最多 10 项,字符串最多 256 字符;最终 URL 最多 8192 字符。
574
+ */
575
+ data?: Record<string, unknown> | null;
576
+ }
577
+ /** 行为统计,不扣费、不刷新账户、不弹错误,也不会把自身失败转发到飞书。 */
578
+ export interface UsageReportingApi {
579
+ /**
580
+ * 兼容旧 GET /api/report 和 data 的双重 URL 编码;无需登录,不使用 JWT / passport。
581
+ * 返回是否收到 HTTP 成功确认,失败/关闭/取消/非法参数均返回 false,永不向业务抛错;可 void 调用。
582
+ * 默认每次请求最多 4 秒,网络/超时/429/5xx 最多重试一次,两次复用同一个事件 UUID;其他 4xx 不重试。
583
+ * options.timeoutMs 可缩短单次预算,最大 4000;signal 取消后不再重试。
584
+ * 服务端统计 timestamp 由 Worker 生成;客户端发生时间保存在 data.occurred_at。
585
+ * UUID 标识一次事件,data.operation_id 关联同一次业务流程,两者不能混用。
586
+ */
587
+ reportUsage(params: ReportUsageParams, options?: ApiRequestOptions): Promise<boolean>;
588
+ }
@@ -0,0 +1,16 @@
1
+ import { CommonRequestContext } from './request';
2
+ import { UsageReportingApi, UsageReportingConfig } from './types';
3
+ /** Provider 当前快照;账户尚未就绪也可调用,不通过登录校验或账户消费 API。 */
4
+ export interface UsageReportingContext extends CommonRequestContext {
5
+ usageReporting?: UsageReportingConfig;
6
+ /** Provider 提供 session_id/app_version 等基础属性,业务不能覆盖同名字段。 */
7
+ metadata?: Record<string, unknown>;
8
+ /** 已知凭据只参与脱敏,绝不发送至统计接口。 */
9
+ secrets?: readonly string[];
10
+ }
11
+ /**
12
+ * 兼容已有图片 GET 统计接口,改用 fetch 读取 HTTP 确认以便做有限重试。
13
+ * 不通过业务请求层鉴权,不要求账户就绪;任何失败都只返回 false。
14
+ * 重试复用完整 URL(同一 UUID/身份/发生时间),让 Worker 的 UUID 唯一索引去重。
15
+ */
16
+ export declare function createUsageReportingApi(getContext: () => UsageReportingContext): UsageReportingApi;
@@ -0,0 +1,2 @@
1
+ export declare function usageReportingText(value: string, maxLength: number, secrets: readonly string[]): string;
2
+ export declare function usageReportingData(value: unknown, secrets: readonly string[]): Record<string, unknown>;
@@ -0,0 +1,9 @@
1
+ import { ApiContext } from './request';
2
+ import { VttApi } from './types';
3
+ /**
4
+ * 通用音视频转录,只绑定 /get-vtt/create 和 /get-vtt/status。
5
+ * 每次调用读取最新身份,创建正文的 userId 由公共请求层注入系统用户 ID。
6
+ * 保留 code/msg/data 和 jobId 等后端字段,不自动上传、轮询、重试或调用消费接口。
7
+ * 中止请求只停止客户端等待,不能取消已经创建的后端任务。
8
+ */
9
+ export declare function createVttApi(getContext: () => ApiContext): VttApi;
@@ -1,6 +1,6 @@
1
1
  import { default as React } from 'react';
2
2
  import { AccountError } from './account';
3
- import { ChatApi, ContentExtractionApi, ErrorReportingApi, PredictionApi, TextModerationApi, UploadApi, UsageApi } from '../api/types';
3
+ import { ChatApi, ContentExtractionApi, ErrorReportingApi, PredictionApi, TextModerationApi, TextToSpeechApi, UploadApi, UsageApi, UsageReportingApi, VttApi } from '../api/types';
4
4
  import { canUseError, CheckoutSessionOptions, TestMode, UserStatus } from './interface';
5
5
  /**
6
6
  * `useYiChongCanva()` 返回的客户端:账户状态、历史额度方法和后端同名 API 共用一个 Provider。
@@ -8,7 +8,7 @@ import { canUseError, CheckoutSessionOptions, TestMode, UserStatus } from './int
8
8
  * `userStatus` 等字段随 React 渲染更新;后端 API 则在每次调用时读取 Provider 的最新身份引用。
9
9
  * 新的消费 API 会返回 Promise;历史 `use()` 是本地更新加异步上报,不能等待它确认服务器扣费。
10
10
  */
11
- export interface YiChongCanvaContextType extends PredictionApi, TextModerationApi, ContentExtractionApi, ChatApi, UsageApi, UploadApi, ErrorReportingApi {
11
+ export interface YiChongCanvaContextType extends PredictionApi, TextModerationApi, ContentExtractionApi, ChatApi, VttApi, TextToSpeechApi, UsageApi, UploadApi, ErrorReportingApi, UsageReportingApi {
12
12
  /** 当前账户快照;登录前为 `{}`。Canva 用户 ID 是 userId,系统用户 ID 是 profile.id。 */
13
13
  userStatus: UserStatus;
14
14
  /** 深度合并本地账户快照,并同步 API 使用的引用;不请求服务器,也不触发 onUpdateUserStatus。 */
@@ -73,6 +73,7 @@ export interface YiChongCanvaContextType extends PredictionApi, TextModerationAp
73
73
  /**
74
74
  * 默认 Context 仅用于兼容历史读取方式,不能替代真正的 Provider。
75
75
  * 缺少 Provider 时,历史账户方法返回空值或不执行操作;后端 API 明确拒绝 provider_missing。
76
+ * 行为统计是非阻塞辅助能力:缺少 Provider 的 reportUsage 只返回 false,不影响业务。
76
77
  * 由于这里提供了非空默认对象,useYiChongCanva 的空值保护本身不会在这种场景抛错。
77
78
  */
78
79
  export declare const YiChongCanvaContext: React.Context<YiChongCanvaContextType>;
@@ -1,5 +1,6 @@
1
1
  import { default as React } from 'react';
2
2
  import { Mode, TestMode, UserStatus } from './interface';
3
+ import { UsageReportingConfig } from '../api/types';
3
4
  /**
4
5
  * 应用入口的账户与 API 配置。不同服务有独立根地址,修改其中一个不会自动改写其他服务地址。
5
6
  * productName 应使用后端登记的应用渠道名称,而不是界面中可随意修改的标题。
@@ -15,16 +16,24 @@ export interface YiChongCanvaProviderProps {
15
16
  onUpdateUserStatus?: (userStatus: UserStatus) => void;
16
17
  /** 账户扣费地址(含所需应用路径),无默认值;登录/status 仍使用固定 usa.imgkits.com 地址。 */
17
18
  baseUrl: string;
18
- /** 预测与文本审核服务根地址,默认 https://api.imgkits.com;不覆盖账户、上传或 Chat 地址。 */
19
+ /** 预测、文本审核与音视频转录服务根地址,默认 https://api.imgkits.com;不覆盖账户、上传或 Chat 地址。 */
19
20
  apiBaseUrl?: string;
20
21
  /** 内容提取服务根地址,默认 https://ai.imgkits.com。 */
21
22
  contentBaseUrl?: string;
22
23
  /** 大模型 Chat 服务根地址,默认 https://ai.imgkits.com。 */
23
24
  chatBaseUrl?: string;
25
+ /** 文本转语音的异步创建/结果服务根地址,默认 https://ai.imgkits.com;与转录服务独立。 */
26
+ ttsBaseUrl?: string;
24
27
  /** 既有 Cloudflare R2 签名/分片接口根地址,默认 https://ai.imgkits.com。 */
25
28
  uploadBaseUrl?: string;
26
29
  /** 每次请求获取当前语言,用于 Accept-Language;缺省回退到浏览器语言,不要固定捕获过期语言。 */
27
30
  getLocale?: () => string;
31
+ /**
32
+ * 用户行为统计,默认开启并兼容旧 GET /api/report;与飞书错误上报独立。
33
+ * enabled=false 同时关闭公共与手动埋点;endpoint 可替换统计服务,appKey 可覆盖历史应用键。
34
+ * 自动补充当前身份、会话及应用发布号,登录前可发送;不读取或上报业务输入、结果正文。
35
+ */
36
+ usageReporting?: UsageReportingConfig;
28
37
  /** 默认 true,挂载后自动登录;false 时由 client.handleLogin/manualLogin 显式启动。 */
29
38
  autoLogin?: boolean;
30
39
  /** 初始模拟模式,默认 noTest;挂载 effect 会将开发环境设为 credits、其他环境设为 noTest。 */
@@ -58,4 +67,4 @@ export interface YiChongCanvaProviderProps {
58
67
  * // App 或其子组件内:const client = useYiChongCanva();
59
68
  * // 账号就绪后,直接调用 client.createSpecifyPrediction({ owner, name, input })。
60
69
  */
61
- export declare const YiChongCanvaProvider: ({ children, appId, productName, onUpdateUserStatus, baseUrl, apiBaseUrl, contentBaseUrl, chatBaseUrl, uploadBaseUrl, getLocale, autoLogin, testMode: _testMode, version, mode, retry, maxAvailablePoints, }: YiChongCanvaProviderProps) => React.JSX.Element;
70
+ export declare const YiChongCanvaProvider: ({ children, appId, productName, onUpdateUserStatus, baseUrl, apiBaseUrl, contentBaseUrl, chatBaseUrl, ttsBaseUrl, uploadBaseUrl, getLocale, usageReporting, 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": "2.2.0",
3
+ "version": "2.4.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",