@aippy/runtime 0.4.1 → 0.4.2-beta.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.
Files changed (43) hide show
  1. package/README.md +35 -6
  2. package/dist/ai/errors.d.ts +1 -0
  3. package/dist/ai/index.d.ts +2 -0
  4. package/dist/ai/index.js +22 -17
  5. package/dist/ai/viggle/generate.d.ts +67 -0
  6. package/dist/ai/viggle/models.d.ts +46 -0
  7. package/dist/ai/viggle/recovery.d.ts +12 -0
  8. package/dist/{app-version-checker-Bz7FrEZz.js → app-version-checker-YVIFbytA.js} +18 -17
  9. package/dist/bridge-K3HqQwdj.js +311 -0
  10. package/dist/container-message-gRiGPin4.js +56 -0
  11. package/dist/core/env.d.ts +2 -0
  12. package/dist/core/index.js +2 -2
  13. package/dist/core/parent-message.d.ts +5 -0
  14. package/dist/core/wallet-recharge.d.ts +16 -0
  15. package/dist/helper-CJ3YV3nf.js +748 -0
  16. package/dist/{hooks-D5lkty5r.js → hooks-CMKwSLcQ.js} +1 -1
  17. package/dist/index/index.js +65 -55
  18. package/dist/index.d.ts +1 -0
  19. package/dist/ministore/app-authorization.d.ts +9 -0
  20. package/dist/ministore/authorization.d.ts +6 -0
  21. package/dist/ministore/consume.d.ts +3 -0
  22. package/dist/ministore/errors.d.ts +18 -0
  23. package/dist/ministore/index.d.ts +19 -0
  24. package/dist/ministore/index.js +99 -0
  25. package/dist/ministore/order.d.ts +1 -0
  26. package/dist/ministore/purchase.d.ts +5 -0
  27. package/dist/ministore/queries.d.ts +14 -0
  28. package/dist/ministore/recharge.d.ts +12 -0
  29. package/dist/ministore/transport.d.ts +14 -0
  30. package/dist/ministore/types.d.ts +177 -0
  31. package/dist/ministore/update-item.d.ts +3 -0
  32. package/dist/ministore/validation.d.ts +19 -0
  33. package/dist/ministore.d.ts +2 -0
  34. package/dist/recharge-o5P-y8eV.js +1036 -0
  35. package/dist/user/bridge.d.ts +3 -8
  36. package/dist/user/config.d.ts +2 -0
  37. package/dist/user/index.js +3 -3
  38. package/dist/utils/app-version-requirements.json.d.ts +4 -0
  39. package/dist/utils/index.js +1 -1
  40. package/package.json +5 -1
  41. package/dist/bridge-CtB9L5kL.js +0 -259
  42. package/dist/container-message-C3YXyTZj.js +0 -56
  43. package/dist/helper-WRpB-6MD.js +0 -241
