@gengage/assistant-fe 0.6.27 → 0.6.29

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 (42) hide show
  1. package/dist/agent-ui-steps-WKbTVOS4.js +3197 -0
  2. package/dist/agentic/context/context-store.d.ts +25 -0
  3. package/dist/agentic/index.d.ts +15 -1
  4. package/dist/agentic/index.js +164 -150
  5. package/dist/agentic/types.d.ts +31 -3
  6. package/dist/agentic/worker/agent-ui-steps.d.ts +43 -0
  7. package/dist/agentic/worker/agent-ui.d.ts +44 -0
  8. package/dist/agentic/worker/be-client.d.ts +16 -4
  9. package/dist/agentic/worker/coalesce.d.ts +25 -0
  10. package/dist/agentic/worker/compaction.d.ts +12 -0
  11. package/dist/agentic/worker/pdp-hydrate.d.ts +30 -0
  12. package/dist/agentic/worker/rpc.d.ts +4 -1
  13. package/dist/agentic/worker/tool-schema.d.ts +19 -0
  14. package/dist/agentic/worker.d.ts +15 -1
  15. package/dist/agentic/worker.js +292 -264
  16. package/dist/agentic.iife.js +9 -9
  17. package/dist/{api-paths-C9NwnH29.js → api-paths-DdJr0XJ-.js} +1 -1
  18. package/dist/chat-runtime.js +1 -1
  19. package/dist/chat.iife.js +1 -1
  20. package/dist/chat.js +1 -1
  21. package/dist/{common-Bhl1mzk2.js → common-DlxPSm8-.js} +1 -1
  22. package/dist/common.js +5 -5
  23. package/dist/{connection-warning-D-0Mxk-A.js → connection-warning-B5i-GYl3.js} +1 -1
  24. package/dist/{fastIntent-bAlwVoje.js → fastIntent-BXTc79jM.js} +1 -1
  25. package/dist/index.js +10 -10
  26. package/dist/native.iife.js +1 -1
  27. package/dist/qna-runtime.js +1 -1
  28. package/dist/qna.iife.js +1 -1
  29. package/dist/qna.js +1 -1
  30. package/dist/{runtime-BAFZ7iOP.js → runtime-2RYLgot8.js} +3 -3
  31. package/dist/{runtime-oEtmgT4U.js → runtime-BMBmZgp7.js} +3 -3
  32. package/dist/{runtime-CUNLK1KR.js → runtime-DzSiJPPm.js} +3 -3
  33. package/dist/{simbut-Dt8e5uSk.js → simbut-Bwpt8E03.js} +1 -1
  34. package/dist/simbut.iife.js +1 -1
  35. package/dist/simbut.js +1 -1
  36. package/dist/{simrel-txr23_xG.js → simrel-D0G7CUSn.js} +1 -1
  37. package/dist/simrel-runtime.js +1 -1
  38. package/dist/simrel.iife.js +1 -1
  39. package/dist/simrel.js +2 -2
  40. package/dist/{widget-base-56tkaZZB.js → widget-base-XYJ0Ou6y.js} +1 -1
  41. package/package.json +1 -1
  42. package/dist/route-params-5K4Du1Xa.js +0 -2476
