yichong-canva2 2.5.1 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +107 -0
- package/dist/api/error.js +28 -2
- package/dist/api/predictions.js +7 -2
- package/dist/api/reporting.js +8 -4
- package/dist/api/request.js +11 -5
- package/dist/api/telemetry/client.js +281 -0
- package/dist/api/telemetry/map_legacy.js +68 -0
- package/dist/api/telemetry/sanitize.js +108 -0
- package/dist/api/telemetry/stage.js +74 -0
- package/dist/api/usage_reporting.js +9 -5
- package/dist/index.js +13 -1
- package/dist/login/context.js +3 -0
- package/dist/login/pricing_unit.js +48 -0
- package/dist/login/privider.js +82 -4
- package/dist/types/api/error.d.ts +25 -1
- package/dist/types/api/index.d.ts +3 -2
- package/dist/types/api/reporting.d.ts +3 -1
- package/dist/types/api/request.d.ts +6 -2
- package/dist/types/api/telemetry/client.d.ts +34 -0
- package/dist/types/api/telemetry/index.d.ts +2 -0
- package/dist/types/api/telemetry/map_legacy.d.ts +14 -0
- package/dist/types/api/telemetry/sanitize.d.ts +11 -0
- package/dist/types/api/telemetry/stage.d.ts +34 -0
- package/dist/types/api/telemetry/types.d.ts +86 -0
- package/dist/types/api/types.d.ts +21 -6
- package/dist/types/api/usage_reporting.d.ts +3 -1
- package/dist/types/login/context.d.ts +12 -3
- package/dist/types/login/index.d.ts +2 -0
- package/dist/types/login/pricing_unit.d.ts +15 -0
- package/dist/types/login/privider.d.ts +8 -1
- package/package.json +1 -1
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { isAbortError, ApiError } from "../error.js";
|
|
2
|
+
import { usageReportingText } from "../usage_reporting_payload.js";
|
|
3
|
+
import { isReportStage, StageError, toErrorCode } from "./stage.js";
|
|
4
|
+
const keyPattern = /^[a-z][a-z0-9_]{0,39}$/;
|
|
5
|
+
const sensitiveSegments = /* @__PURE__ */ new Set([
|
|
6
|
+
"prompt",
|
|
7
|
+
"text",
|
|
8
|
+
"content",
|
|
9
|
+
"message",
|
|
10
|
+
"url",
|
|
11
|
+
"uri",
|
|
12
|
+
"link",
|
|
13
|
+
"href",
|
|
14
|
+
"token",
|
|
15
|
+
"jwt",
|
|
16
|
+
"passport",
|
|
17
|
+
"authorization",
|
|
18
|
+
"cookie",
|
|
19
|
+
"password",
|
|
20
|
+
"secret",
|
|
21
|
+
"credential",
|
|
22
|
+
"email",
|
|
23
|
+
"stack",
|
|
24
|
+
"body",
|
|
25
|
+
"html"
|
|
26
|
+
]);
|
|
27
|
+
const sensitiveKeys = /* @__PURE__ */ new Set(["input", "output", "result", "file", "filename", "file_name", "image", "audio", "video", "data"]);
|
|
28
|
+
const MAX_PROPS = 20;
|
|
29
|
+
const MAX_DURATION = 30 * 24 * 60 * 60 * 1e3;
|
|
30
|
+
function isSensitiveKey(key) {
|
|
31
|
+
return sensitiveKeys.has(key) || key.split("_").some((segment) => sensitiveSegments.has(segment));
|
|
32
|
+
}
|
|
33
|
+
function cleanProps(input, secrets) {
|
|
34
|
+
const props = {};
|
|
35
|
+
let dropped = 0;
|
|
36
|
+
if (input === null || typeof input !== "object" || Array.isArray(input)) return { props, dropped };
|
|
37
|
+
for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(input))) {
|
|
38
|
+
if (!descriptor.enumerable || !("value" in descriptor)) continue;
|
|
39
|
+
const value = descriptor.value;
|
|
40
|
+
if (Object.keys(props).length >= MAX_PROPS || !keyPattern.test(key) || isSensitiveKey(key)) {
|
|
41
|
+
dropped++;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (value === null || typeof value === "boolean") props[key] = value;
|
|
45
|
+
else if (typeof value === "number" && Number.isFinite(value)) props[key] = value;
|
|
46
|
+
else if (typeof value === "string") {
|
|
47
|
+
const clean = usageReportingText(value, 128, secrets);
|
|
48
|
+
if (clean.includes("[redacted]") || clean !== value.slice(0, clean.length)) dropped++;
|
|
49
|
+
else props[key] = clean;
|
|
50
|
+
} else dropped++;
|
|
51
|
+
}
|
|
52
|
+
return { props, dropped };
|
|
53
|
+
}
|
|
54
|
+
function cleanTimings(input) {
|
|
55
|
+
if (input === null || typeof input !== "object" || Array.isArray(input)) return void 0;
|
|
56
|
+
const timings = {};
|
|
57
|
+
for (const [key, value] of Object.entries(input)) {
|
|
58
|
+
if (isReportStage(key) && typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= MAX_DURATION) {
|
|
59
|
+
timings[key] = Math.round(value);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return Object.keys(timings).length ? timings : void 0;
|
|
63
|
+
}
|
|
64
|
+
function cleanDuration(value) {
|
|
65
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= MAX_DURATION ? Math.round(value) : void 0;
|
|
66
|
+
}
|
|
67
|
+
const expectedCodes = /* @__PURE__ */ new Set([
|
|
68
|
+
"ABORTED",
|
|
69
|
+
"POLICY_BLOCKED",
|
|
70
|
+
"NOT_FOUND",
|
|
71
|
+
"USER_OFFLINE",
|
|
72
|
+
"PERMISSION_DENIED",
|
|
73
|
+
"IMAGE_UNAVAILABLE",
|
|
74
|
+
"INVALID_INPUT",
|
|
75
|
+
"TOO_MANY_CONCURRENT_TASKS",
|
|
76
|
+
"IMAGE_PREPROCESSING_FAILED",
|
|
77
|
+
"NO_OUTPUT"
|
|
78
|
+
]);
|
|
79
|
+
function cleanError(input, secrets) {
|
|
80
|
+
var _a;
|
|
81
|
+
const stage = isReportStage(input.stage) ? input.stage : "unknown";
|
|
82
|
+
const cause = input.cause instanceof StageError ? input.cause.cause : input.cause;
|
|
83
|
+
const code = typeof input.code === "string" && /^[A-Z][A-Z0-9_]{1,63}$/.test(input.code) ? input.code : input.cause instanceof StageError ? input.cause.code : toErrorCode(cause, stage);
|
|
84
|
+
const stageExpected = input.cause instanceof StageError ? input.cause.expected : void 0;
|
|
85
|
+
const expected = input.expected ?? stageExpected ?? (isAbortError(cause) || expectedCodes.has(code));
|
|
86
|
+
const payload = { code, stage, expected };
|
|
87
|
+
const fields = cause !== null && typeof cause === "object" ? cause : void 0;
|
|
88
|
+
if (typeof (fields == null ? void 0 : fields.name) === "string") payload.name = usageReportingText(fields.name, 128, secrets);
|
|
89
|
+
const message = typeof cause === "string" ? cause : typeof (fields == null ? void 0 : fields.message) === "string" ? fields.message : void 0;
|
|
90
|
+
if (message) payload.message = usageReportingText(message, 500, secrets);
|
|
91
|
+
if (!expected && typeof (fields == null ? void 0 : fields.stack) === "string") {
|
|
92
|
+
payload.stack = Array.from(fields.stack.split("\n").slice(0, 40).map((line) => usageReportingText(line, 300, secrets)).join("\n")).slice(0, 4096).join("");
|
|
93
|
+
}
|
|
94
|
+
if (cause instanceof ApiError) {
|
|
95
|
+
if (cause.status !== void 0) payload.http_status = cause.status;
|
|
96
|
+
if (typeof cause.code === "number") payload.backend_code = String(cause.code);
|
|
97
|
+
const requestId = cause.traceId ?? ((_a = cause.data) == null ? void 0 : _a.request_id);
|
|
98
|
+
if (typeof requestId === "string") payload.request_id = usageReportingText(requestId, 128, secrets);
|
|
99
|
+
}
|
|
100
|
+
return payload;
|
|
101
|
+
}
|
|
102
|
+
export {
|
|
103
|
+
cleanDuration,
|
|
104
|
+
cleanError,
|
|
105
|
+
cleanProps,
|
|
106
|
+
cleanTimings,
|
|
107
|
+
isSensitiveKey
|
|
108
|
+
};
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { isAbortError, ApiError } from "../error.js";
|
|
2
|
+
const REPORT_STAGES = [
|
|
3
|
+
"input_read",
|
|
4
|
+
"selection_read",
|
|
5
|
+
"upload",
|
|
6
|
+
"text_check",
|
|
7
|
+
"content_extract",
|
|
8
|
+
"chat",
|
|
9
|
+
"create_prediction",
|
|
10
|
+
"wait_prediction",
|
|
11
|
+
"cancel_prediction",
|
|
12
|
+
"tts",
|
|
13
|
+
"vtt",
|
|
14
|
+
"direct_api",
|
|
15
|
+
"parse_result",
|
|
16
|
+
"download_result",
|
|
17
|
+
"local_render",
|
|
18
|
+
"insert",
|
|
19
|
+
"consume",
|
|
20
|
+
"render",
|
|
21
|
+
"account",
|
|
22
|
+
"unknown"
|
|
23
|
+
];
|
|
24
|
+
function isReportStage(value) {
|
|
25
|
+
return typeof value === "string" && REPORT_STAGES.includes(value);
|
|
26
|
+
}
|
|
27
|
+
const errorCodePattern = /^[A-Z][A-Z0-9_]{1,63}$/;
|
|
28
|
+
class StageError extends Error {
|
|
29
|
+
constructor(cause, options) {
|
|
30
|
+
super(cause instanceof Error ? cause.message : typeof cause === "string" ? cause : "Stage failed.");
|
|
31
|
+
this.name = "StageError";
|
|
32
|
+
this.stage = options.stage;
|
|
33
|
+
this.code = options.code !== void 0 && errorCodePattern.test(options.code) ? options.code : toErrorCode(cause, options.stage);
|
|
34
|
+
this.expected = options.expected;
|
|
35
|
+
this.cause = cause;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function toErrorCode(error, stage) {
|
|
39
|
+
if (error instanceof StageError) return error.code;
|
|
40
|
+
if (isAbortError(error)) return "ABORTED";
|
|
41
|
+
if (error instanceof ApiError && error.errorCode) {
|
|
42
|
+
return error.errorCode === "content_policy_violation" ? "POLICY_BLOCKED" : error.errorCode.toUpperCase();
|
|
43
|
+
}
|
|
44
|
+
const code = error instanceof ApiError ? error.code : error !== null && typeof error === "object" && "code" in error ? error.code : void 0;
|
|
45
|
+
if (typeof code === "string" && /^[a-z][a-z0-9_]{1,63}$/.test(code)) return code.toUpperCase();
|
|
46
|
+
if (typeof code === "string" && errorCodePattern.test(code)) return code;
|
|
47
|
+
if (stage && stage !== "unknown") return `${stage.toUpperCase()}_FAILED`;
|
|
48
|
+
return "UNKNOWN";
|
|
49
|
+
}
|
|
50
|
+
function createStageTimer(now = () => Date.now()) {
|
|
51
|
+
const timings = {};
|
|
52
|
+
const add = (stage, ms) => {
|
|
53
|
+
timings[stage] = (timings[stage] ?? 0) + Math.max(0, Math.round(ms));
|
|
54
|
+
};
|
|
55
|
+
return {
|
|
56
|
+
timings,
|
|
57
|
+
async run(stage, task) {
|
|
58
|
+
const startedAt = now();
|
|
59
|
+
try {
|
|
60
|
+
return await task();
|
|
61
|
+
} finally {
|
|
62
|
+
add(stage, now() - startedAt);
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
add
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
export {
|
|
69
|
+
REPORT_STAGES,
|
|
70
|
+
StageError,
|
|
71
|
+
createStageTimer,
|
|
72
|
+
isReportStage,
|
|
73
|
+
toErrorCode
|
|
74
|
+
};
|
|
@@ -5,25 +5,29 @@ import { usageReportingData, usageReportingText } from "./usage_reporting_payloa
|
|
|
5
5
|
function createUsageReportingApi(getContext) {
|
|
6
6
|
return {
|
|
7
7
|
async reportUsage(params, options = {}) {
|
|
8
|
-
var _a, _b, _c, _d, _e;
|
|
8
|
+
var _a, _b, _c, _d, _e, _f;
|
|
9
9
|
try {
|
|
10
10
|
const context = getContext();
|
|
11
11
|
const config = context.usageReporting ?? {};
|
|
12
12
|
if (config.enabled === false || ((_a = options.signal) == null ? void 0 : _a.aborted)) return false;
|
|
13
13
|
if (config.enabled !== void 0 && typeof config.enabled !== "boolean") return false;
|
|
14
|
-
|
|
14
|
+
try {
|
|
15
|
+
if (params && typeof params === "object") (_b = context.capture) == null ? void 0 : _b.call(context, params);
|
|
16
|
+
} catch {
|
|
17
|
+
}
|
|
18
|
+
if (!params || typeof params !== "object" || Array.isArray(params) || Object.keys(params).some((key) => !["sum_key", "title", "data", "flow", "timings", "error"].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
19
|
const appKey = config.appKey ?? `${context.productName}_canva`;
|
|
16
20
|
if (typeof appKey !== "string" || !/^[a-zA-Z0-9_.:-]{1,128}$/.test(appKey)) return false;
|
|
17
21
|
const timeoutMs = options.timeoutMs ?? 4e3;
|
|
18
22
|
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 4e3) return false;
|
|
19
23
|
const url = new URL(config.endpoint ?? "https://log.aibabygenerator.io/api/report");
|
|
20
24
|
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, (
|
|
25
|
+
const secrets = [context.userStatus.jwt, (_c = context.userStatus.profile) == null ? void 0 : _c.token, (_d = context.userStatus.drive) == null ? void 0 : _d.fresh_token, ...context.secrets ?? []].filter((value) => typeof value === "string" && value.length > 0);
|
|
22
26
|
const occurredAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
23
27
|
const base = usageReportingData({ ...context.metadata, occurred_at: occurredAt }, secrets);
|
|
24
28
|
const attributes = usageReportingData(params.data, secrets);
|
|
25
29
|
const data = usageReportingData({ ...base, ...Object.fromEntries(Object.entries(attributes).filter(([key]) => !(key in base))) }, secrets);
|
|
26
|
-
const userId = (
|
|
30
|
+
const userId = (_e = context.userStatus.profile) == null ? void 0 : _e.id;
|
|
27
31
|
if (userId !== void 0 && (typeof userId !== "string" || userId.length > 128)) return false;
|
|
28
32
|
const title = usageReportingText(params.title, 128, secrets);
|
|
29
33
|
url.searchParams.set("app_key", appKey);
|
|
@@ -45,7 +49,7 @@ function createUsageReportingApi(getContext) {
|
|
|
45
49
|
if (url.href.length > 8192) return false;
|
|
46
50
|
const requestUrl = url.toString();
|
|
47
51
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
48
|
-
if ((
|
|
52
|
+
if ((_f = options.signal) == null ? void 0 : _f.aborted) return false;
|
|
49
53
|
try {
|
|
50
54
|
const response = await withRequest({ signal: options.signal, timeoutMs }, (signal) => fetch(requestUrl, {
|
|
51
55
|
method: "GET",
|
package/dist/index.js
CHANGED
|
@@ -1,13 +1,25 @@
|
|
|
1
1
|
import { YiChongCanvaProvider } from "./login/privider.js";
|
|
2
2
|
import { YiChongCanvaContext } from "./login/context.js";
|
|
3
3
|
import { useYiChongCanva } from "./login/use_canva.js";
|
|
4
|
-
import {
|
|
4
|
+
import { PRICING_LANGUAGE_BASE_URL, loadPricingUnit } from "./login/pricing_unit.js";
|
|
5
|
+
import { ApiError, getBackendErrorCode, getDisplayMessage, isAbortError, isPolicyBlocked } from "./api/error.js";
|
|
5
6
|
import { getPredictionOutputUrl } from "./api/predictions.js";
|
|
7
|
+
import { REPORT_STAGES, StageError, createStageTimer, isReportStage, toErrorCode } from "./api/telemetry/stage.js";
|
|
6
8
|
export {
|
|
7
9
|
ApiError,
|
|
10
|
+
PRICING_LANGUAGE_BASE_URL,
|
|
11
|
+
REPORT_STAGES,
|
|
12
|
+
StageError,
|
|
8
13
|
YiChongCanvaContext,
|
|
9
14
|
YiChongCanvaProvider,
|
|
15
|
+
createStageTimer,
|
|
16
|
+
getBackendErrorCode,
|
|
17
|
+
getDisplayMessage,
|
|
10
18
|
getPredictionOutputUrl,
|
|
11
19
|
isAbortError,
|
|
20
|
+
isPolicyBlocked,
|
|
21
|
+
isReportStage,
|
|
22
|
+
loadPricingUnit,
|
|
23
|
+
toErrorCode,
|
|
12
24
|
useYiChongCanva
|
|
13
25
|
};
|
package/dist/login/context.js
CHANGED
|
@@ -34,6 +34,7 @@ const YiChongCanvaContext = React.createContext(
|
|
|
34
34
|
},
|
|
35
35
|
loginStatus: "idle",
|
|
36
36
|
accountError: null,
|
|
37
|
+
pricingUnit: null,
|
|
37
38
|
manualLogin: () => {
|
|
38
39
|
},
|
|
39
40
|
createSpecifyPrediction: async () => {
|
|
@@ -73,6 +74,8 @@ const YiChongCanvaContext = React.createContext(
|
|
|
73
74
|
throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
|
|
74
75
|
},
|
|
75
76
|
reportUsage: async () => false,
|
|
77
|
+
track: () => {
|
|
78
|
+
},
|
|
76
79
|
reduceFreeCnt: async () => {
|
|
77
80
|
throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
|
|
78
81
|
},
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { withRequest } from "../api/transport.js";
|
|
2
|
+
const PRICING_LANGUAGE_BASE_URL = "https://project.deletetweets.ai/yichong_pricing_language";
|
|
3
|
+
const channelPattern = /^[a-z0-9_]{1,64}$/;
|
|
4
|
+
const languagePattern = /^[a-z]{2,3}$/;
|
|
5
|
+
const TIMEOUT_MS = 1e4;
|
|
6
|
+
const MAX_UNIT_LENGTH = 40;
|
|
7
|
+
function cleanUnit(value) {
|
|
8
|
+
if (typeof value !== "string") return void 0;
|
|
9
|
+
const text = value.trim();
|
|
10
|
+
return text && text.length <= MAX_UNIT_LENGTH && !/[<>{}]/.test(text) ? text : void 0;
|
|
11
|
+
}
|
|
12
|
+
async function fetchUnit(channel, lang, signal) {
|
|
13
|
+
return withRequest({ signal, timeoutMs: TIMEOUT_MS }, async (requestSignal) => {
|
|
14
|
+
const response = await fetch(`${PRICING_LANGUAGE_BASE_URL}/${channel}/${lang}.json`, {
|
|
15
|
+
cache: "no-cache",
|
|
16
|
+
credentials: "omit",
|
|
17
|
+
redirect: "error",
|
|
18
|
+
signal: requestSignal
|
|
19
|
+
});
|
|
20
|
+
if (!response.ok) return null;
|
|
21
|
+
const body = await response.json().catch(() => null);
|
|
22
|
+
const config = body !== null && typeof body === "object" ? body.config : void 0;
|
|
23
|
+
const fields = config !== null && typeof config === "object" ? config : {};
|
|
24
|
+
const unitNoun = cleanUnit(fields.unit);
|
|
25
|
+
if (!unitNoun) return null;
|
|
26
|
+
return { unitNoun, unitNounPlural: cleanUnit(fields.plural_unit) ?? unitNoun, locale: lang };
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
async function loadPricingUnit(channel, locale, signal) {
|
|
30
|
+
var _a;
|
|
31
|
+
if (!channelPattern.test(channel)) return null;
|
|
32
|
+
const primary = ((_a = locale.split("-")[0]) == null ? void 0 : _a.toLowerCase()) ?? "";
|
|
33
|
+
const candidates = languagePattern.test(primary) && primary !== "en" ? [primary, "en"] : ["en"];
|
|
34
|
+
for (const lang of candidates) {
|
|
35
|
+
if (signal == null ? void 0 : signal.aborted) return null;
|
|
36
|
+
try {
|
|
37
|
+
const unit = await fetchUnit(channel, lang, signal);
|
|
38
|
+
if (unit) return unit;
|
|
39
|
+
} catch {
|
|
40
|
+
if (signal == null ? void 0 : signal.aborted) return null;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
export {
|
|
46
|
+
PRICING_LANGUAGE_BASE_URL,
|
|
47
|
+
loadPricingUnit
|
|
48
|
+
};
|
package/dist/login/privider.js
CHANGED
|
@@ -14,11 +14,15 @@ import { createUsageApi } from "../api/usage.js";
|
|
|
14
14
|
import { createUploadApi } from "../api/uploads.js";
|
|
15
15
|
import { createErrorReportingApi } from "../api/reporting.js";
|
|
16
16
|
import { createUsageReportingApi } from "../api/usage_reporting.js";
|
|
17
|
+
import { createTelemetry } from "../api/telemetry/client.js";
|
|
18
|
+
import { mapError, mapUsage } from "../api/telemetry/map_legacy.js";
|
|
19
|
+
import { language } from "../api/request.js";
|
|
17
20
|
import { isValidUsageCount, invalidUsageResult, skippedUsage, recordUsage } from "./consumption.js";
|
|
18
21
|
import { readCache, writeCache, versionCacheKey, testCacheKey } from "./cache.js";
|
|
19
22
|
import { ApiError } from "../api/error.js";
|
|
20
23
|
import { withRequest, throwIfAborted } from "../api/transport.js";
|
|
21
24
|
import { createAccountReporter, AccountRequestError, retryableAccountError, accountDelay } from "./account.js";
|
|
25
|
+
import { loadPricingUnit } from "./pricing_unit.js";
|
|
22
26
|
let usageIdSequence = 0;
|
|
23
27
|
function usageId() {
|
|
24
28
|
try {
|
|
@@ -41,6 +45,7 @@ const YiChongCanvaProvider = ({
|
|
|
41
45
|
uploadBaseUrl = "https://ai.imgkits.com",
|
|
42
46
|
getLocale,
|
|
43
47
|
usageReporting,
|
|
48
|
+
telemetry: telemetryConfig,
|
|
44
49
|
autoLogin = true,
|
|
45
50
|
testMode: _testMode = "noTest",
|
|
46
51
|
version = 1,
|
|
@@ -74,6 +79,8 @@ const YiChongCanvaProvider = ({
|
|
|
74
79
|
const sessionStopRef = useRef(null);
|
|
75
80
|
const [loginStatus, setLoginStatus] = useState("idle");
|
|
76
81
|
const [accountError, setAccountError] = useState(null);
|
|
82
|
+
const [pricingUnit, setPricingUnit] = useState(null);
|
|
83
|
+
const pricingLocale = language(getLocale);
|
|
77
84
|
const accountRunRef = useRef(null);
|
|
78
85
|
const loginPendingRef = useRef(false);
|
|
79
86
|
const mountedRef = useRef(true);
|
|
@@ -135,9 +142,37 @@ const YiChongCanvaProvider = ({
|
|
|
135
142
|
var _a;
|
|
136
143
|
return {
|
|
137
144
|
...getApiContext(),
|
|
138
|
-
passport: (_a = passportRef.current) == null ? void 0 : _a.passport
|
|
145
|
+
passport: (_a = passportRef.current) == null ? void 0 : _a.passport,
|
|
146
|
+
capture: (params) => telemetry.capture(mapError(params))
|
|
147
|
+
};
|
|
148
|
+
}));
|
|
149
|
+
const telemetryConfigRef = useRef(telemetryConfig);
|
|
150
|
+
telemetryConfigRef.current = telemetryConfig;
|
|
151
|
+
const telemetryPlanRef = useRef(() => "unknown");
|
|
152
|
+
const [telemetry] = useState(() => createTelemetry(() => {
|
|
153
|
+
var _a, _b, _c, _d, _e;
|
|
154
|
+
const context = getApiContext();
|
|
155
|
+
const scope = `${context.appId}|${context.productName}`;
|
|
156
|
+
const status = identityScopeRef.current === scope ? context.userStatus : {};
|
|
157
|
+
return {
|
|
158
|
+
config: telemetryConfigRef.current,
|
|
159
|
+
reportingDisabled: ((_a = context.usageReporting) == null ? void 0 : _a.enabled) === false,
|
|
160
|
+
appId: context.appId,
|
|
161
|
+
productName: context.productName,
|
|
162
|
+
version: context.version,
|
|
163
|
+
userId: (_b = status.profile) == null ? void 0 : _b.id,
|
|
164
|
+
plan: status.profile ? telemetryPlanRef.current() : "unknown",
|
|
165
|
+
sessionId: ((_c = usageSessionRef.current) == null ? void 0 : _c.id) ?? "",
|
|
166
|
+
locale: language(context.getLocale),
|
|
167
|
+
inReview: isInTestRef.current,
|
|
168
|
+
testMode: testRef.current !== "noTest",
|
|
169
|
+
secrets: [status.jwt, (_d = status.profile) == null ? void 0 : _d.token, (_e = passportRef.current) == null ? void 0 : _e.passport].filter((value) => !!value)
|
|
139
170
|
};
|
|
140
171
|
}));
|
|
172
|
+
const captureUsage = (params) => {
|
|
173
|
+
const mapped = mapUsage(params);
|
|
174
|
+
if (mapped) telemetry.capture(mapped);
|
|
175
|
+
};
|
|
141
176
|
const [usageReportingApi] = useState(() => createUsageReportingApi(() => {
|
|
142
177
|
var _a, _b, _c;
|
|
143
178
|
const context = getApiContext();
|
|
@@ -147,7 +182,8 @@ const YiChongCanvaProvider = ({
|
|
|
147
182
|
// 子组件 effect 可能先于 Provider 的换应用 effect 执行,不能把旧用户算入新应用。
|
|
148
183
|
userStatus: identityScopeRef.current === scope ? context.userStatus : {},
|
|
149
184
|
metadata: { session_id: (_a = usageSessionRef.current) == null ? void 0 : _a.id, app_version: String(context.version), platform: "canva_addon" },
|
|
150
|
-
secrets: [context.userStatus.jwt, (_b = context.userStatus.profile) == null ? void 0 : _b.token, (_c = passportRef.current) == null ? void 0 : _c.passport].filter((value) => !!value)
|
|
185
|
+
secrets: [context.userStatus.jwt, (_b = context.userStatus.profile) == null ? void 0 : _b.token, (_c = passportRef.current) == null ? void 0 : _c.passport].filter((value) => !!value),
|
|
186
|
+
capture: captureUsage
|
|
151
187
|
};
|
|
152
188
|
}));
|
|
153
189
|
const reportAccountUsage = (sum_key, title, run, data = {}) => {
|
|
@@ -204,7 +240,13 @@ const YiChongCanvaProvider = ({
|
|
|
204
240
|
var _a, _b;
|
|
205
241
|
return ((_b = (_a = userStatusRef.current.profile) == null ? void 0 : _a.usage_limits) == null ? void 0 : _b.free_limit) === -1;
|
|
206
242
|
};
|
|
207
|
-
const [reportAccountFailure] = useState(() => createAccountReporter(
|
|
243
|
+
const [reportAccountFailure] = useState(() => createAccountReporter(createErrorReportingApi(() => {
|
|
244
|
+
var _a;
|
|
245
|
+
return {
|
|
246
|
+
...getApiContext(),
|
|
247
|
+
passport: (_a = passportRef.current) == null ? void 0 : _a.passport
|
|
248
|
+
};
|
|
249
|
+
}).reportError));
|
|
208
250
|
const beginAccountRun = (operation) => {
|
|
209
251
|
var _a, _b;
|
|
210
252
|
(_a = sessionStopRef.current) == null ? void 0 : _a.call(sessionStopRef, false);
|
|
@@ -410,6 +452,7 @@ const YiChongCanvaProvider = ({
|
|
|
410
452
|
useEffect(() => {
|
|
411
453
|
updateUserStatus({});
|
|
412
454
|
}, [test]);
|
|
455
|
+
useEffect(() => () => telemetry.shutdown(), []);
|
|
413
456
|
useEffect(() => {
|
|
414
457
|
mountedRef.current = true;
|
|
415
458
|
const scope = `${appId}|${productName}`;
|
|
@@ -595,7 +638,12 @@ const YiChongCanvaProvider = ({
|
|
|
595
638
|
const detail = subscription == null ? void 0 : subscription.detail;
|
|
596
639
|
return !!detail && (!detail.ends_at || new Date(detail.ends_at) > /* @__PURE__ */ new Date() || !!(team_subscription == null ? void 0 : team_subscription.detail));
|
|
597
640
|
};
|
|
598
|
-
|
|
641
|
+
telemetryPlanRef.current = () => {
|
|
642
|
+
var _a, _b;
|
|
643
|
+
if (currentSubscribed()) return ((_b = (_a = userStatusRef.current.profile) == null ? void 0 : _a.usage_limits) == null ? void 0 : _b.monthly_usage_limit) === -1 ? "unlimited" : "subscriber";
|
|
644
|
+
return isFreeUnlimited() ? "unlimited" : "free";
|
|
645
|
+
};
|
|
646
|
+
const use = (cnt = 1, force = false, notUpload = false, options) => {
|
|
599
647
|
if (!isValidUsageCount(cnt)) return Promise.resolve(invalidUsageResult());
|
|
600
648
|
const queue = getUsageQueue();
|
|
601
649
|
const isCurrent = () => mountedRef.current && getUsageQueue() === queue;
|
|
@@ -645,6 +693,21 @@ const YiChongCanvaProvider = ({
|
|
|
645
693
|
error: { code: "unexpected_error", message: "Usage recording could not be started." }
|
|
646
694
|
}));
|
|
647
695
|
queue.tail = pending;
|
|
696
|
+
void pending.then((result) => {
|
|
697
|
+
const code = "error" in result && result.error ? result.error.code : void 0;
|
|
698
|
+
const error = result.status === "failed" || result.status === "unknown" || result.status === "partial" && result.remaining !== "skipped" ? {
|
|
699
|
+
stage: "consume",
|
|
700
|
+
expected: false,
|
|
701
|
+
code: typeof code === "string" && /^[a-z][a-z0-9_]{1,63}$/.test(code) ? code.toUpperCase() : "CONSUME_FAILED"
|
|
702
|
+
} : void 0;
|
|
703
|
+
telemetry.capture({ params: {
|
|
704
|
+
name: "consume_result",
|
|
705
|
+
operation_id: options == null ? void 0 : options.operationId,
|
|
706
|
+
props: { status: result.status, cnt, ..."reason" in result && result.reason ? { reason: result.reason } : {} },
|
|
707
|
+
error
|
|
708
|
+
} });
|
|
709
|
+
}).catch(() => {
|
|
710
|
+
});
|
|
648
711
|
return pending;
|
|
649
712
|
};
|
|
650
713
|
const canUse = (cnt = 1, force = false) => {
|
|
@@ -710,6 +773,13 @@ const YiChongCanvaProvider = ({
|
|
|
710
773
|
return creditsRef.current;
|
|
711
774
|
}
|
|
712
775
|
};
|
|
776
|
+
useEffect(() => {
|
|
777
|
+
const controller = new AbortController();
|
|
778
|
+
void loadPricingUnit(productName, pricingLocale, controller.signal).then((unit) => {
|
|
779
|
+
if (!controller.signal.aborted) setPricingUnit({ productName, unit });
|
|
780
|
+
});
|
|
781
|
+
return () => controller.abort();
|
|
782
|
+
}, [productName, pricingLocale]);
|
|
713
783
|
const getMonthlyUsageLimit = () => {
|
|
714
784
|
const { profile } = userStatusRef.current;
|
|
715
785
|
const { usage_limits } = profile || {};
|
|
@@ -733,6 +803,12 @@ const YiChongCanvaProvider = ({
|
|
|
733
803
|
...uploadApi,
|
|
734
804
|
...errorReportingApi,
|
|
735
805
|
...usageReportingApi,
|
|
806
|
+
track: (params) => {
|
|
807
|
+
try {
|
|
808
|
+
telemetry.capture({ params });
|
|
809
|
+
} catch {
|
|
810
|
+
}
|
|
811
|
+
},
|
|
736
812
|
userStatus,
|
|
737
813
|
updateUserStatus,
|
|
738
814
|
handleLogin: login,
|
|
@@ -758,6 +834,8 @@ const YiChongCanvaProvider = ({
|
|
|
758
834
|
},
|
|
759
835
|
loginStatus,
|
|
760
836
|
accountError,
|
|
837
|
+
// 换语言期间先保留上一份单位,避免闪回 config.ts 的英文;换渠道时旧单位作废。
|
|
838
|
+
pricingUnit: (pricingUnit == null ? void 0 : pricingUnit.productName) === productName ? pricingUnit.unit : null,
|
|
761
839
|
updateCredits,
|
|
762
840
|
stopCurrentPolling: () => {
|
|
763
841
|
var _a;
|
|
@@ -13,16 +13,40 @@ export declare class ApiError extends Error {
|
|
|
13
13
|
readonly data?: Record<string, unknown>;
|
|
14
14
|
/** Retry-After 响应头的秒数;工具包不会自动重试。 */
|
|
15
15
|
readonly retryAfter?: number;
|
|
16
|
+
/** 后端 error_code(snake_case):创建失败取响应顶层,任务失败取任务对象。2.7.0 起。 */
|
|
17
|
+
readonly errorCode?: string;
|
|
18
|
+
/** 后端 trace_id,目前只有创建接口返回。2.7.0 起。 */
|
|
19
|
+
readonly traceId?: string;
|
|
20
|
+
/**
|
|
21
|
+
* message 是后端分级后的用户文案、可以原样展示时为 true(见 docs/前后端约定-错误文案msg分级.md)。
|
|
22
|
+
* SDK 本地错误、约定范围外的接口、后端尚未打开分级时恒为 false。界面取文案用 getDisplayMessage。2.7.0 起。
|
|
23
|
+
*/
|
|
24
|
+
readonly displayable: boolean;
|
|
16
25
|
/**
|
|
17
26
|
* @param message 可展示的错误说明。
|
|
18
27
|
* @param code 后端业务码或 SDK 标识,例如 invalid_request、timeout、network_error。
|
|
19
28
|
* @param status 已取得的 HTTP 状态;请求发出前的错误等情况通常没有此值。
|
|
20
|
-
* @param details
|
|
29
|
+
* @param details 可选诊断数据、Retry-After 秒数和后端分级信息;仅提供信息,不触发重试。
|
|
21
30
|
*/
|
|
22
31
|
constructor(message: string, code: string | number, status?: number | undefined, details?: {
|
|
23
32
|
data?: Record<string, unknown>;
|
|
24
33
|
retryAfter?: number;
|
|
34
|
+
errorCode?: unknown;
|
|
35
|
+
traceId?: unknown;
|
|
36
|
+
displayable?: boolean;
|
|
25
37
|
});
|
|
26
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* 能原样展示给用户的后端文案;没有时返回 "",由应用显示自己的翻译兜底。
|
|
41
|
+
* 只认 displayable 的 ApiError:SDK 本地英文错误、服务商原文、未分级的 msg 都返回 ""。
|
|
42
|
+
*/
|
|
43
|
+
export declare function getDisplayMessage(error: unknown): string;
|
|
44
|
+
/** 后端 error_code;没有时返回 undefined。应用做逻辑判断只看它,不匹配文案。 */
|
|
45
|
+
export declare function getBackendErrorCode(error: unknown): string | undefined;
|
|
46
|
+
/**
|
|
47
|
+
* 内容违规:后端 error_code 为 content_policy_violation,或 StageError 的 code 为 POLICY_BLOCKED。
|
|
48
|
+
* StageError 定义在 telemetry/stage.ts 且依赖本文件,这里按 code 字段判断,避免循环依赖。
|
|
49
|
+
*/
|
|
50
|
+
export declare function isPolicyBlocked(error: unknown): boolean;
|
|
27
51
|
/** 仅识别主动取消;普通 DOMException(例如 SecurityError)或后端任务失败不应被静默忽略。 */
|
|
28
52
|
export declare function isAbortError(error: unknown): boolean;
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* 实现工厂保持内部使用,业务通过 Provider 的 client 调用方法,共享登录身份和配置。
|
|
4
4
|
* 参数、返回值及方法的 JSDoc 定义在 types.ts,会随声明文件发布供编辑器提示。
|
|
5
5
|
*/
|
|
6
|
-
export { ApiError, isAbortError } from './error';
|
|
6
|
+
export { ApiError, getBackendErrorCode, getDisplayMessage, isAbortError, isPolicyBlocked } from './error';
|
|
7
7
|
export { getPredictionOutputUrl } from './predictions';
|
|
8
|
-
export
|
|
8
|
+
export * from './telemetry';
|
|
9
|
+
export type { ApiRequestOptions, ApiResponse, CancelPredictionResponse, ChatApi, ChatParams, ChatPayload, ChatResult, CreateTextToSpeechParams, CreateTextToSpeechResult, GetTextToSpeechResultParams, TextToSpeechApi, TextToSpeechResult, TextToSpeechTaskState, CreateVttParams, CreateVttResult, GetVttStatusParams, VttApi, VttStatusResult, VttTaskState, CompleteUploadParams, CompleteUploadResponse, ContentExtractParams, ContentExtractResult, ContentExtractionApi, TextCheckParams, CreateSpecifyPredictionParams, ErrorReportingApi, ErrorReportSource, GetPredictionParams, GeneratePresignedUrlParams, GetUploadUrlParams, InitiateUploadParams, InitiateUploadResponse, JsonObject, JsonValue, Prediction, PredictionApi, WaitForPredictionOptions, ReportErrorParams, ReportUsageParams, TelemetryApi, UsageReportingApi, UsageReportingConfig, ReportErrorResult, PresignedUrlResponse, TextModerationApi, TextModerationCategory, TextModerationDecision, TextModerationResult, UploadApi, UploadFileParams, UploadFileResult, UploadedPart, UploadPartUrlResponse, UploadProgress, UsageApi, UsageParams, UsageResponse, } from './types';
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { ApiContext } from './request';
|
|
2
|
-
import { ErrorReportingApi } from './types';
|
|
2
|
+
import { ErrorReportingApi, ReportErrorParams } from './types';
|
|
3
3
|
/** 上报的应用/账号归属由 Provider 注入;passport 只参与脱敏,不会作为上报认证票据。 */
|
|
4
4
|
export interface ReportingContext extends Pick<ApiContext, "userStatus" | "productName"> {
|
|
5
5
|
appId: string;
|
|
6
6
|
version: number;
|
|
7
7
|
/** 只用于从诊断内容中移除当前账户凭据。 */
|
|
8
8
|
passport?: string;
|
|
9
|
+
/** 2.6.0:把同一次调用登记到新通道(app_error)。同步、不抛错,不改变下面旧上报的结果或异常。 */
|
|
10
|
+
capture?: (params: ReportErrorParams) => void;
|
|
9
11
|
}
|
|
10
12
|
/**
|
|
11
13
|
* 绑定显式错误上报能力:整理诊断信息,交由现有 Worker 转发到指定飞书机器人。
|
|
@@ -62,10 +62,14 @@ export declare function addContextQuery(url: URL, context: CommonRequestContext)
|
|
|
62
62
|
/** 读取完整 JSON 正文;HTML 错误页或损坏 JSON 只产生统一错误,不把原始正文混进异常。 */
|
|
63
63
|
export declare function readJson(response: Response): Promise<unknown>;
|
|
64
64
|
/**
|
|
65
|
-
* 尽量保留后端 msg / code 以及对象类型的诊断 data,供应用展示或识别业务失败。
|
|
65
|
+
* 尽量保留后端 msg / code / error_code / trace_id 以及对象类型的诊断 data,供应用展示或识别业务失败。
|
|
66
66
|
* Retry-After 仅接受整数秒并作为提示返回;此处不会安排重试,也不解析 HTTP 日期格式。
|
|
67
|
+
* tiered 表示该接口属于 msg 分级约定(docs/前后端约定-错误文案msg分级.md):响应带 debug_msg 时
|
|
68
|
+
* 说明后端已打开分级、msg 可以原样展示。其它接口的 msg 仍可能是内部代号,displayable 恒为 false。
|
|
67
69
|
*/
|
|
68
|
-
export declare function backendError(response: Response, payload: unknown, fallbackCode: string | number
|
|
70
|
+
export declare function backendError(response: Response, payload: unknown, fallbackCode: string | number, options?: {
|
|
71
|
+
tiered?: boolean;
|
|
72
|
+
}): ApiError;
|
|
69
73
|
/**
|
|
70
74
|
* AI 接口的公共 POST:注入鉴权、Channel、语言与通用 query,并校验响应包。
|
|
71
75
|
* 旧 TTS 路由的 JWT 可选,其余保持原有 JWT 要求;账户归属不等于服务端身份验证。
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { MappedEvent } from './map_legacy';
|
|
2
|
+
import { TelemetryConfig, TelemetryEvent } from './types';
|
|
3
|
+
export declare const DEFAULT_TELEMETRY_ENDPOINT = "https://telemetry.imgkits.com/v1/events";
|
|
4
|
+
/** Provider 在每次 capture 时提供的最新快照;任何字段读取失败都只丢弃本条事件。 */
|
|
5
|
+
export interface TelemetryContext {
|
|
6
|
+
config?: TelemetryConfig;
|
|
7
|
+
/** usageReporting.enabled === false 时两条通道都关闭。 */
|
|
8
|
+
reportingDisabled: boolean;
|
|
9
|
+
appId: string;
|
|
10
|
+
productName: string;
|
|
11
|
+
version: number;
|
|
12
|
+
userId?: string;
|
|
13
|
+
plan: TelemetryEvent["user"]["plan"];
|
|
14
|
+
sessionId: string;
|
|
15
|
+
locale: string;
|
|
16
|
+
inReview: boolean;
|
|
17
|
+
testMode: boolean;
|
|
18
|
+
secrets: readonly string[];
|
|
19
|
+
}
|
|
20
|
+
export interface TelemetryClient {
|
|
21
|
+
/** 同步登记一条事件,永不抛错、不返回 Promise;新通道关闭时直接忽略。 */
|
|
22
|
+
capture(event: MappedEvent): void;
|
|
23
|
+
/** 立即发送队列;unloading=true 时使用 keepalive。 */
|
|
24
|
+
flush(unloading?: boolean): void;
|
|
25
|
+
/** Provider 卸载:发送剩余事件并移除监听。 */
|
|
26
|
+
shutdown(): void;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* 新通道客户端。设计见 02-SDK上报层.md 第 6 节:
|
|
30
|
+
* 内存队列,满 20 条或 5 秒发送;页面隐藏时 keepalive;只对网络/超时/429/5xx 重试两次;
|
|
31
|
+
* 服务端返回 pause_seconds 或 503 时本会话停止;每会话最多 500 条;同一错误 60 秒内合并计数。
|
|
32
|
+
* 不读写本地存储,不调用 reportError,任何异常都在内部吞掉。
|
|
33
|
+
*/
|
|
34
|
+
export declare function createTelemetry(getContext: () => TelemetryContext): TelemetryClient;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { TrackParams } from './types';
|
|
2
|
+
import { ReportErrorParams, ReportUsageParams } from '../types';
|
|
3
|
+
/** 映射结果;envOverride 用于把模板本地演示(mode: demo)记为 dev。 */
|
|
4
|
+
export interface MappedEvent {
|
|
5
|
+
params: TrackParams;
|
|
6
|
+
envOverride?: "dev";
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* reportUsage → 新通道事件(01 第 7.1 节)。返回 null 表示该事件不进新通道。
|
|
10
|
+
* 只读取参数,不修改;旧通道的发送内容不受映射影响。
|
|
11
|
+
*/
|
|
12
|
+
export declare function mapUsage(params: ReportUsageParams): MappedEvent | null;
|
|
13
|
+
/** reportError → 新通道 app_error(01 第 7.2 节)。调用 reportError 即表示需要关注,expected 恒为 false。 */
|
|
14
|
+
export declare function mapError(params: ReportErrorParams): MappedEvent;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { TelemetryErrorInput, TelemetryErrorPayload, TelemetryProps, TelemetryTimings } from './types';
|
|
2
|
+
export declare function isSensitiveKey(key: string): boolean;
|
|
3
|
+
/** 只保留扁平的基本类型;敏感键和被脱敏改动过的字符串整键丢弃,并返回丢弃数量。 */
|
|
4
|
+
export declare function cleanProps(input: unknown, secrets: readonly string[]): {
|
|
5
|
+
props: TelemetryProps;
|
|
6
|
+
dropped: number;
|
|
7
|
+
};
|
|
8
|
+
export declare function cleanTimings(input: unknown): TelemetryTimings | undefined;
|
|
9
|
+
export declare function cleanDuration(value: unknown): number | undefined;
|
|
10
|
+
/** 从应用传入的错误描述生成上报对象;stack 只在 expected=false 时保留。 */
|
|
11
|
+
export declare function cleanError(input: TelemetryErrorInput, secrets: readonly string[]): TelemetryErrorPayload;
|