yichong-canva2 2.4.0 → 2.5.1

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.
@@ -14,10 +14,11 @@ 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 { isValidUsageCount, invalidUsageResult, skippedUsage, recordUsage } from "./consumption.js";
18
+ import { readCache, writeCache, versionCacheKey, testCacheKey } from "./cache.js";
17
19
  import { ApiError } from "../api/error.js";
18
20
  import { withRequest, throwIfAborted } from "../api/transport.js";
19
21
  import { createAccountReporter, AccountRequestError, retryableAccountError, accountDelay } from "./account.js";
20
- import { language, addContextQuery } from "../api/request.js";
21
22
  let usageIdSequence = 0;
22
23
  function usageId() {
23
24
  try {
@@ -26,41 +27,6 @@ function usageId() {
26
27
  return `usage-${Date.now().toString(36)}-${(++usageIdSequence).toString(36)}-${Math.random().toString(36).slice(2)}`;
27
28
  }
28
29
  }
29
- function reduceFreeTimes(baseUrl, passport, cnt, context) {
30
- const header = {
31
- "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
32
- "X-Access-Ticket": passport,
33
- "Accept-Language": language(context.getLocale)
34
- };
35
- const url = new URL(baseUrl + "/api/user/reduce-free-cnt?cnt=" + cnt);
36
- addContextQuery(url, context);
37
- return fetch(url.toString(), {
38
- method: "POST",
39
- headers: header,
40
- redirect: "follow"
41
- }).catch((error) => {
42
- console.log("reduceFreeTimes: ", error);
43
- reduceFreeTimes(baseUrl, passport, cnt, context);
44
- });
45
- }
46
- function addMonthlyUsage(passport, cnt, productName, context) {
47
- const headers = {
48
- "X-Access-Ticket": passport,
49
- "Content-Type": "application/json",
50
- "X-Access-Channel": productName,
51
- "Accept-Language": language(context.getLocale)
52
- };
53
- const data = {
54
- cnt
55
- };
56
- const url = new URL("https://usa.imgkits.com/api/user/add-monthly-usage");
57
- addContextQuery(url, context);
58
- return fetch(url.toString(), {
59
- method: "POST",
60
- headers,
61
- body: JSON.stringify(data)
62
- });
63
- }
64
30
  const YiChongCanvaProvider = ({
65
31
  children,
66
32
  appId,
@@ -83,11 +49,26 @@ const YiChongCanvaProvider = ({
83
49
  maxAvailablePoints = 1
84
50
  }) => {
85
51
  const [userStatus, setUserStatus] = useState({});
86
- const [credits, setCredits] = useState(0);
52
+ const [credits, setCreditsState] = useState(0);
53
+ const creditsRef = useRef(0);
54
+ const setCredits = (value) => {
55
+ creditsRef.current = value;
56
+ setCreditsState(value);
57
+ };
87
58
  const [isSubscribed, setIsSubscribed] = useState(false);
88
59
  const pollUserStatus = useRef(null);
89
- const [test, setTest] = useState(_testMode);
90
- const [isInTest, setIsInTest] = useState(false);
60
+ const [test, setTestState] = useState(_testMode);
61
+ const testRef = useRef(_testMode);
62
+ const setTest = (value) => {
63
+ testRef.current = value;
64
+ setTestState(value);
65
+ };
66
+ const [isInTest, setIsInTestState] = useState(false);
67
+ const isInTestRef = useRef(false);
68
+ const setIsInTest = (value) => {
69
+ isInTestRef.current = value;
70
+ setIsInTestState(value);
71
+ };
91
72
  const [hasClickedUpgrade, setHasClickedUpgrade] = useState(false);
92
73
  const stopCurrentPolling = useRef(null);
93
74
  const sessionStopRef = useRef(null);
@@ -108,11 +89,13 @@ const YiChongCanvaProvider = ({
108
89
  apiConfigRef.current = { apiBaseUrl, contentBaseUrl, chatBaseUrl, ttsBaseUrl, baseUrl, uploadBaseUrl, productName, appId, version, getLocale, usageReporting };
109
90
  const passportRef = useRef(null);
110
91
  const onPassport = (passport, userId, uid) => {
111
- passportRef.current = { passport, userId, uid, productName };
92
+ if (apiConfigRef.current.appId !== appId || apiConfigRef.current.productName !== productName) return;
93
+ passportRef.current = { passport, userId, uid, productName, appId };
112
94
  };
113
95
  const getApiContext = () => ({
114
96
  ...apiConfigRef.current,
115
- userStatus: userStatusRef.current
97
+ // 切换应用的子组件 effect 可能早于清理 effect,不暴露上一应用的账户快照。
98
+ userStatus: identityScopeRef.current === `${apiConfigRef.current.appId}|${apiConfigRef.current.productName}` ? userStatusRef.current : {}
116
99
  });
117
100
  const [predictionApi] = useState(() => createPredictionApi(getApiContext));
118
101
  const [textModerationApi] = useState(() => createTextModerationApi(getApiContext));
@@ -129,13 +112,24 @@ const YiChongCanvaProvider = ({
129
112
  ...getApiContext(),
130
113
  apiBaseUrl: apiConfigRef.current.ttsBaseUrl
131
114
  })));
132
- const [usageApi] = useState(() => createUsageApi(() => {
115
+ const getUsageContext = () => {
133
116
  var _a;
134
117
  const context = getApiContext();
135
118
  const credential = passportRef.current;
136
- const matches = (credential == null ? void 0 : credential.userId) === context.userStatus.userId && (credential == null ? void 0 : credential.uid) === ((_a = context.userStatus.profile) == null ? void 0 : _a.id) && (credential == null ? void 0 : credential.productName) === context.productName;
119
+ const matches = (credential == null ? void 0 : credential.userId) === context.userStatus.userId && (credential == null ? void 0 : credential.uid) === ((_a = context.userStatus.profile) == null ? void 0 : _a.id) && (credential == null ? void 0 : credential.productName) === context.productName && (credential == null ? void 0 : credential.appId) === context.appId;
137
120
  return { ...context, passport: matches ? credential == null ? void 0 : credential.passport : void 0 };
138
- }));
121
+ };
122
+ const [usageApi] = useState(() => createUsageApi(getUsageContext));
123
+ const usageQueueRef = useRef(null);
124
+ const getUsageQueue = () => {
125
+ var _a, _b;
126
+ const context = getApiContext();
127
+ const key = JSON.stringify([context.appId, context.productName, context.userStatus.userId, (_a = context.userStatus.profile) == null ? void 0 : _a.id]);
128
+ if (((_b = usageQueueRef.current) == null ? void 0 : _b.key) !== key) usageQueueRef.current = { key, tail: Promise.resolve() };
129
+ return usageQueueRef.current;
130
+ };
131
+ getUsageQueue();
132
+ const localUsageSnapshotRef = useRef(null);
139
133
  const [uploadApi] = useState(() => createUploadApi(getApiContext));
140
134
  const [errorReportingApi] = useState(() => createErrorReportingApi(() => {
141
135
  var _a;
@@ -173,28 +167,25 @@ const YiChongCanvaProvider = ({
173
167
  retry_of: previous.operationId
174
168
  });
175
169
  };
176
- useEffect(() => {
177
- userStatusRef.current = userStatus;
178
- }, [userStatus]);
179
170
  const updateUserStatus = (user) => {
180
- if (test !== "noTest" && !user.subscription) {
171
+ if (testRef.current !== "noTest" && !user.subscription) {
181
172
  user = {
182
173
  ...user,
183
174
  subscription: {}
184
175
  };
185
176
  }
186
- if (test === "credits") {
177
+ if (testRef.current === "credits") {
187
178
  user.subscription = {
188
179
  free_cnt: 9999
189
180
  };
190
- } else if (test === "subscribed") {
181
+ } else if (testRef.current === "subscribed") {
191
182
  user.subscription = {
192
183
  detail: {
193
184
  name: "yearly",
194
185
  ends_at: null
195
186
  }
196
187
  };
197
- } else if (test === "expired") {
188
+ } else if (testRef.current === "expired") {
198
189
  user.subscription = {
199
190
  detail: {
200
191
  name: "yearly",
@@ -206,11 +197,12 @@ const YiChongCanvaProvider = ({
206
197
  if (JSON.stringify(new_user) !== JSON.stringify(userStatusRef.current)) {
207
198
  userStatusRef.current = new_user;
208
199
  setUserStatus(new_user);
200
+ getUsageQueue();
209
201
  }
210
202
  };
211
203
  const isFreeUnlimited = () => {
212
- var _a;
213
- return ((_a = userStatus.profile) == null ? void 0 : _a.usage_limits.free_limit) === -1;
204
+ var _a, _b;
205
+ return ((_b = (_a = userStatusRef.current.profile) == null ? void 0 : _a.usage_limits) == null ? void 0 : _b.free_limit) === -1;
214
206
  };
215
207
  const [reportAccountFailure] = useState(() => createAccountReporter(errorReportingApi.reportError));
216
208
  const beginAccountRun = (operation) => {
@@ -372,67 +364,45 @@ const YiChongCanvaProvider = ({
372
364
  {
373
365
  setTest("noTest");
374
366
  }
375
- const _version = parseInt(localStorage.getItem("version") || "");
376
- console.log("code version: ", version);
377
- console.log("local version: ", _version);
378
- if (Number.isNaN(_version)) {
379
- getAppVersion("canva_" + appId, getApiContext()).then((res) => {
380
- console.log("latest version: ", res.version);
381
- if (typeof res.version !== "number") {
382
- res.version = version + 1;
383
- }
384
- if (res.version >= version) {
385
- setIsInTest(false);
386
- localStorage.setItem("version", version.toString());
387
- } else {
388
- setIsInTest(true);
389
- }
390
- });
391
- } else {
392
- if (version !== _version) {
393
- getAppVersion("canva_" + appId, getApiContext()).then((res) => {
394
- if (typeof res.version !== "number") {
395
- res.version = version + 1;
396
- }
397
- console.log("latest version: ", res.version);
398
- if (res.version >= version) {
399
- setIsInTest(false);
400
- localStorage.setItem("version", version.toString());
401
- } else {
402
- setIsInTest(true);
403
- }
404
- });
405
- } else {
406
- setIsInTest(false);
407
- }
408
- }
367
+ const cacheKey = versionCacheKey(appId);
368
+ const cachedVersion = Number.parseInt(readCache(cacheKey) ?? "", 10);
369
+ setIsInTest(false);
370
+ if (cachedVersion === version) return;
371
+ const controller = new AbortController();
372
+ let active = true;
373
+ void getAppVersion("canva_" + appId, getApiContext(), { signal: controller.signal }).then((res) => {
374
+ if (!active || apiConfigRef.current.appId !== appId || apiConfigRef.current.version !== version) return;
375
+ if (typeof res.version !== "number" || !Number.isFinite(res.version)) return;
376
+ const inReview = res.version < version;
377
+ setIsInTest(inReview);
378
+ if (!inReview) writeCache(cacheKey, String(version));
379
+ }).catch(() => {
380
+ });
381
+ return () => {
382
+ active = false;
383
+ controller.abort();
384
+ };
409
385
  }, [appId, version, baseUrl, productName]);
386
+ const getTestCacheKey = (kind) => {
387
+ var _a;
388
+ const context = getApiContext();
389
+ return testCacheKey(kind, context.appId, context.productName, context.userStatus.userId, (_a = context.userStatus.profile) == null ? void 0 : _a.id);
390
+ };
410
391
  function updateTestInfo(info) {
411
- localStorage.setItem(
412
- "test_info",
413
- JSON.stringify({
414
- ...info
415
- })
416
- );
392
+ writeCache(getTestCacheKey("test_info"), JSON.stringify(info));
417
393
  }
418
394
  function getTestInfo() {
419
- const p = localStorage.getItem("test_info");
420
- if (p) {
395
+ const cached = readCache(getTestCacheKey("test_info"));
396
+ if (cached) {
421
397
  try {
422
- return JSON.parse(p);
398
+ const value = JSON.parse(cached);
399
+ if (value && typeof value.time === "string" && typeof value.usage === "number" && Number.isFinite(value.usage)) {
400
+ return { time: value.time, flag: value.flag === true, usage: value.usage };
401
+ }
423
402
  } catch {
424
- return {
425
- time: "",
426
- flag: false,
427
- usage: 0
428
- };
429
403
  }
430
404
  }
431
- return {
432
- time: "",
433
- flag: false,
434
- usage: 20
435
- };
405
+ return { time: "", flag: false, usage: 20 };
436
406
  }
437
407
  function updateCredits(credits2) {
438
408
  setCredits(credits2);
@@ -449,6 +419,10 @@ const YiChongCanvaProvider = ({
449
419
  passportRef.current = null;
450
420
  userStatusRef.current = {};
451
421
  setUserStatus({});
422
+ setCredits(0);
423
+ setIsSubscribed(false);
424
+ localUsageSnapshotRef.current = null;
425
+ getUsageQueue();
452
426
  pollUserStatus.current = null;
453
427
  previousAccountFailureRef.current = null;
454
428
  }
@@ -469,12 +443,12 @@ const YiChongCanvaProvider = ({
469
443
  };
470
444
  }, [autoLogin, appId, productName]);
471
445
  const initCredits = () => {
472
- var _a, _b;
473
- if (!userStatus.subscription || !userStatus.profile) {
446
+ const snapshot = userStatusRef.current;
447
+ if (!snapshot.subscription || !snapshot.profile) {
474
448
  return;
475
449
  }
476
- const { free_cnt, is_subscribed, monthly_usage_cnt, free_usage_cnt } = userStatus.subscription;
477
- const { usage_limits } = userStatus.profile;
450
+ const { free_cnt, is_subscribed, monthly_usage_cnt, free_usage_cnt } = snapshot.subscription;
451
+ const { usage_limits } = snapshot.profile;
478
452
  const freeTimes = (usage_limits == null ? void 0 : usage_limits.free_limit) || 0;
479
453
  if (isInTest) {
480
454
  let isNull = false;
@@ -483,11 +457,11 @@ const YiChongCanvaProvider = ({
483
457
  }
484
458
  const _credits = mode === "normal" ? 20 : 1e3;
485
459
  if (mode === "server_credits" && !free_cnt) {
486
- setUserStatus((pre) => {
487
- const _o = JSON.parse(JSON.stringify(pre));
488
- _o.subscription.free_time = _credits;
489
- return _o;
490
- });
460
+ const next = _.merge({}, userStatusRef.current, { subscription: { free_time: _credits } });
461
+ if (JSON.stringify(next) !== JSON.stringify(userStatusRef.current)) {
462
+ userStatusRef.current = next;
463
+ setUserStatus(next);
464
+ }
491
465
  }
492
466
  const freeTimeFn = () => {
493
467
  if (isNull) {
@@ -496,8 +470,10 @@ const YiChongCanvaProvider = ({
496
470
  return free_cnt || 0;
497
471
  }
498
472
  };
499
- const forceUpdateUsage = localStorage.getItem("test_free_cnt") ? localStorage.getItem("test_free_cnt") !== ((_a = freeTimeFn()) == null ? void 0 : _a.toString()) : false;
500
- localStorage.setItem("test_free_cnt", ((_b = freeTimeFn()) == null ? void 0 : _b.toString()) || "0");
473
+ const freeCountKey = getTestCacheKey("test_free_cnt");
474
+ const cachedFreeCount = readCache(freeCountKey);
475
+ const forceUpdateUsage = cachedFreeCount !== null && cachedFreeCount !== String(freeTimeFn());
476
+ writeCache(freeCountKey, String(freeTimeFn()));
501
477
  const test_info = getTestInfo();
502
478
  const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
503
479
  if (today !== test_info.time || forceUpdateUsage) {
@@ -544,7 +520,8 @@ const YiChongCanvaProvider = ({
544
520
  }
545
521
  const initSubscribedUser = () => {
546
522
  var _a, _b;
547
- const { subscription, team_subscription } = userStatus;
523
+ const snapshot = userStatusRef.current;
524
+ const { subscription, team_subscription } = snapshot;
548
525
  let is_subscribed = false;
549
526
  if (subscription && subscription.detail) {
550
527
  const detail = subscription.detail;
@@ -553,11 +530,11 @@ const YiChongCanvaProvider = ({
553
530
  is_subscribed = !!(new Date(detail.ends_at) > /* @__PURE__ */ new Date());
554
531
  if (team_subscription && (team_subscription == null ? void 0 : team_subscription.detail)) is_subscribed = true;
555
532
  }
556
- const planName = checkPlanName((_b = (_a = userStatus.subscription) == null ? void 0 : _a.detail) == null ? void 0 : _b.name);
533
+ const planName = checkPlanName((_b = (_a = snapshot.subscription) == null ? void 0 : _a.detail) == null ? void 0 : _b.name);
557
534
  setIsSubscribed(is_subscribed);
558
535
  updateUserStatus({
559
536
  subscription: {
560
- ...userStatus.subscription,
537
+ ...snapshot.subscription,
561
538
  is_subscribed
562
539
  },
563
540
  planName
@@ -567,6 +544,9 @@ const YiChongCanvaProvider = ({
567
544
  if (!plan_name) {
568
545
  return "Free";
569
546
  }
547
+ if (typeof plan_name !== "string") {
548
+ return "Premium";
549
+ }
570
550
  if (plan_name.toLowerCase().includes("month")) {
571
551
  return "Pro Monthly plan";
572
552
  } else if (plan_name.toLowerCase().includes("year")) {
@@ -607,81 +587,71 @@ const YiChongCanvaProvider = ({
607
587
  return run.promise;
608
588
  }
609
589
  useEffect(() => {
610
- initCredits();
590
+ if (localUsageSnapshotRef.current !== userStatusRef.current) initCredits();
611
591
  initSubscribedUser();
612
- }, [userStatus]);
592
+ }, [userStatus, isInTest, mode, maxAvailablePoints]);
593
+ const currentSubscribed = () => {
594
+ const { subscription, team_subscription } = userStatusRef.current;
595
+ const detail = subscription == null ? void 0 : subscription.detail;
596
+ return !!detail && (!detail.ends_at || new Date(detail.ends_at) > /* @__PURE__ */ new Date() || !!(team_subscription == null ? void 0 : team_subscription.detail));
597
+ };
613
598
  const use = (cnt = 1, force = false, notUpload = false) => {
614
- if (test !== "noTest") return;
615
- if (isInTest) {
616
- let _c = credits - cnt;
617
- if (_c < 0) {
618
- _c = 0;
599
+ if (!isValidUsageCount(cnt)) return Promise.resolve(invalidUsageResult());
600
+ const queue = getUsageQueue();
601
+ const isCurrent = () => mountedRef.current && getUsageQueue() === queue;
602
+ const execute = async () => {
603
+ var _a, _b, _c;
604
+ if (!isCurrent()) return skippedUsage("account_changed");
605
+ if (testRef.current !== "noTest") return skippedUsage("test_mode");
606
+ if (isInTestRef.current) {
607
+ const remaining = Math.max(0, creditsRef.current - cnt);
608
+ setCredits(remaining);
609
+ updateTestInfo({ ...getTestInfo(), usage: remaining });
610
+ return skippedUsage("in_review_test");
619
611
  }
620
- setCredits(_c);
621
- const test_info = getTestInfo();
622
- updateTestInfo({
623
- ...test_info,
624
- usage: _c
625
- });
626
- return;
627
- }
628
- if (isFreeUnlimited()) {
629
- return {
630
- canUse: true
631
- };
632
- }
633
- if (isSubscribed && !force) {
634
- handleSubscribedUse(cnt, notUpload);
635
- } else {
636
- handleCreditsUse(cnt, notUpload);
637
- }
638
- };
639
- const handleCreditsUse = (cnt, notUpload) => {
640
- const passport = localStorage.getItem(window.userId + "_passport") || "";
641
- setCredits(credits - cnt);
642
- if (!notUpload) {
643
- reduceFreeTimes(baseUrl, passport, cnt, getApiContext());
644
- }
645
- };
646
- const handleSubscribedUse = (cnt, notUpload) => {
647
- var _a, _b;
648
- const passport = localStorage.getItem(window.userId + "_passport") || "";
649
- const { profile, subscription } = userStatus;
650
- const { usage_limits } = profile || {};
651
- const monthly_usage_cnt = (subscription == null ? void 0 : subscription.monthly_usage_cnt) ?? 0;
652
- let limitUsage = ((usage_limits == null ? void 0 : usage_limits.monthly_usage_limit) ?? 0) - monthly_usage_cnt;
653
- if (((usage_limits == null ? void 0 : usage_limits.monthly_usage_limit) ?? 0) <= -1 || limitUsage >= cnt) {
654
- addMonthlyUsage(passport, cnt, productName, getApiContext());
655
- updateUserStatus({
656
- ...userStatus,
657
- subscription: {
658
- ...userStatus.subscription,
659
- monthly_usage_cnt: (((_a = userStatus.subscription) == null ? void 0 : _a.monthly_usage_cnt) || 0) + cnt
612
+ if (isFreeUnlimited()) return skippedUsage("free_unlimited");
613
+ const context = getUsageContext();
614
+ const snapshot = userStatusRef.current;
615
+ const used = ((_a = snapshot.subscription) == null ? void 0 : _a.monthly_usage_cnt) ?? 0;
616
+ const limit = ((_c = (_b = snapshot.profile) == null ? void 0 : _b.usage_limits) == null ? void 0 : _c.monthly_usage_limit) ?? 0;
617
+ const monthly = currentSubscribed() && !force ? limit <= -1 ? cnt : Math.min(cnt, Math.max(0, limit - used)) : 0;
618
+ const freeCnt = cnt - monthly;
619
+ if (context.passport || notUpload && monthly === 0) {
620
+ if (monthly > 0) {
621
+ const next = { ...snapshot, subscription: { ...snapshot.subscription, monthly_usage_cnt: used + monthly } };
622
+ localUsageSnapshotRef.current = next;
623
+ userStatusRef.current = next;
624
+ setUserStatus(next);
660
625
  }
661
- });
662
- } else if (limitUsage < cnt) {
663
- if (limitUsage <= 0) {
664
- limitUsage = 0;
665
- }
666
- if (limitUsage > 0) {
667
- addMonthlyUsage(passport, limitUsage, productName, getApiContext());
668
- updateUserStatus({
669
- ...userStatus,
670
- subscription: {
671
- ...userStatus.subscription,
672
- monthly_usage_cnt: (((_b = userStatus.subscription) == null ? void 0 : _b.monthly_usage_cnt) || 0) + limitUsage
673
- }
674
- });
626
+ if (freeCnt > 0) setCredits(creditsRef.current - freeCnt);
675
627
  }
676
- handleCreditsUse(cnt - limitUsage, notUpload);
677
- return;
678
- }
628
+ const creditApi = createUsageApi(() => context);
629
+ const monthlyApi = createUsageApi(() => ({ ...context, baseUrl: "https://usa.imgkits.com" }));
630
+ const reporter = createErrorReportingApi(() => context);
631
+ return recordUsage({
632
+ monthly,
633
+ freeCnt,
634
+ notUpload,
635
+ isCurrent,
636
+ api: { reduceFreeCnt: creditApi.reduceFreeCnt, addMonthlyUsage: monthlyApi.addMonthlyUsage },
637
+ report: reporter.reportError
638
+ });
639
+ };
640
+ const pending = queue.tail.then(execute).catch(() => ({
641
+ status: "failed",
642
+ charged: false,
643
+ reason: "request_failed",
644
+ confirmed: { monthly: 0, freeCnt: 0 },
645
+ error: { code: "unexpected_error", message: "Usage recording could not be started." }
646
+ }));
647
+ queue.tail = pending;
648
+ return pending;
679
649
  };
680
650
  const canUse = (cnt = 1, force = false) => {
681
- if (isSubscribed && !force) {
651
+ if (currentSubscribed() && !force) {
682
652
  return true;
683
653
  } else {
684
- return credits - cnt >= 0;
654
+ return creditsRef.current - cnt >= 0;
685
655
  }
686
656
  };
687
657
  const canUseLimit = (cnt = 1, force = false) => {
@@ -690,8 +660,8 @@ const YiChongCanvaProvider = ({
690
660
  canUse: true
691
661
  };
692
662
  }
693
- if (isSubscribed && !force) {
694
- const { profile, subscription } = userStatus;
663
+ if (currentSubscribed() && !force) {
664
+ const { profile, subscription } = userStatusRef.current;
695
665
  const { usage_limits } = profile || {};
696
666
  const monthly_usage_cnt = (subscription == null ? void 0 : subscription.monthly_usage_cnt) ?? 0;
697
667
  if (!(monthly_usage_cnt >= 0) || !usage_limits) return {
@@ -706,7 +676,7 @@ const YiChongCanvaProvider = ({
706
676
  }
707
677
  const canUse2 = totalUsage - cnt >= 0;
708
678
  let error = "no_credits";
709
- if (usage_limits.monthly_usage_limit - monthly_usage_cnt - credits < 0 && credits === 0) {
679
+ if (usage_limits.monthly_usage_limit - monthly_usage_cnt - creditsRef.current < 0 && creditsRef.current === 0) {
710
680
  error = "monthly_usage_limit";
711
681
  }
712
682
  return {
@@ -714,20 +684,20 @@ const YiChongCanvaProvider = ({
714
684
  canUse: canUse2
715
685
  };
716
686
  } else {
717
- const canUse2 = credits - cnt >= 0;
687
+ const canUse2 = creditsRef.current - cnt >= 0;
718
688
  return {
719
689
  error: canUse2 ? void 0 : "no_credits",
720
- canUse: credits - cnt >= 0
690
+ canUse: creditsRef.current - cnt >= 0
721
691
  };
722
692
  }
723
693
  };
724
694
  function getPricingLink() {
725
- const link = `https://www.livepolls.app/${productName}/pricing?from=canva_addon&canva_id=${userStatus.userId}&close=1`;
695
+ const link = `https://www.livepolls.app/${apiConfigRef.current.productName}/pricing?from=canva_addon&canva_id=${userStatusRef.current.userId}&close=1`;
726
696
  return link;
727
697
  }
728
698
  const getLimitUsage = () => {
729
- if (isSubscribed) {
730
- const { profile, subscription } = userStatus;
699
+ if (currentSubscribed()) {
700
+ const { profile, subscription } = userStatusRef.current;
731
701
  const { usage_limits } = profile || {};
732
702
  const monthly_usage_cnt = (subscription == null ? void 0 : subscription.monthly_usage_cnt) ?? 0;
733
703
  const monthly_usage_limit = (usage_limits == null ? void 0 : usage_limits.monthly_usage_limit) ?? 0;
@@ -735,13 +705,13 @@ const YiChongCanvaProvider = ({
735
705
  return null;
736
706
  }
737
707
  const monthly_usage = Math.max(0, monthly_usage_limit - monthly_usage_cnt);
738
- return Math.max(monthly_usage + credits, 0);
708
+ return Math.max(monthly_usage + creditsRef.current, 0);
739
709
  } else {
740
- return credits;
710
+ return creditsRef.current;
741
711
  }
742
712
  };
743
713
  const getMonthlyUsageLimit = () => {
744
- const { profile } = userStatus;
714
+ const { profile } = userStatusRef.current;
745
715
  const { usage_limits } = profile || {};
746
716
  const monthly_usage_limit = (usage_limits == null ? void 0 : usage_limits.monthly_usage_limit) ?? 0;
747
717
  if (monthly_usage_limit === -1) {
@@ -1,25 +1,30 @@
1
- import requestUrl from "./login/apis/request.js";
2
- function getAppVersion(key, context) {
1
+ import { language, addContextQuery } from "../api/request.js";
2
+ import { withRequest } from "../api/transport.js";
3
+ import { ApiError } from "../api/error.js";
4
+ function getAppVersion(key, context, options = {}) {
3
5
  const myHeaders = new Headers();
4
- myHeaders.append("User-Agent", "Apifox/1.0.0 (https://apifox.com)");
5
6
  myHeaders.append("Accept", "*/*");
6
- myHeaders.append("Host", "usa.imgkits.com");
7
- myHeaders.append("Connection", "keep-alive");
8
7
  myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
8
+ myHeaders.append("Accept-Language", language(context == null ? void 0 : context.getLocale));
9
9
  const urlencoded = new URLSearchParams();
10
10
  urlencoded.append("key", key);
11
- const requestOptions = {
12
- method: "POST",
13
- headers: myHeaders,
14
- body: urlencoded,
15
- redirect: "follow"
16
- };
17
- return requestUrl({ ...requestOptions, url: "https://usa.imgkits.com/site/get" }, context).then((res) => {
18
- if (!(res == null ? void 0 : res.success)) {
19
- return {};
20
- } else {
21
- return JSON.parse(res.data.value);
22
- }
11
+ return withRequest({ ...options, timeoutMs: options.timeoutMs ?? 1e4 }, async (signal) => {
12
+ const url = new URL("https://usa.imgkits.com/site/get");
13
+ if (context) addContextQuery(url, context);
14
+ const response = await fetch(url.toString(), {
15
+ method: "POST",
16
+ headers: myHeaders,
17
+ body: urlencoded,
18
+ credentials: "omit",
19
+ redirect: "error",
20
+ signal
21
+ });
22
+ if (!response.ok) throw new ApiError("Version configuration is unavailable.", "http_error", response.status);
23
+ const body = await response.json();
24
+ if (!(body == null ? void 0 : body.success)) return {};
25
+ const value = JSON.parse(body.data.value);
26
+ if (!value || typeof value !== "object" || !("version" in value) || typeof value.version !== "number" || !Number.isFinite(value.version)) return {};
27
+ return { version: value.version };
23
28
  });
24
29
  }
25
30
  export {
@@ -24,3 +24,5 @@ export declare class ApiError extends Error {
24
24
  retryAfter?: number;
25
25
  });
26
26
  }
27
+ /** 仅识别主动取消;普通 DOMException(例如 SecurityError)或后端任务失败不应被静默忽略。 */
28
+ export declare function isAbortError(error: unknown): boolean;
@@ -3,5 +3,6 @@
3
3
  * 实现工厂保持内部使用,业务通过 Provider 的 client 调用方法,共享登录身份和配置。
4
4
  * 参数、返回值及方法的 JSDoc 定义在 types.ts,会随声明文件发布供编辑器提示。
5
5
  */
6
- export { ApiError } from './error';
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';
6
+ export { ApiError, isAbortError } from './error';
7
+ export { getPredictionOutputUrl } from './predictions';
8
+ 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, UsageReportingApi, UsageReportingConfig, ReportErrorResult, PresignedUrlResponse, TextModerationApi, TextModerationCategory, TextModerationDecision, TextModerationResult, UploadApi, UploadFileParams, UploadFileResult, UploadedPart, UploadPartUrlResponse, UploadProgress, UsageApi, UsageParams, UsageResponse, } from './types';
@@ -1,8 +1,13 @@
1
1
  import { ApiContext } from './request';
2
2
  import { PredictionApi } from './types';
3
3
  /**
4
- * 将后端同名的任务创建/查询接口绑定到 Provider,保留参数名与原始响应结构。
5
- * 创建仅返回任务 ID,查询仅取得一次状态;轮询间隔、取消业务与结果展示由应用编排。
6
- * 两种调用都只发送一次请求,不自动重试、审核输入或记录消费,避免重复创建/扣费。
4
+ * 从 URL 字符串、嵌套数组或 { url } 中取得第一个有效 HTTP(S) 地址,没有则返回空字符串。
5
+ * 不把文本输出、blob:/data: 或其它模型元数据当图片链接;调用者仍需按模型检查资源类型。
6
+ */
7
+ export declare function getPredictionOutputUrl(output: unknown): string;
8
+ /**
9
+ * 将后端同名的任务创建/查询/取消接口绑定到 Provider,保留参数名与原始响应结构。
10
+ * 原始方法各请求一次;waitForPrediction 是显式调用的等待流程,仅安全地重试有限次状态查询。
11
+ * 不审核输入、创建额外任务或记录消费;停止等待不会自动取消后端任务。
7
12
  */
8
13
  export declare function createPredictionApi(getContext: () => ApiContext): PredictionApi;