@@ -0,0 +1,3197 @@
1
+ import { t as ve } from "./request-response-cache-BxRsKGJ0.js";
2
+ var Ce = 120 * 1e3, Te = "gengage-agentic-ref";
3
+ function Ee({ namespace: t = Te, ttlMs: e = Ce, maxEntries: r = 100 } = {}) {
4
+ const n = /* @__PURE__ */ new Map();
5
+ async function o(u, l = {}) {
6
+ c();
7
+ const f = Ie(), d = l.kind || "pageRef", p = {
8
+ kind: d,
9
+ value: u,
10
+ expiresAt: Date.now() + (l.ttlMs || e)
11
+ };
12
+ for (n.set(f, p); n.size > r; ) n.delete(n.keys().next().value);
13
+ return await Oe(t, f, p), {
14
+ kind: d,
15
+ id: f
16
+ };
17
+ }
18
+ async function i(u) {
19
+ const l = typeof u == "string" ? u : u?.id;
20
+ if (!l) return;
21
+ const f = n.get(l) || await je(t, l);
22
+ if (f) {
23
+ if (f.expiresAt <= Date.now()) {
24
+ n.delete(l), await Ft(t, l);
25
+ return;
26
+ }
27
+ return n.set(l, f), f.value;
28
+ }
29
+ }
30
+ async function a(u) {
31
+ const l = typeof u == "string" ? u : u?.id;
32
+ l && (n.delete(l), await Ft(t, l));
33
+ }
34
+ async function s(u) {
35
+ if (Pe(u)) return i(u);
36
+ if (Array.isArray(u)) return Promise.all(u.map((f) => s(f)));
37
+ if (!u || typeof u != "object") return u;
38
+ const l = await Promise.all(Object.entries(u).map(async ([f, d]) => [f, await s(d)]));
39
+ return Object.fromEntries(l);
40
+ }
41
+ function c() {
42
+ const u = Date.now();
43
+ for (const [l, f] of n.entries()) f.expiresAt <= u && n.delete(l);
44
+ }
45
+ return {
46
+ put: o,
47
+ get: i,
48
+ delete: a,
49
+ materialize: s,
50
+ cleanup: c
51
+ };
52
+ }
53
+ function Pe(t) {
54
+ return !!(t && typeof t == "object" && typeof t.kind == "string" && typeof t.id == "string");
55
+ }
56
+ function Ie() {
57
+ return globalThis.crypto?.randomUUID ? globalThis.crypto.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
58
+ }
59
+ async function Oe(t, e, r) {
60
+ const n = await St(t);
61
+ n && (await ot(n.transaction("refs", "readwrite").objectStore("refs").put(r, e)), n.close());
62
+ }
63
+ async function je(t, e) {
64
+ const r = await St(t);
65
+ if (!r) return;
66
+ const n = await ot(r.transaction("refs", "readonly").objectStore("refs").get(e));
67
+ return r.close(), n;
68
+ }
69
+ async function Ft(t, e) {
70
+ const r = await St(t);
71
+ r && (await ot(r.transaction("refs", "readwrite").objectStore("refs").delete(e)), r.close());
72
+ }
73
+ async function St(t) {
74
+ if (!globalThis.indexedDB) return null;
75
+ try {
76
+ const e = globalThis.indexedDB.open(t, 1);
77
+ return e.onupgradeneeded = () => {
78
+ e.result.createObjectStore("refs");
79
+ }, await ot(e);
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+ function ot(t) {
85
+ return new Promise((e, r) => {
86
+ t.onsuccess = () => e(t.result), t.onerror = () => r(t.error);
87
+ });
88
+ }
89
+ var Me = 12e4;
90
+ function Re(t) {
91
+ return !!t && typeof t == "object" && t.type === "rpc.result";
92
+ }
93
+ function Be(t) {
94
+ return !!t && typeof t == "object" && t.type === "rpc.req";
95
+ }
96
+ function wo(t = self, e = {}) {
97
+ let r = 1;
98
+ const n = /* @__PURE__ */ new Map(), o = e.timeoutMs === void 0 ? Me : Number.isFinite(e.timeoutMs) && e.timeoutMs > 0 ? e.timeoutMs : 0, i = (a) => {
99
+ const s = n.get(a);
100
+ if (s)
101
+ return n.delete(a), s.timer && clearTimeout(s.timer), s;
102
+ };
103
+ return t.addEventListener("message", (a) => {
104
+ const s = a.data;
105
+ if (!Re(s)) return;
106
+ const c = i(s.rpcId);
107
+ if (c) {
108
+ if (s.ok === !1) {
109
+ const u = typeof s.error == "object" ? s.error?.message : s.error;
110
+ c.reject(new Error(u || "RPC failed"));
111
+ return;
112
+ }
113
+ c.resolve(s.value);
114
+ }
115
+ }), function(s, c, u) {
116
+ const l = r++;
117
+ return t.postMessage({
118
+ type: "rpc.req",
119
+ rpcId: l,
120
+ method: s,
121
+ payload: c
122
+ }, u || []), new Promise((f, d) => {
123
+ const p = {
124
+ resolve: (m) => f(m),
125
+ reject: d
126
+ };
127
+ o && (p.timer = setTimeout(() => {
128
+ n.has(l) && (n.delete(l), d(/* @__PURE__ */ new Error(`RPC '${s}' timed out after ${o}ms`)));
129
+ }, o)), n.set(l, p);
130
+ });
131
+ };
132
+ }
133
+ function bo({ worker: t, tools: e = {}, beacon: r, confirmation: n, memory: o = Ne(), refStore: i }) {
134
+ t.addEventListener("message", (a) => {
135
+ const s = a.data;
136
+ Be(s) && $e(t, s, {
137
+ tools: e,
138
+ beacon: r,
139
+ confirmation: n,
140
+ memory: o,
141
+ refStore: i
142
+ });
143
+ });
144
+ }
145
+ async function $e(t, e, r) {
146
+ try {
147
+ const n = await We(e.method, e.payload, r);
148
+ t.postMessage({
149
+ type: "rpc.result",
150
+ rpcId: e.rpcId,
151
+ ok: !0,
152
+ value: n
153
+ });
154
+ } catch (n) {
155
+ t.postMessage({
156
+ type: "rpc.result",
157
+ rpcId: e.rpcId,
158
+ ok: !1,
159
+ error: { message: n instanceof Error ? n.message : String(n) }
160
+ });
161
+ }
162
+ }
163
+ var lt = /* @__PURE__ */ new Map(), qt = null;
164
+ function Ne() {
165
+ try {
166
+ if (typeof sessionStorage < "u") return sessionStorage;
167
+ } catch {
168
+ }
169
+ return {
170
+ getItem: (t) => lt.get(t) ?? null,
171
+ setItem: (t, e) => {
172
+ lt.set(t, e);
173
+ },
174
+ removeItem: (t) => {
175
+ lt.delete(t);
176
+ }
177
+ };
178
+ }
179
+ function Le() {
180
+ return qt ||= Ee(), qt;
181
+ }
182
+ function Fe(t) {
183
+ if (t && typeof t == "object" && typeof t.name == "string") return t;
184
+ throw new Error("tool.invoke requires { name, input }");
185
+ }
186
+ function qe(t) {
187
+ if (t && typeof t == "object" && t.key !== void 0) return t;
188
+ throw new Error("memory.get requires { key }");
189
+ }
190
+ function De(t) {
191
+ if (t && typeof t == "object" && t.key !== void 0) return t;
192
+ throw new Error("memory.set requires { key }");
193
+ }
194
+ function Ue(t) {
195
+ if (t && typeof t == "object" && t.key !== void 0) return t;
196
+ throw new Error("memory.remove requires { key }");
197
+ }
198
+ function ze(t) {
199
+ return !t || typeof t != "object" ? { value: t } : t;
200
+ }
201
+ function Ve(t) {
202
+ const e = typeof t.kind == "string" && t.kind.trim() ? t.kind.trim() : void 0, r = typeof t.ttlMs == "number" && Number.isFinite(t.ttlMs) && t.ttlMs > 0 ? t.ttlMs : void 0;
203
+ return e || r ? {
204
+ ...e ? { kind: e } : {},
205
+ ...r ? { ttlMs: r } : {}
206
+ } : void 0;
207
+ }
208
+ function ft(t) {
209
+ if (t == null) return "session";
210
+ if (t === "volatile" || t === "session" || t === "local" || t === "indexedDb") return t;
211
+ if (typeof t == "string") {
212
+ const e = t.toLowerCase();
213
+ if (e === "indexeddb" || e === "idb") return "indexedDb";
214
+ }
215
+ throw new Error(`Unsupported memory tier: ${String(t)}`);
216
+ }
217
+ function xt(t) {
218
+ return typeof t.getItem == "function" && typeof t.setItem == "function";
219
+ }
220
+ function vt(t) {
221
+ return typeof t.get == "function" && typeof t.set == "function";
222
+ }
223
+ function Ct(t) {
224
+ return typeof t.accountId == "string" && !!t.session && !!t.indexedDb;
225
+ }
226
+ function Ke(t) {
227
+ const e = t.options?.ttlMs ?? t.ttlMs;
228
+ return typeof e == "number" && Number.isFinite(e) && e > 0 ? { ttlMs: e } : void 0;
229
+ }
230
+ async function He(t, e, r) {
231
+ if (xt(t)) {
232
+ const n = t.getItem(r);
233
+ if (!n) return null;
234
+ try {
235
+ return JSON.parse(n);
236
+ } catch {
237
+ return t.removeItem?.(r), null;
238
+ }
239
+ }
240
+ return vt(t) && !Ct(t) ? await t.get(e, r) ?? null : await t[e].get(r) ?? null;
241
+ }
242
+ async function Je(t, e, r, n, o) {
243
+ return xt(t) ? (t.setItem(r, JSON.stringify(n ?? null)), !0) : vt(t) && !Ct(t) ? await t.set(e, r, n ?? null, o) !== !1 : await t[e].set(r, n ?? null, o) !== !1;
244
+ }
245
+ async function Ze(t, e, r) {
246
+ return xt(t) ? (t.removeItem?.(r), !0) : vt(t) && !Ct(t) ? t.remove ? (await t.remove(e, r), !0) : !1 : (await t[e].remove(r), !0);
247
+ }
248
+ async function We(t, e, { tools: r, beacon: n, confirmation: o, memory: i, refStore: a }) {
249
+ if (t === "tool.invoke") {
250
+ const { name: s, input: c } = Fe(e), u = r[s];
251
+ if (typeof u != "function") throw new Error(`Unknown tool: ${s}`);
252
+ return u(c);
253
+ }
254
+ if (t === "beacon.send")
255
+ return n?.(e), { sent: !0 };
256
+ if (t === "confirmation.request") {
257
+ if (typeof o != "function") throw new Error("No confirmation handler is configured.");
258
+ const s = await o(e);
259
+ return typeof s == "boolean" ? { confirmed: s } : s;
260
+ }
261
+ if (t === "memory.get") {
262
+ const { key: s, tier: c } = qe(e);
263
+ return He(i, ft(c), String(s));
264
+ }
265
+ if (t === "memory.set") {
266
+ const s = De(e);
267
+ return { ok: await Je(i, ft(s.tier), String(s.key), s.value, Ke(s)) };
268
+ }
269
+ if (t === "memory.remove") {
270
+ const { key: s, tier: c } = Ue(e);
271
+ return { ok: await Ze(i, ft(c), String(s)) };
272
+ }
273
+ if (t === "ref.put") {
274
+ const s = tt({
275
+ tools: r,
276
+ beacon: n,
277
+ confirmation: o,
278
+ memory: i,
279
+ refStore: a
280
+ }), c = ze(e);
281
+ return s.put(c.value, Ve(c));
282
+ }
283
+ if (t === "ref.get") return tt({
284
+ tools: r,
285
+ beacon: n,
286
+ confirmation: o,
287
+ memory: i,
288
+ refStore: a
289
+ }).get(e);
290
+ if (t === "ref.materialize") return tt({
291
+ tools: r,
292
+ beacon: n,
293
+ confirmation: o,
294
+ memory: i,
295
+ refStore: a
296
+ }).materialize(e);
297
+ if (t === "ref.remove")
298
+ return await tt({
299
+ tools: r,
300
+ beacon: n,
301
+ confirmation: o,
302
+ memory: i,
303
+ refStore: a
304
+ }).delete(e), { ok: !0 };
305
+ throw new Error(`Unknown RPC method: ${t}`);
306
+ }
307
+ function tt(t) {
308
+ const e = t.refStore || Le();
309
+ if (!e || typeof e.put != "function" || typeof e.get != "function") throw new Error("No ref store is configured.");
310
+ return e;
311
+ }
312
+ function Ge() {
313
+ return (/* @__PURE__ */ new Date()).toISOString();
314
+ }
315
+ function I(t) {
316
+ return Math.max(0, Math.round(performance.now() - t));
317
+ }
318
+ function V(t) {
319
+ return typeof t == "object" && t !== null && !Array.isArray(t);
320
+ }
321
+ function Ye(t) {
322
+ const { accountId: e, locale: r = "en-GB", parentUrl: n = "", threadId: o, incomingContext: i, messageLimit: a } = t, s = V(i) ? i : {}, c = V(s.thread) ? s.thread : {}, u = V(s.panel) ? s.panel : {}, l = V(s.meta) ? s.meta : {}, f = Qt(s.messages, a), d = {
323
+ id: String(o || c.id || self.crypto.randomUUID()),
324
+ started_at: String(c.started_at || Ge()),
325
+ extensions: V(c.extensions) ? { ...c.extensions } : {}
326
+ }, p = String(l.locale || r), m = String(l.parentUrl || n || typeof self < "u" && self.location?.href || "");
327
+ return {
328
+ panel: { ...u },
329
+ messages: f,
330
+ thread: d,
331
+ meta: {
332
+ locale: p,
333
+ parentUrl: m,
334
+ accountId: e
335
+ }
336
+ };
337
+ }
338
+ function Dt(t, e, r) {
339
+ const n = Qt([e], r)[0];
340
+ return n ? {
341
+ ...t,
342
+ messages: it([...t.messages, n], r)
343
+ } : t;
344
+ }
345
+ function it(t, e) {
346
+ const r = Qe(e);
347
+ return r === 1 / 0 ? [...t] : t.slice(-r);
348
+ }
349
+ function Qt(t, e) {
350
+ return Array.isArray(t) ? it(t.map((r) => {
351
+ const n = r?.role;
352
+ return {
353
+ role: n === "model" ? "assistant" : typeof n == "string" ? n : "",
354
+ content: String(r?.content || "")
355
+ };
356
+ }).filter((r) => (r.role === "user" || r.role === "assistant" || r.role === "tool_result") && (r.role === "tool_result" || !!r.content)), e) : [];
357
+ }
358
+ function Qe(t) {
359
+ if (t === void 0) return 50;
360
+ if (!Number.isFinite(t)) return 1 / 0;
361
+ const e = Math.floor(t);
362
+ return e > 0 ? e : 50;
363
+ }
364
+ var Xe = "gengage:agent:context:";
365
+ async function tr({ accountId: t, threadId: e, rpc: r }) {
366
+ const n = await r("memory.get", {
367
+ tier: "session",
368
+ key: Xt(t, e)
369
+ });
370
+ return n && typeof n == "object" && !Array.isArray(n) ? n : {};
371
+ }
372
+ async function er({ accountId: t, threadId: e, extensions: r, panel: n, rpc: o }) {
373
+ await o("memory.set", {
374
+ tier: "session",
375
+ key: Xt(t, e),
376
+ value: {
377
+ thread: { extensions: r },
378
+ ...n && Object.keys(n).length > 0 ? { panel: n } : {}
379
+ }
380
+ });
381
+ }
382
+ function Xt(t, e) {
383
+ return `${Xe}${t}:${e}`;
384
+ }
385
+ function w(t) {
386
+ return typeof t == "object" && t !== null && !Array.isArray(t);
387
+ }
388
+ var rr = "gengage_agentic_savepoints", et = "savepoints", Ut = 3600 * 1e3, nr = 1, ko = class {
389
+ #t = /* @__PURE__ */ new Map();
390
+ #i = /* @__PURE__ */ new Map();
391
+ #e;
392
+ #u;
393
+ #l;
394
+ #a;
395
+ #f;
396
+ #d;
397
+ #o;
398
+ #s;
399
+ #c;
400
+ #r = /* @__PURE__ */ new Map();
401
+ constructor({ accountId: t, locale: e, parentUrl: r, rpc: n, persistentPanelKeys: o = [], panelKeyLimits: i = {}, messageLimit: a, maxThreads: s, threadTtlMs: c }) {
402
+ this.#e = t, this.#u = e, this.#l = r, this.#a = n, this.#f = [...new Set(o.filter(Boolean))], this.#d = ar(i), this.#o = mt(a), this.#s = mt(s), this.#c = mt(c);
403
+ }
404
+ get size() {
405
+ return this.pruneExpired(), this.#t.size;
406
+ }
407
+ get(t = "default") {
408
+ this.pruneExpired();
409
+ const e = String(t || "default"), r = this.#t.get(e);
410
+ return r ? (this.#n(e, r), r) : null;
411
+ }
412
+ getPanel(t = "default") {
413
+ return this.get(t)?.panel ?? null;
414
+ }
415
+ getRecentProducts(t = "default", e = "last_search_products") {
416
+ const r = this.getPanel(t)?.[e];
417
+ return Array.isArray(r) ? r : [];
418
+ }
419
+ async load(t) {
420
+ this.pruneExpired();
421
+ const e = t?.session_id || t?.meta?.threadId || t?.sessionId, r = String(e || "default"), n = this.#t.get(r);
422
+ if (n) {
423
+ const a = ur(n, t?.context, this.#o);
424
+ return this.#n(r, a), a;
425
+ }
426
+ const o = await tr({
427
+ accountId: this.#e,
428
+ threadId: r,
429
+ rpc: this.#a
430
+ }), i = Ye({
431
+ accountId: this.#e,
432
+ locale: t?.locale || this.#u,
433
+ parentUrl: this.#l,
434
+ threadId: r,
435
+ incomingContext: cr(o, t?.context),
436
+ messageLimit: this.#o
437
+ });
438
+ return this.#n(r, i), this.#m(), i;
439
+ }
440
+ patch(t, e) {
441
+ this.pruneExpired();
442
+ const r = String(t || "default"), n = this.#t.get(r);
443
+ if (!n) return null;
444
+ const o = Tt(n, typeof e == "function" ? e(n) : e, this.#o);
445
+ return this.#n(r, o), o;
446
+ }
447
+ appendUserMessage(t, e) {
448
+ this.pruneExpired();
449
+ const r = String(t || "default");
450
+ if (!e) return this.#t.get(r) ?? null;
451
+ const n = this.#t.get(r);
452
+ if (!n) return null;
453
+ const o = Dt(n, {
454
+ role: "user",
455
+ content: e
456
+ }, this.#o);
457
+ return this.#n(r, o), o;
458
+ }
459
+ appendToolResult(t, e) {
460
+ this.pruneExpired();
461
+ const r = String(t || "default"), n = this.#t.get(r);
462
+ if (!n) return null;
463
+ const o = Dt(n, {
464
+ role: "tool_result",
465
+ content: String(e?.content || ""),
466
+ ...e?.name ? { name: String(e.name) } : {},
467
+ ...e?.details !== void 0 ? { details: e.details } : {}
468
+ }, this.#o);
469
+ return this.#n(r, o), o;
470
+ }
471
+ async commit(t) {
472
+ this.pruneExpired();
473
+ const e = String(t || "default"), r = this.#t.get(e);
474
+ return r ? (this.#n(e, r), await er({
475
+ accountId: this.#e,
476
+ threadId: e,
477
+ extensions: r.thread.extensions,
478
+ panel: ir(r.panel, this.#f, this.#d),
479
+ rpc: this.#a
480
+ }), r) : null;
481
+ }
482
+ delete(t) {
483
+ const e = String(t || "default");
484
+ return this.#i.delete(e), this.#r.delete(e), this.#t.delete(e);
485
+ }
486
+ clear() {
487
+ this.#t.clear(), this.#i.clear(), this.#r.clear();
488
+ }
489
+ enqueueSteer(t, e, r = "all") {
490
+ this.#p(t, "steer", e, r);
491
+ }
492
+ enqueueFollowUp(t, e, r = "all") {
493
+ this.#p(t, "follow_up", e, r);
494
+ }
495
+ drainPending(t, e) {
496
+ const r = String(t || "default"), n = this.#r.get(r);
497
+ if (!n || !n.length) return null;
498
+ const o = n.findIndex((a) => a.kind === e);
499
+ if (o < 0) return null;
500
+ const [i] = n.splice(o, 1);
501
+ return n.length || this.#r.delete(r), i || null;
502
+ }
503
+ peekPending(t = "default") {
504
+ const e = String(t || "default"), r = this.#r.get(e);
505
+ return r ? [...r] : [];
506
+ }
507
+ #p(t, e, r, n) {
508
+ const o = String(r || "").trim();
509
+ if (!o) return;
510
+ const i = String(t || "default"), a = this.#r.get(i) || [];
511
+ if (n === "one-at-a-time")
512
+ for (let s = a.length - 1; s >= 0; s -= 1) a[s].kind === e && a.splice(s, 1);
513
+ a.push({
514
+ kind: e,
515
+ text: o,
516
+ enqueuedAt: Date.now()
517
+ }), this.#r.set(i, a);
518
+ }
519
+ async savepoint(t, e, r) {
520
+ if (!t || typeof e != "number" || !Number.isFinite(e)) return;
521
+ const n = {
522
+ threadId: t,
523
+ turnIndex: e,
524
+ payload: r,
525
+ createdAt: Date.now()
526
+ };
527
+ try {
528
+ await pt(this.#e, "readwrite", (o) => {
529
+ o.put(n, dt(t, e));
530
+ });
531
+ } catch {
532
+ }
533
+ }
534
+ async restoreSavepoint(t, e) {
535
+ if (!t) return null;
536
+ try {
537
+ let r = null;
538
+ return await pt(this.#e, "readonly", (n) => {
539
+ const o = typeof e == "number" ? dt(t, e) : null;
540
+ if (o !== null) {
541
+ const i = n.get(o);
542
+ i.onsuccess = () => {
543
+ const a = i.result;
544
+ a && Date.now() - a.createdAt < Ut && (r = a);
545
+ };
546
+ } else {
547
+ const i = n.openCursor(null, "prev");
548
+ i.onsuccess = () => {
549
+ const a = i.result;
550
+ if (!a || r) return;
551
+ const s = a.value;
552
+ if (s.threadId !== t) {
553
+ a.continue();
554
+ return;
555
+ }
556
+ Date.now() - s.createdAt < Ut && (r = s);
557
+ };
558
+ }
559
+ }), r;
560
+ } catch {
561
+ return null;
562
+ }
563
+ }
564
+ async clearSavepoint(t, e) {
565
+ if (t)
566
+ try {
567
+ await pt(this.#e, "readwrite", (r) => {
568
+ if (typeof e == "number") {
569
+ r.delete(dt(t, e));
570
+ return;
571
+ }
572
+ const n = r.openCursor();
573
+ n.onsuccess = () => {
574
+ const o = n.result;
575
+ o && (o.value.threadId === t && o.delete(), o.continue());
576
+ };
577
+ });
578
+ } catch {
579
+ }
580
+ }
581
+ pruneExpired(t = Date.now()) {
582
+ if (!this.#c) return 0;
583
+ let e = 0;
584
+ for (const [r, n] of this.#i)
585
+ t - n <= this.#c || (this.#i.delete(r), this.#t.delete(r) && (e += 1));
586
+ return e;
587
+ }
588
+ #n(t, e) {
589
+ this.#t.delete(t), this.#t.set(t, e), this.#i.set(t, Date.now());
590
+ }
591
+ #m() {
592
+ if (this.#s)
593
+ for (; this.#t.size > this.#s; ) {
594
+ const t = this.#t.keys().next().value;
595
+ if (!t) return;
596
+ this.delete(t);
597
+ }
598
+ }
599
+ };
600
+ function dt(t, e) {
601
+ return `${t}|${e}`;
602
+ }
603
+ function or() {
604
+ return (typeof self < "u" ? self : globalThis)?.indexedDB || null;
605
+ }
606
+ async function pt(t, e, r) {
607
+ const n = or();
608
+ if (!n) return;
609
+ const o = `${rr}_${t}`;
610
+ await new Promise((i, a) => {
611
+ const s = n.open(o, nr);
612
+ s.onupgradeneeded = () => {
613
+ const c = s.result;
614
+ c.objectStoreNames.contains(et) || c.createObjectStore(et);
615
+ }, s.onerror = () => a(s.error || /* @__PURE__ */ new Error("savepoint:open_failed")), s.onsuccess = () => {
616
+ const c = s.result;
617
+ try {
618
+ const u = c.transaction(et, e);
619
+ r(u.objectStore(et)), u.oncomplete = () => {
620
+ c.close(), i();
621
+ }, u.onerror = () => {
622
+ c.close(), a(u.error || /* @__PURE__ */ new Error("savepoint:tx_failed"));
623
+ }, u.onabort = () => {
624
+ c.close(), a(u.error || /* @__PURE__ */ new Error("savepoint:tx_aborted"));
625
+ };
626
+ } catch (u) {
627
+ c.close(), a(u instanceof Error ? u : new Error(String(u)));
628
+ }
629
+ };
630
+ });
631
+ }
632
+ function ir(t, e, r) {
633
+ if (!e.length || !w(t)) return;
634
+ const n = {};
635
+ for (const o of e) Object.prototype.hasOwnProperty.call(t, o) && (n[o] = sr(t[o], r[o]));
636
+ return n;
637
+ }
638
+ function ar(t) {
639
+ const e = {};
640
+ for (const [r, n] of Object.entries(t || {})) {
641
+ const o = Math.floor(Number(n));
642
+ r && Number.isFinite(o) && o > 0 && (e[r] = o);
643
+ }
644
+ return e;
645
+ }
646
+ function mt(t) {
647
+ if (t === void 0) return;
648
+ const e = Math.floor(Number(t));
649
+ return Number.isFinite(e) && e > 0 ? e : void 0;
650
+ }
651
+ function sr(t, e) {
652
+ return !e || !Array.isArray(t) ? t : t.slice(-e);
653
+ }
654
+ function cr(t, e) {
655
+ if (!w(t) && !w(e)) return {};
656
+ const r = w(t) ? t : {}, n = Tt(r, w(e) ? e : {});
657
+ return w(r.panel) && (n.panel = r.panel), n;
658
+ }
659
+ function ur(t, e, r) {
660
+ if (!w(e)) return t;
661
+ const n = Tt(t, e, r);
662
+ return {
663
+ ...n,
664
+ panel: t.panel,
665
+ thread: {
666
+ ...n.thread,
667
+ id: t.thread.id,
668
+ started_at: t.thread.started_at
669
+ },
670
+ meta: {
671
+ ...n.meta,
672
+ accountId: t.meta.accountId
673
+ }
674
+ };
675
+ }
676
+ function Tt(t, e, r) {
677
+ if (!w(e)) return t;
678
+ const n = t, o = e, i = w(n.panel) ? n.panel : {}, a = w(o.panel) ? o.panel : {}, s = w(n.thread) ? n.thread : {}, c = w(o.thread) ? o.thread : {}, u = w(s.extensions) ? s.extensions : {}, l = w(c.extensions) ? c.extensions : {}, f = w(n.meta) ? n.meta : {}, d = w(o.meta) ? o.meta : {};
679
+ return {
680
+ ...t,
681
+ ...e,
682
+ panel: {
683
+ ...i,
684
+ ...a
685
+ },
686
+ thread: {
687
+ ...s,
688
+ ...c,
689
+ extensions: {
690
+ ...u,
691
+ ...l
692
+ }
693
+ },
694
+ meta: {
695
+ ...f,
696
+ ...d
697
+ },
698
+ messages: Array.isArray(o.messages) ? it(o.messages, r) : t.messages ?? []
699
+ };
700
+ }
701
+ function te(t) {
702
+ const e = String.fromCharCode(...t);
703
+ return btoa(e).replace(/\+/gu, "-").replace(/\//gu, "_").replace(/=+$/u, "");
704
+ }
705
+ function zt(t) {
706
+ return te(new TextEncoder().encode(JSON.stringify(t)));
707
+ }
708
+ async function lr({ accountId: t, devJwtSecret: e, ttlS: r = 300 }) {
709
+ if (!e) throw new Error("devJwtSecret is required for local agent mode.");
710
+ const n = Math.floor(Date.now() / 1e3), o = `${zt({
711
+ alg: "HS256",
712
+ typ: "JWT"
713
+ })}.${zt({
714
+ sub: t,
715
+ iat: n,
716
+ exp: n + r,
717
+ scope: "invoke",
718
+ jti: crypto.randomUUID?.() || `${n}-${Math.random()}`
719
+ })}`, i = await crypto.subtle.importKey("raw", new TextEncoder().encode(e), {
720
+ name: "HMAC",
721
+ hash: "SHA-256"
722
+ }, !1, ["sign"]), a = await crypto.subtle.sign("HMAC", i, new TextEncoder().encode(o));
723
+ return `${o}.${te(new Uint8Array(a))}`;
724
+ }
725
+ function fr({ accountId: t, devJwtSecret: e, tokenBrokerUrl: r, tokenBrokerAudience: n, refreshSkewS: o = 30, fetchImpl: i = fetch }) {
726
+ let a = null;
727
+ return async ({ signal: s, parentUrl: c } = {}) => {
728
+ if (e) return lr({
729
+ accountId: t,
730
+ devJwtSecret: e
731
+ });
732
+ if (!r) throw new Error("tokenBrokerUrl is required for production agent mode.");
733
+ const u = Math.floor(Date.now() / 1e3);
734
+ return a?.token && a.expiresAtS - o > u || (a = await dr({
735
+ accountId: t,
736
+ tokenBrokerUrl: r,
737
+ tokenBrokerAudience: n,
738
+ parentUrl: c,
739
+ signal: s,
740
+ fetchImpl: i
741
+ })), a.token;
742
+ };
743
+ }
744
+ async function dr({ accountId: t, tokenBrokerUrl: e, tokenBrokerAudience: r, parentUrl: n, signal: o, fetchImpl: i }) {
745
+ const a = await i(e, {
746
+ method: "POST",
747
+ credentials: "include",
748
+ headers: {
749
+ accept: "application/json",
750
+ "content-type": "application/json"
751
+ },
752
+ body: JSON.stringify({
753
+ accountId: t,
754
+ scope: "invoke",
755
+ audience: r || void 0,
756
+ parentUrl: n || void 0
757
+ }),
758
+ ...o ? { signal: o } : {}
759
+ });
760
+ if (!a.ok) throw new Error(`Token broker request failed (${a.status}).`);
761
+ const s = await a.json(), c = s?.token || s?.jwt || s?.access_token;
762
+ if (!c || typeof c != "string") throw new Error("Token broker response did not include a JWT.");
763
+ return {
764
+ token: c,
765
+ expiresAtS: pr(s) || mr(c) || Math.floor(Date.now() / 1e3) + 300
766
+ };
767
+ }
768
+ function pr(t) {
769
+ const e = t?.expiresAtS ?? t?.expires_at_s ?? t?.expiresInS ?? t?.expires_in_s;
770
+ if (Number.isFinite(e)) return Number(e);
771
+ const r = t?.expiresIn ?? t?.expires_in;
772
+ if (Number.isFinite(r)) return Math.floor(Date.now() / 1e3) + Number(r);
773
+ const n = t?.expiresAt ?? t?.expires_at;
774
+ if (typeof n == "string") {
775
+ const o = Date.parse(n);
776
+ if (Number.isFinite(o)) return Math.floor(o / 1e3);
777
+ }
778
+ return null;
779
+ }
780
+ function mr(t) {
781
+ try {
782
+ const [, e] = t.split(".");
783
+ if (!e) return null;
784
+ const r = e.replace(/-/gu, "+").replace(/_/gu, "/"), n = atob(r.padEnd(Math.ceil(r.length / 4) * 4, "=")), o = JSON.parse(n);
785
+ return Number.isFinite(o?.exp) ? Number(o.exp) : null;
786
+ } catch {
787
+ return null;
788
+ }
789
+ }
790
+ var Vt = {
791
+ unauthorized: {
792
+ code: "auth",
793
+ message: "Assistant authentication failed. Please retry."
794
+ },
795
+ forbidden: {
796
+ code: "auth",
797
+ message: "Assistant authentication failed. Please retry."
798
+ },
799
+ unknown_op: {
800
+ code: "op_unavailable",
801
+ message: "This assistant action is not available yet."
802
+ },
803
+ invalid_input: {
804
+ code: "invalid_request",
805
+ message: "The assistant request was not valid."
806
+ },
807
+ account_config: {
808
+ code: "account_config",
809
+ message: "Assistant configuration is unavailable."
810
+ },
811
+ upstream_llm: {
812
+ code: "op_failed",
813
+ message: "The assistant could not complete that request."
814
+ },
815
+ upstream_timeout: {
816
+ code: "op_timeout",
817
+ message: "The assistant took too long to respond."
818
+ },
819
+ schema_mismatch: {
820
+ code: "op_failed",
821
+ message: "The assistant could not complete that request."
822
+ },
823
+ rate_limited: {
824
+ code: "rate_limited",
825
+ message: "The assistant is receiving too many requests. Please retry shortly."
826
+ },
827
+ internal: {
828
+ code: "op_failed",
829
+ message: "The assistant could not complete that request."
830
+ },
831
+ payload_too_large: {
832
+ code: "invalid_request",
833
+ message: "The assistant request was too large."
834
+ }
835
+ }, x = class extends Error {
836
+ constructor(t, e, r = {}) {
837
+ super(e), this.name = "AgentError", this.code = t, this.source = r.source || "agent", r.sourceCode && (this.sourceCode = r.sourceCode), r.detail !== void 0 && (this.detail = r.detail);
838
+ }
839
+ };
840
+ function ee(t) {
841
+ const e = String(t?.code || "upstream_llm"), r = Vt[e] || Vt.upstream_llm;
842
+ return new x(r.code, r.message, {
843
+ source: "be",
844
+ sourceCode: e,
845
+ detail: t?.detail
846
+ });
847
+ }
848
+ function yr(t, e) {
849
+ const r = e?.error && typeof e.error == "object" ? e.error : {};
850
+ return ee({
851
+ code: String(r.code || gr(t)),
852
+ detail: r.detail
853
+ });
854
+ }
855
+ function _o(t) {
856
+ return t instanceof x ? {
857
+ type: "error",
858
+ code: t.code,
859
+ message: t.message
860
+ } : {
861
+ type: "error",
862
+ code: "agent_invoke_failed",
863
+ message: "The assistant could not complete that request."
864
+ };
865
+ }
866
+ function gr(t) {
867
+ return t === 401 ? "unauthorized" : t === 403 ? "forbidden" : t === 413 ? "payload_too_large" : t === 429 ? "rate_limited" : "internal";
868
+ }
869
+ async function Ao(t) {
870
+ const { beUrl: e, accountId: r, devJwtSecret: n, tokenBrokerUrl: o, tokenBrokerAudience: i, jwtProvider: a, parentUrl: s, op: c, input: u, cacheTtlS: l, cacheKey: f, browserCache: d, signal: p, interceptors: m } = t, h = await (a || fr({
871
+ accountId: r,
872
+ devJwtSecret: n,
873
+ tokenBrokerUrl: o,
874
+ tokenBrokerAudience: i
875
+ }))({
876
+ ...p ? { signal: p } : {},
877
+ ...s ? { parentUrl: s } : {}
878
+ }), { opDomain: T, opName: $ } = hr(c, r);
879
+ let M = {
880
+ method: "POST",
881
+ headers: {
882
+ authorization: `Bearer ${h}`,
883
+ "content-type": "application/json",
884
+ accept: "application/x-ndjson"
885
+ },
886
+ body: JSON.stringify({
887
+ op_domain: T,
888
+ op_name: $,
889
+ op_payload: u,
890
+ ...l !== void 0 ? { cache_ttl_s: l } : {},
891
+ ...f !== void 0 ? { cache_key: f } : {}
892
+ }),
893
+ ...p ? { signal: p } : {}
894
+ };
895
+ const N = `${String(e).replace(/\/+$/u, "")}/v1/execute`;
896
+ if (m?.beforeRequest) {
897
+ const k = await m.beforeRequest(t, {
898
+ url: N,
899
+ init: M
900
+ });
901
+ if (k && "cached" in k && k.cached !== void 0) return k.cached;
902
+ k?.init && (M = k.init);
903
+ }
904
+ const R = d === !1 ? await fetch(N, M) : await ve(N, M, typeof d == "object" ? d : {});
905
+ if (!R.ok) throw yr(R.status, await br(R));
906
+ let L = await kr(R);
907
+ if (m?.afterResponse) {
908
+ const k = await m.afterResponse(t, L);
909
+ k && "result" in k && k.result !== void 0 && (L = k.result);
910
+ }
911
+ return L;
912
+ }
913
+ function hr(t, e) {
914
+ if (!t || t.startsWith("-") || t.endsWith("-")) throw new Error(`Invalid BE op name: ${t}`);
915
+ return {
916
+ opDomain: wr(e),
917
+ opName: t
918
+ };
919
+ }
920
+ function wr(t) {
921
+ return t.replace(/-agentic$/u, "");
922
+ }
923
+ async function br(t) {
924
+ try {
925
+ return await t.json();
926
+ } catch {
927
+ return { error: { code: t.statusText || "internal" } };
928
+ }
929
+ }
930
+ async function kr(t) {
931
+ const e = t.body?.getReader();
932
+ if (!e) throw new Error("BE response body is not readable.");
933
+ const r = new TextDecoder();
934
+ let n = "";
935
+ const o = {};
936
+ for (; ; ) {
937
+ const { value: a, done: s } = await e.read();
938
+ if (s) break;
939
+ n += r.decode(a, { stream: !0 });
940
+ let c = n.indexOf(`
941
+ `);
942
+ for (; c >= 0; ) {
943
+ const u = n.slice(0, c).trim();
944
+ n = n.slice(c + 1), u && Kt(JSON.parse(u), o), c = n.indexOf(`
945
+ `);
946
+ }
947
+ }
948
+ const i = n.trim();
949
+ return i && Kt(JSON.parse(i), o), o;
950
+ }
951
+ function Kt(t, e) {
952
+ if (t._error) throw ee(t._error);
953
+ if (!t._end)
954
+ for (const [r, n] of Object.entries(t)) {
955
+ if (Object.prototype.hasOwnProperty.call(e, r)) throw new x("op_failed", `BE streamed duplicate field "${r}".`, {
956
+ source: "be",
957
+ sourceCode: "schema_mismatch"
958
+ });
959
+ e[r] = n;
960
+ }
961
+ }
962
+ function So(t = {}) {
963
+ return {
964
+ type: "metadata",
965
+ ...t
966
+ };
967
+ }
968
+ function _r(t, e = !1, r = {}) {
969
+ return {
970
+ type: "text_chunk",
971
+ content: t,
972
+ final: e,
973
+ ...r
974
+ };
975
+ }
976
+ function xo(t) {
977
+ return {
978
+ type: "ui_spec",
979
+ ...t
980
+ };
981
+ }
982
+ function vo(t) {
983
+ return {
984
+ type: "action",
985
+ action: t
986
+ };
987
+ }
988
+ function Ar(t, e) {
989
+ return {
990
+ type: "error",
991
+ code: t,
992
+ message: e
993
+ };
994
+ }
995
+ function re() {
996
+ return { type: "done" };
997
+ }
998
+ function Sr(t, e) {
999
+ return t[e?.type || e?.action?.type || "inputText"] || t.inputText;
1000
+ }
1001
+ function ne(t) {
1002
+ return t && typeof t == "object" && !Array.isArray(t) ? t : null;
1003
+ }
1004
+ function Et(t, e = {}) {
1005
+ const r = ne(t);
1006
+ if (!r) return null;
1007
+ const n = e.catalogMapper?.(r);
1008
+ if (n) return n;
1009
+ const o = F(r.sku, r.SKU);
1010
+ if (!o) return null;
1011
+ const i = {
1012
+ sku: o,
1013
+ name: F(r.name, r.title, r.short_name, o) || o,
1014
+ url: F(r.url) || ""
1015
+ }, a = Array.isArray(r.images) ? r.images : void 0, s = F(r.imageUrl, r.image_url, r.image, a?.[0]);
1016
+ s && (i.imageUrl = s), a && a.length > 1 && (i.images = a.filter(($) => !!$).map(String));
1017
+ const c = K(r.price_discounted), u = K(r.price), l = c || u;
1018
+ l > 0 && (i.price = String(l));
1019
+ const f = c > 0 ? u : 0;
1020
+ f > 0 && (i.originalPrice = String(f));
1021
+ const d = F(r.brand);
1022
+ d && (i.brand = d);
1023
+ const p = K(r.rating);
1024
+ p > 0 && (i.rating = p);
1025
+ const m = K(r.review_count) || K(r.reviewCount);
1026
+ m > 0 && (i.reviewCount = m);
1027
+ const h = F(r.cart_code, r.cartCode);
1028
+ h && (i.cartCode = h), typeof r.in_stock == "boolean" && (i.inStock = r.in_stock), typeof r.inStock == "boolean" && (i.inStock = r.inStock);
1029
+ const T = r.category_names;
1030
+ return Array.isArray(T) && (i.categoryNames = T.map(String)), i;
1031
+ }
1032
+ function Pt(t) {
1033
+ const e = ne(t);
1034
+ if (!e) return t;
1035
+ const r = e.category_names, n = Array.isArray(r) ? r : void 0, o = e.images, i = Array.isArray(o) ? o : void 0, a = {
1036
+ sku: e.sku,
1037
+ name: e.name || e.title,
1038
+ url: e.url,
1039
+ price: e.price,
1040
+ currency: e.price_currency || e.currency,
1041
+ category: n?.[n.length - 1] ?? void 0,
1042
+ category_names: n ? n.slice(0, 4) : void 0,
1043
+ image: i ? i[0] : e.image,
1044
+ in_stock: e.in_stock,
1045
+ rating: e.rating,
1046
+ review_count: e.review_count
1047
+ };
1048
+ for (const s of Object.keys(a)) a[s] === void 0 && delete a[s];
1049
+ return a;
1050
+ }
1051
+ function Co(t) {
1052
+ return Array.isArray(t) ? t.map(Pt).filter((e) => !!e) : [];
1053
+ }
1054
+ function F(...t) {
1055
+ for (const e of t) if (typeof e == "string" && e.trim()) return e.trim();
1056
+ return "";
1057
+ }
1058
+ function K(t) {
1059
+ const e = Number(t);
1060
+ return Number.isFinite(e) ? e : 0;
1061
+ }
1062
+ function Ht(t) {
1063
+ return Array.isArray(t) ? t.map(String).filter(Boolean) : typeof t == "string" && t ? [t] : [];
1064
+ }
1065
+ function oe(t, e, r = {}) {
1066
+ return `${t}:${r.version || "v2"}:${ie(e)}`;
1067
+ }
1068
+ function To(t, e = {}) {
1069
+ return ae(t).map((r) => se(typeof r == "string" ? r : r.sku, e.locale)).filter(Boolean).filter((r, n, o) => o.indexOf(r) === n).sort((r, n) => It(r, n, e.locale)).slice(0, e.limit || 16).join(",");
1070
+ }
1071
+ function Eo(t, e = {}) {
1072
+ return ie(ae(t).map((r) => xr(r, e)).filter((r) => !!r).sort((r, n) => It(String(r.sku || r.name || ""), String(n.sku || n.name || ""), e.locale)).slice(0, e.limit || 16));
1073
+ }
1074
+ function Po(t, e) {
1075
+ return O(t, e);
1076
+ }
1077
+ function ie(t) {
1078
+ let e = 2166136261;
1079
+ const r = vr(t);
1080
+ for (let n = 0; n < r.length; n += 1)
1081
+ e ^= r.charCodeAt(n), e = Math.imul(e, 16777619);
1082
+ return (e >>> 0).toString(36);
1083
+ }
1084
+ function xr(t, e) {
1085
+ if (!t || typeof t != "object" || Array.isArray(t)) return null;
1086
+ const r = t, n = e.mapProduct?.(r);
1087
+ if (n) return J(n);
1088
+ const o = Pt(r);
1089
+ return o && typeof o == "object" && !Array.isArray(o) ? J(Cr(o, e)) : null;
1090
+ }
1091
+ function ae(t) {
1092
+ return Array.isArray(t) ? t.filter((e) => typeof e == "string" || !!(e && typeof e == "object" && !Array.isArray(e))) : [];
1093
+ }
1094
+ function vr(t) {
1095
+ return JSON.stringify(J(t));
1096
+ }
1097
+ function J(t) {
1098
+ return Array.isArray(t) ? t.map(J) : !t || typeof t != "object" ? t : Object.fromEntries(Object.entries(t).filter(([, e]) => e !== void 0).sort(([e], [r]) => e.localeCompare(r)).map(([e, r]) => [e, J(r)]));
1099
+ }
1100
+ function Cr(t, e) {
1101
+ return {
1102
+ sku: se(t.sku, e.locale),
1103
+ name: O(t.name, e.locale),
1104
+ url: O(t.url, e.locale),
1105
+ price: t.price,
1106
+ currency: O(t.currency, e.locale),
1107
+ category: O(t.category, e.locale),
1108
+ category_names: Tr(t.category_names, e.locale, 16),
1109
+ image: O(t.image, e.locale),
1110
+ in_stock: t.in_stock,
1111
+ rating: t.rating,
1112
+ review_count: t.review_count
1113
+ };
1114
+ }
1115
+ function se(t, e) {
1116
+ return O(t, e).toUpperCase();
1117
+ }
1118
+ function O(t, e) {
1119
+ return typeof t == "string" ? t.trim().replace(/\s+/gu, " ").toLocaleLowerCase(e || void 0) : "";
1120
+ }
1121
+ function It(t, e, r) {
1122
+ return t.localeCompare(e, r, { numeric: !0 });
1123
+ }
1124
+ function Tr(t, e, r) {
1125
+ return Array.isArray(t) ? t.map((n) => O(n, e)).filter(Boolean).sort((n, o) => It(n, o, e)).slice(0, r) : void 0;
1126
+ }
1127
+ function Er(t, e) {
1128
+ if (!t) return { ok: !0 };
1129
+ const r = [];
1130
+ return bt(t, e, "", r), r.length ? {
1131
+ ok: !1,
1132
+ error: r[0] || "invalid"
1133
+ } : { ok: !0 };
1134
+ }
1135
+ function bt(t, e, r, n) {
1136
+ if (t) {
1137
+ if (Array.isArray(t.enum) && !t.enum.includes(e)) {
1138
+ n.push(`${r || "value"} must be one of [${t.enum.join(", ")}]`);
1139
+ return;
1140
+ }
1141
+ switch (t.type) {
1142
+ case "string":
1143
+ if (typeof e != "string") {
1144
+ n.push(`${r || "value"} must be a string`);
1145
+ return;
1146
+ }
1147
+ t.minLength && e.length < t.minLength && n.push(`${r || "value"} must be at least ${t.minLength} chars`);
1148
+ return;
1149
+ case "number":
1150
+ if (typeof e != "number" || !Number.isFinite(e)) {
1151
+ n.push(`${r || "value"} must be a number`);
1152
+ return;
1153
+ }
1154
+ t.minimum != null && e < t.minimum && n.push(`${r || "value"} must be >= ${t.minimum}`), t.maximum != null && e > t.maximum && n.push(`${r || "value"} must be <= ${t.maximum}`);
1155
+ return;
1156
+ case "boolean":
1157
+ typeof e != "boolean" && n.push(`${r || "value"} must be a boolean`);
1158
+ return;
1159
+ case "array":
1160
+ if (!Array.isArray(e)) {
1161
+ n.push(`${r || "value"} must be an array`);
1162
+ return;
1163
+ }
1164
+ if (t.minItems != null && e.length < t.minItems && n.push(`${r || "value"} must have >= ${t.minItems} items`), t.maxItems != null && e.length > t.maxItems && n.push(`${r || "value"} must have <= ${t.maxItems} items`), t.items) {
1165
+ for (let o = 0; o < e.length; o += 1)
1166
+ if (bt(t.items, e[o], `${r}[${o}]`, n), n.length) return;
1167
+ }
1168
+ return;
1169
+ case "object":
1170
+ if (!e || typeof e != "object" || Array.isArray(e)) {
1171
+ n.push(`${r || "value"} must be an object`);
1172
+ return;
1173
+ }
1174
+ if (Array.isArray(t.required)) for (const o of t.required) {
1175
+ const i = e[o];
1176
+ if (i == null || i === "") {
1177
+ n.push(`${r ? `${r}.` : ""}${o} is required`);
1178
+ return;
1179
+ }
1180
+ }
1181
+ if (t.properties) for (const [o, i] of Object.entries(t.properties)) {
1182
+ const a = e[o];
1183
+ if (a !== void 0 && (bt(i, a, r ? `${r}.${o}` : o, n), n.length))
1184
+ return;
1185
+ }
1186
+ return;
1187
+ default:
1188
+ return;
1189
+ }
1190
+ }
1191
+ }
1192
+ var Pr = 12e4;
1193
+ async function Io({ request: t, accountModule: e, contextStore: r, beClient: n, toolBridge: o, emit: i, rpc: a, signal: s }) {
1194
+ const c = performance.now(), u = await r.load(t), l = u.thread.id, f = Qr(t);
1195
+ zr(u, f) && r.appendUserMessage(l, f);
1196
+ const d = Sr(e.flows, t);
1197
+ if (!d)
1198
+ return i(Ar("unknown_action", `No agent flow for request type ${t?.type || "inputText"}`)), i(re()), {
1199
+ steps: 0,
1200
+ productSkusEmitted: []
1201
+ };
1202
+ const p = {
1203
+ request: t,
1204
+ context: r.patch(l, {}) || u,
1205
+ bag: {},
1206
+ accountConfig: e.accountConfig || {},
1207
+ threadId: l,
1208
+ steps: 0,
1209
+ productSkusEmitted: /* @__PURE__ */ new Set(),
1210
+ committed: !1,
1211
+ messageLimit: Yr(e.contextPersistence?.messageLimit),
1212
+ catalogMapper: e.catalogMapper,
1213
+ similarityMapper: e.similarityMapper
1214
+ }, m = {
1215
+ contextStore: r,
1216
+ beClient: n,
1217
+ toolBridge: o,
1218
+ emit: i,
1219
+ rpc: a,
1220
+ adapters: e.adapters || {},
1221
+ ...s ? { signal: s } : {},
1222
+ ...e.trace ? { trace: e.trace } : {},
1223
+ ...e.hooks ? { hooks: e.hooks } : {}
1224
+ };
1225
+ await v(m, q("turn:start", p));
1226
+ try {
1227
+ await U(d, p, m), p.committed || await Ot(p, m);
1228
+ } catch (h) {
1229
+ throw await v(m, {
1230
+ ...q("turn:error", p),
1231
+ latencyMs: I(c),
1232
+ errorCode: G(h)
1233
+ }), h;
1234
+ }
1235
+ return await a("beacon.send", {
1236
+ type: "turnSummary",
1237
+ threadId: l,
1238
+ sessionId: t?.session_id || t?.sessionId || l,
1239
+ accountId: e.accountId || p.context.meta.accountId,
1240
+ steps: p.steps,
1241
+ totalLatencyMs: I(c),
1242
+ productSkusEmitted: [...p.productSkusEmitted]
1243
+ }), await v(m, {
1244
+ ...q("turn:end", p),
1245
+ latencyMs: I(c)
1246
+ }), {
1247
+ steps: p.steps,
1248
+ productSkusEmitted: [...p.productSkusEmitted]
1249
+ };
1250
+ }
1251
+ async function U(t, e, r) {
1252
+ for (const n of t) {
1253
+ if (r.signal?.aborted || e.committed) return;
1254
+ e.steps += 1;
1255
+ const o = e.steps, i = performance.now();
1256
+ await v(r, yt("step:start", e, n, o));
1257
+ try {
1258
+ await Ir(n, e, r), await v(r, {
1259
+ ...yt("step:end", e, n, o),
1260
+ latencyMs: I(i)
1261
+ });
1262
+ } catch (a) {
1263
+ throw await v(r, {
1264
+ ...yt("step:error", e, n, o),
1265
+ latencyMs: I(i),
1266
+ errorCode: G(a)
1267
+ }), a;
1268
+ }
1269
+ e.context = r.contextStore.patch(e.threadId, {}) || e.context;
1270
+ }
1271
+ }
1272
+ async function Ir(t, e, r) {
1273
+ if (r.hooks?.transformContext) {
1274
+ const o = await W(r, e, "transformContext", () => r.hooks.transformContext(e.context));
1275
+ o && (e.context = o);
1276
+ }
1277
+ const n = D(e, r);
1278
+ if (t.kind === "be_op") {
1279
+ await Or(t, e, r, n);
1280
+ return;
1281
+ }
1282
+ if (t.kind === "tool") {
1283
+ await Rr(t, e, r, n);
1284
+ return;
1285
+ }
1286
+ if (t.kind === "adapter") {
1287
+ await Br(t, e, r, n);
1288
+ return;
1289
+ }
1290
+ if (t.kind === "emit") {
1291
+ await $r(t, e, r);
1292
+ return;
1293
+ }
1294
+ if (t.kind === "patch") {
1295
+ await Nr(t, e, r);
1296
+ return;
1297
+ }
1298
+ if (t.kind === "branch") {
1299
+ await Lr(t, e, r, n);
1300
+ return;
1301
+ }
1302
+ if (t.kind === "agent_loop") {
1303
+ await Fr(t, e, r, n);
1304
+ return;
1305
+ }
1306
+ if (t.kind === "parallel") {
1307
+ await qr(t, e, r);
1308
+ return;
1309
+ }
1310
+ if (t.kind === "refusal") {
1311
+ await Dr(t, e, r, n);
1312
+ return;
1313
+ }
1314
+ t.kind === "commit" && await Ur(t, e, r);
1315
+ }
1316
+ async function Or(t, e, r, n) {
1317
+ const o = performance.now();
1318
+ let i;
1319
+ try {
1320
+ let s = await _(t.input, n);
1321
+ if (r.hooks?.beforeBeOp) {
1322
+ const c = await W(r, e, "beforeBeOp", () => r.hooks.beforeBeOp(t.op, s, n));
1323
+ c && "cached" in c && c.cached !== void 0 ? i = c.cached : c && "input" in c && c.input !== void 0 && (s = c.input);
1324
+ }
1325
+ if (i === void 0) {
1326
+ const c = await _(t.cache, n), u = jr(t, e, s, c), l = await _(t.cacheTtlS, n) ?? u.cacheTtlS, f = await _(t.cacheKey, n) ?? u.cacheKey, d = await _(t.browserCache, n), p = Y(await _(t.timeoutMs, n));
1327
+ await jt(t, e, r, n);
1328
+ const m = p ? new AbortController() : null, h = ce(r.signal, m?.signal);
1329
+ i = await Q(r.beClient.invoke({
1330
+ op: t.op,
1331
+ input: s,
1332
+ ...l !== void 0 ? { cacheTtlS: l } : {},
1333
+ ...f !== void 0 ? { cacheKey: f } : {},
1334
+ ...d !== void 0 ? { browserCache: d } : {},
1335
+ ...h ? { signal: h } : {}
1336
+ }), p, () => new x("op_timeout", "The assistant took too long to respond.", {
1337
+ source: "be",
1338
+ sourceCode: "timeout"
1339
+ }), () => m?.abort());
1340
+ }
1341
+ if (r.hooks?.afterBeOp) {
1342
+ const c = await W(r, e, "afterBeOp", () => r.hooks.afterBeOp(t.op, i, n));
1343
+ c && "result" in c && c.result !== void 0 && (i = c.result);
1344
+ }
1345
+ } catch (s) {
1346
+ const c = s, u = String(c?.sourceCode || c?.code || "unknown"), l = {
1347
+ type: "agentOp",
1348
+ threadId: e.threadId,
1349
+ sessionId: e.request?.session_id || e.request?.sessionId || e.threadId,
1350
+ accountId: e.context.meta.accountId,
1351
+ op: t.op,
1352
+ status: "error",
1353
+ latencyMs: I(o),
1354
+ errorCode: u
1355
+ };
1356
+ if (await r.rpc("beacon.send", l), t.onError) {
1357
+ t.errorOut && (e.bag[t.errorOut] = s), await U(t.onError, e, r);
1358
+ return;
1359
+ }
1360
+ throw s;
1361
+ }
1362
+ t.out && (e.bag[t.out] = i), await at(t, i, e, r.contextStore);
1363
+ const a = {
1364
+ type: "agentOp",
1365
+ threadId: e.threadId,
1366
+ sessionId: e.request?.session_id || e.request?.sessionId || e.threadId,
1367
+ accountId: e.context.meta.accountId,
1368
+ op: t.op,
1369
+ status: "ok",
1370
+ latencyMs: I(o)
1371
+ };
1372
+ await r.rpc("beacon.send", a);
1373
+ }
1374
+ function jr(t, e, r, n) {
1375
+ if (!n || n.strategy !== "input-hash") return {};
1376
+ const o = Y(n.ttlS);
1377
+ if (!o) return {};
1378
+ const i = e.context.meta.locale, a = n.promptVersion || Mr(r) || "current";
1379
+ return {
1380
+ cacheTtlS: o,
1381
+ cacheKey: oe(t.op, {
1382
+ account: e.context.meta.accountId,
1383
+ locale: i,
1384
+ promptVersion: a,
1385
+ payload: r
1386
+ }, { version: "input-hash" })
1387
+ };
1388
+ }
1389
+ function Mr(t) {
1390
+ if (!t || typeof t != "object" || Array.isArray(t)) return;
1391
+ const e = t, r = e.prompt_version || e.promptVersion;
1392
+ return typeof r == "string" && r.trim() ? r.trim() : void 0;
1393
+ }
1394
+ async function Rr(t, e, r, n) {
1395
+ const o = performance.now();
1396
+ try {
1397
+ await jt(t, e, r, n);
1398
+ const i = Y(await _(t.timeoutMs, n));
1399
+ let a = await _(t.input, n);
1400
+ if (r.hooks?.beforeToolCall) {
1401
+ const c = await W(r, e, "beforeToolCall", () => r.hooks.beforeToolCall(t.name, a, n));
1402
+ if (c?.block) throw new x("tool_blocked", c.reason || `Tool '${t.name}' blocked by hook.`, {
1403
+ source: "tool",
1404
+ sourceCode: "blocked"
1405
+ });
1406
+ c && "args" in c && c.args !== void 0 && (a = c.args);
1407
+ }
1408
+ if (t.parameters) {
1409
+ const c = Er(t.parameters, a);
1410
+ if (!c.ok) throw new x("tool_invalid_args", `Invalid args for tool '${t.name}': ${c.error}`, {
1411
+ source: "tool",
1412
+ sourceCode: "invalid_args"
1413
+ });
1414
+ }
1415
+ let s = await Q(r.toolBridge.invoke(t.name, a), i, () => new x("tool_timeout", "The assistant tool took too long to respond.", {
1416
+ source: "tool",
1417
+ sourceCode: "timeout"
1418
+ }));
1419
+ if (r.hooks?.afterToolCall) {
1420
+ const c = await W(r, e, "afterToolCall", () => r.hooks.afterToolCall(t.name, s, n));
1421
+ c && "result" in c && c.result !== void 0 && (s = c.result), c?.terminate && (e.committed = !0);
1422
+ }
1423
+ t.out && (e.bag[t.out] = s), await at(t, s, e, r.contextStore), await r.rpc("beacon.send", {
1424
+ type: "agentTool",
1425
+ threadId: e.threadId,
1426
+ sessionId: Z(e),
1427
+ accountId: e.context.meta.accountId,
1428
+ tool: t.name,
1429
+ status: "ok",
1430
+ latencyMs: I(o)
1431
+ });
1432
+ } catch (i) {
1433
+ const a = i;
1434
+ if (await r.rpc("beacon.send", {
1435
+ type: "agentTool",
1436
+ threadId: e.threadId,
1437
+ sessionId: Z(e),
1438
+ accountId: e.context.meta.accountId,
1439
+ tool: t.name,
1440
+ status: "error",
1441
+ latencyMs: I(o),
1442
+ errorCode: String(a?.code || a?.name || "unknown")
1443
+ }), t.onError) {
1444
+ t.errorOut && (e.bag[t.errorOut] = i), await U(t.onError, e, r);
1445
+ return;
1446
+ }
1447
+ throw i;
1448
+ }
1449
+ }
1450
+ async function Br(t, e, r, n) {
1451
+ const o = r.adapters?.[t.name];
1452
+ if (typeof o != "function") throw new Error(`Unknown flow adapter: ${t.name}`);
1453
+ await jt(t, e, r, n);
1454
+ const i = Y(await _(t.timeoutMs, n)), a = await Q(o(await _(t.input, n), n), i, () => new x("adapter_timeout", "The assistant adapter took too long to respond.", {
1455
+ source: "adapter",
1456
+ sourceCode: "timeout"
1457
+ }));
1458
+ t.out && (e.bag[t.out] = a), await at(t, a, e, r.contextStore);
1459
+ }
1460
+ async function $r(t, e, r) {
1461
+ const n = await t.build(D(e, r));
1462
+ Xr(n, e.productSkusEmitted), r.emit(n);
1463
+ }
1464
+ async function Nr(t, e, r) {
1465
+ await at(t, void 0, e, r.contextStore);
1466
+ }
1467
+ async function Lr(t, e, r, n) {
1468
+ const o = String(await _(t.on, n) || "default");
1469
+ await U(t.cases[o] || t.cases.default || [], e, r);
1470
+ }
1471
+ async function Fr(t, e, r, n) {
1472
+ if (!await t.shouldContinue(e.bag, n)) return;
1473
+ const o = Math.max(0, Math.floor(Number(t.maxIterations) || 0));
1474
+ let i = 0;
1475
+ for (; !r.signal?.aborted && !e.committed; ) {
1476
+ if (await U(t.body, e, r), r.signal?.aborted || e.committed || !await t.shouldContinue(e.bag, D(e, r)) || i >= o) return;
1477
+ const a = await t.onIterate?.(e.bag, D(e, r));
1478
+ a && typeof a == "object" && Object.assign(e.bag, a), i += 1;
1479
+ }
1480
+ }
1481
+ async function qr(t, e, r) {
1482
+ const n = Y(await _(t.timeoutMs, D(e, r))), o = n ? new AbortController() : null, i = ce(r.signal, o?.signal), a = t.steps.map((u) => {
1483
+ const l = {
1484
+ ...e,
1485
+ context: Vr(e.context),
1486
+ bag: kt(e.bag),
1487
+ productSkusEmitted: new Set(e.productSkusEmitted),
1488
+ committed: !1
1489
+ }, f = [];
1490
+ return U(u, l, {
1491
+ ...r,
1492
+ emit: (d) => {
1493
+ !i?.aborted && d.type !== "done" && f.push(d);
1494
+ },
1495
+ contextStore: Kr(l),
1496
+ ...i ? { signal: i } : {}
1497
+ }).then(() => ({
1498
+ state: l,
1499
+ events: f
1500
+ }));
1501
+ }), s = await Q(Promise.all(a), n, () => new x("parallel_timeout", "The assistant parallel step took too long to respond.", {
1502
+ source: "agent",
1503
+ sourceCode: "timeout"
1504
+ }), () => o?.abort()), c = t.merge || {};
1505
+ for (const { state: u, events: l } of s) {
1506
+ for (const f of l) r.emit(f);
1507
+ for (const f of u.productSkusEmitted) e.productSkusEmitted.add(f);
1508
+ for (const f of c.bag || []) Object.prototype.hasOwnProperty.call(u.bag, f) && (e.bag[f] = u.bag[f]);
1509
+ if (c.panel?.length) {
1510
+ const f = Jt(u.context.panel, c.panel);
1511
+ Object.keys(f).length && (e.context = r.contextStore.patch(e.threadId, { panel: f }) || e.context);
1512
+ }
1513
+ if (c.threadExtensions?.length) {
1514
+ const f = Jt(u.context.thread.extensions, c.threadExtensions);
1515
+ Object.keys(f).length && (e.context = r.contextStore.patch(e.threadId, { thread: {
1516
+ ...e.context.thread,
1517
+ extensions: f
1518
+ } }) || e.context);
1519
+ }
1520
+ }
1521
+ }
1522
+ async function Dr(t, e, r, n) {
1523
+ r.emit(_r(await _(t.message, n), !0)), await Ot(e, r);
1524
+ }
1525
+ async function Ur(t, e, r) {
1526
+ await Ot(e, r);
1527
+ }
1528
+ async function Ot(t, { contextStore: e, emit: r }) {
1529
+ t.committed || (t.context = await e.commit(t.threadId) || t.context, t.committed = !0, r(re()));
1530
+ }
1531
+ async function at(t, e, r, n) {
1532
+ if (typeof t.patch != "function") return;
1533
+ const o = await t.patch(r.context, e, D(r));
1534
+ o && (r.context = n.patch(r.threadId, o) || r.context);
1535
+ }
1536
+ function D(t, e) {
1537
+ return {
1538
+ request: t.request,
1539
+ context: t.context,
1540
+ bag: t.bag,
1541
+ accountConfig: t.accountConfig,
1542
+ catalogMapper: t.catalogMapper,
1543
+ similarityMapper: t.similarityMapper,
1544
+ ...e ? {
1545
+ beClient: e.beClient,
1546
+ toolBridge: e.toolBridge
1547
+ } : {},
1548
+ ...e?.signal ? { signal: e.signal } : {}
1549
+ };
1550
+ }
1551
+ function Z(t) {
1552
+ return t.request?.session_id || t.request?.sessionId || t.threadId;
1553
+ }
1554
+ function zr(t, e) {
1555
+ if (!e) return !1;
1556
+ const r = t.messages[t.messages.length - 1];
1557
+ return r?.role !== "user" || r.content !== e;
1558
+ }
1559
+ function Jt(t, e) {
1560
+ const r = {};
1561
+ for (const n of e) Object.prototype.hasOwnProperty.call(t, n) && (r[n] = t[n]);
1562
+ return r;
1563
+ }
1564
+ function Vr(t) {
1565
+ return {
1566
+ ...t,
1567
+ panel: kt(t.panel || {}),
1568
+ thread: {
1569
+ ...t.thread,
1570
+ extensions: kt(t.thread?.extensions || {})
1571
+ },
1572
+ meta: t.meta,
1573
+ messages: t.messages
1574
+ };
1575
+ }
1576
+ function Kr(t) {
1577
+ return {
1578
+ async load() {
1579
+ return t.context;
1580
+ },
1581
+ patch(e, r) {
1582
+ return t.context = Hr(t.context, r, t.messageLimit), t.context;
1583
+ },
1584
+ appendUserMessage() {
1585
+ return t.context;
1586
+ },
1587
+ async commit() {
1588
+ return t.context;
1589
+ }
1590
+ };
1591
+ }
1592
+ function Hr(t, e, r) {
1593
+ if (!e || typeof e != "object") return t;
1594
+ const n = Zt(t.panel, e.panel), o = Zt(t.thread?.extensions || {}, e.thread?.extensions);
1595
+ return {
1596
+ ...t,
1597
+ ...e,
1598
+ panel: n,
1599
+ thread: {
1600
+ ...t.thread || {},
1601
+ ...e.thread || {},
1602
+ extensions: o
1603
+ },
1604
+ meta: {
1605
+ ...t.meta || {},
1606
+ ...e.meta || {}
1607
+ },
1608
+ messages: Array.isArray(e.messages) ? it(e.messages, r) : t.messages
1609
+ };
1610
+ }
1611
+ function Zt(t, e) {
1612
+ if (!e || typeof e != "object" || Array.isArray(e)) return t;
1613
+ const r = {};
1614
+ for (const n of Object.keys(t)) r[n] = t[n];
1615
+ for (const [n, o] of Object.entries(e)) r[n] = o;
1616
+ return r;
1617
+ }
1618
+ function kt(t) {
1619
+ return new Proxy({}, {
1620
+ get(e, r, n) {
1621
+ if (typeof r != "string") return Reflect.get(e, r, n);
1622
+ if (Object.prototype.hasOwnProperty.call(e, r)) return e[r];
1623
+ const o = t[r];
1624
+ if (Jr(o)) {
1625
+ const i = Zr(o);
1626
+ return e[r] = i, i;
1627
+ }
1628
+ return o;
1629
+ },
1630
+ has(e, r) {
1631
+ return Reflect.has(e, r) || Reflect.has(t, r);
1632
+ },
1633
+ ownKeys(e) {
1634
+ return Reflect.ownKeys(e);
1635
+ },
1636
+ getOwnPropertyDescriptor(e, r) {
1637
+ return Object.getOwnPropertyDescriptor(e, r);
1638
+ }
1639
+ });
1640
+ }
1641
+ function Jr(t) {
1642
+ return !!(t && typeof t == "object");
1643
+ }
1644
+ function Zr(t) {
1645
+ if (typeof structuredClone == "function") try {
1646
+ return structuredClone(t);
1647
+ } catch {
1648
+ }
1649
+ try {
1650
+ return JSON.parse(JSON.stringify(t));
1651
+ } catch {
1652
+ return t;
1653
+ }
1654
+ }
1655
+ async function _(t, e) {
1656
+ return typeof t == "function" ? await t(e) : t;
1657
+ }
1658
+ function Y(t) {
1659
+ if (t === void 0) return;
1660
+ const e = Math.floor(Number(t));
1661
+ return Number.isFinite(e) && e > 0 ? e : void 0;
1662
+ }
1663
+ async function Q(t, e, r, n) {
1664
+ if (!e) return t;
1665
+ let o, i = !1;
1666
+ return new Promise((a, s) => {
1667
+ o = setTimeout(() => {
1668
+ i || (i = !0, n?.(), s(r()));
1669
+ }, e), Promise.resolve(t).then((c) => {
1670
+ i || (i = !0, o && clearTimeout(o), a(c));
1671
+ }, (c) => {
1672
+ i || (i = !0, o && clearTimeout(o), s(c));
1673
+ });
1674
+ });
1675
+ }
1676
+ function ce(t, e) {
1677
+ if (!t) return e;
1678
+ if (!e || t.aborted) return t;
1679
+ if (e.aborted) return e;
1680
+ const r = new AbortController(), n = () => r.abort();
1681
+ return t.addEventListener("abort", n, { once: !0 }), e.addEventListener("abort", n, { once: !0 }), r.signal;
1682
+ }
1683
+ async function jt(t, e, r, n) {
1684
+ if (!t.confirm) return;
1685
+ const o = await _(t.confirm, n);
1686
+ if (!o) return;
1687
+ const i = Wr(o, t, e);
1688
+ await v(r, gt("confirmation:start", e, t));
1689
+ try {
1690
+ const a = await Q(r.rpc("confirmation.request", i), Pr, () => new x("confirmation_timeout", "The confirmation prompt timed out without a response.", {
1691
+ source: t.kind === "be_op" ? "be" : t.kind,
1692
+ sourceCode: "confirmation_timeout"
1693
+ })), s = typeof a == "boolean" ? a : a?.confirmed === !0;
1694
+ if (await v(r, gt("confirmation:end", e, t)), s) return;
1695
+ throw new x("confirmation_declined", "The requested action was not confirmed.", {
1696
+ source: t.kind === "be_op" ? "be" : t.kind,
1697
+ sourceCode: "confirmation_declined",
1698
+ detail: a
1699
+ });
1700
+ } catch (a) {
1701
+ throw await v(r, {
1702
+ ...gt("confirmation:error", e, t),
1703
+ errorCode: G(a)
1704
+ }), a;
1705
+ }
1706
+ }
1707
+ function Wr(t, e, r) {
1708
+ return {
1709
+ ...Gr(t),
1710
+ accountId: r.context.meta.accountId,
1711
+ threadId: r.threadId,
1712
+ sessionId: Z(r),
1713
+ stepKind: e.kind,
1714
+ ...e.kind === "be_op" ? { stepName: e.op } : { stepName: e.name }
1715
+ };
1716
+ }
1717
+ function Gr(t) {
1718
+ return typeof t == "string" ? { message: t } : t === !0 ? {} : t && typeof t == "object" ? {
1719
+ ...typeof t.title == "string" ? { title: t.title } : {},
1720
+ ...typeof t.message == "string" ? { message: t.message } : {},
1721
+ ...typeof t.action == "string" ? { action: t.action } : {},
1722
+ ...Object.prototype.hasOwnProperty.call(t, "payload") ? { payload: t.payload } : {}
1723
+ } : {};
1724
+ }
1725
+ async function v(t, e) {
1726
+ try {
1727
+ await t.trace?.(e);
1728
+ } catch {
1729
+ }
1730
+ }
1731
+ async function W(t, e, r, n) {
1732
+ try {
1733
+ return await n();
1734
+ } catch (o) {
1735
+ await v(t, {
1736
+ ...q("step:error", e),
1737
+ stepName: `hook:${r}`,
1738
+ errorCode: G(o)
1739
+ });
1740
+ try {
1741
+ await t.rpc("beacon.send", {
1742
+ type: "agentHookError",
1743
+ threadId: e.threadId,
1744
+ sessionId: Z(e),
1745
+ accountId: e.context.meta.accountId,
1746
+ hook: r,
1747
+ errorCode: G(o),
1748
+ message: o instanceof Error ? o.message : String(o)
1749
+ });
1750
+ } catch {
1751
+ }
1752
+ return;
1753
+ }
1754
+ }
1755
+ function q(t, e) {
1756
+ return {
1757
+ type: t,
1758
+ accountId: e.context.meta.accountId,
1759
+ threadId: e.threadId,
1760
+ sessionId: Z(e)
1761
+ };
1762
+ }
1763
+ function yt(t, e, r, n) {
1764
+ const o = ue(r);
1765
+ return {
1766
+ ...q(t, e),
1767
+ stepIndex: n,
1768
+ stepKind: r.kind,
1769
+ ...o ? { stepName: o } : {}
1770
+ };
1771
+ }
1772
+ function gt(t, e, r) {
1773
+ const n = ue(r);
1774
+ return {
1775
+ ...q(t, e),
1776
+ stepKind: r.kind,
1777
+ ...n ? { stepName: n } : {}
1778
+ };
1779
+ }
1780
+ function ue(t) {
1781
+ if (t.kind === "be_op") return t.op;
1782
+ if (t.kind === "tool" || t.kind === "adapter") return t.name;
1783
+ }
1784
+ function G(t) {
1785
+ if (t && typeof t == "object") {
1786
+ const e = t;
1787
+ return String(e.sourceCode || e.code || e.name || "unknown");
1788
+ }
1789
+ return "unknown";
1790
+ }
1791
+ function Yr(t) {
1792
+ if (t === void 0) return;
1793
+ const e = Math.floor(Number(t));
1794
+ return Number.isFinite(e) && e > 0 ? e : void 0;
1795
+ }
1796
+ function Qr(t) {
1797
+ const e = t?.payload;
1798
+ if (typeof e == "string") return e;
1799
+ if (e && typeof e == "object" && "text" in e) {
1800
+ const r = e.text;
1801
+ if (typeof r == "string") return r;
1802
+ }
1803
+ return typeof t?.action?.payload == "string" ? t.action.payload : typeof t?.action?.title == "string" ? t.action.title : "";
1804
+ }
1805
+ function Xr(t, e) {
1806
+ const r = t, n = r.spec, o = Array.isArray(n?.items) ? n.items : void 0, i = Array.isArray(r.items) ? r.items : void 0, a = o || i;
1807
+ if (Array.isArray(a)) {
1808
+ for (const s of a) if (s && typeof s == "object") {
1809
+ const c = s.sku;
1810
+ typeof c == "string" && e.add(c);
1811
+ }
1812
+ }
1813
+ }
1814
+ function Oo(t) {
1815
+ return { invoke(e, r) {
1816
+ return t("tool.invoke", {
1817
+ name: e,
1818
+ input: r
1819
+ });
1820
+ } };
1821
+ }
1822
+ function jo(t, e = {}) {
1823
+ if (!Array.isArray(t)) return [];
1824
+ const r = e.maxItems ?? 8, n = e.maxFeatures ?? 8;
1825
+ return t.map((o) => tn(o, e.defaultBrand, n)).filter((o) => !!o).slice(0, r);
1826
+ }
1827
+ function tn(t, e, r) {
1828
+ if (!t || typeof t != "object" || Array.isArray(t)) return null;
1829
+ const n = t, o = Pt(n);
1830
+ return o ? nn({
1831
+ sku: o.sku,
1832
+ name: o.name,
1833
+ url: o.url,
1834
+ image: o.image,
1835
+ price: o.price,
1836
+ currency: o.currency,
1837
+ category: o.category,
1838
+ category_names: o.category_names,
1839
+ brand: n.brand || e,
1840
+ features: en(n.features, r),
1841
+ specs: rn(n.specs, r),
1842
+ in_stock: o.in_stock
1843
+ }) : null;
1844
+ }
1845
+ function en(t, e) {
1846
+ return Array.isArray(t) ? t.filter(Boolean).slice(0, e) : void 0;
1847
+ }
1848
+ function rn(t, e) {
1849
+ if (!(!t || typeof t != "object" || Array.isArray(t)))
1850
+ return Object.fromEntries(Object.entries(t).filter(([, r]) => r != null).slice(0, e));
1851
+ }
1852
+ function nn(t) {
1853
+ return Object.fromEntries(Object.entries(t).filter(([, e]) => e != null));
1854
+ }
1855
+ function le(t) {
1856
+ if (!t || typeof t != "object" || Array.isArray(t)) return {};
1857
+ const e = t, r = Array.isArray(e.rows) ? e.rows : [];
1858
+ return {
1859
+ ...e,
1860
+ rows: r.map(an).filter(Boolean)
1861
+ };
1862
+ }
1863
+ function on(t, e) {
1864
+ const r = Array.isArray(t) ? t.filter((s) => !!(s && typeof s == "object" && !Array.isArray(s))) : [], n = le(e), o = Array.isArray(n.columns) ? n.columns.map(String) : [];
1865
+ if (!o.length) return r;
1866
+ const i = new Map(r.map((s) => [String(s.sku || s.id || ""), s])), a = o.map((s) => i.get(s)).filter((s) => !!s);
1867
+ return a.length ? a : r;
1868
+ }
1869
+ function Mo(t, e) {
1870
+ const r = le(t?.table), n = on(e, r);
1871
+ return {
1872
+ ...t || {},
1873
+ table: r,
1874
+ products: n,
1875
+ multiple_product_details: n
1876
+ };
1877
+ }
1878
+ function an(t) {
1879
+ return !t || typeof t != "object" || Array.isArray(t) ? null : Object.fromEntries(Object.entries(t).filter(([, e]) => e !== void 0));
1880
+ }
1881
+ function Ro(t = [], e = {}) {
1882
+ const r = {}, n = [];
1883
+ return (Array.isArray(t) ? t.map((o) => Et(o, e)).filter((o) => !!o) : []).forEach((o, i) => {
1884
+ const a = `product-${i.toString()}`;
1885
+ n.push(a);
1886
+ const s = {
1887
+ sku: o.sku,
1888
+ product: o
1889
+ };
1890
+ r[a] = {
1891
+ type: "ProductCard",
1892
+ props: {
1893
+ product: o,
1894
+ index: i,
1895
+ action: {
1896
+ title: o.name,
1897
+ type: "launchSingleProduct",
1898
+ payload: s
1899
+ }
1900
+ }
1901
+ };
1902
+ }), r.root = {
1903
+ type: "ProductGrid",
1904
+ props: { layout: "grid" },
1905
+ children: n
1906
+ }, {
1907
+ widget: "chat",
1908
+ panelHint: "panel",
1909
+ spec: {
1910
+ root: "root",
1911
+ elements: r
1912
+ }
1913
+ };
1914
+ }
1915
+ function Bo(t, e = {}) {
1916
+ return {
1917
+ widget: "chat",
1918
+ panelHint: "panel",
1919
+ spec: {
1920
+ root: "root",
1921
+ elements: { root: {
1922
+ type: "ProductDetailsPanel",
1923
+ props: { product: Et(t, e) || t || {} }
1924
+ } }
1925
+ }
1926
+ };
1927
+ }
1928
+ function $o(t = {}, e = {}) {
1929
+ const r = (t.multiple_product_details || t.products || []).map((o) => Et(o, e)).filter((o) => !!o), n = t.table || sn(t.comparison_table);
1930
+ return {
1931
+ widget: "chat",
1932
+ panelHint: "panel",
1933
+ spec: {
1934
+ root: "root",
1935
+ elements: { root: {
1936
+ type: "ComparisonTable",
1937
+ props: {
1938
+ products: r,
1939
+ recommended: r.find((o) => o.sku === t.recommended_choice_sku) || r[0],
1940
+ attributes: Object.entries(n).map(([o, i]) => ({
1941
+ label: o,
1942
+ values: Array.isArray(i) ? i.map(String) : [String(i ?? "")]
1943
+ })),
1944
+ highlights: Ht(t.key_differences),
1945
+ specialCases: Ht(t.special_considerations),
1946
+ recommendedText: t.recommended_choice,
1947
+ productActions: Object.fromEntries(r.map((o) => [o.sku, {
1948
+ title: o.name,
1949
+ type: "launchSingleProduct",
1950
+ payload: {
1951
+ sku: o.sku,
1952
+ product: o
1953
+ }
1954
+ }]))
1955
+ }
1956
+ } }
1957
+ }
1958
+ };
1959
+ }
1960
+ function sn(t) {
1961
+ return Array.isArray(t) ? Object.fromEntries(t.map((e) => {
1962
+ const r = typeof e?.label == "string" ? e.label.trim() : "";
1963
+ return r ? [r, e.values] : null;
1964
+ }).filter((e) => !!e)) : {};
1965
+ }
1966
+ function No(t = []) {
1967
+ return {
1968
+ widget: "chat",
1969
+ panelHint: "inline",
1970
+ spec: {
1971
+ root: "root",
1972
+ elements: { root: {
1973
+ type: "ActionButtons",
1974
+ props: { buttons: (Array.isArray(t) ? t : []).map((e) => {
1975
+ const r = e.label || e.title || e.shortName || "", n = e.action || e.requestDetails || e.request_details;
1976
+ return !r || !n?.type ? null : {
1977
+ label: r,
1978
+ action: {
1979
+ title: r,
1980
+ type: n.type,
1981
+ ...n.payload !== void 0 ? { payload: n.payload } : {}
1982
+ }
1983
+ };
1984
+ }).filter((e) => !!e) }
1985
+ } }
1986
+ }
1987
+ };
1988
+ }
1989
+ function Lo(t) {
1990
+ return Object.freeze([...t]);
1991
+ }
1992
+ function cn(t) {
1993
+ const e = t?.payload;
1994
+ if (typeof e == "string") return e;
1995
+ if (e && typeof e == "object" && "text" in e) {
1996
+ const n = e.text;
1997
+ if (typeof n == "string") return n;
1998
+ }
1999
+ const r = t?.action;
2000
+ return r && typeof r.payload == "string" ? r.payload : r && typeof r.title == "string" ? r.title : "";
2001
+ }
2002
+ var fe = [
2003
+ {
2004
+ pattern: /\bhttps?:\/\/[^\s?#]+(?:\?[^\s#]*)?/giu,
2005
+ replacement: ln
2006
+ },
2007
+ {
2008
+ pattern: /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/giu,
2009
+ replacement: "[email]"
2010
+ },
2011
+ {
2012
+ pattern: /\b(?:\+?\d[\d\s().-]{7,}\d)\b/gu,
2013
+ replacement: "[phone]"
2014
+ },
2015
+ {
2016
+ pattern: /\b(?:token|secret|csrf|cookie|bearer|session|sid|cart(?:[_-]?id)?)\s*[:=]\s*[^\s,;&]+/giu,
2017
+ replacement: "[secret]"
2018
+ },
2019
+ {
2020
+ pattern: /\b(?:order|cart|session)[_-]?(?:id|no|number)?\s*[:#=]?\s*[A-Z0-9-]{6,}\b/giu,
2021
+ replacement: "[secret]"
2022
+ }
2023
+ ], de = { patterns: fe };
2024
+ function pe(t, e = de) {
2025
+ let r = typeof t == "string" ? t : t == null ? "" : String(t);
2026
+ for (const n of e.patterns || []) {
2027
+ const o = n.replacement;
2028
+ r = typeof o == "function" ? r.replace(n.pattern, (i) => o(i)) : r.replace(n.pattern, o);
2029
+ }
2030
+ return r;
2031
+ }
2032
+ function un(t, e = de) {
2033
+ return pe(cn(t), e);
2034
+ }
2035
+ function ln(t) {
2036
+ try {
2037
+ const e = new URL(t);
2038
+ return `${e.origin}${e.pathname}${e.search ? "?[query]" : ""}`;
2039
+ } catch {
2040
+ return "[url]";
2041
+ }
2042
+ }
2043
+ var fn = [
2044
+ "assistantName",
2045
+ "homeDomain",
2046
+ "categories",
2047
+ "policyTopics"
2048
+ ], dn = { intent: ["searchContract", "competitorBrands"] };
2049
+ function Fo(t, e, r, n = {}) {
2050
+ const o = pn(e, r, n);
2051
+ return Object.keys(o).length ? {
2052
+ ...t,
2053
+ account_config: o
2054
+ } : t;
2055
+ }
2056
+ function pn(t, e, r = {}) {
2057
+ if (!t) return {};
2058
+ const n = {}, o = r.baseKeys || fn;
2059
+ for (const s of o) Wt(n, t, s);
2060
+ const i = t[e];
2061
+ i && typeof i == "object" && !Array.isArray(i) && Object.assign(n, mn(i));
2062
+ const a = r.opAllowlist || dn;
2063
+ for (const s of a[e] || []) Wt(n, t, s);
2064
+ return n;
2065
+ }
2066
+ function Wt(t, e, r) {
2067
+ e[r] !== void 0 && (t[r] = e[r]);
2068
+ }
2069
+ function mn(t) {
2070
+ return Object.fromEntries(Object.entries(t).filter(([, e]) => e !== void 0));
2071
+ }
2072
+ var yn = "input-hash";
2073
+ function gn({ ttlS: t, promptVersion: e = "current" } = {}) {
2074
+ if (!Number.isFinite(t) || t <= 0) throw new Error("inputHashCachePolicy requires a positive ttlS");
2075
+ return {
2076
+ strategy: yn,
2077
+ ttlS: t,
2078
+ promptVersion: e
2079
+ };
2080
+ }
2081
+ function hn({ accountId: t = "", op: e, ttlS: r, promptVersion: n = "current", input: o, keyParts: i, locale: a } = {}) {
2082
+ if (!e) throw new Error("declarativeBeOpCache requires an op");
2083
+ return {
2084
+ cache: gn({
2085
+ ttlS: r,
2086
+ promptVersion: n
2087
+ }),
2088
+ cacheTtlS: r,
2089
+ cacheKey: (s = {}) => oe(e, {
2090
+ account: t,
2091
+ locale: ht(a, s) || s.context?.meta?.locale || s.locale || "",
2092
+ promptVersion: n,
2093
+ payload: _t(ht(o, s)),
2094
+ ...wn(ht(i, s))
2095
+ })
2096
+ };
2097
+ }
2098
+ function qo(t, e = {}) {
2099
+ return !t || t.kind !== "be_op" ? t : {
2100
+ ...t,
2101
+ ...hn({
2102
+ op: t.op,
2103
+ ttlS: t.cacheTtlS,
2104
+ input: t.input,
2105
+ ...e
2106
+ })
2107
+ };
2108
+ }
2109
+ function ht(t, e) {
2110
+ return typeof t == "function" ? t(e) : t;
2111
+ }
2112
+ function _t(t) {
2113
+ return Array.isArray(t) ? t.map(_t) : !t || typeof t != "object" ? t : Object.fromEntries(Object.entries(t).filter(([, e]) => e !== void 0).sort(([e], [r]) => e.localeCompare(r)).map(([e, r]) => [e, _t(r)]));
2114
+ }
2115
+ function wn(t) {
2116
+ return !t || typeof t != "object" || Array.isArray(t) ? {} : Object.fromEntries(Object.entries(t).filter(([, e]) => e != null));
2117
+ }
2118
+ var Do = Object.freeze({
2119
+ FALLBACK_RESULTS: "fallback_results",
2120
+ FALLBACK_NO_RESULTS: "fallback_no_results",
2121
+ FALLBACK_PARTIAL: "fallback_partial",
2122
+ OP_UNAVAILABLE: "op_unavailable"
2123
+ });
2124
+ function Uo(t, e = {}) {
2125
+ return {
2126
+ status: t,
2127
+ ...e
2128
+ };
2129
+ }
2130
+ function zo(t) {
2131
+ return !!(t && typeof t == "object" && typeof t.status == "string");
2132
+ }
2133
+ function Vo(t) {
2134
+ return function() {
2135
+ return [{
2136
+ kind: "tool",
2137
+ name: "readPage",
2138
+ input: () => ({}),
2139
+ out: "page",
2140
+ patch: (r, n) => n?.product && typeof t == "function" ? t(r, n.product) : null,
2141
+ onError: []
2142
+ }];
2143
+ };
2144
+ }
2145
+ function Ko(t) {
2146
+ return !t || typeof t != "object" || Array.isArray(t) ? {} : Object.fromEntries(Object.entries(t).filter(([, e]) => e != null && e !== "" && (!Array.isArray(e) || e.length > 0)));
2147
+ }
2148
+ function Ho(t, { screenSummary: e } = {}) {
2149
+ return { panel: {
2150
+ ...t?.panel || {},
2151
+ screen_type: "homepage",
2152
+ screen_sku_list: [],
2153
+ screen_summary: e || null,
2154
+ last_search_products: [],
2155
+ last_search: null,
2156
+ chat_mentioned_skus: [],
2157
+ reviews_summary_skus: [],
2158
+ ai_plist_summary: null,
2159
+ search_suggestions_skus: [],
2160
+ list_source: null,
2161
+ active_product_panel: !1,
2162
+ assistant_mode: "shopping",
2163
+ redirected_agent_state: null,
2164
+ ui_hints: null
2165
+ } };
2166
+ }
2167
+ function bn({ patterns: t, messageFilter: e, messageNormalizer: r = (o) => o, messageLimit: n = 10 } = {}) {
2168
+ const o = { patterns: [...fe, ...Array.isArray(t) ? t : []] };
2169
+ function i(c) {
2170
+ return pe(c, o);
2171
+ }
2172
+ function a(c) {
2173
+ return un(c, o);
2174
+ }
2175
+ function s(c = []) {
2176
+ const u = (Array.isArray(c) ? c : []).filter((l) => typeof e == "function" ? e(l) : l && typeof l == "object").filter(Boolean);
2177
+ return (Number.isFinite(n) && n > 0 ? u.slice(-n) : u).map((l) => ({
2178
+ role: l.role,
2179
+ content: i(r(l.content)).slice(0, 1e3)
2180
+ }));
2181
+ }
2182
+ return {
2183
+ redactPii: i,
2184
+ anonymousRequestText: a,
2185
+ anonymizeMessages: s
2186
+ };
2187
+ }
2188
+ function Jo(t) {
2189
+ return String(t || "").replace(/<script\b[\s\S]*?<\/script>/giu, " ").replace(/<style\b[\s\S]*?<\/style>/giu, " ").replace(/<[^>]+>/gu, " ").replace(/&nbsp;/giu, " ").replace(/&amp;/giu, "&").replace(/&lt;|&gt;/giu, " ").replace(/\s+/gu, " ").trim();
2190
+ }
2191
+ var A = {
2192
+ features: 18,
2193
+ reviews: 4,
2194
+ qna: 4,
2195
+ sellers: 4,
2196
+ variants: 12,
2197
+ documents: 6,
2198
+ textBlocks: 6,
2199
+ relatedProducts: 8,
2200
+ textChars: 220
2201
+ }, Mt = {
2202
+ description: /\b(?:description|details|product information|urun bilgisi|urun aciklamasi|açıklama|aciklama)\b/iu,
2203
+ seller: /\b(?:seller|merchant|store|satici|satıcı|magaza|mağaza)\b/iu,
2204
+ review: /\b(?:review|reviews|rating|ratings|yorum|degerlendirme|değerlendirme|puan)\b/iu,
2205
+ qna: /\b(?:questions?|answers?|qna|q&a|soru|cevap)\b/iu,
2206
+ payment: /\b(?:installment|instalment|payment|pay in|taksit|odeme|ödeme|vade)\b/iu,
2207
+ delivery: /\b(?:delivery|shipping|cargo|stock|availability|teslimat|kargo|stok|gonderim|gönderim)\b/iu,
2208
+ promotion: /\b(?:campaign|promotion|discount|coupon|deal|kampanya|indirim|kupon|firsat|fırsat)\b/iu,
2209
+ variant: /\b(?:variant|size|colour|color|beden|olcu|ölçü|renk|numara)\b/iu
2210
+ }, kn = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|\+?\d[\d\s().-]{8,}\d|\b[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}\b|\b(?:token|session|csrf|secret)\s*[:=]\s*[\w.-]+/giu, _n = /(?:token|session|sid|auth|code|csrf|secret|key|password|passwd|phone|email|address|postcode|zip|jwt|bearer)/iu, An = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|\+?\d[\d\s().-]{8,}\d|[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}|[A-Za-z0-9_-]{24,}/iu;
2211
+ function Zo({ accountId: t, getPageType: e, getProduct: r, getProducts: n, normalizeProduct: o = (i) => i }) {
2212
+ return (i = {}) => Sn({
2213
+ accountId: t,
2214
+ getPageType: e,
2215
+ getProduct: r,
2216
+ getProducts: n,
2217
+ normalizeProduct: o,
2218
+ input: i
2219
+ });
2220
+ }
2221
+ function Sn({ accountId: t, getPageType: e, getProduct: r, getProducts: n, normalizeProduct: o = (a) => a, input: i = {} }) {
2222
+ const a = Wn(i), s = o(i.product || wt(r)), c = (wt(n) || []).map(o).filter(Boolean), u = b(i.sku || s?.sku || i.product?.sku), l = u ? c.find((ut) => b(ut?.sku) === u) || s : s || c[0] || null, f = Cn(u || l?.sku), d = Gt({
2223
+ ...f.product,
2224
+ ...l
2225
+ }), p = Nt(nt(l?.features), nt(l?.specs), Ln(l?.facet_hits), nt(f.product?.features), En(), Pn(), In()).slice(0, a.features), m = ye(st(l?.reviews), f.reviews, On()).slice(0, a.reviews), h = ge(Rt(l?.qna), jn()).slice(0, a.qna), T = he(Bt(l?.sellers), Mn()).slice(0, a.sellers), $ = B([...l?.payment || [], ...rt("payment", a)]), M = B([...l?.delivery || [], ...rt("delivery", a)]), N = B([...l?.promotions || [], ...rt("promotion", a)]), R = we($t(l?.variants), Rn()).slice(0, a.variants), L = Bn(a.documents), k = ke(l?.description, f.product?.description, $n("description"), rt("description", {
2226
+ ...a,
2227
+ textBlocks: 2
2228
+ })[0]), Lt = c.filter((ut) => !u || b(ut?.sku) !== u).map(Gt).filter(Boolean).slice(0, a.relatedProducts);
2229
+ return z({
2230
+ accountId: t,
2231
+ pageType: wt(e) || "other",
2232
+ url: Zn(),
2233
+ product: d,
2234
+ description: k,
2235
+ features: p,
2236
+ sellers: T,
2237
+ reviews: m,
2238
+ qna: h,
2239
+ rating: S(l?.rating ?? f.rating),
2240
+ review_count: S(l?.review_count ?? f.review_count),
2241
+ payment: $,
2242
+ delivery: M,
2243
+ promotions: N,
2244
+ variants: R,
2245
+ documents: L,
2246
+ related_products: Lt,
2247
+ capabilities: Vn({
2248
+ description: k,
2249
+ features: p,
2250
+ sellers: T,
2251
+ reviews: m,
2252
+ qna: h,
2253
+ payment: $,
2254
+ delivery: M,
2255
+ promotions: N,
2256
+ variants: R,
2257
+ documents: L,
2258
+ relatedProducts: Lt
2259
+ }),
2260
+ privacy: {
2261
+ browserLocal: !0,
2262
+ rawHtml: !1,
2263
+ formValues: !1,
2264
+ cookies: !1,
2265
+ storage: !1,
2266
+ redacted: !0
2267
+ }
2268
+ });
2269
+ }
2270
+ function Wo(t, e) {
2271
+ const r = Array.isArray(t) ? t.filter(Boolean) : [];
2272
+ if (!e || typeof e != "object" || !r.length) return r;
2273
+ const n = b(e.product?.sku);
2274
+ return r.map((o, i) => {
2275
+ const a = b(o?.sku);
2276
+ return r.length === 1 || n && a && n === a || i === 0 ? vn(o, e) : o;
2277
+ });
2278
+ }
2279
+ function xn(t) {
2280
+ return !t || typeof t != "object" ? null : z({
2281
+ product: t.product,
2282
+ description: g(t.description, 500),
2283
+ features: Fn(t.features, 14),
2284
+ sellers: Un(t.sellers, 4),
2285
+ reviews: qn(t.reviews, 4),
2286
+ qna: Dn(t.qna, 4),
2287
+ rating: t.rating,
2288
+ review_count: t.review_count,
2289
+ payment: j(t.payment, 5, 160),
2290
+ delivery: j(t.delivery, 5, 160),
2291
+ promotions: j(t.promotions, 5, 160),
2292
+ variants: zn(t.variants, 10),
2293
+ documents: j(t.documents, 5, 220),
2294
+ capabilities: Array.isArray(t.capabilities) ? t.capabilities.slice(0, 12) : void 0
2295
+ });
2296
+ }
2297
+ function Go(t, e, r = {}) {
2298
+ const n = xn(t);
2299
+ if (!n) return e;
2300
+ const o = String(r.locale || "").toLowerCase().startsWith("en"), i = [], a = [n.rating ? `${n.rating}/5` : "", n.review_count ? `${n.review_count} ${o ? "reviews" : "yorum"}` : ""].filter(Boolean).join(", ");
2301
+ return a && i.push(o ? `Visible rating: ${a}.` : `Görünür puan bilgisi: ${a}.`), n.reviews?.length && i.push(`${o ? "Visible review highlights" : "Görünür yorumlardan öne çıkanlar"}: ${n.reviews.map((s) => [s.star ? `${s.star}/5` : "", s.content].filter(Boolean).join(" ")).filter(Boolean).slice(0, 3).join(" | ")}.`), i.length ? (i.push(o ? "This summary only uses product review and rating fields visible in the browser." : "Bu özet yalnızca tarayıcıda görünen ürün yorumu ve puan alanlarından hazırlandı."), i.join(" ")) : e;
2302
+ }
2303
+ function vn(t, e) {
2304
+ return z({
2305
+ ...t,
2306
+ description: ke(t.description, e.description),
2307
+ features: Nt(nt(t.features), e.features).slice(0, 24),
2308
+ specs: t.specs || (e.features?.length ? Object.fromEntries(e.features.map(Kn)) : void 0),
2309
+ sellers: he(Bt(t.sellers), e.sellers),
2310
+ reviews: ye(st(t.reviews), e.reviews),
2311
+ qna: ge(Rt(t.qna), e.qna),
2312
+ rating: t.rating ?? e.rating,
2313
+ review_count: t.review_count ?? e.review_count,
2314
+ payment: B([...t.payment || [], ...e.payment || []]),
2315
+ delivery: B([...t.delivery || [], ...e.delivery || []]),
2316
+ promotions: B([...t.promotions || [], ...e.promotions || []]),
2317
+ variants: we($t(t.variants), e.variants),
2318
+ documents: B([...t.documents || [], ...e.documents || []])
2319
+ });
2320
+ }
2321
+ function Cn(t) {
2322
+ const e = [];
2323
+ for (const o of C('script[type="application/ld+json"]')) {
2324
+ const i = Tn(o.textContent);
2325
+ for (const a of At(i))
2326
+ String(a?.["@type"] || "").toLowerCase() === "product" && e.push(a);
2327
+ }
2328
+ const r = e.find((o) => b(o.sku || o.productID || o.mpn) === b(t)) || e[0];
2329
+ if (!r) return {};
2330
+ const n = r.aggregateRating || {};
2331
+ return {
2332
+ product: z({
2333
+ sku: b(r.sku || r.productID || r.mpn),
2334
+ name: y(r.name),
2335
+ brand: y(r.brand?.name || r.brand),
2336
+ description: y(r.description),
2337
+ images: j(r.image, 8, 280),
2338
+ url: X(r.url),
2339
+ rating: S(n.ratingValue),
2340
+ review_count: S(n.reviewCount || n.ratingCount)
2341
+ }),
2342
+ reviews: st(r.review),
2343
+ rating: S(n.ratingValue),
2344
+ review_count: S(n.reviewCount || n.ratingCount)
2345
+ };
2346
+ }
2347
+ function At(t) {
2348
+ return Array.isArray(t) ? t.flatMap(At) : !t || typeof t != "object" ? [] : [t, ...At(t["@graph"])];
2349
+ }
2350
+ function Tn(t) {
2351
+ try {
2352
+ return JSON.parse(String(t || ""));
2353
+ } catch {
2354
+ return null;
2355
+ }
2356
+ }
2357
+ function En() {
2358
+ const t = [];
2359
+ for (const e of C("table tr")) {
2360
+ const r = [...e.querySelectorAll?.("th,td") || []].map((n) => y(n.textContent));
2361
+ r.length >= 2 && r[0] && r[1] && t.push({
2362
+ key: r[0],
2363
+ value: r.slice(1).join(" ")
2364
+ });
2365
+ }
2366
+ return t;
2367
+ }
2368
+ function Pn() {
2369
+ const t = [];
2370
+ for (const e of C("dt")) {
2371
+ const r = y(e.textContent), n = y(e.nextElementSibling?.matches?.("dd") ? e.nextElementSibling.textContent : "");
2372
+ r && n && t.push({
2373
+ key: r,
2374
+ value: n
2375
+ });
2376
+ }
2377
+ return t;
2378
+ }
2379
+ function In() {
2380
+ return C('[class*="spec" i], [class*="feature" i], [class*="attribute" i], li').map((t) => me(y(t.textContent))).filter(Boolean).slice(0, A.features);
2381
+ }
2382
+ function On() {
2383
+ return C('[class*="review" i], [data-review], [itemprop="review"]').map((t) => {
2384
+ const e = y(t.textContent);
2385
+ return !e || e.length < 8 || Mt.qna.test(e) ? null : {
2386
+ content: g(e, 260),
2387
+ star: S(t.getAttribute?.("data-rating"))
2388
+ };
2389
+ }).filter(Boolean);
2390
+ }
2391
+ function jn() {
2392
+ const t = C('[class*="question" i], [class*="answer" i], [data-question], [data-answer]'), e = [];
2393
+ for (const r of t) {
2394
+ const n = y(r.textContent);
2395
+ if (!n || !Mt.qna.test(n)) continue;
2396
+ const o = y(r.getAttribute?.("data-question") || n), i = y(r.getAttribute?.("data-answer") || r.nextElementSibling?.textContent || "");
2397
+ e.push({
2398
+ question: g(o, 220),
2399
+ answer: g(i, 260)
2400
+ });
2401
+ }
2402
+ return e;
2403
+ }
2404
+ function Mn() {
2405
+ return C('[class*="seller" i], [class*="merchant" i], [data-seller], [data-merchant]').map((t) => y(t.getAttribute?.("data-seller") || t.getAttribute?.("data-merchant") || t.textContent)).filter(Boolean).map((t) => ({ merchant: g(t, 120) }));
2406
+ }
2407
+ function Rn() {
2408
+ return C('[class*="variant" i] a,[class*="variant" i] button,[class*="size" i] button,[class*="color" i] button,[data-variant],[data-size],[data-color]').map((t) => z({
2409
+ name: g(_e(t), 120),
2410
+ value: g(t.getAttribute?.("data-value") || t.getAttribute?.("data-size") || t.getAttribute?.("data-color"), 120),
2411
+ sku: b(t.getAttribute?.("data-sku") || t.getAttribute?.("data-product-id")),
2412
+ url: X(t.getAttribute?.("href")),
2413
+ in_stock: t.getAttribute?.("disabled") == null && t.getAttribute?.("aria-disabled") !== "true"
2414
+ })).filter((t) => t.name || t.value || t.sku);
2415
+ }
2416
+ function Bn(t) {
2417
+ return C("a[href]").filter((e) => /\.pdf(?:$|[?#])/iu.test(e.getAttribute?.("href") || "")).map((e) => {
2418
+ const r = _e(e) || "PDF", n = X(e.getAttribute?.("href"));
2419
+ return n ? `${r}: ${n}` : "";
2420
+ }).filter(Boolean).slice(0, t);
2421
+ }
2422
+ function rt(t, e) {
2423
+ const r = Mt[t];
2424
+ return r ? C("section,article,div,li,p,span,button,a").map((n) => y(n.textContent)).filter((n) => n && r.test(n) && n.length <= 900).map((n) => g(n, e.textChars || A.textChars)).filter(be()).slice(0, e.textBlocks || A.textBlocks) : [];
2425
+ }
2426
+ function $n(t) {
2427
+ return y(document.querySelector?.(`meta[name="${t}"]`)?.getAttribute?.("content") || document.querySelector?.(`meta[property="og:${t}"]`)?.getAttribute?.("content"));
2428
+ }
2429
+ function C(t) {
2430
+ try {
2431
+ return [...document.querySelectorAll?.(t) || []].filter(Nn);
2432
+ } catch {
2433
+ return [];
2434
+ }
2435
+ }
2436
+ function Nn(t) {
2437
+ if (!t) return !1;
2438
+ if (!t.getBoundingClientRect) return !0;
2439
+ const e = t.getBoundingClientRect();
2440
+ if (e.width <= 0 || e.height <= 0) return !1;
2441
+ const r = window.getComputedStyle?.(t);
2442
+ return !r || r.visibility !== "hidden" && r.display !== "none" && Number(r.opacity || 1) > 0;
2443
+ }
2444
+ function nt(t) {
2445
+ return t ? (Array.isArray(t) ? t : Object.entries(t).map(([e, r]) => ({
2446
+ key: e,
2447
+ value: r
2448
+ }))).map((e) => typeof e == "string" ? me(e) || {
2449
+ key: "",
2450
+ value: y(e)
2451
+ } : {
2452
+ key: y(e.key || e.name || e.label),
2453
+ value: y(e.value || e.text || "")
2454
+ }).filter((e) => e.key || e.value) : [];
2455
+ }
2456
+ function Ln(t) {
2457
+ return !t || typeof t != "object" ? [] : Object.entries(t).map(([e, r]) => ({
2458
+ key: y(e),
2459
+ value: y(r)
2460
+ }));
2461
+ }
2462
+ function me(t) {
2463
+ const e = /^(.{2,80}?)\s*[::]\s*(.{1,220})$/u.exec(y(t));
2464
+ return e ? {
2465
+ key: e[1],
2466
+ value: e[2]
2467
+ } : null;
2468
+ }
2469
+ function st(t) {
2470
+ return (Array.isArray(t) ? t : t ? [t] : []).map((e) => typeof e == "string" ? { content: g(e, 260) } : {
2471
+ content: g(e.content || e.reviewBody || e.description || e.text, 260),
2472
+ star: S(e.star || e.rating || e.reviewRating?.ratingValue)
2473
+ }).filter((e) => e.content || e.star);
2474
+ }
2475
+ function Rt(t) {
2476
+ return (Array.isArray(t) ? t : t ? [t] : []).map((e) => ({
2477
+ question: g(e.question || e.name || "", 220),
2478
+ answer: g(e.answer || e.acceptedAnswer?.text || e.text || "", 260)
2479
+ })).filter((e) => e.question || e.answer);
2480
+ }
2481
+ function Bt(t) {
2482
+ return (Array.isArray(t) ? t : t ? [t] : []).map((e) => typeof e == "string" ? { merchant: g(e, 120) } : {
2483
+ merchant: g(e.merchant || e.name || e.seller || "", 120),
2484
+ merchant_id: b(e.merchant_id || e.id || ""),
2485
+ merchant_rating: S(e.merchant_rating || e.rating),
2486
+ price_offer: S(e.price_offer || e.price)
2487
+ }).filter((e) => e.merchant || e.merchant_id);
2488
+ }
2489
+ function $t(t) {
2490
+ return (Array.isArray(t) ? t : t ? [t] : []).map((e) => ({
2491
+ name: g(e.name || e.label || e.title || "", 120),
2492
+ value: g(e.value || e.size || e.color || "", 120),
2493
+ sku: b(e.sku || e.code || ""),
2494
+ url: X(e.url),
2495
+ in_stock: e.in_stock
2496
+ })).filter((e) => e.name || e.value || e.sku || e.url);
2497
+ }
2498
+ function Nt(...t) {
2499
+ const e = /* @__PURE__ */ new Set(), r = [];
2500
+ for (const n of t.flat().filter(Boolean)) {
2501
+ const o = {
2502
+ key: g(n.key || n.name || "", 90),
2503
+ value: g(n.value || n.text || "", 180)
2504
+ }, i = `${o.key}:${o.value}`.toLocaleLowerCase("tr-TR");
2505
+ !o.key && !o.value || e.has(i) || (e.add(i), r.push(o));
2506
+ }
2507
+ return r;
2508
+ }
2509
+ function ye(...t) {
2510
+ return ct(t.flat().filter(Boolean), (e) => `${e.star || ""}:${e.content || ""}`);
2511
+ }
2512
+ function ge(...t) {
2513
+ return ct(t.flat().filter(Boolean), (e) => `${e.question || ""}:${e.answer || ""}`);
2514
+ }
2515
+ function he(...t) {
2516
+ return ct(t.flat().filter(Boolean), (e) => `${e.merchant || ""}:${e.merchant_id || ""}`);
2517
+ }
2518
+ function we(...t) {
2519
+ return ct(t.flat().filter(Boolean), (e) => `${e.sku || ""}:${e.name || ""}:${e.value || ""}`);
2520
+ }
2521
+ function ct(t, e) {
2522
+ const r = /* @__PURE__ */ new Set();
2523
+ return t.filter((n) => {
2524
+ const o = e(n).toLocaleLowerCase("tr-TR");
2525
+ return !o.trim() || r.has(o) ? !1 : (r.add(o), !0);
2526
+ });
2527
+ }
2528
+ function B(t) {
2529
+ return j(t, 20, A.textChars);
2530
+ }
2531
+ function j(t, e, r) {
2532
+ return (Array.isArray(t) ? t : t ? [t] : []).map((n) => g(n, r)).filter(Boolean).filter(be()).slice(0, e);
2533
+ }
2534
+ function be() {
2535
+ const t = /* @__PURE__ */ new Set();
2536
+ return (e) => {
2537
+ const r = y(e).toLocaleLowerCase("tr-TR");
2538
+ return !r || t.has(r) ? !1 : (t.add(r), !0);
2539
+ };
2540
+ }
2541
+ function Fn(t, e) {
2542
+ return Nt(t).slice(0, e);
2543
+ }
2544
+ function qn(t, e) {
2545
+ return st(t).slice(0, e);
2546
+ }
2547
+ function Dn(t, e) {
2548
+ return Rt(t).slice(0, e);
2549
+ }
2550
+ function Un(t, e) {
2551
+ return Bt(t).slice(0, e);
2552
+ }
2553
+ function zn(t, e) {
2554
+ return $t(t).slice(0, e);
2555
+ }
2556
+ function Gt(t) {
2557
+ return !t || typeof t != "object" ? null : z({
2558
+ sku: b(t.sku || t.id || ""),
2559
+ group_id: b(t.group_id || t.groupId || ""),
2560
+ name: y(t.name || t.title || ""),
2561
+ brand: y(t.brand || ""),
2562
+ url: X(t.url),
2563
+ images: j(t.images || t.image, 8, 280),
2564
+ price: S(t.price),
2565
+ price_discounted: S(t.price_discounted || t.discountedPrice),
2566
+ price_text: y(t.price_text || t.priceText || ""),
2567
+ price_currency: y(t.price_currency || t.currency || ""),
2568
+ category_ids: Hn(t.category_ids || t.categoryIds, 8, 90),
2569
+ category_names: j(t.category_names || t.categoryNames || t.category, 8, 140),
2570
+ in_stock: t.in_stock
2571
+ });
2572
+ }
2573
+ function Vn(t) {
2574
+ return [
2575
+ t.description ? "description" : "",
2576
+ t.features?.length ? "features" : "",
2577
+ t.sellers?.length ? "seller" : "",
2578
+ t.reviews?.length || t.rating || t.review_count ? "reviews_ratings" : "",
2579
+ t.qna?.length ? "qna" : "",
2580
+ t.payment?.length ? "installment_payment" : "",
2581
+ t.delivery?.length ? "shipping_delivery_stock" : "",
2582
+ t.promotions?.length ? "campaigns_promotions" : "",
2583
+ t.variants?.length ? "variants" : "",
2584
+ t.documents?.length ? "documents" : "",
2585
+ t.relatedProducts?.length ? "related_products" : ""
2586
+ ].filter(Boolean);
2587
+ }
2588
+ function Kn(t) {
2589
+ return [y(t.key || t.name), y(t.value || t.text)];
2590
+ }
2591
+ function ke(...t) {
2592
+ return t.map((e) => g(e, 700)).find(Boolean) || "";
2593
+ }
2594
+ function g(t, e) {
2595
+ return y(t).slice(0, e);
2596
+ }
2597
+ function _e(t) {
2598
+ return y(t.getAttribute?.("aria-label") || t.getAttribute?.("title") || t.getAttribute?.("alt") || t.textContent);
2599
+ }
2600
+ function y(t) {
2601
+ return String(t ?? "").replace(/<script\b[\s\S]*?<\/script>/giu, " ").replace(/<style\b[\s\S]*?<\/style>/giu, " ").replace(/<[^>]+>/gu, " ").replace(kn, "[redacted]").replace(/\s+/gu, " ").trim();
2602
+ }
2603
+ function b(t) {
2604
+ const e = String(t ?? "").replace(/<script\b[\s\S]*?<\/script>/giu, " ").replace(/<style\b[\s\S]*?<\/style>/giu, " ").replace(/<[^>]+>/gu, " ").replace(/\s+/gu, " ").trim();
2605
+ return !e || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/iu.test(e) || /\b(?:token|session|csrf|secret|password|passwd|jwt|bearer)\s*[:=]\s*[\w.-]+/iu.test(e) ? "" : e.slice(0, 120);
2606
+ }
2607
+ function Hn(t, e, r) {
2608
+ return (Array.isArray(t) ? t : t ? [t] : []).map((n) => b(n).slice(0, r)).filter(Boolean).filter(Jn()).slice(0, e);
2609
+ }
2610
+ function Jn() {
2611
+ const t = /* @__PURE__ */ new Set();
2612
+ return (e) => {
2613
+ const r = b(e).toLocaleLowerCase("tr-TR");
2614
+ return !r || t.has(r) ? !1 : (t.add(r), !0);
2615
+ };
2616
+ }
2617
+ function S(t) {
2618
+ const e = Number(String(t ?? "").replace(",", "."));
2619
+ return Number.isFinite(e) && e > 0 ? e : void 0;
2620
+ }
2621
+ function X(t) {
2622
+ if (!t) return "";
2623
+ try {
2624
+ const e = new URL(t, window.location.href);
2625
+ return /^https?:$/u.test(e.protocol) ? (e.hash = "", Ae(e), e.href) : "";
2626
+ } catch {
2627
+ return "";
2628
+ }
2629
+ }
2630
+ function Zn() {
2631
+ try {
2632
+ const t = new URL(window.location.href);
2633
+ return t.hash = "", Ae(t), `${t.origin}${t.pathname}${t.search}`;
2634
+ } catch {
2635
+ return "";
2636
+ }
2637
+ }
2638
+ function Ae(t) {
2639
+ for (const [e, r] of [...t.searchParams.entries()]) {
2640
+ const n = String(r || "");
2641
+ (_n.test(e) || An.test(n)) && t.searchParams.set(e, "redacted");
2642
+ }
2643
+ return t;
2644
+ }
2645
+ function Wn(t = {}) {
2646
+ return {
2647
+ features: E(t.maxFeatures, A.features, 40),
2648
+ reviews: E(t.maxReviews, A.reviews, 12),
2649
+ qna: E(t.maxQna, A.qna, 12),
2650
+ sellers: E(t.maxSellers, A.sellers, 12),
2651
+ variants: E(t.maxVariants, A.variants, 30),
2652
+ documents: E(t.maxDocuments, A.documents, 12),
2653
+ textBlocks: E(t.maxTextBlocks, A.textBlocks, 16),
2654
+ relatedProducts: E(t.maxRelatedProducts, A.relatedProducts, 20),
2655
+ textChars: E(t.textChars, A.textChars, 420)
2656
+ };
2657
+ }
2658
+ function E(t, e, r) {
2659
+ const n = Number(t);
2660
+ return !Number.isFinite(n) || n <= 0 ? e : Math.min(Math.floor(n), r);
2661
+ }
2662
+ function wt(t) {
2663
+ try {
2664
+ return typeof t == "function" ? t() : null;
2665
+ } catch {
2666
+ return null;
2667
+ }
2668
+ }
2669
+ function z(t) {
2670
+ return Object.fromEntries(Object.entries(t || {}).filter(([, e]) => e != null && e !== "" && (!Array.isArray(e) || e.length)));
2671
+ }
2672
+ var { redactPii: Yo, anonymousRequestText: Qo, anonymizeMessages: Xo } = bn({ patterns: [{
2673
+ pattern: /\b\d{5}\b/gu,
2674
+ replacement: "[postcode]"
2675
+ }, {
2676
+ pattern: /\b(?:adresim|adres|mahalle|sokak|cadde)\b[^,.!?\n]{8,160}/giu,
2677
+ replacement: "[address]"
2678
+ }] });
2679
+ function Gn(t) {
2680
+ return (t?.route?.flow_params && typeof t.route.flow_params == "object" ? t.route.flow_params : null) || (t?.route?.flowParams && typeof t.route.flowParams == "object" ? t.route.flowParams : null) || {};
2681
+ }
2682
+ function ti(t) {
2683
+ return Array.isArray(t) ? t.find((e) => String(e || "").trim()) : void 0;
2684
+ }
2685
+ function ei(t) {
2686
+ const e = Gn(t);
2687
+ return [
2688
+ ...e.sku ? [e.sku] : [],
2689
+ ...Array.isArray(e.sku_list) ? e.sku_list : [],
2690
+ ...Array.isArray(e.skus) ? e.skus : [],
2691
+ ...Array.isArray(e.target_skus) ? e.target_skus : []
2692
+ ].map((r) => String(r || "").trim()).filter(Boolean).filter((r, n, o) => o.indexOf(r) === n);
2693
+ }
2694
+ var Yn = 3e4;
2695
+ function Qn(t, e, r = {}) {
2696
+ const n = r.ttlMs ?? Yn, o = r.clock ?? Date.now, i = /* @__PURE__ */ new Map(), a = /* @__PURE__ */ new Map();
2697
+ return async function(c) {
2698
+ const u = String(e(c) ?? "");
2699
+ if (!u) return t(c);
2700
+ const l = o();
2701
+ Xn(a, l, n);
2702
+ const f = i.get(u);
2703
+ if (f) return f;
2704
+ const d = a.get(u);
2705
+ if (d && l - d.at < n) return to(d.observation, u);
2706
+ const p = (async () => {
2707
+ try {
2708
+ const m = await t(c);
2709
+ return a.set(u, {
2710
+ at: o(),
2711
+ observation: m
2712
+ }), m;
2713
+ } finally {
2714
+ i.delete(u);
2715
+ }
2716
+ })();
2717
+ return i.set(u, p), p;
2718
+ };
2719
+ }
2720
+ function Xn(t, e, r) {
2721
+ for (const [n, o] of t) e - o.at >= r && t.delete(n);
2722
+ }
2723
+ function to(t, e) {
2724
+ return !t || typeof t != "object" ? t : {
2725
+ ...t,
2726
+ deduped: !0,
2727
+ dedupe_key: e
2728
+ };
2729
+ }
2730
+ var eo = 3e4, Se = /* @__PURE__ */ new Set();
2731
+ function ri(t) {
2732
+ const e = () => Qn(async (o) => t(o || {}), (o) => {
2733
+ const i = ro(o), a = Number(o?.quantity || o?.qty || 1) || 1, s = no(o);
2734
+ return i ? `${i}|${a}|${s}` : "";
2735
+ }, { ttlMs: eo });
2736
+ let r = e();
2737
+ const n = async function(i = {}) {
2738
+ return r(i);
2739
+ };
2740
+ return n.__resetForTesting = () => {
2741
+ r = e();
2742
+ }, Se.add(n), n;
2743
+ }
2744
+ function ni() {
2745
+ for (const t of Se) typeof t.__resetForTesting == "function" && t.__resetForTesting();
2746
+ }
2747
+ function ro(t) {
2748
+ const e = t?.cartCode ?? t?.sku ?? t?.productCode ?? t?.product?.sku ?? t?.product?.cart_code;
2749
+ return e == null ? "" : String(e).trim();
2750
+ }
2751
+ function no(t) {
2752
+ const e = t?.variantId ?? t?.variantCode ?? t?.product?.variantId ?? "";
2753
+ return e == null ? "" : String(e).trim();
2754
+ }
2755
+ var oo = 32, xe = /* @__PURE__ */ new Set();
2756
+ function oi(t, e) {
2757
+ const { accountId: r, allowedHostnames: n, productFromPage: o, mergeProduct: i = ao, needsHydration: a = io, fetchOptions: s = { credentials: "include" }, maxConcurrency: c = 4 } = e;
2758
+ if (!r) throw new Error("wrapResolveProductsWithPdpHydration: accountId is required");
2759
+ if (typeof o != "function") throw new Error("wrapResolveProductsWithPdpHydration: productFromPage(doc, url) is required");
2760
+ if (!Array.isArray(n) || !n.length) throw new Error("wrapResolveProductsWithPdpHydration: allowedHostnames must be a non-empty array");
2761
+ const u = /* @__PURE__ */ new Map(), l = uo({
2762
+ productFromPage: o,
2763
+ fetchOptions: s,
2764
+ isAllowed: so(n)
2765
+ }), f = async function(p = {}) {
2766
+ const m = await t(p || {});
2767
+ if (p?.hydrateFromPdp === !1) return m;
2768
+ const h = Array.isArray(m?.products) ? m.products : [];
2769
+ if (!h.length) return m;
2770
+ const T = await lo(h, l, u, c, i, a);
2771
+ return {
2772
+ ...m,
2773
+ products: T
2774
+ };
2775
+ };
2776
+ return f.__resetCacheForTesting = () => u.clear(), f.__cacheSizeForTesting = () => u.size, xe.add(f), f;
2777
+ }
2778
+ function ii() {
2779
+ for (const t of xe) typeof t.__resetCacheForTesting == "function" && t.__resetCacheForTesting();
2780
+ }
2781
+ function io(t) {
2782
+ if (!t || !t.url) return !1;
2783
+ const e = t, r = e.features, n = e.specs, o = e.category_names, i = Array.isArray(r) && r.length > 0, a = !!n && typeof n == "object" && Object.keys(n).length > 0, s = Array.isArray(o) && o.length > 0;
2784
+ return !i && !a && !s;
2785
+ }
2786
+ function ao(t, e) {
2787
+ return t ? e ? {
2788
+ ...t,
2789
+ ...e
2790
+ } : t : e;
2791
+ }
2792
+ function so(t) {
2793
+ const e = t.map((r) => String(r || "").toLowerCase().trim()).filter(Boolean);
2794
+ return (r) => {
2795
+ const n = String(r || "").toLowerCase();
2796
+ if (!n) return !1;
2797
+ for (const o of e)
2798
+ if (n === o || n.endsWith(`.${o}`)) return !0;
2799
+ return !1;
2800
+ };
2801
+ }
2802
+ function co(t, e) {
2803
+ if (!t) return null;
2804
+ try {
2805
+ const r = new URL(String(t));
2806
+ return r.protocol !== "https:" || !e(r.hostname) ? null : r.href;
2807
+ } catch {
2808
+ return null;
2809
+ }
2810
+ }
2811
+ function uo(t) {
2812
+ const { productFromPage: e, fetchOptions: r, isAllowed: n } = t;
2813
+ return async function(i) {
2814
+ const a = co(i?.url, n);
2815
+ if (!a || typeof fetch != "function") return null;
2816
+ let s;
2817
+ try {
2818
+ const u = await fetch(a, r);
2819
+ if (!u?.ok) return null;
2820
+ s = await u.text();
2821
+ } catch {
2822
+ return null;
2823
+ }
2824
+ if (!s || typeof DOMParser > "u") return null;
2825
+ let c;
2826
+ try {
2827
+ c = new DOMParser().parseFromString(s, "text/html");
2828
+ } catch {
2829
+ return null;
2830
+ }
2831
+ if (!c) return null;
2832
+ try {
2833
+ return e(c, a) || null;
2834
+ } catch {
2835
+ return null;
2836
+ }
2837
+ };
2838
+ }
2839
+ async function lo(t, e, r, n, o, i) {
2840
+ const a = new Array(t.length);
2841
+ let s = 0;
2842
+ const c = Math.max(1, Math.min(n, t.length)), u = new Array(c).fill(null).map(() => l());
2843
+ return await Promise.all(u), a;
2844
+ async function l() {
2845
+ for (; ; ) {
2846
+ const d = s++;
2847
+ if (d >= t.length) return;
2848
+ a[d] = await f(t[d]);
2849
+ }
2850
+ }
2851
+ async function f(d) {
2852
+ if (!d || !i(d)) return d;
2853
+ const p = d?.sku == null ? "" : String(d.sku).trim();
2854
+ if (p && r.has(p)) {
2855
+ const h = r.get(p);
2856
+ return h ? o(d, h) : d;
2857
+ }
2858
+ const m = await e(d);
2859
+ return p && (r.set(p, m || null), fo(r)), m ? o(d, m) : d;
2860
+ }
2861
+ }
2862
+ function fo(t) {
2863
+ for (; t.size > oo; ) {
2864
+ const e = t.keys().next().value;
2865
+ if (e === void 0) break;
2866
+ t.delete(e);
2867
+ }
2868
+ }
2869
+ var po = 20;
2870
+ function mo(t, e = {}) {
2871
+ const { context: r, accountConfig: n } = e, o = Array.isArray(t) ? t.filter(Boolean) : [];
2872
+ if (!o.length) return [];
2873
+ const i = String(r?.meta?.locale || n?.locale || n?.defaultLocale || "tr-TR").toLowerCase().startsWith("en"), a = i ? "Compare the first two" : "İlk ikisini karşılaştır", s = i ? "Open product page" : "Ürün sayfasını aç", c = i ? "Tell me the comfort details" : "Konfor özelliklerini anlat", u = i ? "Show similar" : "Benzerlerini göster", l = [];
2874
+ o.length >= 2 && l.push({
2875
+ label: a,
2876
+ action: {
2877
+ type: "getComparisonTable",
2878
+ payload: {
2879
+ skus: o.slice(0, 2).map((d) => d.sku).filter(Boolean),
2880
+ limit: 2
2881
+ }
2882
+ }
2883
+ });
2884
+ const f = o[0]?.sku;
2885
+ return f && !i && (l.push({
2886
+ label: s,
2887
+ action: {
2888
+ type: "openProductPage",
2889
+ payload: {
2890
+ sku: f,
2891
+ url: o[0]?.url
2892
+ }
2893
+ }
2894
+ }), l.push({
2895
+ label: c,
2896
+ action: {
2897
+ type: "productQuestion",
2898
+ payload: { sku_list: [f] }
2899
+ }
2900
+ })), l.push({
2901
+ label: u,
2902
+ action: {
2903
+ type: "findSimilar",
2904
+ payload: { sku: f }
2905
+ }
2906
+ }), l;
2907
+ }
2908
+ function Yt(t, e = po) {
2909
+ const r = [];
2910
+ if (!Array.isArray(t)) return [];
2911
+ for (const a of t) {
2912
+ const s = Array.isArray(a?.observation?.products) ? a.observation.products : [];
2913
+ s.length && r.push([...s]);
2914
+ }
2915
+ if (r.length <= 1) return (r[0] || []).slice(0, e);
2916
+ const n = [], o = /* @__PURE__ */ new Set();
2917
+ let i = 0;
2918
+ for (; n.length < e; ) {
2919
+ let a = !1;
2920
+ for (const s of r) {
2921
+ const c = s[i];
2922
+ if (!c) continue;
2923
+ const u = String(c.sku || c.url || c.name || "");
2924
+ if (u && o.has(u)) {
2925
+ a = !0;
2926
+ continue;
2927
+ }
2928
+ if (u && o.add(u), n.push(c), a = !0, n.length >= e) break;
2929
+ }
2930
+ if (!a) break;
2931
+ i += 1;
2932
+ }
2933
+ return n;
2934
+ }
2935
+ function ai(t) {
2936
+ if (!t?.spec?.elements) return t;
2937
+ const e = t.spec.root;
2938
+ if (!e) return t;
2939
+ const r = t.spec.elements[e];
2940
+ return !r || r.type !== "ProductGrid" ? (typeof console < "u" && console.warn && console.warn("[agentic] withSimilarsAppend: products envelope root is not ProductGrid", r?.type), t) : {
2941
+ ...t,
2942
+ spec: {
2943
+ ...t.spec,
2944
+ elements: {
2945
+ ...t.spec.elements,
2946
+ [e]: {
2947
+ ...r,
2948
+ props: {
2949
+ ...r.props || {},
2950
+ similarsAppend: !0
2951
+ }
2952
+ }
2953
+ }
2954
+ }
2955
+ };
2956
+ }
2957
+ function si(t, e = {}) {
2958
+ const r = e.threshold ?? 0;
2959
+ return !r || r <= 0 || !Array.isArray(t) ? !1 : t.length > r;
2960
+ }
2961
+ function ci(t, e = {}) {
2962
+ const r = Math.max(0, e.retainTail ?? 4);
2963
+ if (!Array.isArray(t) || t.length === 0 || t.length <= r) return null;
2964
+ const n = t.slice(t.length - r), o = t.slice(0, t.length - r);
2965
+ return o.length ? {
2966
+ messagesToSummarize: o,
2967
+ retainedTail: n
2968
+ } : null;
2969
+ }
2970
+ function ui(t, e, r = {}) {
2971
+ const n = String(e || "").trim();
2972
+ if (!n) return t;
2973
+ const o = Math.max(0, r.retainTail ?? 4), i = Array.isArray(t.messages) ? t.messages : [], a = i.slice(Math.max(0, i.length - o));
2974
+ return {
2975
+ ...t,
2976
+ messages: [{
2977
+ role: "assistant",
2978
+ content: n,
2979
+ name: "compaction"
2980
+ }, ...a],
2981
+ panel: {
2982
+ ...t.panel || {},
2983
+ compaction_summary: {
2984
+ summary: n,
2985
+ replacedCount: i.length - a.length,
2986
+ retainedTailCount: a.length,
2987
+ compactedAt: (/* @__PURE__ */ new Date()).toISOString()
2988
+ }
2989
+ }
2990
+ };
2991
+ }
2992
+ function P(t, e) {
2993
+ const r = t?.[e];
2994
+ return Array.isArray(r) ? r : [];
2995
+ }
2996
+ function H(t, e, r = !1) {
2997
+ return [...t].reverse().find((n) => n?.name === e && (!r || n?.observation?.status === "ok"));
2998
+ }
2999
+ function yo(t) {
3000
+ return {
3001
+ kind: "patch",
3002
+ patch: (e, r, n) => {
3003
+ const o = H(P(n.bag, t), "search_catalog"), i = Array.isArray(o?.observation?.products) ? o.observation.products : null;
3004
+ return i?.length ? { panel: {
3005
+ ...e.panel,
3006
+ screen_type: "product_list",
3007
+ list_source: "agent",
3008
+ last_search_products: i,
3009
+ last_search: {
3010
+ query: o.observation.query,
3011
+ source: o.observation.source,
3012
+ count: o.observation.count
3013
+ },
3014
+ screen_sku_list: i.map((a) => a?.sku).filter(Boolean).slice(0, 24)
3015
+ } } : null;
3016
+ }
3017
+ };
3018
+ }
3019
+ function li(t) {
3020
+ const e = t.obsKey || "roundObservations", r = t.gridLimit ?? 20, n = t.similarsFollowupSteps ? t.similarsFollowupSteps() : [];
3021
+ return [
3022
+ yo(e),
3023
+ {
3024
+ kind: "branch",
3025
+ on: ({ bag: o }) => P(o, e).some((i) => Array.isArray(i?.observation?.products) && i.observation.products.length) ? "has_products" : "no_products",
3026
+ cases: {
3027
+ has_products: [{
3028
+ kind: "emit",
3029
+ build: ({ bag: o }) => {
3030
+ const i = Yt(P(o, e), r);
3031
+ return t.uiSpec(t.productsUiSpec(i));
3032
+ }
3033
+ }, {
3034
+ kind: "emit",
3035
+ build: ({ bag: o, context: i, accountConfig: a }) => {
3036
+ const s = Yt(P(o, e), r);
3037
+ return t.uiSpec(t.actionButtonsUiSpec(mo(s, {
3038
+ context: i,
3039
+ accountConfig: a
3040
+ })));
3041
+ }
3042
+ }],
3043
+ no_products: []
3044
+ }
3045
+ },
3046
+ {
3047
+ kind: "branch",
3048
+ on: ({ bag: o }) => H(P(o, e), "compare_products", !0) ? "has_compare" : "no_compare",
3049
+ cases: {
3050
+ has_compare: [{
3051
+ kind: "emit",
3052
+ build: ({ context: o, bag: i }) => {
3053
+ const a = H(P(i, e), "compare_products"), s = a?.observation || {}, c = a?.arguments || {}, u = Array.isArray(c.target_skus) ? c.target_skus.map(String) : [], l = Array.isArray(o?.panel?.last_search_products) ? o.panel.last_search_products : [], f = u.length ? u.map((d) => l.find((p) => String(p?.sku) === d)).filter(Boolean) : l.slice(0, 4);
3054
+ return t.uiSpec(t.comparisonUiSpec({
3055
+ products: f,
3056
+ comparison_table: s.comparison_table,
3057
+ key_differences: s.key_differences,
3058
+ recommended_choice_sku: s.recommendation?.sku,
3059
+ recommended_choice: s.recommendation?.reason
3060
+ }));
3061
+ }
3062
+ }],
3063
+ no_compare: []
3064
+ }
3065
+ },
3066
+ {
3067
+ kind: "branch",
3068
+ on: ({ bag: o }) => H(P(o, e), "get_product_details", !0) ? "has_details" : "no_details",
3069
+ cases: {
3070
+ has_details: [{
3071
+ kind: "emit",
3072
+ build: ({ context: o, bag: i }) => {
3073
+ const a = H(P(i, e), "get_product_details"), s = a?.observation?.surface || {}, c = a?.arguments || {}, u = Array.isArray(o?.panel?.last_search_products) ? o.panel.last_search_products : [], l = c.sku ? u.find((d) => String(d?.sku) === String(c.sku)) : null, f = s.product || l || s || {};
3074
+ return t.uiSpec(t.productDetailsUiSpec(f));
3075
+ }
3076
+ }, ...n],
3077
+ no_details: []
3078
+ }
3079
+ },
3080
+ ...go({
3081
+ ...t,
3082
+ obsKey: e
3083
+ })
3084
+ ];
3085
+ }
3086
+ function go(t) {
3087
+ const e = t.obsKey || "roundObservations", r = t.pdpFollowupProduct;
3088
+ return r ? [{
3089
+ kind: "branch",
3090
+ on: ({ bag: n, context: o }) => n.pdpFollowupRendered || P(n, e).some((i) => {
3091
+ const a = i?.name;
3092
+ return a === "search_catalog" || a === "compare_products" || a === "get_product_details" || Array.isArray(i?.observation?.products) && i.observation.products.length;
3093
+ }) ? "skip" : r(n, o) ? "render" : "skip",
3094
+ cases: {
3095
+ render: [
3096
+ {
3097
+ kind: "emit",
3098
+ build: ({ bag: n, context: o }) => t.uiSpec(t.productDetailsUiSpec(r(n, o)))
3099
+ },
3100
+ {
3101
+ kind: "patch",
3102
+ patch: (n, o, i) => (i.bag.pdpFollowupRendered = !0, null)
3103
+ },
3104
+ ...t.similarsFollowupSteps ? t.similarsFollowupSteps() : []
3105
+ ],
3106
+ skip: []
3107
+ }
3108
+ }] : [];
3109
+ }
3110
+ export {
3111
+ Io as $,
3112
+ Do as A,
3113
+ We as At,
3114
+ fe as B,
3115
+ Wo as C,
3116
+ ko as Ct,
3117
+ Ho as D,
3118
+ wo as Dt,
3119
+ Jo as E,
3120
+ Ge as Et,
3121
+ qo as F,
3122
+ $o as G,
3123
+ cn as H,
3124
+ pn as I,
3125
+ on as J,
3126
+ Bo as K,
3127
+ Fo as L,
3128
+ zo as M,
3129
+ Pe as Mt,
3130
+ hn as N,
3131
+ Ko as O,
3132
+ Ne as Ot,
3133
+ gn as P,
3134
+ Oo as Q,
3135
+ un as R,
3136
+ Sn as S,
3137
+ lr as St,
3138
+ bn as T,
3139
+ I as Tt,
3140
+ Lo as U,
3141
+ pe as V,
3142
+ No as W,
3143
+ le as X,
3144
+ Mo as Y,
3145
+ jo as Z,
3146
+ Xo as _,
3147
+ x as _t,
3148
+ si as a,
3149
+ Po as at,
3150
+ xn as b,
3151
+ yr as bt,
3152
+ ai as c,
3153
+ Co as ct,
3154
+ ni as d,
3155
+ re as dt,
3156
+ Er as et,
3157
+ ri as f,
3158
+ Ar as ft,
3159
+ ei as g,
3160
+ Ao as gt,
3161
+ Gn as h,
3162
+ xo as ht,
3163
+ ci as i,
3164
+ ie as it,
3165
+ Uo as j,
3166
+ Ee as jt,
3167
+ Vo as k,
3168
+ bo as kt,
3169
+ ii as l,
3170
+ Sr as lt,
3171
+ ti as m,
3172
+ _r as mt,
3173
+ li as n,
3174
+ Eo as nt,
3175
+ Yt as o,
3176
+ Et as ot,
3177
+ Qn as p,
3178
+ So as pt,
3179
+ Ro as q,
3180
+ ui as r,
3181
+ To as rt,
3182
+ mo as s,
3183
+ Pt as st,
3184
+ go as t,
3185
+ oe as tt,
3186
+ oi as u,
3187
+ vo as ut,
3188
+ Qo as v,
3189
+ ee as vt,
3190
+ Go as w,
3191
+ Xt as wt,
3192
+ Zo as x,
3193
+ fr as xt,
3194
+ Yo as y,
3195
+ _o as yt,
3196
+ de as z
3197
+ };