@@ -0,0 +1,748 @@
1
+ var z = Object.defineProperty;
2
+ var F = (e, t, n) => t in e ? z(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
+ var l = (e, t, n) => F(e, typeof t != "symbol" ? t + "" : t, n);
4
+ import { createOpenAICompatible as G } from "@ai-sdk/openai-compatible";
5
+ import { s as U, a as j } from "./container-message-gRiGPin4.js";
6
+ import { AISDKError as m, DefaultChatTransport as J } from "ai";
7
+ import { E as h, b as w, a as v } from "./errors-B3bDbQbD.js";
8
+ import { j as P } from "./url-c26cuIpu.js";
9
+ import { r as E, c as q } from "./bridge-K3HqQwdj.js";
10
+ import { M as O, R as B, q as K, r as H, w as W } from "./recharge-o5P-y8eV.js";
11
+ const T = `${E()}/aisdk/v1/`, Oe = `${E()}/aisdk/v1/ui/`, Q = "gpt-5-nano", X = "";
12
+ function Y(e = {}) {
13
+ return {
14
+ baseUrl: e.baseUrl ?? `${E()}/aisdk/v1/`
15
+ };
16
+ }
17
+ function Z(e = {}) {
18
+ return {
19
+ baseUrl: e.baseUrl ?? `${E()}/aisdk/v1/ui/`
20
+ };
21
+ }
22
+ function ee(e, t) {
23
+ const n = e.status;
24
+ if (t && typeof t == "object" && "error" in t) {
25
+ const r = t, s = r.error.code, i = s != null ? `AippyAIError_${s}` : `AippyAIError_${n}`, a = t;
26
+ return "appMessage" in a && a.appMessage !== void 0 && U(a.appMessage), new m({
27
+ name: i,
28
+ message: `${h.RUNTIME} ${r.error.message}`,
29
+ cause: {
30
+ type: r.error.type ?? void 0,
31
+ param: r.error.param ?? void 0,
32
+ status: n
33
+ }
34
+ });
35
+ }
36
+ if (t && typeof t == "object" && t !== null) {
37
+ const r = t;
38
+ "appMessage" in r && r.appMessage !== void 0 && U(r.appMessage);
39
+ }
40
+ return new m({
41
+ name: `AippyAIError_${n}`,
42
+ message: `${h.RUNTIME} Request failed with status ${n}`,
43
+ cause: { status: n }
44
+ });
45
+ }
46
+ function N() {
47
+ return async (e, t) => {
48
+ const n = await j(t?.headers), r = await globalThis.fetch(e, { ...t, headers: n });
49
+ if (!r.ok) {
50
+ const s = await r.text().catch(() => null);
51
+ let i = null;
52
+ if (s)
53
+ try {
54
+ i = JSON.parse(s);
55
+ } catch {
56
+ i = { message: s };
57
+ }
58
+ throw ee(r, i);
59
+ }
60
+ return r;
61
+ };
62
+ }
63
+ const te = [
64
+ "gpt-image-1",
65
+ "gpt-image-1-mini",
66
+ "gpt-image-1.5"
67
+ ];
68
+ function re(e) {
69
+ try {
70
+ const t = JSON.parse(e);
71
+ if (t.model && te.some((n) => t.model.startsWith(n))) {
72
+ const { response_format: n, ...r } = t;
73
+ return JSON.stringify(r);
74
+ }
75
+ } catch {
76
+ }
77
+ return e;
78
+ }
79
+ function Se(e = {}) {
80
+ const { baseUrl: t } = Y(e), n = N();
81
+ return G({
82
+ name: "aippy",
83
+ baseURL: t,
84
+ fetch: async (s, i) => s.toString().includes("/images/generations") && i?.method?.toUpperCase() === "POST" && i?.body ? n(s, {
85
+ ...i,
86
+ body: re(i.body)
87
+ }) : n(s, i),
88
+ // Enable structured outputs support (json_schema response format)
89
+ // This is required for Output.object() and Output.array() to work properly
90
+ supportsStructuredOutputs: !0
91
+ });
92
+ }
93
+ const ne = "/chat";
94
+ function $e(e = {}) {
95
+ const { baseUrl: t } = Z(e), n = e.model ?? Q, r = e.system ?? X, s = e.api ?? P(t, ne), i = { model: n, system: r }, a = N();
96
+ return {
97
+ transport: new J({
98
+ api: s,
99
+ body: i,
100
+ // Ensure token is fetched fresh for every request
101
+ fetch: a
102
+ })
103
+ };
104
+ }
105
+ const b = /* @__PURE__ */ new Map(), I = /* @__PURE__ */ new Map(), se = /^vg1_[0-9]{10}_[0-9a-f]{32}$/;
106
+ async function S(e) {
107
+ const t = e instanceof Blob ? await e.arrayBuffer() : new TextEncoder().encode(JSON.stringify(e)), n = await globalThis.crypto.subtle.digest("SHA-256", t);
108
+ return Array.from(
109
+ new Uint8Array(n),
110
+ (r) => r.toString(16).padStart(2, "0")
111
+ ).join("");
112
+ }
113
+ function ie(e, t) {
114
+ const n = q();
115
+ if (!n || typeof window > "u") return;
116
+ const r = new URL(window.location.href).origin;
117
+ return `aippy:viggle:${JSON.stringify([T, r, n, e, t])}`;
118
+ }
119
+ function ae(e) {
120
+ if (!e) return;
121
+ const t = b.get(e);
122
+ let n = t?.value;
123
+ try {
124
+ if (!t || t.stored) {
125
+ const r = window.localStorage.getItem(e);
126
+ if (r) n = JSON.parse(r);
127
+ else {
128
+ b.delete(e);
129
+ return;
130
+ }
131
+ }
132
+ } catch {
133
+ }
134
+ if (!(!n || !se.test(n.requestId) || n.jobId !== void 0 && !/^job_[0-9a-f]{32}$/.test(n.jobId)))
135
+ return n;
136
+ }
137
+ function oe(e, t) {
138
+ if (!e) return;
139
+ const n = { value: { ...t }, stored: !1 };
140
+ b.set(e, n);
141
+ try {
142
+ window.localStorage.setItem(e, JSON.stringify(t)), n.stored = !0;
143
+ } catch {
144
+ }
145
+ }
146
+ function ce(e, t) {
147
+ if (e) {
148
+ b.get(e)?.value.requestId === t && b.delete(e);
149
+ try {
150
+ const n = window.localStorage.getItem(e);
151
+ n && JSON.parse(n)?.requestId === t && window.localStorage.removeItem(e);
152
+ } catch {
153
+ }
154
+ }
155
+ }
156
+ function ue(e, t, n) {
157
+ if (!e) return t();
158
+ const r = I.get(e);
159
+ if (r) return de(r, n);
160
+ const s = t().finally(() => {
161
+ I.get(e) === s && I.delete(e);
162
+ });
163
+ return I.set(e, s), s;
164
+ }
165
+ function de(e, t) {
166
+ return new Promise((n, r) => {
167
+ const s = () => r(t.reason);
168
+ t.addEventListener("abort", s, { once: !0 }), e.then(
169
+ (i) => {
170
+ t.removeEventListener("abort", s), n(i);
171
+ },
172
+ (i) => {
173
+ t.removeEventListener("abort", s), r(i);
174
+ }
175
+ ), t.aborted && s();
176
+ });
177
+ }
178
+ class g extends m {
179
+ constructor(n, r, s, i, a, o) {
180
+ super({
181
+ name: "AippyAIError_viggle",
182
+ message: `${h.RUNTIME} ${n}`,
183
+ cause: i
184
+ });
185
+ l(this, "requestId");
186
+ l(this, "jobId");
187
+ /** True only after the backend confirmed that this job was persisted. */
188
+ l(this, "jobConfirmed");
189
+ l(this, "kind");
190
+ l(this, "stage");
191
+ l(this, "reason");
192
+ l(this, "httpStatus");
193
+ l(this, "activeJob");
194
+ this.requestId = r.requestId, this.jobId = r.jobId, this.jobConfirmed = r.jobConfirmed === !0, this.kind = r.kind, this.stage = r.stage, this.reason = s, this.httpStatus = a, this.activeJob = o;
195
+ }
196
+ }
197
+ function le() {
198
+ const e = new Uint8Array(16);
199
+ return globalThis.crypto.getRandomValues(e), `vg1_${Math.floor(Date.now() / 1e3)}_${Array.from(e, (t) => t.toString(16).padStart(2, "0")).join("")}`;
200
+ }
201
+ const A = /^vg1_[0-9]{10}_[0-9a-f]{32}$/, fe = 900 * 1e3, $ = (e) => [...e].length;
202
+ async function Te(e) {
203
+ const t = e.prompt?.trim() ?? "", n = e.imageUrl?.trim() ?? "", r = e.image;
204
+ return $(t) > 1e3 && f("generateCharacter3D prompt must be at most 1000 characters"), r != null && !(r instanceof Blob) && f("generateCharacter3D image must be a file"), r instanceof Blob && r.size === 0 && f("generateCharacter3D image is empty"), !r && !t && !n && f(
205
+ "generateCharacter3D requires an image, an https imageUrl, or a prompt"
206
+ ), !r && n && !n.startsWith("https://") && f("generateCharacter3D imageUrl must be an https URL"), M(
207
+ "character",
208
+ async () => S([
209
+ "character",
210
+ t,
211
+ r ? "" : n,
212
+ r ? await S(r) : ""
213
+ ]),
214
+ (s) => {
215
+ let i;
216
+ if (r instanceof Blob) {
217
+ const a = new FormData();
218
+ a.append("requestId", s), a.append(
219
+ "image",
220
+ r,
221
+ typeof File < "u" && r instanceof File && r.name ? r.name : "image.png"
222
+ ), t && a.append("prompt", t), i = { body: a };
223
+ } else
224
+ i = V({
225
+ requestId: s,
226
+ ...n ? { imageUrl: n } : {},
227
+ ...t ? { prompt: t } : {}
228
+ });
229
+ return i;
230
+ },
231
+ e
232
+ );
233
+ }
234
+ async function Ue(e) {
235
+ const t = e.text?.trim() ?? "", n = e.durationSeconds;
236
+ return ($(t) < 1 || $(t) > 400) && f("generateMotion text must be 1 to 400 characters"), n != null && (!Number.isInteger(n) || n < 3 || n > 60) && f("generateMotion durationSeconds must be an integer from 3 to 60"), M(
237
+ "motion",
238
+ () => S(["motion", t, n ?? 5]),
239
+ (r) => V({
240
+ requestId: r,
241
+ text: t,
242
+ ...n != null ? { durationSeconds: n } : {}
243
+ }),
244
+ e
245
+ );
246
+ }
247
+ async function M(e, t, n, r) {
248
+ r = { ...r };
249
+ const s = { kind: e, stage: "create" };
250
+ return x(s, r, async (i) => {
251
+ const a = await t();
252
+ i.check(), await j(), i.check();
253
+ const o = r.requestId ? void 0 : ie(e, a), c = await ue(
254
+ o,
255
+ async () => {
256
+ const u = ae(o);
257
+ s.requestId = r.requestId ?? u?.requestId ?? le(), A.test(s.requestId) || f("Invalid Viggle requestId"), s.jobId = u?.jobId, s.jobConfirmed = !!u?.jobId, s.persist = () => oe(o, {
258
+ requestId: s.requestId,
259
+ ...s.jobId ? { jobId: s.jobId } : {}
260
+ }), s.clear = () => ce(o, s.requestId), s.persist();
261
+ try {
262
+ let d;
263
+ if (s.jobId)
264
+ s.stage = "resume", d = await i.get(!0);
265
+ else
266
+ try {
267
+ d = await i.job(D(e), {
268
+ method: "POST",
269
+ ...n(s.requestId)
270
+ });
271
+ } catch (_) {
272
+ const p = _ instanceof g ? _.activeJob : void 0;
273
+ if (!p || !p.sameInput || p.kind !== e) throw _;
274
+ s.requestId = p.requestId, s.jobId = p.jobId, s.jobConfirmed = !0, s.stage = "resume", s.persist(), d = await i.get(!0);
275
+ }
276
+ s.stage = "poll";
277
+ const y = await i.wait(d, !0);
278
+ return s.clear?.(), y;
279
+ } catch (d) {
280
+ throw d instanceof g && (["generation_failed", "request_expired"].includes(d.reason) || d.httpStatus === 404) && s.clear?.(), d;
281
+ }
282
+ },
283
+ i.signal
284
+ );
285
+ return i.check(), c;
286
+ });
287
+ }
288
+ async function ke(e) {
289
+ (!e || !["character", "motion"].includes(e.kind) || !/^job_[0-9a-f]{32}$/.test(e.jobId)) && f("Invalid Viggle jobId or kind"), e.requestId != null && !A.test(e.requestId) && f("Invalid Viggle requestId");
290
+ const t = {
291
+ requestId: e.requestId,
292
+ jobId: e.jobId,
293
+ kind: e.kind,
294
+ stage: "resume"
295
+ };
296
+ return x(
297
+ t,
298
+ e,
299
+ async (n) => n.wait(await n.get(!0), !0)
300
+ );
301
+ }
302
+ function D(e) {
303
+ return `viggle/${e === "character" ? "characters" : "motions"}`;
304
+ }
305
+ function V(e) {
306
+ return {
307
+ headers: { "Content-Type": "application/json" },
308
+ body: JSON.stringify(e)
309
+ };
310
+ }
311
+ function k(e) {
312
+ return typeof e.benefitKey == "string" && !!e.benefitKey && typeof e.bizOrderNo == "string" && e.bizOrderNo.startsWith("aisdk:managed:") && e.bizOrderNo.length <= 64 && e.quantity === 1 && Number.isSafeInteger(e.priceGEM) && e.priceGEM >= 0;
313
+ }
314
+ function R(e) {
315
+ const t = typeof window > "u" ? void 0 : window, n = t?.location?.href;
316
+ let r = q();
317
+ return () => {
318
+ if (e.aborted) throw e.reason;
319
+ if ((typeof window > "u" ? void 0 : window) !== t || t?.location?.href !== n)
320
+ throw new DOMException("Generation page changed", "AbortError");
321
+ const s = q();
322
+ if (r === null)
323
+ r = s;
324
+ else if (s !== r)
325
+ throw new DOMException("Generation account changed", "AbortError");
326
+ };
327
+ }
328
+ async function x(e, t, n) {
329
+ t = { ...t };
330
+ const r = new AbortController(), s = () => r.abort(t.signal?.reason);
331
+ t.signal?.addEventListener("abort", s, { once: !0 }), t.signal?.aborted && s();
332
+ const i = t, a = setTimeout(
333
+ () => r.abort(
334
+ new DOMException("Viggle generation timed out", "TimeoutError")
335
+ ),
336
+ i.timeoutMs ?? fe
337
+ ), o = new ge(
338
+ e,
339
+ r.signal,
340
+ i.pollIntervalMs ?? (e.kind === "character" ? 3e3 : 5e3)
341
+ );
342
+ try {
343
+ return await n(o);
344
+ } catch (c) {
345
+ if (c instanceof g) throw c;
346
+ const u = r.signal.aborted ? r.signal.reason : c, d = u instanceof Error && u.name === "TimeoutError" ? "timeout" : r.signal.aborted || u instanceof Error && u.name === "AbortError" || c instanceof O && (c.kind === "abort" || c.type === "closed" || c.type === "cancelled") ? "cancelled" : c instanceof O ? c.type === "timeout" || c.type === "balance_timeout" ? "timeout" : c.reason || (c.kind === "unsupported" ? "authorization_unavailable" : "request_failed") : "request_failed";
347
+ throw new g(
348
+ u instanceof Error ? u.message : "Viggle request failed",
349
+ e,
350
+ d,
351
+ c
352
+ );
353
+ } finally {
354
+ clearTimeout(a), t.signal?.removeEventListener("abort", s);
355
+ }
356
+ }
357
+ class ge {
358
+ constructor(t, n, r) {
359
+ l(this, "check");
360
+ this.handle = t, this.signal = n, this.interval = r, this.check = R(n);
361
+ }
362
+ miniOptions() {
363
+ return { signal: this.signal, [B]: this.check };
364
+ }
365
+ async send(t, n, r, s = this.signal) {
366
+ this.check(), r?.();
367
+ const i = await j(n.headers);
368
+ if (this.check(), r?.(), s.aborted) throw s.reason;
369
+ const a = await globalThis.fetch(
370
+ `${T.replace(/\/$/, "")}/${t}`,
371
+ {
372
+ ...n,
373
+ headers: i,
374
+ signal: s,
375
+ cache: "no-store",
376
+ credentials: "omit",
377
+ redirect: "error"
378
+ }
379
+ ), o = await a.json().catch(() => {
380
+ });
381
+ if (this.check(), r?.(), a.status !== 200) {
382
+ const c = o?.error;
383
+ throw new g(
384
+ typeof c?.message == "string" ? c.message : `Viggle request failed (${a.status})`,
385
+ this.handle,
386
+ typeof c?.param?.reason == "string" ? c.param.reason : "http_error",
387
+ void 0,
388
+ a.status,
389
+ pe(c?.param)
390
+ );
391
+ }
392
+ return o;
393
+ }
394
+ async job(t, n, r) {
395
+ const s = await this.send(t, n, r);
396
+ if (!s || s.billingVersion !== 2 || typeof s.id != "string" || !/^job_[0-9a-f]{32}$/.test(s.id) || this.handle.jobId && s.id !== this.handle.jobId || typeof s.requestId != "string" || !A.test(s.requestId) || this.handle.requestId && s.requestId !== this.handle.requestId || !["queued", "processing", "ready", "failed"].includes(s.status))
397
+ throw new Error("Invalid Viggle job response");
398
+ return this.handle.jobId = s.id, this.handle.requestId = s.requestId, this.handle.jobConfirmed = !0, this.handle.persist?.(), s;
399
+ }
400
+ get(t = !1, n) {
401
+ return this.job(
402
+ `${D(this.handle.kind)}/${encodeURIComponent(this.handle.jobId)}${t ? "?resume=1" : ""}`,
403
+ { method: "GET" },
404
+ n
405
+ );
406
+ }
407
+ async authorize(t) {
408
+ if (!k(t))
409
+ throw new Error("Invalid Viggle purchase offer");
410
+ this.check();
411
+ const n = this.handle.stage;
412
+ this.handle.stage = "authorize";
413
+ let r;
414
+ try {
415
+ r = await K(
416
+ {
417
+ operation: "purchase",
418
+ benefitKey: t.benefitKey,
419
+ bizOrderNo: t.bizOrderNo,
420
+ quantity: 1,
421
+ title: t.title || "Viggle 3D",
422
+ buttonText: "确认",
423
+ content: `购买扣除 ${t.priceGEM} GEM;生成失败保留生成券`
424
+ },
425
+ this.miniOptions()
426
+ );
427
+ } catch (s) {
428
+ if (s instanceof O && ["closed", "cancelled"].includes(s.type ?? "")) {
429
+ const i = new g(
430
+ "Viggle purchase authorization was cancelled",
431
+ this.handle,
432
+ "cancelled",
433
+ s
434
+ );
435
+ throw await this.cancelDraft(), i;
436
+ }
437
+ throw s;
438
+ }
439
+ if (this.check(), !r.ok)
440
+ throw await this.cancelDraft(), new g(
441
+ "Viggle purchase authorization was not confirmed",
442
+ this.handle,
443
+ r.reason
444
+ );
445
+ this.handle.stage = n;
446
+ }
447
+ async cancelDraft() {
448
+ if (!this.handle.jobConfirmed || !this.handle.jobId) return;
449
+ const t = new AbortController();
450
+ let n;
451
+ const r = new Promise((a) => {
452
+ n = a;
453
+ }), s = () => {
454
+ t.abort(), n();
455
+ }, i = setTimeout(s, 1e3);
456
+ this.signal.addEventListener("abort", s, { once: !0 }), this.signal.aborted && s();
457
+ try {
458
+ await Promise.race([
459
+ this.send(
460
+ `viggle/jobs/${encodeURIComponent(this.handle.jobId)}/cancel`,
461
+ { method: "POST" },
462
+ void 0,
463
+ t.signal
464
+ ).then((a) => {
465
+ const o = a;
466
+ o && o.id === this.handle.jobId && o.requestId === this.handle.requestId && o.billingVersion === 2 && o.status === "failed" && this.handle.clear?.();
467
+ }),
468
+ r
469
+ ]);
470
+ } catch {
471
+ } finally {
472
+ clearTimeout(i), this.signal.removeEventListener("abort", s), t.abort();
473
+ }
474
+ }
475
+ async wait(t, n) {
476
+ let r = t, s = !1, i = !1;
477
+ for (; ; ) {
478
+ if (this.check(), r.status === "ready") {
479
+ if (r.billing?.state !== "consumed")
480
+ throw new Error("Viggle coupon consumption is not confirmed");
481
+ if (typeof r.url != "string" || !r.url.startsWith("https://"))
482
+ throw new Error("Viggle generation finished without a file URL");
483
+ return {
484
+ url: r.url,
485
+ thumbnailUrl: r.thumbnailUrl,
486
+ jobId: r.id,
487
+ requestId: r.requestId,
488
+ kind: this.handle.kind,
489
+ billingState: r.billing?.state
490
+ };
491
+ }
492
+ if (r.status === "failed")
493
+ throw new g(
494
+ r.error || "Viggle generation failed",
495
+ this.handle,
496
+ "generation_failed"
497
+ );
498
+ const a = r.billing, o = a?.reason, c = [
499
+ "awaiting_authorization",
500
+ "insufficient_balance",
501
+ "purchase_refused"
502
+ ].includes(a?.state ?? "");
503
+ if (o && ![
504
+ "purchase_pending",
505
+ "consume_pending",
506
+ "creation_unknown",
507
+ "service_unavailable"
508
+ ].includes(o)) {
509
+ if (n && c && o === "authorization_required" && !s && a) {
510
+ s = !0, await this.authorize(a), r = await this.get(!0);
511
+ continue;
512
+ }
513
+ if (n && c && o === "insufficient_balance" && !i && a && k(a)) {
514
+ i = !0;
515
+ const u = H(this.miniOptions());
516
+ u.check();
517
+ let d = !0;
518
+ const y = await W(
519
+ async () => (this.check(), d || (r = await this.get(!0, u.check)), d = !1, r.billing?.reason === "insufficient_balance" ? {
520
+ ok: !1,
521
+ reason: "insufficient_balance",
522
+ data: r
523
+ } : { ok: !0, data: r }),
524
+ u,
525
+ a.bizOrderNo
526
+ );
527
+ if (this.check(), r = y.data, y.ok) continue;
528
+ }
529
+ throw new g(
530
+ `Viggle purchase needs attention: ${o}`,
531
+ this.handle,
532
+ o
533
+ );
534
+ }
535
+ await he(this.interval, this.signal), r = await this.get();
536
+ }
537
+ }
538
+ }
539
+ function he(e, t) {
540
+ return t.aborted ? Promise.reject(t.reason) : new Promise((n, r) => {
541
+ const s = () => {
542
+ clearTimeout(i), r(t.reason);
543
+ }, i = setTimeout(() => {
544
+ t.removeEventListener("abort", s), n();
545
+ }, e);
546
+ t.addEventListener("abort", s, { once: !0 });
547
+ });
548
+ }
549
+ function f(e) {
550
+ throw new m({
551
+ name: "AippyAIError_viggle_input",
552
+ message: `${h.CODE} ${e}`
553
+ });
554
+ }
555
+ function pe(e) {
556
+ if (!e || typeof e != "object") return;
557
+ const t = e;
558
+ if (!(t.reason !== "generation_busy" || typeof t.jobId != "string" || !/^job_[0-9a-f]{32}$/.test(t.jobId) || t.kind !== "motion" && t.kind !== "character" || typeof t.requestId != "string" || !A.test(t.requestId) || typeof t.sameInput != "boolean"))
559
+ return {
560
+ jobId: t.jobId,
561
+ kind: t.kind,
562
+ requestId: t.requestId,
563
+ sameInput: t.sameInput
564
+ };
565
+ }
566
+ async function Ne(e = {}) {
567
+ if (e.kind != null && !["character", "motion"].includes(e.kind) || e.limit != null && (!Number.isInteger(e.limit) || e.limit < 1 || e.limit > 50) || e.cursor != null && e.cursor !== "" && !/^[1-9][0-9]*$/.test(e.cursor))
568
+ throw C("Invalid Viggle model-list query", !0);
569
+ const t = e.signal ?? new AbortController().signal, n = R(t);
570
+ n();
571
+ const r = new URLSearchParams();
572
+ e.limit != null && r.set("limit", String(e.limit)), e.kind && r.set("kind", e.kind), e.cursor && r.set("cursor", e.cursor);
573
+ const s = await j();
574
+ n();
575
+ const i = r.size ? `?${r.toString()}` : "", a = await globalThis.fetch(
576
+ `${T.replace(/\/$/, "")}/viggle/models${i}`,
577
+ {
578
+ method: "GET",
579
+ headers: s,
580
+ signal: t,
581
+ cache: "no-store",
582
+ credentials: "omit",
583
+ redirect: "error"
584
+ }
585
+ ), o = await a.json().catch(() => {
586
+ });
587
+ if (n(), a.status !== 200)
588
+ throw C(`Viggle models request failed (${a.status})`);
589
+ if (!o || !Array.isArray(o.models) || o.models.length > 50 || typeof o.nextCursor != "string" || o.nextCursor !== "" && !/^[1-9][0-9]*$/.test(o.nextCursor) || !o.models.every(me))
590
+ throw C("Invalid Viggle model-list response");
591
+ return o;
592
+ }
593
+ function me(e) {
594
+ return !!e && typeof e.recordId == "string" && /^[1-9][0-9]*$/.test(e.recordId) && typeof e.benefitKey == "string" && !!e.benefitKey && typeof e.bizOrderNo == "string" && typeof e.jobId == "string" && /^job_[0-9a-f]{32}$/.test(e.jobId) && ["character", "motion"].includes(e.kind) && typeof e.url == "string" && e.url.startsWith("https://") && typeof e.generatedAt == "string" && typeof e.consumedAt == "string" && !!e.value && e.value.schemaVersion === 1 && e.value.source === "aisdk.viggle" && e.value.provider === "viggle" && e.value.kind === e.kind && e.value.jobId === e.jobId && e.value.asset?.url === e.url;
595
+ }
596
+ function C(e, t = !1) {
597
+ return new m({
598
+ name: "AippyAIError_viggle_models",
599
+ message: `${t ? h.CODE : h.RUNTIME} ${e}`
600
+ });
601
+ }
602
+ function L(e) {
603
+ const t = [];
604
+ if (!e || typeof e != "object")
605
+ throw w("AIConfig must be an object", v.INVALID_CONFIG);
606
+ const n = e;
607
+ for (const [r, s] of Object.entries(n)) {
608
+ if (!s || typeof s != "object") {
609
+ t.push({ key: r, message: "Item must be an object" });
610
+ continue;
611
+ }
612
+ const i = s;
613
+ typeof i.index != "number" && t.push({ key: r, message: "index must be a number" }), typeof i.name != "string" && t.push({ key: r, message: "name must be a string" }), typeof i.description != "string" && t.push({ key: r, message: "description must be a string" });
614
+ const a = i.type;
615
+ if (!["number", "boolean", "text", "enum"].includes(a)) {
616
+ t.push({
617
+ key: r,
618
+ message: `type must be one of: number, boolean, text, enum (got: ${a})`
619
+ });
620
+ continue;
621
+ }
622
+ if (a === "number")
623
+ typeof i.value != "number" && t.push({ key: r, message: 'value must be a number for type "number"' }), i.min !== void 0 && typeof i.min != "number" && t.push({ key: r, message: "min must be a number" }), i.max !== void 0 && typeof i.max != "number" && t.push({ key: r, message: "max must be a number" }), i.step !== void 0 && typeof i.step != "number" && t.push({ key: r, message: "step must be a number" });
624
+ else if (a === "boolean")
625
+ typeof i.value != "boolean" && t.push({ key: r, message: 'value must be a boolean for type "boolean"' });
626
+ else if (a === "text")
627
+ typeof i.value != "string" && t.push({ key: r, message: 'value must be a string for type "text"' });
628
+ else if (a === "enum") {
629
+ if (!Array.isArray(i.options))
630
+ t.push({ key: r, message: 'options must be an array for type "enum"' });
631
+ else if (i.options.length === 0)
632
+ t.push({ key: r, message: 'options array cannot be empty for type "enum"' });
633
+ else
634
+ for (let o = 0; o < i.options.length; o++)
635
+ typeof i.options[o] != "string" && t.push({
636
+ key: r,
637
+ message: `options[${o}] must be a string`
638
+ });
639
+ typeof i.value != "string" ? t.push({ key: r, message: 'value must be a string for type "enum"' }) : Array.isArray(i.options) && !i.options.includes(i.value) && t.push({
640
+ key: r,
641
+ message: `value "${i.value}" is not in options: [${i.options.join(", ")}]`
642
+ });
643
+ }
644
+ i.group !== void 0 && typeof i.group != "string" && t.push({ key: r, message: "group must be a string" });
645
+ }
646
+ if (t.length > 0)
647
+ throw w(
648
+ `AIConfig validation failed with ${t.length} error(s)`,
649
+ v.INVALID_CONFIG,
650
+ { errors: t }
651
+ );
652
+ }
653
+ function Me(e) {
654
+ let t;
655
+ try {
656
+ t = JSON.parse(e);
657
+ } catch (n) {
658
+ throw w(
659
+ `Invalid JSON: ${n instanceof Error ? n.message : String(n)}`,
660
+ v.INVALID_CONFIG
661
+ );
662
+ }
663
+ return L(t), t;
664
+ }
665
+ function be(e) {
666
+ return L(e), e;
667
+ }
668
+ function ye(e, t) {
669
+ const n = e[t];
670
+ if (!n)
671
+ throw w(
672
+ `AIConfig key "${t}" not found`,
673
+ v.INVALID_CONFIG,
674
+ { key: t }
675
+ );
676
+ return n.value;
677
+ }
678
+ function Ie(e) {
679
+ if (!(typeof window > "u"))
680
+ try {
681
+ const t = window.webkit?.messageHandlers?.aippyListener;
682
+ if (t)
683
+ try {
684
+ const n = {
685
+ command: "ai.initialize",
686
+ parameters: JSON.stringify(e)
687
+ };
688
+ t.postMessage(n);
689
+ } catch (n) {
690
+ console.warn("❌ [Aippy AI Config] Failed to send config to iOS app:", n);
691
+ }
692
+ if (window.parent && window.parent !== window)
693
+ try {
694
+ const n = {
695
+ type: "ai.initialize",
696
+ config: JSON.stringify(e)
697
+ };
698
+ window.parent.postMessage(n, "*");
699
+ } catch (n) {
700
+ console.warn("❌ [Aippy AI Config] Failed to send config to parent window:", n);
701
+ }
702
+ } catch (t) {
703
+ console.warn("⚠️ [Aippy AI Config] Failed to send config:", t);
704
+ }
705
+ }
706
+ function De(e) {
707
+ const t = be(e);
708
+ return Ie(t), new Proxy({}, {
709
+ get(n, r) {
710
+ if (typeof r == "string")
711
+ try {
712
+ return ye(t, r);
713
+ } catch {
714
+ return;
715
+ }
716
+ },
717
+ has(n, r) {
718
+ return typeof r != "string" ? !1 : r in t;
719
+ },
720
+ ownKeys(n) {
721
+ return Object.keys(t);
722
+ }
723
+ });
724
+ }
725
+ export {
726
+ T as D,
727
+ ne as U,
728
+ g as V,
729
+ Se as a,
730
+ $e as b,
731
+ Oe as c,
732
+ Q as d,
733
+ X as e,
734
+ Z as f,
735
+ Te as g,
736
+ Ue as h,
737
+ le as i,
738
+ ke as j,
739
+ be as k,
740
+ Ne as l,
741
+ ye as m,
742
+ ee as n,
743
+ De as o,
744
+ Me as p,
745
+ Y as r,
746
+ Ie as s,
747
+ L as v
748
+ };