@commerce-blocks/sdk 2.0.0-alpha.1 → 2.0.0-alpha.3

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 (4) hide show
  1. package/README.md +313 -758
  2. package/dist/index.d.ts +328 -636
  3. package/dist/index.js +1176 -1946
  4. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,163 +1,145 @@
1
- import { signal as L, computed as N } from "@preact/signals-core";
2
- import { batch as wn, computed as On, effect as Cn, signal as kn } from "@preact/signals-core";
3
- const Qe = "2.0.0-alpha.1", Ke = {
4
- version: Qe
5
- }, ze = "2026-01", Xe = "https://app.uselayers.com/api/storefront/v1", We = 1e3, Ce = 1e3, ke = 100, Je = 300 * We, pe = Ke.version, ae = 250, B = 20, G = 250, se = 250, ie = 250, ce = 1, le = 1, Y = 1, Z = 24, ue = 1, de = 1, fe = 100, Ye = 20, Ze = 50, et = 300, tt = 50, De = "USD", nt = "en-US", rt = 1e3, Re = /* @__PURE__ */ new Map();
6
- function Ne(e, t) {
7
- const n = `${e}:${t}`;
8
- let o = Re.get(n);
9
- return o || (o = new Intl.NumberFormat(nt, {
1
+ import { effect as re, signal as P, computed as O } from "@preact/signals-core";
2
+ import { batch as Wt, computed as Zt, effect as en, signal as tn } from "@preact/signals-core";
3
+ const Se = "2.0.0-alpha.3", Re = {
4
+ version: Se
5
+ }, Te = "https://app.uselayers.com/api/storefront/v1", ke = 1e3, Oe = 100, Ne = 300 * ke, oe = Re.version, K = 1, J = 24, Z = 1, ee = 1, te = 100, Ce = 20, Le = 50, Pe = 300, De = 50, ve = "USD", Me = "en-US", qe = 1e3, pe = /* @__PURE__ */ new Map();
6
+ function _e(e, t) {
7
+ const r = `${e}:${t}`;
8
+ let n = pe.get(r);
9
+ return n || (n = new Intl.NumberFormat(Me, {
10
10
  style: "currency",
11
11
  currency: t
12
- }).format(e), Re.set(n, o)), o;
12
+ }).format(e), pe.set(r, n)), n;
13
13
  }
14
- function D(e) {
14
+ function L(e) {
15
15
  return { data: e };
16
16
  }
17
- function v(e) {
17
+ function b(e) {
18
18
  return { error: e };
19
19
  }
20
- function ee() {
21
- return (/* @__PURE__ */ new Date()).toISOString();
22
- }
23
- function ot(e, t, n, o) {
24
- return {
25
- status: e,
26
- statusText: t,
27
- headers: n ? st(n) : void 0,
28
- body: o ? it(o) : void 0
29
- };
30
- }
31
- const at = ["authorization", "x-shopify-access-token", "cookie", "set-cookie"];
32
- function st(e) {
33
- const t = {};
34
- for (const [n, o] of Object.entries(e))
35
- t[n] = at.includes(n.toLowerCase()) ? "[REDACTED]" : o;
36
- return t;
37
- }
38
- function it(e, t = 1e3) {
39
- return e.length > t ? e.slice(0, t) + "...[truncated]" : e;
40
- }
41
- const ct = ["TIMEOUT", "CONNECTION_FAILED", "DNS_FAILED"];
42
- function J(e) {
43
- const t = ct.includes(e.code);
20
+ const Ue = ["TIMEOUT", "CONNECTION_FAILED", "DNS_FAILED"];
21
+ function ae(e) {
22
+ const t = Ue.includes(e.code);
44
23
  return {
45
24
  _tag: "NetworkError",
46
25
  code: e.code,
47
26
  message: e.message,
48
- timestamp: ee(),
49
- request: e.request,
50
27
  cause: e.cause,
51
28
  retryable: t,
52
29
  retryAfterMs: t ? 1e3 : void 0
53
30
  };
54
31
  }
55
- function lt(e) {
32
+ function Fe(e) {
56
33
  if (!e) return;
57
34
  const t = e["retry-after"] ?? e["Retry-After"];
58
35
  if (!t) return;
59
- const n = t.trim();
60
- if (/^\d+$/.test(n))
61
- return Number(n) * 1e3;
62
- const o = new Date(t);
63
- if (!isNaN(o.getTime()))
64
- return Math.max(0, o.getTime() - Date.now());
65
- }
66
- function $(e) {
67
- const t = e.code === "RATE_LIMITED" || e.code === "SERVICE_UNAVAILABLE" || e.status !== void 0 && e.status >= 500, n = e.retryAfterMs ?? lt(e.response?.headers) ?? (t ? 1e3 : void 0);
36
+ const r = t.trim();
37
+ if (/^\d+$/.test(r))
38
+ return Number(r) * 1e3;
39
+ const n = new Date(t);
40
+ if (!isNaN(n.getTime()))
41
+ return Math.max(0, n.getTime() - Date.now());
42
+ }
43
+ function be(e) {
44
+ const t = e.code === "RATE_LIMITED" || e.code === "SERVICE_UNAVAILABLE" || e.code === "NOT_READY" || e.status !== void 0 && e.status >= 500, r = e.retryAfterMs ?? Fe(e.responseHeaders) ?? (t ? 1e3 : void 0);
68
45
  return {
69
46
  _tag: "ApiError",
70
47
  code: e.code,
71
48
  source: e.source,
72
49
  message: e.message,
73
- timestamp: ee(),
74
50
  status: e.status,
75
51
  retryable: t,
76
- retryAfterMs: n,
77
- request: e.request,
78
- response: e.response,
79
- cause: e.cause,
80
- details: e.details
52
+ retryAfterMs: r,
53
+ cause: e.cause
81
54
  };
82
55
  }
83
- function q(e) {
56
+ function x(e) {
84
57
  return {
85
58
  _tag: "ValidationError",
86
59
  code: "VALIDATION_FAILED",
87
60
  message: e.fields.length === 1 ? `Validation failed: ${e.fields[0].message}` : `Validation failed with ${e.fields.length} errors`,
88
- timestamp: ee(),
89
61
  operation: e.operation,
90
62
  fields: e.fields,
91
63
  input: e.input
92
64
  };
93
65
  }
94
- function k(e, t, n, o) {
66
+ function F(e, t, r, n) {
95
67
  return {
96
- path: e.split("."),
97
- field: e.split(".").pop() ?? e,
68
+ field: e,
98
69
  code: t,
99
- message: n,
100
- ...o
70
+ message: r,
71
+ ...n
101
72
  };
102
73
  }
103
- function U(e) {
74
+ function Q(e) {
104
75
  return {
105
76
  _tag: "ConfigError",
106
77
  code: e.code,
107
78
  message: e.message,
108
- timestamp: ee(),
109
79
  field: e.field,
110
80
  value: e.value,
111
81
  expected: e.expected
112
82
  };
113
83
  }
114
- const ut = ["NetworkError", "ApiError", "ValidationError", "ConfigError"];
115
- function un(e) {
116
- return typeof e == "object" && e !== null && ut.includes(e._tag ?? "");
84
+ const $e = /* @__PURE__ */ new Set(["NetworkError", "ApiError", "ValidationError", "ConfigError"]);
85
+ function Ct(e) {
86
+ return typeof e == "object" && e !== null && $e.has(e._tag ?? "");
117
87
  }
118
- function dn(e) {
88
+ function Ve(e) {
119
89
  return "retryable" in e ? e.retryable : !1;
120
90
  }
121
- function dt(e, t) {
122
- const { status: n } = e, o = n === 401 ? "UNAUTHORIZED" : n === 403 ? "FORBIDDEN" : n === 404 ? "NOT_FOUND" : n === 429 ? "RATE_LIMITED" : n >= 500 ? "SERVICE_UNAVAILABLE" : "UNKNOWN";
123
- return $({
124
- code: o,
91
+ function Be(e) {
92
+ if ("retryAfterMs" in e) return e.retryAfterMs;
93
+ }
94
+ const xe = {
95
+ 401: "UNAUTHORIZED",
96
+ 403: "FORBIDDEN",
97
+ 404: "NOT_FOUND",
98
+ 425: "NOT_READY",
99
+ 429: "RATE_LIMITED"
100
+ };
101
+ function Ge(e, t) {
102
+ const { status: r } = e, n = xe[r] ?? (r >= 500 ? "SERVICE_UNAVAILABLE" : "UNKNOWN");
103
+ let a;
104
+ try {
105
+ const o = JSON.parse(t);
106
+ typeof o.retry_after_ms == "number" && (a = o.retry_after_ms);
107
+ } catch {
108
+ }
109
+ return be({
110
+ code: n,
125
111
  source: "layers",
126
- message: t || `HTTP ${n}`,
127
- status: n,
128
- response: ot(
129
- n,
130
- e.statusText,
131
- Object.fromEntries(e.headers.entries()),
132
- t
133
- )
112
+ message: t || `HTTP ${r}`,
113
+ status: r,
114
+ retryAfterMs: a,
115
+ responseHeaders: Object.fromEntries(e.headers.entries())
134
116
  });
135
117
  }
136
- function ve(e) {
118
+ function He(e) {
137
119
  if (e instanceof Error && (e.name === "AbortError" || e.name === "TimeoutError")) {
138
120
  const t = e.name === "TimeoutError" || e.message.includes("timeout");
139
- return J({
121
+ return ae({
140
122
  code: t ? "TIMEOUT" : "ABORTED",
141
123
  message: t ? "Request timed out" : "Request was aborted",
142
124
  cause: e
143
125
  });
144
126
  }
145
- return J({
127
+ return ae({
146
128
  code: "CONNECTION_FAILED",
147
129
  message: e instanceof Error ? e.message : "Network request failed",
148
130
  cause: e
149
131
  });
150
132
  }
151
- async function ye(e) {
133
+ async function je(e) {
152
134
  if (!e.ok) {
153
135
  const t = await e.text().catch(() => "");
154
- return v(dt(e, t));
136
+ return b(Ge(e, t));
155
137
  }
156
138
  try {
157
- return D(await e.json());
139
+ return L(await e.json());
158
140
  } catch (t) {
159
- return v(
160
- $({
141
+ return b(
142
+ be({
161
143
  code: "PARSE_ERROR",
162
144
  source: "layers",
163
145
  message: "Invalid JSON response",
@@ -166,979 +148,250 @@ async function ye(e) {
166
148
  );
167
149
  }
168
150
  }
169
- function Ie({
151
+ function ie({
170
152
  token: e,
171
153
  json: t = !0
172
154
  }) {
173
- const n = {
155
+ const r = {
174
156
  Accept: "application/json",
175
157
  "X-Storefront-Access-Token": e,
176
- "X-SDK-Client": `commerce-blocks-sdk/${pe}`
158
+ "X-SDK-Client": `commerce-blocks-sdk/${oe}`
177
159
  };
178
- return t && (n["Content-Type"] = "application/json"), n;
160
+ return t && (r["Content-Type"] = "application/json"), r;
179
161
  }
180
- function Ee({ config: e, endpoint: t }) {
181
- const { layersBaseUrl: n = Xe } = e;
182
- return `${n}${t}`;
162
+ function ce({ config: e, endpoint: t }) {
163
+ const { baseUrl: r = Te } = e;
164
+ return `${r}${t}`;
183
165
  }
184
- async function x(e) {
185
- const t = e.config.fetch ?? fetch;
166
+ function ue(e) {
167
+ return e.fetch ?? ((t, r) => fetch(t, r));
168
+ }
169
+ async function le(e, t, r) {
186
170
  try {
187
- const n = await t(Ee({ config: e.config, endpoint: e.endpoint }), {
188
- method: "POST",
189
- headers: Ie({ token: e.config.layersPublicToken }),
190
- body: JSON.stringify(e.body),
191
- signal: e.signal
192
- });
193
- return ye(n);
171
+ const n = await e(t, r);
172
+ return je(n);
194
173
  } catch (n) {
195
- return v(ve(n));
174
+ return b(He(n));
196
175
  }
197
176
  }
198
- async function ft(e) {
177
+ async function B(e) {
178
+ return le(ue(e.config), ce(e), {
179
+ method: "POST",
180
+ headers: ie({ token: e.config.token }),
181
+ body: JSON.stringify(e.body),
182
+ signal: e.signal
183
+ });
184
+ }
185
+ async function Qe(e) {
199
186
  const t = new URLSearchParams();
200
- for (const [a, i] of Object.entries(e.params))
201
- i != null && t.append(a, typeof i == "object" ? JSON.stringify(i) : String(i));
202
- const n = t.toString(), o = n ? `${e.endpoint}?${n}` : e.endpoint, r = e.config.fetch ?? fetch;
203
- try {
204
- const a = await r(Ee({ config: e.config, endpoint: o }), {
187
+ for (const [a, o] of Object.entries(e.params))
188
+ o != null && t.append(a, typeof o == "object" ? JSON.stringify(o) : String(o));
189
+ const r = t.toString(), n = r ? `${e.endpoint}?${r}` : e.endpoint;
190
+ return le(
191
+ ue(e.config),
192
+ ce({ config: e.config, endpoint: n }),
193
+ {
205
194
  method: "GET",
206
- headers: Ie({ token: e.config.layersPublicToken }),
195
+ headers: ie({ token: e.config.token }),
207
196
  signal: e.signal
208
- });
209
- return ye(a);
210
- } catch (a) {
211
- return v(ve(a));
212
- }
197
+ }
198
+ );
213
199
  }
214
- async function gt(e) {
215
- const t = e.config.fetch ?? fetch;
216
- try {
217
- const n = await t(Ee({ config: e.config, endpoint: e.endpoint }), {
218
- method: "POST",
219
- headers: Ie({ token: e.config.layersPublicToken, json: !1 }),
220
- body: e.formData,
221
- signal: e.signal
222
- });
223
- return ye(n);
224
- } catch (n) {
225
- return v(ve(n));
226
- }
200
+ async function Ke(e) {
201
+ return le(ue(e.config), ce(e), {
202
+ method: "POST",
203
+ headers: ie({ token: e.config.token, json: !1 }),
204
+ body: e.formData,
205
+ signal: e.signal
206
+ });
207
+ }
208
+ function U(e, t, r) {
209
+ return r ? null : x({
210
+ operation: e,
211
+ fields: [F(t, "REQUIRED_FIELD", `${t} is required`)]
212
+ });
227
213
  }
228
214
  function j(e, t) {
229
215
  if (!e) return null;
230
- const n = [];
231
- return e.page !== void 0 && e.page < ue && n.push(
232
- k("pagination.page", "OUT_OF_RANGE", `page must be >= ${ue}`, {
216
+ const r = [];
217
+ return e.page !== void 0 && e.page < Z && r.push(
218
+ F("page", "OUT_OF_RANGE", `page must be >= ${Z}`, {
233
219
  value: e.page,
234
- constraints: { min: ue }
220
+ constraints: { min: Z }
235
221
  })
236
- ), e.limit !== void 0 && (e.limit < de || e.limit > fe) && n.push(
237
- k(
238
- "pagination.limit",
222
+ ), e.limit !== void 0 && (e.limit < ee || e.limit > te) && r.push(
223
+ F(
224
+ "limit",
239
225
  "OUT_OF_RANGE",
240
- `limit must be between ${de} and ${fe}`,
226
+ `limit must be between ${ee} and ${te}`,
241
227
  {
242
228
  value: e.limit,
243
- constraints: { min: de, max: fe }
229
+ constraints: { min: ee, max: te }
244
230
  }
245
231
  )
246
- ), n.length > 0 ? q({ operation: t, fields: n }) : null;
232
+ ), r.length > 0 ? x({ operation: t, fields: r }) : null;
247
233
  }
248
- const mt = [
234
+ const Je = [
249
235
  "title",
250
236
  "handle",
251
- "body_html",
252
- "vendor",
253
- "product_type",
254
237
  "available",
255
- "is_gift_card",
256
- "tags",
257
238
  "images",
258
- "price_range",
259
239
  "options",
260
240
  "options_v2",
261
- "first_or_matched_variant",
262
- "featured_media",
263
241
  "variants",
242
+ "first_or_matched_variant",
243
+ "price_range",
244
+ "vendor",
245
+ "product_type",
246
+ "tags",
264
247
  "metafields",
265
248
  "calculated",
266
- "named_tags",
249
+ "featured_media",
267
250
  "category",
268
- "created_at",
269
- "published_at",
270
- "updated_at",
271
251
  "combined_listing_parent_product_id",
272
- "combined_listing_role",
273
- "has_variants_that_require_components",
274
- "original_options"
252
+ "combined_listing_role"
275
253
  ];
276
- function pt(e) {
277
- if (!e.layersPublicToken)
278
- return v(
279
- U({
254
+ function Ye(e) {
255
+ if (!e.token)
256
+ return b(
257
+ Q({
280
258
  code: "MISSING_CONFIG",
281
- message: "layersPublicToken is required",
282
- field: "layersPublicToken",
259
+ message: "token is required",
260
+ field: "token",
283
261
  expected: "non-empty string"
284
262
  })
285
263
  );
286
264
  if (!e.sorts || e.sorts.length === 0)
287
- return v(
288
- U({
265
+ return b(
266
+ Q({
289
267
  code: "MISSING_CONFIG",
290
268
  message: "At least one sort option is required",
291
269
  field: "sorts",
292
270
  expected: "non-empty array of Sort"
293
271
  })
294
272
  );
295
- function t(r) {
296
- return [.../* @__PURE__ */ new Set([...mt, ...e.attributes ?? [], ...r ?? []])];
273
+ function t(o) {
274
+ return [.../* @__PURE__ */ new Set([...Je, ...e.attributes ?? [], ...o ?? []])];
275
+ }
276
+ function r({
277
+ attributes: o,
278
+ transformBody: s,
279
+ rest: u,
280
+ includeFacets: c = !0
281
+ }) {
282
+ let l = {
283
+ attributes: t(o),
284
+ ...u
285
+ };
286
+ return c && (l.facets = e.facets.map((i) => i.code), l.retrieveFacetCount = !0, l.includeFacetRanges = !0), s && (l = s(l)), l;
297
287
  }
298
288
  const n = {
299
- layersPublicToken: e.layersPublicToken,
300
- layersBaseUrl: e.layersBaseUrl,
289
+ token: e.token,
290
+ baseUrl: e.baseUrl,
301
291
  fetch: e.fetch
302
292
  };
303
- return D({
304
- browse: async (r, a) => {
305
- if (!r.collectionHandle)
306
- return v(
307
- q({
308
- operation: "browse",
309
- fields: [
310
- k("collectionHandle", "REQUIRED_FIELD", "collectionHandle is required")
311
- ]
312
- })
313
- );
314
- if (!r.sort_order_code)
315
- return v(
316
- q({
317
- operation: "browse",
318
- fields: [
319
- k("sort_order_code", "REQUIRED_FIELD", "sort_order_code is required")
320
- ]
321
- })
322
- );
323
- const i = j(r.pagination, "browse");
324
- if (i) return v(i);
325
- const { collectionHandle: s, attributes: l, transformBody: c, ...g } = r;
326
- let d = {
327
- facets: e.facets.map((p) => p.code),
328
- attributes: t(l),
329
- retrieveFacetCount: !0,
330
- includeFacetRanges: !0,
331
- ...g
332
- };
333
- return c && (d = c(d)), x({
293
+ return L({
294
+ browse: async (o, s) => {
295
+ const u = U("browse", "collectionHandle", o.collectionHandle);
296
+ if (u) return b(u);
297
+ const c = U("browse", "sort_order_code", o.sort_order_code);
298
+ if (c) return b(c);
299
+ const l = j(o.pagination, "browse");
300
+ if (l) return b(l);
301
+ const { collectionHandle: i, attributes: f, transformBody: g, ...p } = o;
302
+ return B({
334
303
  config: n,
335
- endpoint: `/browse/${s}`,
336
- body: d,
337
- signal: a
304
+ endpoint: `/browse/${i}`,
305
+ body: r({ attributes: f, transformBody: g, rest: p }),
306
+ signal: s
338
307
  });
339
308
  },
340
- predictiveSearch: async (r, a) => r ? ft({
341
- config: n,
342
- endpoint: "/search/complete",
343
- params: { query: r },
344
- signal: a
345
- }) : v(
346
- q({
347
- operation: "predictiveSearch",
348
- fields: [k("query", "REQUIRED_FIELD", "query is required")]
349
- })
350
- ),
351
- prepareSearch: async (r, a) => {
352
- if (!r.query)
353
- return v(
354
- q({
355
- operation: "prepareSearch",
356
- fields: [k("query", "REQUIRED_FIELD", "query is required")]
357
- })
358
- );
359
- const { query: i, transformBody: s, ...l } = r;
360
- let c = { ...l };
361
- return s && (c = s(c)), x({
309
+ predictiveSearch: async (o, s) => {
310
+ const u = U("predictiveSearch", "query", o);
311
+ return u ? b(u) : Qe({
362
312
  config: n,
363
- endpoint: `/search/${encodeURIComponent(i)}/prepare`,
364
- body: c,
365
- signal: a
313
+ endpoint: "/search/complete",
314
+ params: { query: o },
315
+ signal: s
366
316
  });
367
317
  },
368
- search: async (r, a) => {
369
- if (!r.query)
370
- return v(
371
- q({
372
- operation: "search",
373
- fields: [k("query", "REQUIRED_FIELD", "query is required")]
374
- })
375
- );
376
- const i = j(r.pagination, "search");
377
- if (i) return v(i);
378
- const { query: s, attributes: l, transformBody: c, ...g } = r;
379
- let d = {
380
- facets: e.facets.map((p) => p.code),
381
- attributes: t(l),
382
- retrieveFacetCount: !0,
383
- includeFacetRanges: !0,
384
- ...g
385
- };
386
- return c && (d = c(d)), x({
318
+ prepareSearch: async (o, s) => {
319
+ const u = U("prepareSearch", "query", o.query);
320
+ if (u) return b(u);
321
+ const { query: c, transformBody: l, ...i } = o;
322
+ let f = { ...i };
323
+ return l && (f = l(f)), B({
387
324
  config: n,
388
- endpoint: `/search/${encodeURIComponent(s)}/execute`,
389
- body: d,
390
- signal: a
325
+ endpoint: `/search/${encodeURIComponent(c)}/prepare`,
326
+ body: f,
327
+ signal: s
328
+ });
329
+ },
330
+ search: async (o, s) => {
331
+ const u = U("search", "query", o.query);
332
+ if (u) return b(u);
333
+ const c = j(o.pagination, "search");
334
+ if (c) return b(c);
335
+ const { query: l, attributes: i, transformBody: f, ...g } = o;
336
+ return B({
337
+ config: n,
338
+ endpoint: `/search/${encodeURIComponent(l)}/execute`,
339
+ body: r({ attributes: i, transformBody: f, rest: g }),
340
+ signal: s
391
341
  });
392
342
  },
393
- imageSearch: async (r, a) => {
394
- if (!r.image_data && !r.image_id)
395
- return v(
396
- q({
343
+ imageSearch: async (o, s) => {
344
+ if (!o.image_data && !o.image_id)
345
+ return b(
346
+ x({
397
347
  operation: "imageSearch",
398
348
  fields: [
399
- k("image_data", "REQUIRED_FIELD", "image_data or image_id is required")
349
+ F("image_data", "REQUIRED_FIELD", "image_data or image_id is required")
400
350
  ]
401
351
  })
402
352
  );
403
- const i = j(r.pagination, "imageSearch");
404
- if (i) return v(i);
405
- const { attributes: s, transformBody: l, ...c } = r;
406
- let g = {
407
- attributes: t(s),
408
- ...c
409
- };
410
- return l && (g = l(g)), x({
353
+ const u = j(o.pagination, "imageSearch");
354
+ if (u) return b(u);
355
+ const { attributes: c, transformBody: l, ...i } = o;
356
+ return B({
411
357
  config: n,
412
358
  endpoint: "/search/image",
413
- body: g,
414
- signal: a
359
+ body: r({ attributes: c, transformBody: l, rest: i, includeFacets: !1 }),
360
+ signal: s
415
361
  });
416
362
  },
417
- uploadImage: async (r, a) => {
418
- const i = new FormData();
419
- return i.append("image", r), gt({
363
+ uploadImage: async (o, s) => {
364
+ const u = new FormData();
365
+ return u.append("image", o), Ke({
420
366
  config: n,
421
367
  endpoint: "/images/upload",
422
- formData: i,
423
- signal: a
424
- });
425
- },
426
- blocks: async (r, a) => {
427
- if (!r.blockId)
428
- return v(
429
- q({
430
- operation: "block",
431
- fields: [k("blockId", "REQUIRED_FIELD", "blockId is required")]
432
- })
433
- );
434
- const i = j(r.pagination, "block");
435
- if (i) return v(i);
436
- const { blockId: s, attributes: l, transformBody: c, ...g } = r;
437
- let d = {
438
- facets: e.facets.map((p) => p.code),
439
- attributes: t(l),
440
- retrieveFacetCount: !0,
441
- includeFacetRanges: !0,
442
- ...g
443
- };
444
- return c && (d = c(d)), x({
445
- config: n,
446
- endpoint: `/blocks/${s}/products`,
447
- body: d,
448
- signal: a
368
+ formData: u,
369
+ signal: s
449
370
  });
450
371
  },
451
- similarProducts: async (r, a) => {
452
- if (!r.productId)
453
- return v(
454
- q({
455
- operation: "similarProducts",
456
- fields: [k("productId", "REQUIRED_FIELD", "productId is required")]
457
- })
458
- );
459
- const i = j(r.pagination, "similarProducts");
460
- if (i) return v(i);
461
- const { productId: s, attributes: l, transformBody: c, ...g } = r;
462
- let d = {
463
- attributes: t(l),
464
- ...g
465
- };
466
- return c && (d = c(d)), x({
372
+ blocks: async (o, s) => {
373
+ const u = U("block", "blockId", o.blockId);
374
+ if (u) return b(u);
375
+ const c = j(o.pagination, "block");
376
+ if (c) return b(c);
377
+ const { blockId: l, attributes: i, transformBody: f, ...g } = o;
378
+ return B({
467
379
  config: n,
468
- endpoint: `/search/product/${s}`,
469
- body: d,
470
- signal: a
471
- });
472
- }
473
- });
474
- }
475
- const te = `
476
- fragment SeoFields on SEO {
477
- title
478
- description
479
- }
480
- `, qe = `
481
- fragment FilterValueFields on FilterValue {
482
- id
483
- label
484
- count
485
- input
486
- }
487
- `, $e = `
488
- fragment FilterFields on Filter {
489
- id
490
- label
491
- type
492
- values { ...FilterValueFields }
493
- }
494
- `, ne = `
495
- fragment ImageFields on Image {
496
- url
497
- altText
498
- width
499
- height
500
- }
501
- `, be = `
502
- fragment MoneyFields on MoneyV2 {
503
- amount
504
- currencyCode
505
- }
506
- `, Fe = `
507
- fragment SelectedOptionFields on SelectedOption {
508
- name
509
- value
510
- }
511
- `, Se = `
512
- fragment PriceRangeFields on ProductPriceRange {
513
- minVariantPrice { ...MoneyFields }
514
- maxVariantPrice { ...MoneyFields }
515
- }
516
- `, Me = `
517
- fragment ProductOptionFields on ProductOption {
518
- id
519
- name
520
- optionValues {
521
- id
522
- name
523
- swatch {
524
- color
525
- image {
526
- previewImage { url }
527
- }
528
- }
529
- }
530
- }
531
- `, z = `
532
- fragment MetafieldFields on Metafield {
533
- namespace
534
- key
535
- value
536
- type
537
- }
538
- `;
539
- function Pe(e) {
540
- return `
541
- fragment VariantFields on ProductVariant {
542
- id
543
- title
544
- availableForSale
545
- currentlyNotInStock
546
- sku
547
- price { ...MoneyFields }
548
- compareAtPrice { ...MoneyFields }
549
- selectedOptions { ...SelectedOptionFields }
550
- image { ...ImageFields }
551
- ${e ? "metafields(identifiers: $variantMetafields) { ...MetafieldFields }" : ""}
552
- }
553
- `;
554
- }
555
- function Ae(e) {
556
- const { maxImages: t, maxVariants: n, includeProductMetafields: o } = e;
557
- return `
558
- fragment ProductFields on Product {
559
- id
560
- title
561
- handle
562
- description
563
- descriptionHtml
564
- vendor
565
- productType
566
- tags
567
- availableForSale
568
- isGiftCard
569
- featuredImage { ...ImageFields }
570
- images(first: ${t}) { nodes { ...ImageFields } }
571
- priceRange { ...PriceRangeFields }
572
- compareAtPriceRange { ...PriceRangeFields }
573
- options { ...ProductOptionFields }
574
- variants(first: ${n}) { nodes { ...VariantFields } }
575
- selectedOrFirstAvailableVariant { ...VariantFields }
576
- ${o ? "metafields(identifiers: $productMetafields) { ...MetafieldFields }" : ""}
577
- }
578
- `;
579
- }
580
- function Le(e) {
581
- return `
582
- fragment CollectionFields on Collection {
583
- id
584
- handle
585
- title
586
- description
587
- descriptionHtml
588
- image { ...ImageFields }
589
- seo { ...SeoFields }
590
- updatedAt
591
- ${e ? "metafields(identifiers: $collectionMetafields) { ...MetafieldFields }" : ""}
592
- }
593
- `;
594
- }
595
- function Ve(e) {
596
- return `
597
- fragment PageFields on Page {
598
- id
599
- handle
600
- title
601
- body
602
- bodySummary
603
- seo { ...SeoFields }
604
- createdAt
605
- updatedAt
606
- onlineStoreUrl
607
- ${e ? "metafields(identifiers: $pageMetafields) { ...MetafieldFields }" : ""}
608
- }
609
- `;
610
- }
611
- function ht(e) {
612
- const { includeProductMetafields: t, includeVariantMetafields: n } = e;
613
- return [
614
- ne,
615
- be,
616
- Fe,
617
- Se,
618
- Me,
619
- t || n ? z : "",
620
- Pe(n),
621
- Ae(e)
622
- ].join(`
623
- `);
624
- }
625
- function _t(e = {}) {
626
- const {
627
- maxImages: t = B,
628
- maxVariants: n = G,
629
- productMetafields: o = [],
630
- variantMetafields: r = []
631
- } = e, a = o.length > 0, i = r.length > 0, s = ["$ids: [ID!]!"];
632
- return a && s.push("$productMetafields: [HasMetafieldsIdentifier!]!"), i && s.push("$variantMetafields: [HasMetafieldsIdentifier!]!"), `
633
- ${ht({
634
- maxImages: t,
635
- maxVariants: n,
636
- includeProductMetafields: a,
637
- includeVariantMetafields: i
638
- })}
639
-
640
- query ProductsByIds(${s.join(", ")}) {
641
- nodes(ids: $ids) {
642
- ... on Product {
643
- ...ProductFields
644
- }
645
- }
646
- }
647
- `;
648
- }
649
- function vt(e = {}) {
650
- const {
651
- maxImages: t = B,
652
- maxVariants: n = G,
653
- productMetafields: o = [],
654
- variantMetafields: r = [],
655
- collectionMetafields: a = [],
656
- includeFilters: i = !1
657
- } = e, s = o.length > 0, l = r.length > 0, c = a.length > 0, g = s || l || c, d = ["$ids: [ID!]!", "$handle: String!"];
658
- return s && d.push("$productMetafields: [HasMetafieldsIdentifier!]!"), l && d.push("$variantMetafields: [HasMetafieldsIdentifier!]!"), c && d.push("$collectionMetafields: [HasMetafieldsIdentifier!]!"), `
659
- ${[
660
- ne,
661
- be,
662
- Fe,
663
- Se,
664
- Me,
665
- te,
666
- g ? z : "",
667
- i ? qe : "",
668
- i ? $e : "",
669
- Pe(l),
670
- Ae({
671
- maxImages: t,
672
- maxVariants: n,
673
- includeProductMetafields: s
674
- }),
675
- Le(c)
676
- ].join(`
677
- `)}
678
-
679
- query CollectionWithProducts(${d.join(", ")}) {
680
- collection(handle: $handle) {
681
- ...CollectionFields
682
- ${i ? "products(first: 1) { filters { ...FilterFields } }" : ""}
683
- }
684
- nodes(ids: $ids) {
685
- ... on Product {
686
- ...ProductFields
687
- }
688
- }
689
- }
690
- `;
691
- }
692
- function yt(e = {}) {
693
- const { collectionMetafields: t = [], includeFilters: n = !1 } = e, o = t.length > 0, r = ["$handle: String!"];
694
- return o && r.push("$collectionMetafields: [HasMetafieldsIdentifier!]!"), `
695
- ${[
696
- ne,
697
- te,
698
- o ? z : "",
699
- n ? qe : "",
700
- n ? $e : "",
701
- Le(o)
702
- ].join(`
703
- `)}
704
-
705
- query Collection(${r.join(", ")}) {
706
- collection(handle: $handle) {
707
- ...CollectionFields
708
- ${n ? "products(first: 1) { filters { ...FilterFields } }" : ""}
709
- }
710
- }
711
- `;
712
- }
713
- function It(e = {}) {
714
- const { pageMetafields: t = [] } = e, n = t.length > 0, o = ["$handle: String!"];
715
- return n && o.push("$pageMetafields: [HasMetafieldsIdentifier!]!"), `
716
- ${[
717
- te,
718
- n ? z : "",
719
- Ve(n)
720
- ].join(`
721
- `)}
722
-
723
- query Page(${o.join(", ")}) {
724
- page(handle: $handle) {
725
- ...PageFields
726
- }
727
- }
728
- `;
729
- }
730
- function Et(e = {}) {
731
- const {
732
- maxImages: t = B,
733
- maxVariants: n = G,
734
- productMetafields: o = [],
735
- variantMetafields: r = [],
736
- pageMetafields: a = []
737
- } = e, i = o.length > 0, s = r.length > 0, l = a.length > 0, c = i || s || l, g = ["$ids: [ID!]!", "$handle: String!"];
738
- return i && g.push("$productMetafields: [HasMetafieldsIdentifier!]!"), s && g.push("$variantMetafields: [HasMetafieldsIdentifier!]!"), l && g.push("$pageMetafields: [HasMetafieldsIdentifier!]!"), `
739
- ${[
740
- ne,
741
- be,
742
- Fe,
743
- Se,
744
- Me,
745
- te,
746
- c ? z : "",
747
- Pe(s),
748
- Ae({
749
- maxImages: t,
750
- maxVariants: n,
751
- includeProductMetafields: i
752
- }),
753
- Ve(l)
754
- ].join(`
755
- `)}
756
-
757
- query PageWithProducts(${g.join(", ")}) {
758
- page(handle: $handle) {
759
- ...PageFields
760
- }
761
- nodes(ids: $ids) {
762
- ... on Product {
763
- ...ProductFields
764
- }
765
- }
766
- }
767
- `;
768
- }
769
- function bt({
770
- shop: e,
771
- token: t,
772
- apiVersion: n,
773
- customFetch: o = fetch
774
- }) {
775
- const r = `https://${e}/api/${n}/graphql.json`;
776
- return {
777
- async request(a, { variables: i, signal: s } = {}) {
778
- const l = await o(r, {
779
- method: "POST",
780
- headers: {
781
- "Content-Type": "application/json",
782
- "X-Shopify-Storefront-Access-Token": t
783
- },
784
- body: JSON.stringify({ query: a, variables: i }),
380
+ endpoint: `/blocks/${l}/products`,
381
+ body: r({ attributes: i, transformBody: f, rest: g }),
785
382
  signal: s
786
383
  });
787
- if (!l.ok)
788
- return {
789
- data: null,
790
- errors: { message: `HTTP ${l.status}`, networkStatusCode: l.status }
791
- };
792
- const c = await l.json();
793
- return c.errors ? { data: c.data, errors: { graphQLErrors: c.errors } } : { data: c.data };
794
- }
795
- };
796
- }
797
- function ge({ ids: e, maxSize: t }) {
798
- const n = [];
799
- for (let o = 0; o < e.length; o += t)
800
- n.push(e.slice(o, o + t));
801
- return n;
802
- }
803
- function Ft(e) {
804
- if (!e.storefrontPublicToken)
805
- return v(
806
- U({
807
- code: "MISSING_CONFIG",
808
- message: "storefrontPublicToken is required",
809
- field: "storefrontPublicToken",
810
- expected: "non-empty string"
811
- })
812
- );
813
- if (!e.shop)
814
- return v(
815
- U({
816
- code: "MISSING_CONFIG",
817
- message: "shop is required",
818
- field: "shop",
819
- expected: "non-empty string"
820
- })
821
- );
822
- const { storefrontApiVersion: t = ze } = e, n = bt({
823
- shop: e.shop,
824
- token: e.storefrontPublicToken,
825
- apiVersion: t,
826
- customFetch: e.fetch
827
- });
828
- return D({
829
- async getProducts(r) {
830
- const {
831
- ids: a,
832
- productMetafields: i = [],
833
- variantMetafields: s = [],
834
- maxImages: l = B,
835
- maxVariants: c = G,
836
- signal: g
837
- } = r, d = me(r);
838
- if (d.length > 0)
839
- return v(q({ operation: "getProducts", fields: d }));
840
- if (a.length === 0)
841
- return D([]);
842
- const p = _t({
843
- maxImages: l,
844
- maxVariants: c,
845
- productMetafields: i,
846
- variantMetafields: s
847
- }), u = ge({ ids: a, maxSize: ae }), f = [];
848
- for (const h of u) {
849
- const y = { ids: h };
850
- i.length > 0 && (y.productMetafields = i), s.length > 0 && (y.variantMetafields = s);
851
- const E = await St({ graphqlClient: n, query: p, variables: y, signal: g });
852
- if (E.error)
853
- return E;
854
- f.push(...E.data);
855
- }
856
- return D(f);
857
- },
858
- async getCollection(r) {
859
- const { handle: a, collectionMetafields: i = [], includeFilters: s = !1, signal: l } = r;
860
- if (!a)
861
- return v(
862
- q({
863
- operation: "getCollection",
864
- fields: [k("handle", "REQUIRED_FIELD", "handle is required")]
865
- })
866
- );
867
- const c = yt({ collectionMetafields: i, includeFilters: s }), g = { handle: a };
868
- i.length > 0 && (g.collectionMetafields = i);
869
- try {
870
- const { data: d, errors: p } = await n.request(c, { variables: g, signal: l });
871
- if (p)
872
- return v(H(p));
873
- const u = d;
874
- return u.collection ? D(u.collection) : v(
875
- $({
876
- code: "NOT_FOUND",
877
- source: "storefront",
878
- message: `Collection not found: ${a}`
879
- })
880
- );
881
- } catch (d) {
882
- return v(Q(d));
883
- }
884
- },
885
- async getCollectionWithProducts(r) {
886
- const {
887
- handle: a,
888
- ids: i,
889
- productMetafields: s = [],
890
- variantMetafields: l = [],
891
- collectionMetafields: c = [],
892
- includeFilters: g = !1,
893
- maxImages: d = B,
894
- maxVariants: p = G,
895
- signal: u
896
- } = r, f = me(r);
897
- if (a || f.push(k("handle", "REQUIRED_FIELD", "handle is required")), f.length > 0)
898
- return v(
899
- q({
900
- operation: "getCollectionWithProducts",
901
- fields: f
902
- })
903
- );
904
- const h = vt({
905
- maxImages: d,
906
- maxVariants: p,
907
- productMetafields: s,
908
- variantMetafields: l,
909
- collectionMetafields: c,
910
- includeFilters: g
911
- }), y = i.length > 0 ? ge({ ids: i, maxSize: ae }) : [[]];
912
- let E = null;
913
- const M = [];
914
- for (let A = 0; A < y.length; A++) {
915
- const b = { ids: y[A], handle: a };
916
- s.length > 0 && (b.productMetafields = s), l.length > 0 && (b.variantMetafields = l), c.length > 0 && (b.collectionMetafields = c);
917
- try {
918
- const { data: m, errors: _ } = await n.request(h, { variables: b, signal: u });
919
- if (_)
920
- return v(H(_));
921
- const F = m;
922
- if (A === 0 && (E = F.collection ?? null, !E))
923
- return v(
924
- $({
925
- code: "NOT_FOUND",
926
- source: "storefront",
927
- message: `Collection not found: ${a}`
928
- })
929
- );
930
- const S = (F.nodes ?? []).filter((P) => P !== null);
931
- M.push(...S);
932
- } catch (m) {
933
- return v(Q(m));
934
- }
935
- }
936
- return D({ collection: E, products: M });
937
- },
938
- async getPage(r) {
939
- const { handle: a, pageMetafields: i = [], signal: s } = r;
940
- if (!a)
941
- return v(
942
- q({
943
- operation: "getPage",
944
- fields: [k("handle", "REQUIRED_FIELD", "handle is required")]
945
- })
946
- );
947
- const l = It({ pageMetafields: i }), c = { handle: a };
948
- i.length > 0 && (c.pageMetafields = i);
949
- try {
950
- const { data: g, errors: d } = await n.request(l, { variables: c, signal: s });
951
- if (d)
952
- return v(H(d));
953
- const p = g;
954
- return p.page ? D(p.page) : v(
955
- $({
956
- code: "NOT_FOUND",
957
- source: "storefront",
958
- message: `Page not found: ${a}`
959
- })
960
- );
961
- } catch (g) {
962
- return v(Q(g));
963
- }
964
- },
965
- async getPageWithProducts(r) {
966
- const {
967
- handle: a,
968
- ids: i,
969
- productMetafields: s = [],
970
- variantMetafields: l = [],
971
- pageMetafields: c = [],
972
- maxImages: g = B,
973
- maxVariants: d = G,
974
- signal: p
975
- } = r, u = me(r);
976
- if (a || u.push(k("handle", "REQUIRED_FIELD", "handle is required")), u.length > 0)
977
- return v(
978
- q({ operation: "getPageWithProducts", fields: u })
979
- );
980
- const f = Et({
981
- maxImages: g,
982
- maxVariants: d,
983
- productMetafields: s,
984
- variantMetafields: l,
985
- pageMetafields: c
986
- }), h = i.length > 0 ? ge({ ids: i, maxSize: ae }) : [[]];
987
- let y = null;
988
- const E = [];
989
- for (let M = 0; M < h.length; M++) {
990
- const R = { ids: h[M], handle: a };
991
- s.length > 0 && (R.productMetafields = s), l.length > 0 && (R.variantMetafields = l), c.length > 0 && (R.pageMetafields = c);
992
- try {
993
- const { data: b, errors: m } = await n.request(f, { variables: R, signal: p });
994
- if (m)
995
- return v(H(m));
996
- const _ = b;
997
- if (M === 0 && (y = _.page ?? null, !y))
998
- return v(
999
- $({
1000
- code: "NOT_FOUND",
1001
- source: "storefront",
1002
- message: `Page not found: ${a}`
1003
- })
1004
- );
1005
- const F = (_.nodes ?? []).filter((S) => S !== null);
1006
- E.push(...F);
1007
- } catch (b) {
1008
- return v(Q(b));
1009
- }
1010
- }
1011
- return D({ page: y, products: E });
1012
384
  }
1013
385
  });
1014
386
  }
1015
- function me(e) {
1016
- const t = [];
1017
- e.maxImages !== void 0 && (e.maxImages < ce || e.maxImages > se) && t.push(
1018
- k(
1019
- "maxImages",
1020
- "OUT_OF_RANGE",
1021
- `maxImages must be between ${ce} and ${se}`,
1022
- {
1023
- value: e.maxImages,
1024
- constraints: { min: ce, max: se }
1025
- }
1026
- )
1027
- ), e.maxVariants !== void 0 && (e.maxVariants < le || e.maxVariants > ie) && t.push(
1028
- k(
1029
- "maxVariants",
1030
- "OUT_OF_RANGE",
1031
- `maxVariants must be between ${le} and ${ie}`,
1032
- {
1033
- value: e.maxVariants,
1034
- constraints: { min: le, max: ie }
1035
- }
1036
- )
1037
- );
1038
- for (const n of e.productMetafields ?? [])
1039
- (!n.namespace || !n.key) && t.push(
1040
- k(
1041
- "productMetafields",
1042
- "REQUIRED_FIELD",
1043
- "Metafield identifier requires both namespace and key",
1044
- {
1045
- value: n,
1046
- expected: "{ namespace: string, key: string }"
1047
- }
1048
- )
1049
- );
1050
- for (const n of e.variantMetafields ?? [])
1051
- (!n.namespace || !n.key) && t.push(
1052
- k(
1053
- "variantMetafields",
1054
- "REQUIRED_FIELD",
1055
- "Metafield identifier requires both namespace and key",
1056
- {
1057
- value: n,
1058
- expected: "{ namespace: string, key: string }"
1059
- }
1060
- )
1061
- );
1062
- return t;
1063
- }
1064
- async function St({
1065
- graphqlClient: e,
1066
- query: t,
1067
- variables: n,
1068
- signal: o
1069
- }) {
1070
- try {
1071
- const { data: r, errors: a } = await e.request(t, { variables: n, signal: o });
1072
- if (a)
1073
- return v(H(a));
1074
- const i = (r?.nodes ?? []).filter(
1075
- (s) => s !== null
1076
- );
1077
- return D(i);
1078
- } catch (r) {
1079
- return v(Q(r));
1080
- }
1081
- }
1082
- function H(e) {
1083
- const t = e.networkStatusCode;
1084
- return t === 401 ? $({
1085
- code: "UNAUTHORIZED",
1086
- source: "storefront",
1087
- message: "Unauthorized: Invalid or missing storefront access token",
1088
- status: t
1089
- }) : t === 403 ? $({
1090
- code: "FORBIDDEN",
1091
- source: "storefront",
1092
- message: "Forbidden: Access denied to the requested resource",
1093
- status: t
1094
- }) : t === 429 ? $({
1095
- code: "RATE_LIMITED",
1096
- source: "storefront",
1097
- message: "Rate limited: Too many requests to the Storefront API",
1098
- status: t
1099
- }) : t !== void 0 && t >= 500 ? $({
1100
- code: "SERVICE_UNAVAILABLE",
1101
- source: "storefront",
1102
- message: `Storefront service error: ${e.message ?? `HTTP ${t}`}`,
1103
- status: t
1104
- }) : $({
1105
- code: "GRAPHQL_ERROR",
1106
- source: "storefront",
1107
- message: e.message ?? "GraphQL request failed",
1108
- status: t,
1109
- details: {
1110
- graphqlErrors: e.graphQLErrors?.map((n) => ({
1111
- message: n.message,
1112
- path: n.path,
1113
- extensions: n.extensions
1114
- }))
1115
- }
1116
- });
1117
- }
1118
- function Q(e) {
1119
- if (e instanceof Error && (e.name === "AbortError" || e.name === "TimeoutError")) {
1120
- const t = e.name === "TimeoutError" || e.message.includes("timeout");
1121
- return J({
1122
- code: t ? "TIMEOUT" : "ABORTED",
1123
- message: t ? "Request timed out" : "Request was aborted",
1124
- cause: e
1125
- });
1126
- }
1127
- return J({
1128
- code: "CONNECTION_FAILED",
1129
- message: e instanceof Error ? e.message : "Network request failed",
1130
- cause: e
1131
- });
1132
- }
1133
- const Mt = "cb-sdk-store";
1134
- function Pt(e) {
387
+ function ze(e) {
1135
388
  return typeof window > "u" || !window.localStorage ? null : {
1136
389
  read: () => window.localStorage.getItem(e),
1137
390
  write: (t) => window.localStorage.setItem(e, t),
1138
391
  remove: () => window.localStorage.removeItem(e)
1139
392
  };
1140
393
  }
1141
- function fn(e, t) {
394
+ function Lt(e, t) {
1142
395
  return {
1143
396
  read() {
1144
397
  try {
@@ -1147,9 +400,9 @@ function fn(e, t) {
1147
400
  return null;
1148
401
  }
1149
402
  },
1150
- write(n) {
403
+ write(r) {
1151
404
  try {
1152
- t.writeFileSync(e, n, "utf-8");
405
+ t.writeFileSync(e, r, "utf-8");
1153
406
  } catch {
1154
407
  }
1155
408
  },
@@ -1161,407 +414,329 @@ function fn(e, t) {
1161
414
  }
1162
415
  };
1163
416
  }
1164
- function At(e) {
1165
- typeof requestIdleCallback == "function" ? requestIdleCallback(e, { timeout: rt }) : setTimeout(e, 0);
1166
- }
1167
- function we(e) {
1168
- return [...e].sort((t, n) => n[1].timestamp - t[1].timestamp);
1169
- }
1170
- function Tt({
1171
- storageKey: e = Mt,
1172
- maxProducts: t = Ce,
1173
- maxQueries: n = ke,
1174
- adapter: o
1175
- } = {}) {
1176
- const r = o ?? Pt(e);
1177
- let a = 0;
1178
- return {
1179
- save(i) {
1180
- if (!r) return;
1181
- const s = ++a;
1182
- At(() => {
1183
- if (s === a)
1184
- try {
1185
- const l = {
1186
- products: we(i.products).slice(
1187
- 0,
1188
- t
1189
- ),
1190
- queries: we(i.queries).slice(0, n),
1191
- collections: i.collections,
1192
- version: pe
1193
- };
1194
- r.write(JSON.stringify(l));
1195
- } catch {
1196
- }
1197
- });
1198
- },
1199
- restore() {
1200
- if (!r) return null;
1201
- try {
1202
- const i = r.read();
1203
- if (!i) return null;
1204
- const s = JSON.parse(i);
1205
- return s.version !== pe || !Array.isArray(s.products) || !Array.isArray(s.queries) ? (r.remove(), null) : s;
1206
- } catch {
1207
- return r.remove(), null;
1208
- }
1209
- },
1210
- clear() {
1211
- a++, r?.remove();
1212
- }
1213
- };
1214
- }
1215
- function Rt(e, t) {
417
+ const Xe = "cb-sdk-store";
418
+ function We(e, t) {
1216
419
  if (e.size <= t) return;
1217
- const o = [...e.entries()].sort((r, a) => r[1].timestamp - a[1].timestamp).slice(0, e.size - t);
1218
- for (const [r] of o)
1219
- e.delete(r);
420
+ const n = [...e.entries()].sort((a, o) => a[1].timestamp - o[1].timestamp).slice(0, e.size - t);
421
+ for (const [a] of n)
422
+ e.delete(a);
1220
423
  }
1221
- function wt(e, t) {
1222
- if (e.size <= t) return;
1223
- const n = [];
1224
- for (const [r, a] of e)
1225
- a.value && n.push([r, a.value.timestamp]);
1226
- n.sort((r, a) => r[1] - a[1]);
1227
- const o = n.slice(0, e.size - t);
1228
- for (const [r] of o) {
1229
- const a = e.get(r);
1230
- a && (a.value = null), e.delete(r);
1231
- }
424
+ function Ze(e) {
425
+ typeof requestIdleCallback == "function" ? requestIdleCallback(e, { timeout: qe }) : setTimeout(e, 0);
1232
426
  }
1233
- function Ot(e = {}) {
427
+ function et(e = {}) {
1234
428
  const {
1235
- ttl: t = Je,
1236
- maxProducts: n = Ce,
1237
- maxQueries: o = ke,
1238
- storageKey: r,
429
+ ttl: t = Ne,
430
+ maxEntries: r = Oe,
431
+ storageKey: n = Xe,
1239
432
  storageAdapter: a
1240
- } = e, i = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map(), g = Tt({
1241
- storageKey: r,
1242
- maxProducts: n,
1243
- maxQueries: o,
1244
- adapter: a
1245
- });
1246
- function d(u) {
1247
- return Date.now() - u > t;
433
+ } = e, o = /* @__PURE__ */ new Map(), s = a ?? ze(n);
434
+ let u = 0;
435
+ function c(i) {
436
+ return Date.now() - i > t;
1248
437
  }
1249
- function p(u) {
1250
- let f = c.get(u);
1251
- return f || (f = L(null), c.set(u, f)), f;
438
+ function l() {
439
+ if (!s) return;
440
+ const i = ++u;
441
+ Ze(() => {
442
+ if (i === u)
443
+ try {
444
+ const f = [];
445
+ for (const [p, v] of o)
446
+ c(v.timestamp) || f.push([p, v]);
447
+ const g = {
448
+ queries: f.slice(0, r),
449
+ version: oe
450
+ };
451
+ s.write(JSON.stringify(g));
452
+ } catch {
453
+ }
454
+ });
1252
455
  }
1253
456
  return {
1254
- products: {
1255
- get(u) {
1256
- const f = i.get(u);
1257
- if (f) {
1258
- if (d(f.timestamp)) {
1259
- i.delete(u);
1260
- return;
1261
- }
1262
- return f.data;
1263
- }
1264
- },
1265
- getMany(u) {
1266
- const f = [], h = [];
1267
- for (const y of u) {
1268
- const E = i.get(y);
1269
- E && !d(E.timestamp) ? f.push(E.data) : h.push(y);
1270
- }
1271
- return { cached: f, missing: h };
1272
- },
1273
- set(u) {
1274
- const f = Date.now(), h = Array.isArray(u) ? u : [u];
1275
- for (const y of h)
1276
- i.set(y.gid, { data: y, timestamp: f });
1277
- Rt(i, n);
1278
- },
1279
- has(u) {
1280
- const f = i.get(u);
1281
- return f != null && !d(f.timestamp);
1282
- }
457
+ get(i) {
458
+ return o.get(i) ?? null;
1283
459
  },
1284
- queries: {
1285
- get(u) {
1286
- return p(u);
1287
- },
1288
- set(u, f) {
1289
- const h = p(u);
1290
- h.value = { data: f, timestamp: Date.now() }, wt(c, o);
1291
- },
1292
- isExpired(u) {
1293
- const f = c.get(u);
1294
- return f?.value ? d(f.value.timestamp) : !0;
1295
- },
1296
- invalidate(u) {
1297
- for (const [f, h] of c)
1298
- f.includes(u) && (h.value = null);
1299
- }
460
+ set(i, f) {
461
+ o.set(i, { data: f, timestamp: Date.now() }), We(o, r), l();
1300
462
  },
1301
- collections: {
1302
- get(u) {
1303
- return s.get(u);
1304
- },
1305
- set(u, f) {
1306
- s.set(u, { ...f, handle: u });
1307
- },
1308
- delete(u) {
1309
- s.delete(u);
1310
- }
463
+ isExpired(i) {
464
+ const f = o.get(i);
465
+ return f ? c(f.timestamp) : !0;
1311
466
  },
1312
- pages: {
1313
- get(u) {
1314
- return l.get(u);
1315
- },
1316
- set(u, f) {
1317
- l.set(u, { ...f, handle: u });
1318
- },
1319
- delete(u) {
1320
- l.delete(u);
1321
- }
467
+ invalidate(i) {
468
+ for (const f of o.keys())
469
+ f.includes(i) && o.delete(f);
1322
470
  },
1323
471
  persist() {
1324
- const u = [], f = [], h = [];
1325
- for (const [y, E] of i)
1326
- d(E.timestamp) || u.push([y, E]);
1327
- for (const [y, E] of c)
1328
- E.value && !d(E.value.timestamp) && f.push([y, E.value]);
1329
- for (const [y, E] of s)
1330
- h.push([y, E]);
1331
- g.save({ products: u, queries: f, collections: h });
472
+ l();
1332
473
  },
1333
474
  restore() {
1334
- const u = g.restore();
1335
- if (u) {
1336
- for (const [f, h] of u.products)
1337
- d(h.timestamp) || i.set(f, h);
1338
- for (const [f, h] of u.queries)
1339
- if (!d(h.timestamp)) {
1340
- const y = p(f);
1341
- y.value = h;
475
+ if (s)
476
+ try {
477
+ const i = s.read();
478
+ if (!i) return;
479
+ const f = JSON.parse(i);
480
+ if (f.version !== oe) {
481
+ s.remove();
482
+ return;
1342
483
  }
1343
- for (const [f, h] of u.collections)
1344
- s.set(f, h);
1345
- }
484
+ if (!Array.isArray(f.queries)) {
485
+ s.remove();
486
+ return;
487
+ }
488
+ for (const [g, p] of f.queries)
489
+ c(p.timestamp) || o.set(g, p);
490
+ } catch {
491
+ s.remove();
492
+ }
1346
493
  },
1347
494
  clear() {
1348
- i.clear();
1349
- for (const u of c.values()) u.value = null;
1350
- c.clear(), s.clear(), l.clear(), g.clear();
495
+ o.clear(), u++, s?.remove();
1351
496
  },
1352
497
  get stats() {
1353
- return {
1354
- products: i.size,
1355
- queries: c.size,
1356
- collections: s.size,
1357
- pages: l.size
1358
- };
498
+ return { entries: o.size };
1359
499
  }
1360
500
  };
1361
501
  }
1362
- function Ue(e, t) {
1363
- return `gid://shopify/${e}/${t}`;
1364
- }
1365
- function Ct(e) {
1366
- return Ue("Product", e);
1367
- }
1368
- function kt(e) {
1369
- return Ue("ProductVariant", e);
1370
- }
1371
- const Oe = (e) => encodeURIComponent(e).replace(/-/g, "%2D");
1372
- function xe({
1373
- type: e,
1374
- selectedOptions: t
502
+ function de({
503
+ prefix: e,
504
+ id: t,
505
+ params: r = {}
1375
506
  }) {
1376
- if (t.length === 0)
1377
- return `${e}-`;
1378
- const n = t.map(({ name: o, value: r }) => `${Oe(o)}:${Oe(r)}`).join("-");
1379
- return `${e}-${n}`;
1380
- }
1381
- function Be(e) {
1382
- return e.product_id ?? e.id;
1383
- }
1384
- function he(e) {
1385
- return Ct(Be(e));
1386
- }
1387
- function Te(e, t = []) {
1388
- return Object.entries(e).filter(([n, o]) => o != null && !t.includes(n)).sort(([n], [o]) => n.localeCompare(o)).map(
1389
- ([n, o]) => `${encodeURIComponent(n)}=${encodeURIComponent(typeof o == "object" ? JSON.stringify(o) : String(o))}`
507
+ if (!t?.trim()) return;
508
+ const n = `${e}/${encodeURIComponent(t)}`, a = Object.entries(r).filter(([o, s]) => s != null && o !== "signal").sort(([o], [s]) => o.localeCompare(s)).map(
509
+ ([o, s]) => `${encodeURIComponent(o)}=${encodeURIComponent(typeof s == "object" ? JSON.stringify(s) : String(s))}`
1390
510
  ).join("&");
511
+ return a ? `${n}?${a}` : n;
1391
512
  }
1392
- function Dt(e, t = {}) {
1393
- if (!e?.trim()) return;
1394
- const n = `/browse/${encodeURIComponent(e)}`, o = Te(t, ["collectionHandle", "signal"]);
1395
- return o ? `${n}?${o}` : n;
1396
- }
1397
- function Nt(e, t = {}) {
1398
- if (!e?.trim()) return;
1399
- const n = `/search/${encodeURIComponent(e)}`, o = Te(t, ["query", "signal"]);
1400
- return o ? `${n}?${o}` : n;
513
+ function ne() {
514
+ return b(ae({ code: "ABORTED", message: "Request aborted" }));
1401
515
  }
1402
- function qt(e, t = {}) {
1403
- if (!e?.trim()) return;
1404
- const n = `/blocks/${encodeURIComponent(e)}`, o = Te(t, ["blockId", "signal"]);
1405
- return o ? `${n}?${o}` : n;
516
+ function tt() {
517
+ const e = /* @__PURE__ */ new Map();
518
+ return {
519
+ async resolve(t) {
520
+ const { key: r, cache: n, signal: a, onFetch: o, fn: s } = t;
521
+ if (!r)
522
+ return o?.(), s(a);
523
+ const u = n.get(r);
524
+ if (u && !n.isExpired(r))
525
+ return { data: u.data };
526
+ if (a.aborted) return ne();
527
+ const c = e.get(r);
528
+ if (c) {
529
+ c.consumers++, o?.();
530
+ const p = () => {
531
+ c.consumers--, c.consumers <= 0 && (c.controller.abort(), e.delete(r));
532
+ };
533
+ a.addEventListener("abort", p, { once: !0 });
534
+ const v = await c.promise;
535
+ return a.removeEventListener("abort", p), a.aborted ? ne() : v;
536
+ }
537
+ const l = new AbortController(), i = { promise: null, controller: l, consumers: 1 }, f = () => {
538
+ i.consumers--, i.consumers <= 0 && (l.abort(), e.delete(r));
539
+ };
540
+ a.addEventListener("abort", f, { once: !0 }), o?.(), i.promise = s(l.signal).finally(() => {
541
+ e.delete(r);
542
+ }), e.set(r, i);
543
+ const g = await i.promise;
544
+ return a.removeEventListener("abort", f), a.aborted ? ne() : g;
545
+ },
546
+ clear() {
547
+ for (const t of e.values())
548
+ t.controller.abort();
549
+ e.clear();
550
+ }
551
+ };
1406
552
  }
1407
- var _e = /* @__PURE__ */ ((e) => (e.Equal = "eq", e.NotEqual = "not_eq", e.In = "in", e.NotIn = "not_in", e.GreaterThan = "gt", e.GreaterThanOrEqual = "gte", e.LessThan = "lt", e.LessThanOrEqual = "lte", e.Exists = "exists", e.NotExists = "not_exists", e))(_e || {}), Ge = /* @__PURE__ */ ((e) => (e.And = "AND", e.Or = "OR", e))(Ge || {});
1408
- function gn(e, t) {
553
+ var se = /* @__PURE__ */ ((e) => (e.Equal = "eq", e.NotEqual = "not_eq", e.In = "in", e.NotIn = "not_in", e.GreaterThan = "gt", e.GreaterThanOrEqual = "gte", e.LessThan = "lt", e.LessThanOrEqual = "lte", e.Exists = "exists", e.NotExists = "not_exists", e))(se || {}), ye = /* @__PURE__ */ ((e) => (e.And = "AND", e.Or = "OR", e))(ye || {});
554
+ function Pt(e, t) {
1409
555
  return { property: e, operator: "eq", values: [t] };
1410
556
  }
1411
- function mn(e, t) {
557
+ function Dt(e, t) {
1412
558
  return { property: e, operator: "not_eq", values: [t] };
1413
559
  }
1414
- function pn(e, t) {
560
+ function Mt(e, t) {
1415
561
  return { property: e, operator: "in", values: t };
1416
562
  }
1417
- function hn(e, t) {
563
+ function qt(e, t) {
1418
564
  return { property: e, operator: "not_in", values: t };
1419
565
  }
1420
- function _n(e, t) {
566
+ function Ut(e, t) {
1421
567
  return { property: e, operator: "gt", values: [t] };
1422
568
  }
1423
- function vn(e, t) {
569
+ function Ft(e, t) {
1424
570
  return { property: e, operator: "gte", values: [t] };
1425
571
  }
1426
- function yn(e, t) {
572
+ function $t(e, t) {
1427
573
  return { property: e, operator: "lt", values: [t] };
1428
574
  }
1429
- function In(e, t) {
575
+ function Vt(e, t) {
1430
576
  return { property: e, operator: "lte", values: [t] };
1431
577
  }
1432
- function En(e) {
578
+ function Bt(e) {
1433
579
  return { property: e, operator: "exists", values: [] };
1434
580
  }
1435
- function bn(e) {
581
+ function xt(e) {
1436
582
  return { property: e, operator: "not_exists", values: [] };
1437
583
  }
1438
- function $t(...e) {
584
+ function nt(...e) {
1439
585
  return { conditional: "AND", expressions: e };
1440
586
  }
1441
- function Fn(...e) {
587
+ function Gt(...e) {
1442
588
  return { conditional: "OR", expressions: e };
1443
589
  }
1444
- function Lt(e) {
590
+ function rt(e) {
1445
591
  return "conditional" in e;
1446
592
  }
1447
- function Sn(e) {
1448
- return Lt(e) ? e : $t(e);
593
+ function Ht(e) {
594
+ return rt(e) ? e : nt(e);
595
+ }
596
+ function Ee(e, t) {
597
+ return `gid://shopify/${e}/${t}`;
598
+ }
599
+ function ot(e) {
600
+ return Ee("Product", e);
601
+ }
602
+ function at(e) {
603
+ return Ee("ProductVariant", e);
1449
604
  }
1450
- function Vt({
605
+ const he = (e) => encodeURIComponent(e).replace(/-/g, "%2D");
606
+ function we({
607
+ type: e,
608
+ selectedOptions: t
609
+ }) {
610
+ if (t.length === 0)
611
+ return `${e}-`;
612
+ const r = t.map(({ name: n, value: a }) => `${he(n)}:${he(a)}`).join("-");
613
+ return `${e}-${r}`;
614
+ }
615
+ function Ie(e) {
616
+ return e.product_id ?? e.id;
617
+ }
618
+ function st(e) {
619
+ return ot(Ie(e));
620
+ }
621
+ function it({
1451
622
  layers: e,
1452
- currencyCode: t = De,
1453
- formatPrice: n = Ne,
1454
- swatches: o = [],
1455
- breakoutContext: r
623
+ currencyCode: t = ve,
624
+ formatPrice: r = _e,
625
+ swatches: n = [],
626
+ breakoutContext: a
1456
627
  }) {
1457
- const a = Be(e), i = he(e), s = e.title, l = e.handle ?? "", c = e.vendor ?? "", g = e.product_type ?? "", d = e.body_html ?? "", p = e.available ?? !1, u = e.is_gift_card ?? !1, f = e.tags ?? [], h = Ut(e), y = xt(e.price_range, t, n), E = Bt(e, o), M = jt(e, t, n), A = M.map((I) => I.compareAtPrice).filter((I) => I !== null), R = A.length > 0 ? {
1458
- min: A.reduce((I, C) => I.amount < C.amount ? I : C),
1459
- max: A.reduce((I, C) => I.amount > C.amount ? I : C)
1460
- } : void 0, b = e.first_or_matched_variant ? Gt(e.first_or_matched_variant) : [], m = xe({ type: "Product", selectedOptions: b }), _ = e.metafields ?? {}, F = e.category ? {
628
+ const o = Ie(e), s = st(e), u = e.title, c = e.handle, l = e.vendor ?? "", i = e.product_type ?? "", f = e.available, g = e.tags, p = ct(e), v = ut(e.price_range, t, r), I = dt(e, n), y = mt(e, t, r), R = y.map((h) => h.compareAtPrice).filter((h) => h !== null), T = R.length > 0 ? {
629
+ min: R.reduce((h, A) => h.amount < A.amount ? h : A),
630
+ max: R.reduce((h, A) => h.amount > A.amount ? h : A)
631
+ } : void 0, N = e.first_or_matched_variant ? ft(e.first_or_matched_variant) : [], w = we({ type: "Product", selectedOptions: N }), k = e.metafields, d = e.calculated, m = e.category ? {
1461
632
  id: e.category.id,
1462
633
  name: e.category.name,
1463
634
  fullName: e.category.full_name,
1464
635
  isLeaf: e.category.is_leaf,
1465
636
  isRoot: e.category.is_root
1466
- } : null, S = e.featured_media ? {
1467
- mediaContentType: e.featured_media.mediaContentType ?? null,
637
+ } : null, E = e.featured_media ? {
638
+ mediaContentType: e.featured_media.media_type ?? null,
1468
639
  url: e.featured_media.src,
1469
640
  alt: e.featured_media.alt ?? "",
1470
641
  width: e.featured_media.width,
1471
642
  height: e.featured_media.height
1472
- } : null, P = e.named_tags ? Array.isArray(e.named_tags) ? void 0 : Object.entries(e.named_tags).map(([I, C]) => ({ name: I, value: C })) : void 0, O = e.first_or_matched_variant ? M.find((I) => I.numericId === e.first_or_matched_variant.id) ?? null : null;
1473
- let w, T;
1474
- if (r?.isVariantTile) {
1475
- T = r.variantId;
1476
- const I = M.find((C) => C.numericId === T);
1477
- if (I) {
1478
- const C = new Set(r.optionCodes);
1479
- w = I.selectedOptions.filter((V) => C.has(V.name));
643
+ } : null, _ = e.first_or_matched_variant ? y.find((h) => h.numericId === e.first_or_matched_variant.id) ?? null : null;
644
+ let S = [], C = null;
645
+ if (a?.isVariantTile) {
646
+ C = a.variantId;
647
+ const h = y.find((A) => A.numericId === C);
648
+ if (h) {
649
+ const A = new Set(a.optionCodes);
650
+ S = h.selectedOptions.filter((V) => A.has(V.name));
1480
651
  }
1481
652
  }
1482
653
  return {
1483
- id: m,
1484
- gid: i,
1485
- numericId: a,
1486
- title: s,
1487
- handle: l,
1488
- type: g,
1489
- vendor: c,
1490
- description: d,
1491
- availableForSale: p,
1492
- images: h,
1493
- priceRange: y,
1494
- compareAtPriceRange: R,
1495
- options: E,
1496
- tags: f,
1497
- variants: M,
1498
- selectedOptions: b,
1499
- metafields: _,
1500
- calculated: e.calculated,
1501
- isGiftCard: u,
1502
- category: F,
1503
- createdAt: e.created_at ?? null,
1504
- publishedAt: e.published_at ?? null,
1505
- updatedAt: e.updated_at ?? null,
1506
- featuredMedia: S,
1507
- namedTags: P,
1508
- combinedListingParentProductId: e.combined_listing_parent_product_id ?? null,
1509
- combinedListingRole: e.combined_listing_role ?? null,
1510
- hasVariantsThatRequireComponents: e.has_variants_that_require_components ?? !1,
1511
- originalOptions: e.original_options ?? {},
1512
- selectedVariant: O,
1513
- breakoutOptions: w,
1514
- breakoutVariantId: T
654
+ id: w,
655
+ gid: s,
656
+ numericId: o,
657
+ title: u,
658
+ handle: c,
659
+ type: i,
660
+ vendor: l,
661
+ availableForSale: f,
662
+ images: p,
663
+ priceRange: v,
664
+ compareAtPriceRange: T,
665
+ options: I,
666
+ tags: g,
667
+ variants: y,
668
+ selectedOptions: N,
669
+ metafields: k,
670
+ calculated: d,
671
+ category: m,
672
+ featuredMedia: E,
673
+ combinedListingParentProductId: e.combined_listing_parent_product_id,
674
+ combinedListingRole: e.combined_listing_role,
675
+ selectedVariant: _,
676
+ breakoutOptions: S,
677
+ breakoutVariantId: C
1515
678
  };
1516
679
  }
1517
- function Ut(e) {
1518
- return (e.images ?? []).map((t, n) => ({
680
+ function ct(e) {
681
+ return e.images.map((t, r) => ({
1519
682
  url: t.src,
1520
683
  alt: t.alt ?? "",
1521
684
  width: t.width,
1522
685
  height: t.height,
1523
- position: t.position ?? n,
686
+ position: t.position ?? r,
1524
687
  variantIds: t.variant_ids ?? []
1525
688
  }));
1526
689
  }
1527
- function xt(e, t, n) {
1528
- const o = e?.from ?? 0, r = e?.to ?? o;
690
+ function ut(e, t, r) {
691
+ const n = e.from, a = e.to;
1529
692
  return {
1530
- min: { amount: o, currencyCode: t, formatted: n(o, t) },
1531
- max: { amount: r, currencyCode: t, formatted: n(r, t) }
693
+ min: { amount: n, currencyCode: t, formatted: r(n, t) },
694
+ max: { amount: a, currencyCode: t, formatted: r(a, t) }
1532
695
  };
1533
696
  }
1534
- function Bt(e, t) {
1535
- const n = [], o = e.options ?? {};
1536
- for (const [r, a] of Object.entries(o))
1537
- for (const i of a) {
1538
- const s = t.find((l) => l.name === r && l.value === i);
1539
- n.push({ name: r, value: i, swatch: s });
697
+ function lt(e) {
698
+ if (e.length === 0) return;
699
+ const t = /* @__PURE__ */ new Map();
700
+ for (const r of e)
701
+ for (const n of r.values)
702
+ n.swatch && (!n.swatch.color && !n.swatch.image || t.set(`${r.name}:${n.value}`, {
703
+ name: r.name,
704
+ value: n.value,
705
+ color: n.swatch.color,
706
+ imageUrl: n.swatch.image?.url ?? null
707
+ }));
708
+ return t.size > 0 ? t : void 0;
709
+ }
710
+ function dt(e, t) {
711
+ const r = [], n = e.options, a = lt(e.options_v2);
712
+ for (const [o, s] of Object.entries(n))
713
+ for (const u of s) {
714
+ const c = a?.get(`${o}:${u}`) ?? t.find((l) => l.name === o && l.value === u);
715
+ r.push({ name: o, value: u, swatch: c });
1540
716
  }
1541
- return n;
717
+ return r;
1542
718
  }
1543
- function Gt(e) {
719
+ function ft(e) {
1544
720
  return e.selected_options.map((t) => ({ name: t.name, value: t.value }));
1545
721
  }
1546
- function jt(e, t, n) {
1547
- return (e.variants ?? []).map((o) => Ht(o, t, n));
722
+ function mt(e, t, r) {
723
+ return e.variants.map((n) => gt(n, t, r));
1548
724
  }
1549
- function Ht(e, t, n) {
1550
- const o = parseFloat(e.price), r = e.compare_at_price ? parseFloat(e.compare_at_price) : null;
725
+ function gt(e, t, r) {
726
+ const n = parseFloat(e.price), a = e.compare_at_price ? parseFloat(e.compare_at_price) : null;
1551
727
  return {
1552
- id: xe({ type: "ProductVariant", selectedOptions: e.selected_options }),
1553
- gid: kt(e.id),
728
+ id: we({ type: "ProductVariant", selectedOptions: e.selected_options }),
729
+ gid: at(e.id),
1554
730
  numericId: e.id,
1555
731
  title: e.title,
1556
732
  availableForSale: e.available,
1557
- currentlyNotInStock: !e.available,
1558
- sku: e.sku ?? null,
733
+ sku: e.sku,
1559
734
  position: e.position,
1560
- price: { amount: o, currencyCode: t, formatted: n(o, t) },
1561
- compareAtPrice: r != null ? {
1562
- amount: r,
735
+ price: { amount: n, currencyCode: t, formatted: r(n, t) },
736
+ compareAtPrice: a != null ? {
737
+ amount: a,
1563
738
  currencyCode: t,
1564
- formatted: n(r, t)
739
+ formatted: r(a, t)
1565
740
  } : null,
1566
741
  image: e.featured_media ? {
1567
742
  url: e.featured_media.src,
@@ -1571,8 +746,7 @@ function Ht(e, t, n) {
1571
746
  position: 0,
1572
747
  variantIds: [e.id]
1573
748
  } : null,
1574
- selectedOptions: e.selected_options.map((a) => ({ name: a.name, value: a.value })),
1575
- metafields: Qt(e.metafields),
749
+ selectedOptions: e.selected_options.map((o) => ({ name: o.name, value: o.value })),
1576
750
  inventoryLevels: e.inventory_levels ?? {},
1577
751
  inventoryPolicy: e.inventory_policy ?? null,
1578
752
  inStockLocationIds: e.in_stock_location_ids ?? [],
@@ -1580,51 +754,101 @@ function Ht(e, t, n) {
1580
754
  hasSellingPlan: e.has_selling_plan ?? !1
1581
755
  };
1582
756
  }
1583
- function Qt(e) {
1584
- return e ? e.map((t) => ({
1585
- namespace: t.namespace,
1586
- key: t.key,
1587
- value: t.value,
1588
- type: t.value_type
1589
- })) : [];
757
+ function G({
758
+ state: e,
759
+ isFetching: t = !0
760
+ }) {
761
+ return { ...e, isFetching: t };
1590
762
  }
1591
- function je() {
1592
- return typeof window < "u" && typeof window.document < "u";
763
+ function D({
764
+ data: e,
765
+ isFetching: t = !1
766
+ }) {
767
+ return { data: e, error: null, isFetching: t };
1593
768
  }
1594
- const He = "__COMMERCE_BLOCKS__";
1595
- function Kt(e) {
1596
- je() && (window[He] = e);
769
+ function M({
770
+ error: e,
771
+ data: t = null,
772
+ isFetching: r = !1
773
+ }) {
774
+ return { data: t, error: e, isFetching: r };
1597
775
  }
1598
- function zt() {
1599
- if (!je())
1600
- return v(
1601
- U({
776
+ const fe = "__COMMERCE_BLOCKS__", me = typeof window < "u" && typeof window.document < "u";
777
+ function pt(e) {
778
+ me && (window[fe] = e);
779
+ }
780
+ function jt() {
781
+ if (!me)
782
+ return b(
783
+ Q({
1602
784
  code: "INVALID_CONFIG",
1603
- message: "SDK only available in browser",
785
+ message: "Client only available in browser",
1604
786
  field: "environment",
1605
787
  expected: "browser"
1606
788
  })
1607
789
  );
1608
- const e = window[He];
1609
- return e ? D(e) : v(
1610
- U({
790
+ const e = window[fe];
791
+ return e ? L(e) : b(
792
+ Q({
1611
793
  code: "MISSING_CONFIG",
1612
- message: "SDK not initialized. Call createSdk() first.",
1613
- field: "sdk"
794
+ message: "Client not initialized. Call createClient() first.",
795
+ field: "client"
1614
796
  })
1615
797
  );
1616
798
  }
1617
- function Mn() {
1618
- return zt().data !== void 0;
799
+ function Qt() {
800
+ return me && !!window[fe];
801
+ }
802
+ function Y(e) {
803
+ let t = null;
804
+ return {
805
+ next(r) {
806
+ return t?.abort(), t = ge(r, e), t.signal;
807
+ },
808
+ abort() {
809
+ t?.abort();
810
+ }
811
+ };
812
+ }
813
+ function ge(...e) {
814
+ const t = new AbortController(), r = [];
815
+ for (const n of e) {
816
+ if (!n) continue;
817
+ if (n.aborted) {
818
+ t.abort(n.reason);
819
+ break;
820
+ }
821
+ const a = () => t.abort(n.reason);
822
+ n.addEventListener("abort", a, { once: !0 }), r.push(() => n.removeEventListener("abort", a));
823
+ }
824
+ return r.length && t.signal.addEventListener("abort", () => r.forEach((n) => n()), {
825
+ once: !0
826
+ }), t;
827
+ }
828
+ function $(e, t) {
829
+ return re(() => t(e.value));
830
+ }
831
+ function q() {
832
+ const e = /* @__PURE__ */ new Set();
833
+ return {
834
+ add(t) {
835
+ return e.add(t), () => {
836
+ t(), e.delete(t);
837
+ };
838
+ },
839
+ clear() {
840
+ e.forEach((t) => t()), e.clear();
841
+ }
842
+ };
1619
843
  }
1620
- function re({
844
+ function z({
1621
845
  products: e,
1622
846
  raw: t,
1623
- extender: n,
1624
- currencyCode: o = De,
1625
- formatPrice: r = Ne
847
+ extender: r,
848
+ currencyCode: n = ve,
849
+ formatPrice: a = _e
1626
850
  }) {
1627
- const a = {
851
+ const o = {
1628
852
  products: e,
1629
853
  totalResults: t.totalResults,
1630
854
  totalPages: t.totalPages,
@@ -1632,778 +856,784 @@ function re({
1632
856
  resultsPerPage: t.resultsPerPage,
1633
857
  facets: t.facets ?? {},
1634
858
  facetRanges: t.facetRanges,
1635
- priceRange: Xt(t.facetRanges, o, r),
859
+ priceRange: ht(t.facetRanges, n, a),
1636
860
  attributionToken: t.attributionToken,
1637
861
  _workflow: t._workflow
1638
862
  };
1639
- return n ? n(a, t) : a;
863
+ return r ? r(o, t) : o;
1640
864
  }
1641
- function Xt(e, t, n) {
1642
- const o = e?.["variants.price"];
1643
- if (o)
865
+ function ht(e, t, r) {
866
+ const n = e?.["variants.price"];
867
+ if (n)
1644
868
  return {
1645
- min: { amount: o.min, currencyCode: t, formatted: n(o.min, t) },
1646
- max: { amount: o.max, currencyCode: t, formatted: n(o.max, t) }
869
+ min: { amount: n.min, currencyCode: t, formatted: r(n.min, t) },
870
+ max: { amount: n.max, currencyCode: t, formatted: r(n.max, t) }
1647
871
  };
1648
872
  }
1649
- function Wt({ ctx: e }) {
1650
- function t(s) {
1651
- return s.map((l) => he(l));
1652
- }
1653
- function n(s, l) {
1654
- const c = Vt({ layers: s, ...e.mergeConfig, breakoutContext: l });
1655
- return e.config.extendProduct ? { ...e.config.extendProduct({
1656
- base: c,
1657
- raw: s,
1658
- storefront: null
1659
- }), _base: c } : c;
1660
- }
1661
- function o(s, l) {
1662
- if (!(s.__typename !== "Variant" || l.length === 0))
1663
- return {
1664
- isVariantTile: !0,
1665
- variantId: s.variant_id,
1666
- optionCodes: l
1667
- };
1668
- }
1669
- function r(s, l, c) {
1670
- const g = c?.variantBreakouts?.map((d) => d.optionCode) ?? [];
1671
- return s.map((d) => {
1672
- const p = he(d), u = o(d, g);
1673
- if (!u) {
1674
- const f = l.get(p);
1675
- if (f) return f;
1676
- }
1677
- return n(d, u);
873
+ function vt(e, t) {
874
+ if (!(e.__typename !== "Variant" || t.length === 0))
875
+ return {
876
+ isVariantTile: !0,
877
+ variantId: e.variant_id,
878
+ optionCodes: t
879
+ };
880
+ }
881
+ function X(e, { results: t, meta: r }) {
882
+ const n = r?.variantBreakouts?.map((a) => a.optionCode) ?? [];
883
+ return t.map((a) => {
884
+ const o = vt(a, n), s = it({
885
+ layers: a,
886
+ currencyCode: e.config.currency,
887
+ formatPrice: e.config.formatPrice,
888
+ swatches: e.config.swatches,
889
+ breakoutContext: o
1678
890
  });
1679
- }
1680
- function a(s) {
1681
- if (s) {
1682
- if (e.config.transformFilters)
1683
- return e.config.transformFilters(s);
1684
- if (e.config.filterMap && typeof s == "object" && !Array.isArray(s)) {
1685
- const l = s, c = [];
1686
- for (const [g, d] of Object.entries(l)) {
1687
- if (d == null) continue;
1688
- const p = e.config.filterMap[g], u = typeof p == "string" ? p : p?.property ?? g, f = typeof p == "object" ? p.values : void 0, y = (Array.isArray(d) ? d : [d]).map((E) => {
1689
- const M = String(E);
1690
- return f?.[M] ?? M;
1691
- });
1692
- c.push({
1693
- property: u,
1694
- operator: y.length > 1 ? _e.In : _e.Equal,
1695
- values: y
1696
- });
1697
- }
1698
- return c.length === 0 ? void 0 : {
1699
- conditional: Ge.And,
1700
- expressions: c
1701
- };
891
+ return e.config.transforms?.product ? { ...s, ...e.config.transforms.product({ base: s, raw: a }) } : s;
892
+ });
893
+ }
894
+ function H(e, t) {
895
+ if (t) {
896
+ if (e.config.transforms?.filters)
897
+ return e.config.transforms.filters(t);
898
+ if (e.config.filterAliases && typeof t == "object" && !Array.isArray(t)) {
899
+ const r = t, n = [];
900
+ for (const [a, o] of Object.entries(r)) {
901
+ if (o == null) continue;
902
+ const s = e.config.filterAliases[a], u = typeof s == "string" ? s : s?.property ?? a, c = typeof s == "object" ? s.values : void 0, i = (Array.isArray(o) ? o : [o]).map((f) => {
903
+ const g = String(f);
904
+ return c?.[g] ?? g;
905
+ });
906
+ n.push({
907
+ property: u,
908
+ operator: i.length > 1 ? se.In : se.Equal,
909
+ values: i
910
+ });
1702
911
  }
1703
- return s;
912
+ return n.length === 0 ? void 0 : {
913
+ conditional: ye.And,
914
+ expressions: n
915
+ };
1704
916
  }
917
+ return t;
1705
918
  }
1706
- function i(s) {
1707
- return s.filter((l) => !l.breakoutVariantId);
1708
- }
1709
- return {
1710
- extractGids: t,
1711
- buildProducts: r,
1712
- transformFilters: a,
1713
- filterCacheableProducts: i
1714
- };
1715
919
  }
1716
- function oe(e) {
1717
- const t = new AbortController();
1718
- return e && (e.aborted ? t.abort(e.reason) : e.addEventListener("abort", () => t.abort(e.reason), { once: !0 })), t;
1719
- }
1720
- function K({
1721
- params: e,
1722
- paramDefinitions: t,
1723
- transformBody: n
1724
- }) {
1725
- return !e && !t && !n ? (o) => o : (o) => {
1726
- let r = o;
1727
- const a = t && Object.keys(t).length > 0;
1728
- if (e || a) {
1729
- const i = {};
1730
- if (t)
1731
- for (const [s, l] of Object.entries(t)) {
1732
- const c = l(s);
1733
- c != null && (i[s] = c);
1734
- }
1735
- r = { ...r, ...e, ...i };
1736
- }
1737
- return n ? n(r) : r;
1738
- };
1739
- }
1740
- function Jt({
1741
- ctx: e,
1742
- helpers: t
1743
- }) {
1744
- return ({ handle: n, defaultSort: o }) => {
1745
- const r = L({
920
+ function _t({ ctx: e }) {
921
+ return ({ handle: t, defaultSort: r }) => {
922
+ const n = P({
1746
923
  data: null,
1747
924
  error: null,
1748
925
  isFetching: !1
1749
- });
1750
- let a = null, i = o ?? e.config.sorts[0]?.code;
926
+ }), a = Y();
927
+ let o = r ?? e.config.sorts[0]?.code;
928
+ const s = q();
1751
929
  return {
1752
- state: r,
1753
- async execute(s = {}) {
930
+ state: n,
931
+ async execute(u = {}) {
1754
932
  const {
1755
- page: l = Y,
1756
- limit: c = Z,
1757
- filters: g,
1758
- sortOrderCode: d,
1759
- signal: p,
1760
- includeMeta: u = e.config.includeMeta ?? !1,
1761
- dynamicLinking: f,
1762
- params: h,
1763
- paramDefinitions: y,
1764
- transformBody: E
1765
- } = s, M = d ?? i;
1766
- i = M, a?.abort(), a = oe(p);
1767
- const A = r.value.data;
1768
- r.value = { data: A, error: null, isFetching: !0 };
1769
- const { data: R, error: b } = await e.layers.browse(
1770
- {
1771
- collectionHandle: n,
1772
- sort_order_code: M,
1773
- pagination: { page: l, limit: c },
1774
- filter_group: t.transformFilters(g),
1775
- dynamicLinking: f,
1776
- transformBody: K({ params: h, paramDefinitions: y, transformBody: E })
933
+ page: c = K,
934
+ limit: l = J,
935
+ filters: i,
936
+ sort: f,
937
+ signal: g,
938
+ includeMeta: p = e.config.includeMeta ?? !1,
939
+ linking: v,
940
+ transformRequest: I
941
+ } = u, y = f ?? o;
942
+ o = y;
943
+ const R = a.next(g), T = de({
944
+ prefix: "/browse",
945
+ id: t,
946
+ params: { sort: y, page: c, limit: l, filters: i }
947
+ }), { data: N, error: w } = await e.coordinator.resolve({
948
+ key: T,
949
+ cache: e.cache,
950
+ signal: R,
951
+ onFetch: () => {
952
+ n.value = G({ state: n.value });
1777
953
  },
1778
- a.signal
1779
- );
1780
- if (b)
1781
- return r.value = { data: A, error: b, isFetching: !1 }, v(b);
1782
- const { results: m, _meta: _ } = R, F = t.extractGids(m), { cached: S } = e.store.products.getMany(F), P = new Map(S.map((I) => [I.gid, I])), O = t.buildProducts(m, P, _), w = re({
1783
- products: O,
1784
- raw: R,
1785
- extender: e.config.extendCollection,
1786
- currencyCode: e.mergeConfig.currencyCode,
1787
- formatPrice: e.mergeConfig.formatPrice
954
+ fn: async (k) => {
955
+ const { data: d, error: m } = await e.layers.browse(
956
+ {
957
+ collectionHandle: t,
958
+ sort_order_code: y,
959
+ pagination: { page: c, limit: l },
960
+ filter_group: H(e, i),
961
+ dynamicLinking: v,
962
+ transformBody: I
963
+ },
964
+ k
965
+ );
966
+ if (m) return b(m);
967
+ const { results: E, _meta: _ } = d, S = X(e, { results: E, meta: _ }), C = z({
968
+ products: S,
969
+ raw: d,
970
+ extender: e.config.transforms?.collection,
971
+ currencyCode: e.config.currency,
972
+ formatPrice: e.config.formatPrice
973
+ });
974
+ return p && d._meta && (C._meta = d._meta), T && e.cache.set(T, C), L(C);
975
+ }
1788
976
  });
1789
- u && R._meta && (w._meta = R._meta);
1790
- const T = Dt(n, { sortOrderCode: M, page: l, limit: c, filters: g });
1791
- return T && e.store.queries.set(T, w), e.store.products.set(t.filterCacheableProducts(O)), e.store.collections.set(n, {
1792
- totalProducts: w.totalResults,
1793
- totalPages: w.totalPages,
1794
- lastPageFetched: l,
1795
- facets: w.facets,
1796
- lastFetched: Date.now()
1797
- }), r.value = { data: w, error: null, isFetching: !1 }, D(w);
977
+ return w ? (n.value = M({ error: w, data: n.value.data }), b(w)) : (n.value = D({ data: N }), L(N));
978
+ },
979
+ subscribe(u) {
980
+ return s.add($(n, u));
1798
981
  },
1799
982
  dispose() {
1800
- a?.abort();
983
+ s.clear(), a.abort();
1801
984
  }
1802
985
  };
1803
986
  };
1804
987
  }
1805
- function Yt({
1806
- ctx: e,
1807
- helpers: t
1808
- }) {
1809
- return () => {
1810
- const n = L({
988
+ async function bt(e, { maxRetries: t = 3, defaultDelayMs: r = 1e3 } = {}) {
989
+ let n = await e();
990
+ for (let a = 0; a < t && n.error && Ve(n.error); a++)
991
+ await new Promise((o) => setTimeout(o, Be(n.error) ?? r)), n = await e();
992
+ return n;
993
+ }
994
+ function yt({ ctx: e }) {
995
+ return (t = {}) => {
996
+ const r = P({
1811
997
  data: null,
1812
998
  error: null,
1813
999
  isFetching: !1
1814
1000
  });
1815
- let o = null, r;
1001
+ let n = {
1002
+ query: t.query,
1003
+ page: t.page,
1004
+ limit: t.limit,
1005
+ filters: t.filters,
1006
+ tuning: t.tuning,
1007
+ linking: t.linking,
1008
+ transformRequest: t.transformRequest
1009
+ };
1010
+ const a = Y(t.signal);
1011
+ let o;
1012
+ const s = q();
1013
+ function u(c = {}) {
1014
+ const l = { ...n, ...c };
1015
+ return c.temporary || (n = l), l;
1016
+ }
1816
1017
  return {
1817
- state: n,
1818
- async prepare(a) {
1819
- const {
1820
- query: i,
1821
- filters: s,
1822
- tuning: l,
1823
- signal: c,
1824
- dynamicLinking: g,
1825
- params: d,
1826
- paramDefinitions: p,
1827
- transformBody: u
1828
- } = a, f = t.transformFilters(s), h = await e.layers.prepareSearch(
1018
+ state: r,
1019
+ async prepare(c = {}) {
1020
+ const l = u(c), { query: i, filters: f, tuning: g, linking: p, transformRequest: v } = l;
1021
+ if (!i)
1022
+ return b(
1023
+ x({
1024
+ operation: "search.prepare",
1025
+ fields: [F("query", "REQUIRED_FIELD", "query is required")]
1026
+ })
1027
+ );
1028
+ const I = H(e, f), y = await e.layers.prepareSearch(
1829
1029
  {
1830
1030
  query: i,
1831
- filter_group: f,
1832
- tuning: l,
1833
- dynamicLinking: g,
1834
- transformBody: K({ params: d, paramDefinitions: p, transformBody: u })
1031
+ filter_group: I,
1032
+ tuning: g,
1033
+ dynamicLinking: p,
1034
+ transformBody: v
1835
1035
  },
1836
- c
1036
+ c.signal
1837
1037
  );
1838
- return h.error ? v(h.error) : (r = h.data.search_id, D({ searchId: h.data.search_id }));
1038
+ return y.error ? b(y.error) : (o = y.data.search_id, L({ searchId: y.data.search_id }));
1839
1039
  },
1840
- async execute(a) {
1841
- const {
1040
+ async execute(c = {}) {
1041
+ const l = u(c), {
1842
1042
  query: i,
1843
- searchId: s,
1844
- page: l = Y,
1845
- limit: c = Z,
1846
- filters: g,
1847
- tuning: d,
1848
- signal: p,
1849
- dynamicLinking: u,
1850
- params: f,
1851
- paramDefinitions: h,
1852
- transformBody: y
1853
- } = a, E = t.transformFilters(g), M = K({ params: f, paramDefinitions: h, transformBody: y });
1854
- o?.abort(), o = oe(p), n.value = { ...n.value, isFetching: !0, error: null };
1855
- let A = s ?? r;
1856
- if (r = void 0, !A) {
1857
- const I = await e.layers.prepareSearch(
1858
- {
1859
- query: i,
1860
- filter_group: E,
1861
- tuning: d,
1862
- dynamicLinking: u,
1863
- transformBody: M
1864
- },
1865
- o.signal
1866
- );
1867
- if (I.error)
1868
- return n.value = { ...n.value, isFetching: !1, error: I.error }, v(I.error);
1869
- A = I.data.search_id;
1043
+ page: f = K,
1044
+ limit: g = J,
1045
+ filters: p,
1046
+ tuning: v,
1047
+ linking: I,
1048
+ transformRequest: y
1049
+ } = l;
1050
+ if (!i) {
1051
+ const E = x({
1052
+ operation: "search.execute",
1053
+ fields: [F("query", "REQUIRED_FIELD", "query is required")]
1054
+ });
1055
+ return r.value = M({ error: E, data: r.value.data }), b(E);
1870
1056
  }
1871
- const R = Ye;
1872
- let b = await e.layers.search(
1873
- {
1874
- query: i,
1875
- search_id: A,
1876
- pagination: { page: l, limit: c },
1877
- filter_group: E,
1878
- tuning: d,
1879
- dynamicLinking: u,
1880
- transformBody: M
1057
+ const R = c.searchId, T = H(e, p), N = a.next(c.signal), w = R ?? o;
1058
+ o = void 0;
1059
+ const k = de({
1060
+ prefix: "/search",
1061
+ id: i,
1062
+ params: { page: f, limit: g, filters: p }
1063
+ }), { data: d, error: m } = await e.coordinator.resolve({
1064
+ key: k,
1065
+ cache: e.cache,
1066
+ signal: N,
1067
+ onFetch: () => {
1068
+ r.value = G({ state: r.value });
1881
1069
  },
1882
- o.signal
1883
- );
1884
- for (let I = 0; I < R && b.error; I++) {
1885
- const C = b.error;
1886
- if (C._tag !== "ApiError" || C.status !== 425) break;
1887
- let V = Ze;
1888
- try {
1889
- const X = JSON.parse(C.message);
1890
- X.retry_after_ms && (V = X.retry_after_ms);
1891
- } catch {
1070
+ fn: async (E) => {
1071
+ let _ = w;
1072
+ if (!_) {
1073
+ const W = await e.layers.prepareSearch(
1074
+ {
1075
+ query: i,
1076
+ filter_group: T,
1077
+ tuning: v,
1078
+ dynamicLinking: I,
1079
+ transformBody: y
1080
+ },
1081
+ E
1082
+ );
1083
+ if (W.error) return b(W.error);
1084
+ _ = W.data.search_id;
1085
+ }
1086
+ const S = await bt(
1087
+ () => e.layers.search(
1088
+ {
1089
+ query: i,
1090
+ search_id: _,
1091
+ pagination: { page: f, limit: g },
1092
+ filter_group: T,
1093
+ tuning: v,
1094
+ dynamicLinking: I,
1095
+ transformBody: y
1096
+ },
1097
+ E
1098
+ ),
1099
+ { maxRetries: Ce, defaultDelayMs: Le }
1100
+ );
1101
+ if (S.error) return b(S.error);
1102
+ const { results: C, _meta: h } = S.data, A = X(e, { results: C, meta: h }), V = z({
1103
+ products: A,
1104
+ raw: S.data,
1105
+ extender: e.config.transforms?.search,
1106
+ currencyCode: e.config.currency,
1107
+ formatPrice: e.config.formatPrice
1108
+ });
1109
+ return e.config.includeMeta && S.data._meta && (V._meta = S.data._meta), k && e.cache.set(k, V), L(V);
1892
1110
  }
1893
- await new Promise((X) => setTimeout(X, V)), b = await e.layers.search(
1894
- {
1895
- query: i,
1896
- search_id: A,
1897
- pagination: { page: l, limit: c },
1898
- filter_group: E,
1899
- tuning: d,
1900
- dynamicLinking: u,
1901
- transformBody: M
1902
- },
1903
- o.signal
1904
- );
1905
- }
1906
- if (b.error)
1907
- return n.value = { data: n.value.data, error: b.error, isFetching: !1 }, v(b.error);
1908
- const { results: m, _meta: _ } = b.data, F = t.extractGids(m), { cached: S } = e.store.products.getMany(F), P = new Map(S.map((I) => [I.gid, I])), O = t.buildProducts(m, P, _), w = re({
1909
- products: O,
1910
- raw: b.data,
1911
- extender: e.config.extendSearch,
1912
- currencyCode: e.mergeConfig.currencyCode,
1913
- formatPrice: e.mergeConfig.formatPrice
1914
1111
  });
1915
- e.config.includeMeta && b.data._meta && (w._meta = b.data._meta), e.store.products.set(t.filterCacheableProducts(O));
1916
- const T = Nt(i, { page: l, limit: c, filters: g });
1917
- return T && e.store.queries.set(T, w), n.value = { data: w, error: null, isFetching: !1 }, D(w);
1112
+ return m ? (r.value = M({ error: m, data: r.value.data }), b(m)) : (r.value = D({ data: d }), L(d));
1113
+ },
1114
+ subscribe(c) {
1115
+ return s.add($(r, c));
1918
1116
  },
1919
1117
  dispose() {
1920
- o?.abort();
1118
+ s.clear(), a.abort();
1921
1119
  }
1922
1120
  };
1923
1121
  };
1924
1122
  }
1925
- function Zt({
1926
- ctx: e,
1927
- helpers: t
1928
- }) {
1929
- return ({ blockId: n, anchorId: o, anchorHandle: r }) => {
1930
- const a = L({
1123
+ function Et({ ctx: e }) {
1124
+ return ({ blockId: t, anchor: r }) => {
1125
+ const n = P({
1931
1126
  data: null,
1932
1127
  error: null,
1933
1128
  isFetching: !1
1934
- });
1935
- let i = null;
1129
+ }), a = Y(), o = q();
1936
1130
  return {
1937
- state: a,
1131
+ state: n,
1938
1132
  async execute(s = {}) {
1939
1133
  const {
1940
- page: l = Y,
1941
- limit: c = Z,
1942
- filters: g,
1943
- signal: d,
1944
- discountEntitlements: p,
1945
- context: u,
1946
- dynamicLinking: f,
1947
- params: h,
1948
- paramDefinitions: y,
1949
- transformBody: E
1950
- } = s;
1951
- i?.abort(), i = oe(d);
1952
- const M = a.value.data;
1953
- a.value = { data: M, error: null, isFetching: !0 };
1954
- const { data: A, error: R } = await e.layers.blocks(
1955
- {
1956
- blockId: n,
1957
- anchor_id: o,
1958
- anchor_handle: r,
1959
- pagination: { page: l, limit: c },
1960
- filter_group: t.transformFilters(g),
1961
- discountEntitlements: p,
1962
- context: u,
1963
- dynamicLinking: f,
1964
- transformBody: K({ params: h, paramDefinitions: y, transformBody: E })
1134
+ page: u = K,
1135
+ limit: c = J,
1136
+ filters: l,
1137
+ signal: i,
1138
+ discounts: f,
1139
+ context: g,
1140
+ linking: p,
1141
+ transformRequest: v
1142
+ } = s, I = a.next(i), y = de({
1143
+ prefix: "/blocks",
1144
+ id: t,
1145
+ params: { anchor: r, page: u, limit: c, filters: l }
1146
+ }), { data: R, error: T } = await e.coordinator.resolve({
1147
+ key: y,
1148
+ cache: e.cache,
1149
+ signal: I,
1150
+ onFetch: () => {
1151
+ n.value = G({ state: n.value });
1965
1152
  },
1966
- i.signal
1967
- );
1968
- if (R)
1969
- return a.value = { data: M, error: R, isFetching: !1 }, v(R);
1970
- const { results: b, _meta: m } = A, _ = t.extractGids(b), { cached: F } = e.store.products.getMany(_), S = new Map(F.map((T) => [T.gid, T])), P = t.buildProducts(b, S, m), O = re({
1971
- products: P,
1972
- raw: A,
1973
- extender: e.config.extendBlock,
1974
- currencyCode: e.mergeConfig.currencyCode,
1975
- formatPrice: e.mergeConfig.formatPrice
1153
+ fn: async (N) => {
1154
+ const { data: w, error: k } = await e.layers.blocks(
1155
+ {
1156
+ blockId: t,
1157
+ anchor_id: r,
1158
+ pagination: { page: u, limit: c },
1159
+ filter_group: H(e, l),
1160
+ discountEntitlements: f,
1161
+ context: g,
1162
+ dynamicLinking: p,
1163
+ transformBody: v
1164
+ },
1165
+ N
1166
+ );
1167
+ if (k) return b(k);
1168
+ const { results: d, _meta: m } = w, E = X(e, { results: d, meta: m }), _ = z({
1169
+ products: E,
1170
+ raw: w,
1171
+ extender: e.config.transforms?.block,
1172
+ currencyCode: e.config.currency,
1173
+ formatPrice: e.config.formatPrice
1174
+ });
1175
+ return e.config.includeMeta && w._meta && (_._meta = w._meta), w.block && (_.block = w.block), y && e.cache.set(y, _), L(_);
1176
+ }
1976
1177
  });
1977
- e.config.includeMeta && A._meta && (O._meta = A._meta), A.block && (O.block = A.block);
1978
- const w = qt(n, { anchorId: o, anchorHandle: r, page: l, limit: c, filters: g });
1979
- return w && e.store.queries.set(w, O), e.store.products.set(t.filterCacheableProducts(P)), a.value = { data: O, error: null, isFetching: !1 }, D(O);
1178
+ return T ? (n.value = M({ error: T, data: n.value.data }), b(T)) : (n.value = D({ data: R }), L(R));
1179
+ },
1180
+ subscribe(s) {
1181
+ return o.add($(n, s));
1980
1182
  },
1981
1183
  dispose() {
1982
- i?.abort();
1184
+ o.clear(), a.abort();
1983
1185
  }
1984
1186
  };
1985
1187
  };
1986
1188
  }
1987
- function en(e, t) {
1988
- let n = null;
1189
+ function wt(e, t) {
1190
+ let r = null;
1989
1191
  return {
1990
- call(...o) {
1991
- n && clearTimeout(n), n = setTimeout(() => {
1992
- n = null, e(...o);
1192
+ call(...n) {
1193
+ r && clearTimeout(r), r = setTimeout(() => {
1194
+ r = null, e(...n);
1993
1195
  }, t);
1994
1196
  },
1995
1197
  cancel() {
1996
- n && (clearTimeout(n), n = null);
1198
+ r && (clearTimeout(r), r = null);
1997
1199
  }
1998
1200
  };
1999
1201
  }
2000
- function tn({
2001
- ctx: e
2002
- }) {
1202
+ function It(e, t) {
1203
+ const r = new Set(t.map((n) => n.toLowerCase()));
1204
+ return e.filter((n) => !r.has(n.toLowerCase()));
1205
+ }
1206
+ function At({ ctx: e }) {
2003
1207
  return (t = {}) => {
2004
- const { debounceMs: n = et, signal: o } = t, r = L({
1208
+ const {
1209
+ debounce: r = Pe,
1210
+ excludeInputQuery: n = !1,
1211
+ excludeQueries: a,
1212
+ signal: o
1213
+ } = t, s = P({
2005
1214
  data: null,
2006
1215
  error: null,
2007
1216
  isFetching: !1
2008
- });
2009
- let a = null, i = 0;
2010
- const s = /* @__PURE__ */ new Map();
2011
- function l() {
2012
- c.cancel(), a?.abort(), s.clear();
1217
+ }), u = Y(o);
1218
+ let c = 0;
1219
+ const l = /* @__PURE__ */ new Map(), i = q();
1220
+ function f() {
1221
+ i.clear(), g.cancel(), u.abort(), l.clear(), o?.removeEventListener("abort", f);
2013
1222
  }
2014
- o?.addEventListener("abort", l, { once: !0 });
2015
- const c = en(async (g) => {
2016
- if (!g.trim()) {
2017
- r.value = { data: null, error: null, isFetching: !1 };
1223
+ o?.addEventListener("abort", f, { once: !0 });
1224
+ const g = wt(async (v) => {
1225
+ const I = v.trim();
1226
+ if (!I) {
1227
+ s.value = { data: null, error: null, isFetching: !1 };
2018
1228
  return;
2019
1229
  }
2020
- const d = g.trim().toLowerCase(), p = s.get(d);
2021
- if (p) {
2022
- r.value = { data: p, error: null, isFetching: !1 };
1230
+ const y = I.toLowerCase(), R = l.get(y);
1231
+ if (R) {
1232
+ s.value = D({ data: R });
2023
1233
  return;
2024
1234
  }
2025
- a?.abort(), a = oe(o);
2026
- const u = ++i;
2027
- r.value = { ...r.value, isFetching: !0 };
2028
- const f = await e.layers.predictiveSearch(g.trim(), a.signal);
2029
- u === i && (f.error ? f.error._tag !== "NetworkError" || f.error.code !== "ABORTED" ? r.value = { data: null, error: f.error, isFetching: !1 } : r.value = { ...r.value, isFetching: !1 } : (s.set(d, f.data), s.size > tt && s.delete(s.keys().next().value), r.value = { data: f.data, error: null, isFetching: !1 }));
2030
- }, n);
2031
- return { state: r, execute: (g) => c.call(g), dispose: l };
2032
- };
2033
- }
2034
- function nn({
2035
- ctx: e
2036
- }) {
2037
- return (t) => {
2038
- const {
2039
- ids: n,
2040
- meta: o,
2041
- collectionMetafields: r = e.config.collectionMetafields,
2042
- pageMetafields: a = e.config.pageMetafields,
2043
- signal: i
2044
- } = t, s = L({
2045
- data: null,
2046
- error: null,
2047
- isFetching: !1
2048
- });
2049
- if (n.length === 0)
2050
- return s.value = { data: { products: [] }, error: null, isFetching: !1 }, s;
2051
- const l = n, { cached: c } = e.store.products.getMany(l), g = new Map(c.map((p) => [p.gid, p])), d = l.map((p) => g.get(p)).filter((p) => p != null);
2052
- return !o || !e.storefrontEnabled ? (s.value = { data: { products: d }, error: null, isFetching: !1 }, s) : (s.value = { data: null, error: null, isFetching: !0 }, (async () => {
2053
- let p, u;
2054
- if (o.collection) {
2055
- const h = await e.storefront.getCollection({
2056
- handle: o.collection,
2057
- collectionMetafields: r,
2058
- includeFilters: o.includeFilters,
2059
- signal: i
2060
- });
2061
- if (h.error) {
2062
- s.value = { data: null, error: h.error, isFetching: !1 };
2063
- return;
2064
- }
2065
- p = h.data;
2066
- }
2067
- if (o.page) {
2068
- const h = await e.storefront.getPage({
2069
- handle: o.page,
2070
- pageMetafields: a,
2071
- signal: i
2072
- });
2073
- if (h.error) {
2074
- s.value = { data: null, error: h.error, isFetching: !1 };
2075
- return;
1235
+ const T = u.next(), N = ++c;
1236
+ s.value = G({ state: s.value });
1237
+ const w = await e.layers.predictiveSearch(I, T);
1238
+ if (N === c)
1239
+ if (w.error)
1240
+ w.error._tag !== "NetworkError" || w.error.code !== "ABORTED" ? s.value = M({ error: w.error }) : s.value = G({ state: s.value, isFetching: !1 });
1241
+ else {
1242
+ const k = [
1243
+ ...n ? [w.data.originalQuery, w.data.normalizedQuery] : [],
1244
+ ...a ?? []
1245
+ ], d = k.length ? {
1246
+ ...w.data,
1247
+ matchedQueries: It(w.data.matchedQueries, k)
1248
+ } : w.data;
1249
+ l.set(y, d), l.size > De && l.delete(l.keys().next().value), s.value = D({ data: d });
2076
1250
  }
2077
- u = h.data;
2078
- }
2079
- const f = { products: d };
2080
- p && (f.collection = p), u && (f.page = u), s.value = { data: f, error: null, isFetching: !1 };
2081
- })(), s);
1251
+ }, r);
1252
+ function p(v) {
1253
+ return i.add($(s, v));
1254
+ }
1255
+ return {
1256
+ state: s,
1257
+ execute: (v) => g.call(v),
1258
+ subscribe: p,
1259
+ dispose: f
1260
+ };
2082
1261
  };
2083
1262
  }
2084
- function rn({ ctx: e }) {
2085
- return ({
2086
- image: t,
2087
- signal: n
2088
- }) => {
2089
- const o = L({
1263
+ function St({ ctx: e }) {
1264
+ return ({ image: t, signal: r }) => {
1265
+ const n = P({
2090
1266
  data: null,
2091
1267
  error: null,
2092
1268
  isFetching: !0
2093
- });
1269
+ }), a = q(), o = ge(r);
2094
1270
  return (async () => {
2095
- const r = await e.layers.uploadImage(t, n);
2096
- if (r.error) {
2097
- o.value = { data: null, error: r.error, isFetching: !1 };
1271
+ const s = await e.layers.uploadImage(t, o.signal);
1272
+ if (s.error) {
1273
+ n.value = M({ error: s.error });
2098
1274
  return;
2099
1275
  }
2100
- o.value = { data: { imageId: r.data.imageId }, error: null, isFetching: !1 };
2101
- })(), o;
1276
+ n.value = D({ data: { imageId: s.data.imageId } });
1277
+ })(), {
1278
+ state: n,
1279
+ subscribe(s) {
1280
+ return a.add($(n, s));
1281
+ },
1282
+ dispose() {
1283
+ a.clear(), o.abort();
1284
+ }
1285
+ };
2102
1286
  };
2103
1287
  }
2104
- function on({
2105
- ctx: e,
2106
- helpers: t
2107
- }) {
2108
- return (n) => {
1288
+ function Rt({ ctx: e }) {
1289
+ return (t) => {
2109
1290
  const {
2110
- imageId: o,
2111
- page: r = Y,
2112
- limit: a = Z,
2113
- filters: i,
1291
+ imageId: r,
1292
+ page: n = K,
1293
+ limit: a = J,
1294
+ filters: o,
2114
1295
  tuning: s,
2115
- signal: l,
2116
- dynamicLinking: c,
2117
- params: g,
2118
- paramDefinitions: d,
2119
- transformBody: p
2120
- } = n, u = L({
1296
+ signal: u,
1297
+ linking: c,
1298
+ transformRequest: l
1299
+ } = t, i = P({
2121
1300
  data: null,
2122
1301
  error: null,
2123
1302
  isFetching: !0
2124
- });
1303
+ }), f = q(), g = ge(u);
2125
1304
  return (async () => {
2126
- const f = await e.layers.imageSearch(
1305
+ const p = await e.layers.imageSearch(
2127
1306
  {
2128
- image_id: o,
2129
- pagination: { page: r, limit: a },
2130
- filter_group: t.transformFilters(i),
1307
+ image_id: r,
1308
+ pagination: { page: n, limit: a },
1309
+ filter_group: H(e, o),
2131
1310
  tuning: s,
2132
1311
  dynamicLinking: c,
2133
- transformBody: K({ params: g, paramDefinitions: d, transformBody: p })
1312
+ transformBody: l
2134
1313
  },
2135
- l
1314
+ g.signal
2136
1315
  );
2137
- if (f.error) {
2138
- u.value = { data: null, error: f.error, isFetching: !1 };
1316
+ if (p.error) {
1317
+ i.value = M({ error: p.error });
2139
1318
  return;
2140
1319
  }
2141
- const { results: h, _meta: y } = f.data, E = t.extractGids(h), { cached: M } = e.store.products.getMany(E), A = new Map(M.map((m) => [m.gid, m])), R = t.buildProducts(h, A, y), b = re({
2142
- products: R,
2143
- raw: f.data,
2144
- extender: e.config.extendSearch,
2145
- currencyCode: e.mergeConfig.currencyCode,
2146
- formatPrice: e.mergeConfig.formatPrice
1320
+ const { results: v, _meta: I } = p.data, y = X(e, { results: v, meta: I }), R = z({
1321
+ products: y,
1322
+ raw: p.data,
1323
+ extender: e.config.transforms?.search,
1324
+ currencyCode: e.config.currency,
1325
+ formatPrice: e.config.formatPrice
2147
1326
  });
2148
- e.store.products.set(t.filterCacheableProducts(R)), u.value = { data: b, error: null, isFetching: !1 };
2149
- })(), u;
1327
+ i.value = D({ data: R });
1328
+ })(), {
1329
+ state: i,
1330
+ subscribe(p) {
1331
+ return f.add($(i, p));
1332
+ },
1333
+ dispose() {
1334
+ f.clear(), g.abort();
1335
+ }
1336
+ };
2150
1337
  };
2151
1338
  }
2152
- function Pn(e) {
2153
- const t = pt({
2154
- layersPublicToken: e.layersPublicToken,
2155
- layersBaseUrl: e.layersBaseUrl,
1339
+ function Kt(e) {
1340
+ const t = Ye({
1341
+ token: e.token,
1342
+ baseUrl: e.baseUrl,
2156
1343
  sorts: e.sorts,
2157
1344
  facets: e.facets,
2158
1345
  attributes: e.attributes,
2159
1346
  fetch: e.fetch
2160
1347
  });
2161
- if (t.error) return v(t.error);
2162
- const n = t.data;
2163
- let o, r = !1;
2164
- if (e.enableStorefront) {
2165
- if (!e.shop || !e.storefrontPublicToken)
2166
- return v(
2167
- U({
2168
- code: "MISSING_CONFIG",
2169
- message: "shop and storefrontPublicToken are required when enableStorefront is true",
2170
- field: e.shop ? "storefrontPublicToken" : "shop",
2171
- expected: "non-empty string"
2172
- })
2173
- );
2174
- const c = Ft({
2175
- shop: e.shop,
2176
- storefrontPublicToken: e.storefrontPublicToken,
2177
- storefrontApiVersion: e.storefrontApiVersion,
2178
- fetch: e.fetch
2179
- });
2180
- if (c.error) return v(c.error);
2181
- o = c.data, r = !0;
2182
- }
2183
- const a = Ot({
2184
- maxProducts: e.cacheMaxProducts,
2185
- maxQueries: e.cacheMaxEntries,
2186
- ttl: e.cacheTtl,
2187
- storageAdapter: e.storageAdapter
1348
+ if (t.error) return b(t.error);
1349
+ const r = t.data, n = et({
1350
+ maxEntries: e.cacheLimit,
1351
+ ttl: e.cacheLifetime,
1352
+ storageAdapter: e.storage
2188
1353
  });
2189
- if (e.restoreFromStorage !== !1 && a.restore(), e.initialData) {
2190
- const { products: c, queries: g, collections: d } = e.initialData;
2191
- if (c?.length && a.products.set(c), g)
2192
- for (const [p, u] of Object.entries(g))
2193
- a.queries.set(p, u);
2194
- if (d)
2195
- for (const [p, u] of Object.entries(d))
2196
- a.collections.set(p, u);
2197
- }
2198
- const i = {
1354
+ if (e.restoreCache !== !1 && n.restore(), e.initialData)
1355
+ for (const [u, c] of Object.entries(e.initialData))
1356
+ n.set(u, c);
1357
+ const a = tt(), o = {
2199
1358
  config: e,
2200
- layers: n,
2201
- storefront: o,
2202
- storefrontEnabled: r,
2203
- store: a,
2204
- mergeConfig: {
2205
- currencyCode: e.currencyCode,
2206
- formatPrice: e.formatPrice,
2207
- swatches: e.swatches
2208
- }
2209
- }, s = Wt({ ctx: i }), l = {
1359
+ layers: r,
1360
+ cache: n,
1361
+ coordinator: a
1362
+ }, s = {
2210
1363
  config: e,
2211
- store: a,
2212
- collection: Jt({ ctx: i, helpers: s }),
2213
- search: Yt({ ctx: i, helpers: s }),
2214
- blocks: Zt({ ctx: i, helpers: s }),
2215
- autocomplete: tn({ ctx: i }),
2216
- storefront: nn({ ctx: i }),
2217
- uploadImage: rn({ ctx: i }),
2218
- imageSearch: on({ ctx: i, helpers: s })
1364
+ cache: n,
1365
+ collection: _t({ ctx: o }),
1366
+ search: yt({ ctx: o }),
1367
+ blocks: Et({ ctx: o }),
1368
+ suggest: At({ ctx: o }),
1369
+ uploadImage: St({ ctx: o }),
1370
+ searchByImage: Rt({ ctx: o })
2219
1371
  };
2220
- return Kt(l), D(l);
1372
+ return pt(s), L(s);
2221
1373
  }
2222
- function An({
1374
+ function Jt({
2223
1375
  product: e,
2224
1376
  selectedOptions: t = [],
2225
- breakoutOptions: n
1377
+ breakoutOptions: r
2226
1378
  }) {
2227
- const o = "_base" in e ? e._base : e, r = n ?? o.breakoutOptions ?? [], a = L(t), i = L(r), s = N(() => an(o.variants, i.value)), l = N(() => new Set(i.value.map((m) => m.name))), c = N(() => {
2228
- const m = a.value.filter((_) => !l.value.has(_.name));
2229
- return [...i.value, ...m];
2230
- }), g = N(
2231
- () => W(s.value, c.value)
2232
- ), d = N(
2233
- () => sn(s.value, o.options, l.value)
2234
- ), p = N(() => [...new Set(d.value.map((m) => m.name))]), u = N(() => d.value.find((_) => _.swatch)?.name ?? null), f = N(() => {
2235
- const m = u.value;
2236
- if (!m) return /* @__PURE__ */ new Map();
2237
- const _ = /* @__PURE__ */ new Map();
2238
- for (const F of s.value) {
2239
- const S = F.selectedOptions.find((P) => P.name === m);
2240
- S && _.set(F.numericId, S.value);
2241
- }
2242
- return _;
2243
- }), h = N(() => {
2244
- const m = u.value;
2245
- return m ? d.value.filter((_) => _.name === m).map((_) => _.value) : [];
2246
- }), y = N(() => {
2247
- const m = u.value, _ = h.value, F = f.value;
2248
- if (!m || _.length === 0)
2249
- return [...o.images].sort((T, I) => T.position - I.position);
2250
- const S = g.value ? F.get(g.value.numericId) : null, P = /* @__PURE__ */ new Map(), O = [];
2251
- for (const T of o.images) {
2252
- if (T.variantIds.length === 0) {
2253
- O.push(T);
2254
- continue;
2255
- }
2256
- let I = null;
2257
- for (const C of T.variantIds) {
2258
- const V = F.get(C);
2259
- if (V) {
2260
- I = V;
2261
- break;
2262
- }
2263
- }
2264
- if (I) {
2265
- const C = P.get(I) ?? [];
2266
- C.push(T), P.set(I, C);
2267
- } else
2268
- O.push(T);
1379
+ const n = r ?? e.breakoutOptions ?? [], a = new Set(n.map((d) => d.name)), o = P(t), s = P(null), u = q(), c = O(() => Tt(e.variants, n)), l = O(() => {
1380
+ const d = o.value.filter((m) => !a.has(m.name));
1381
+ return [...n, ...d];
1382
+ }), i = O(
1383
+ () => Ae(c.value, l.value)
1384
+ ), f = O(
1385
+ () => kt({
1386
+ variants: c.value,
1387
+ productOptions: e.options,
1388
+ selectedOptions: o.value,
1389
+ breakoutOptions: n,
1390
+ breakoutNames: a
1391
+ })
1392
+ ), g = O(() => e.options.find((m) => m.swatch)?.name ?? null), p = O(() => {
1393
+ const d = g.value;
1394
+ if (!d) return /* @__PURE__ */ new Map();
1395
+ const m = /* @__PURE__ */ new Map();
1396
+ for (const E of c.value) {
1397
+ const _ = E.selectedOptions.find((S) => S.name === d);
1398
+ _ && m.set(E.numericId, _.value);
2269
1399
  }
2270
- for (const T of P.values())
2271
- T.sort((I, C) => I.position - C.position);
2272
- O.sort((T, I) => T.position - I.position);
2273
- const w = [];
2274
- S && P.has(S) && w.push(...P.get(S));
2275
- for (const T of _)
2276
- T !== S && P.has(T) && w.push(...P.get(T));
2277
- return w.push(...O), w;
2278
- }), E = N(() => {
2279
- const m = g.value;
2280
- if (!m?.image) return y.value;
2281
- if (!u.value) return m.image ? [m.image] : y.value;
2282
- const F = f.value.get(m.numericId);
2283
- return F ? y.value.filter((S) => S.variantIds.length === 0 ? !1 : S.variantIds.some(
2284
- (P) => f.value.get(P) === F
2285
- )) : m.image ? [m.image] : y.value;
2286
- }), M = N(() => y.value), A = N(() => {
2287
- const m = new Set(c.value.map((_) => _.name));
2288
- return p.value.every((_) => m.has(_));
2289
- }), R = N(() => {
2290
- const m = g.value;
2291
- if (!m?.image) return 0;
2292
- const _ = E.value.findIndex((F) => F.url === m.image?.url);
2293
- return Math.max(0, _);
1400
+ return m;
1401
+ }), v = O(() => {
1402
+ const d = g.value;
1403
+ return d ? e.options.filter((m) => m.name === d).map((m) => m.value) : [];
1404
+ }), I = O(
1405
+ () => Ot({
1406
+ images: e.images,
1407
+ swatchValues: v.value,
1408
+ variantSwatchMap: p.value,
1409
+ selectedVariantId: i.value?.numericId ?? null
1410
+ })
1411
+ ), y = O(() => {
1412
+ const d = i.value;
1413
+ if (!d?.image) return I.value;
1414
+ if (!g.value) return d.image ? [d.image] : I.value;
1415
+ const E = p.value.get(d.numericId);
1416
+ return E ? I.value.filter((_) => _.variantIds.length === 0 ? !0 : _.variantIds.some(
1417
+ (S) => p.value.get(S) === E
1418
+ )) : d.image ? [d.image] : I.value;
1419
+ }), R = O(() => {
1420
+ const d = i.value;
1421
+ if (!d) return { price: null, compareAtPrice: null, isOnSale: !1 };
1422
+ const m = d.compareAtPrice !== null && d.compareAtPrice.amount > d.price.amount;
1423
+ return { price: d.price, compareAtPrice: d.compareAtPrice, isOnSale: m };
1424
+ }), T = O(() => {
1425
+ const d = c.value;
1426
+ if (d.length === 0)
1427
+ return { priceRange: e.priceRange, compareAtPriceRange: null };
1428
+ const m = d.map((h) => h.price), E = m.reduce((h, A) => h.amount < A.amount ? h : A), _ = m.reduce((h, A) => h.amount > A.amount ? h : A), S = d.map((h) => h.compareAtPrice).filter((h) => h !== null), C = S.length > 0 ? {
1429
+ min: S.reduce((h, A) => h.amount < A.amount ? h : A),
1430
+ max: S.reduce((h, A) => h.amount > A.amount ? h : A)
1431
+ } : null;
1432
+ return { priceRange: { min: E, max: _ }, compareAtPriceRange: C };
1433
+ }), N = O(() => {
1434
+ const d = /* @__PURE__ */ new Set();
1435
+ for (const m of f.value) d.add(m.name);
1436
+ return d;
1437
+ }), w = O(() => {
1438
+ const d = new Set(l.value.map((m) => m.name));
1439
+ return [...N.value].every((m) => d.has(m));
1440
+ }), k = O(() => {
1441
+ const d = s.value;
1442
+ if (d !== null) return d;
1443
+ const m = i.value;
1444
+ if (!m?.image) return 1;
1445
+ const E = y.value.findIndex((_) => _.url === m.image?.url);
1446
+ return E >= 0 ? E + 1 : 1;
2294
1447
  });
2295
- function b(m) {
2296
- if (!m.image) return 0;
2297
- const _ = y.value.findIndex((F) => F.url === m.image?.url);
2298
- return Math.max(0, _);
2299
- }
2300
- return {
1448
+ return u.add(
1449
+ re(() => {
1450
+ o.value, s.value = null;
1451
+ })
1452
+ ), {
2301
1453
  product: e,
2302
1454
  // Reactive state
2303
- variants: s,
2304
- selectedVariant: g,
2305
- selectedOptions: c,
2306
- options: d,
2307
- optionNames: p,
2308
- swatchOptionName: u,
2309
- images: E,
2310
- allImages: M,
2311
- carouselIndex: R,
2312
- isSelectionComplete: A,
1455
+ variants: c,
1456
+ selectedVariant: i,
1457
+ options: f,
1458
+ images: y,
1459
+ price: R,
1460
+ priceRange: T,
1461
+ carouselPosition: k,
1462
+ isSelectionComplete: w,
2313
1463
  // Actions
2314
- selectOption(m, _) {
2315
- const S = a.value.filter((P) => P.name !== m).concat({ name: m, value: _ });
2316
- a.value = S;
2317
- },
2318
- setSelectedOptions(m) {
2319
- const _ = new Set(m.map((S) => S.name)), F = a.value.filter((S) => !_.has(S.name));
2320
- a.value = [...F, ...m];
1464
+ selectOption(d) {
1465
+ const m = o.value;
1466
+ o.value = m.filter((E) => E.name !== d.name).concat(d);
2321
1467
  },
2322
- setBreakoutOptions(m) {
2323
- i.value = m;
1468
+ setSelectedOptions(d) {
1469
+ const m = new Set(d.map((_) => _.name)), E = o.value.filter((_) => !m.has(_.name));
1470
+ o.value = [...E, ...d];
2324
1471
  },
2325
- // Queries
2326
- getOptionValues(m) {
2327
- return cn(s.value, m);
1472
+ setSelectedVariant(d) {
1473
+ const m = c.value.find((_) => _.numericId === d);
1474
+ if (!m) return;
1475
+ const E = m.selectedOptions.filter((_) => !a.has(_.name));
1476
+ o.value = E;
2328
1477
  },
2329
- getSwatches(m) {
2330
- return d.value.filter((_) => _.name === m && _.swatch).map((_) => _.swatch);
1478
+ setCarouselPosition(d) {
1479
+ s.value = d;
2331
1480
  },
2332
- getVariantByOptions(m) {
2333
- const _ = [...i.value, ...m];
2334
- return W(s.value, _);
2335
- },
2336
- getCarouselIndexForVariant: b,
2337
- isOptionAvailable(m, _) {
2338
- const F = a.value.filter((O) => O.name !== m).concat({ name: m, value: _ }), S = [...i.value, ...F];
2339
- return W(s.value, S)?.availableForSale ?? !1;
2340
- },
2341
- isVariantAvailable(m) {
2342
- return m.availableForSale;
2343
- },
2344
- getOptionAvailabilityStatus(m, _) {
2345
- const F = a.value.filter((O) => O.name !== m).concat({ name: m, value: _ }), S = [...i.value, ...F], P = W(s.value, S);
2346
- return P ? P.availableForSale ? "available" : P.inventoryPolicy === "CONTINUE" ? "backorderable" : "sold-out" : "unavailable";
1481
+ subscribe(d) {
1482
+ return u.add(
1483
+ re(() => {
1484
+ d({
1485
+ variants: c.value,
1486
+ selectedVariant: i.value,
1487
+ options: f.value,
1488
+ images: y.value,
1489
+ price: R.value,
1490
+ priceRange: T.value,
1491
+ carouselPosition: k.value,
1492
+ isSelectionComplete: w.value
1493
+ });
1494
+ })
1495
+ );
2347
1496
  },
2348
1497
  dispose() {
1498
+ u.clear();
2349
1499
  }
2350
1500
  };
2351
1501
  }
2352
- function an(e, t) {
1502
+ function Tt(e, t) {
2353
1503
  return t.length === 0 ? e : e.filter(
2354
- (n) => t.every(
2355
- (o) => n.selectedOptions.some((r) => r.name === o.name && r.value === o.value)
1504
+ (r) => t.every(
1505
+ (n) => r.selectedOptions.some((a) => a.name === n.name && a.value === n.value)
2356
1506
  )
2357
1507
  );
2358
1508
  }
2359
- function W(e, t) {
2360
- return t.length === 0 ? e[0] ?? null : e.find(
2361
- (n) => t.every(
2362
- (o) => n.selectedOptions.some((r) => r.name === o.name && r.value === o.value)
1509
+ function Ae(e, t) {
1510
+ return t.length === 0 ? e.length === 1 ? e[0] : null : e.find(
1511
+ (r) => t.every(
1512
+ (n) => r.selectedOptions.some((a) => a.name === n.name && a.value === n.value)
2363
1513
  )
2364
1514
  ) ?? null;
2365
1515
  }
2366
- function sn(e, t, n) {
1516
+ function kt({
1517
+ variants: e,
1518
+ productOptions: t,
1519
+ selectedOptions: r,
1520
+ breakoutOptions: n,
1521
+ breakoutNames: a
1522
+ }) {
2367
1523
  const o = /* @__PURE__ */ new Set();
2368
- for (const r of e)
2369
- for (const a of r.selectedOptions)
2370
- n.has(a.name) || o.add(`${a.name}:${a.value}`);
2371
- return t.filter(
2372
- (r) => !n.has(r.name) && o.has(`${r.name}:${r.value}`)
2373
- );
1524
+ for (const i of e)
1525
+ for (const f of i.selectedOptions)
1526
+ a.has(f.name) || o.add(`${f.name}:${f.value}`);
1527
+ const s = /* @__PURE__ */ new Map();
1528
+ for (const i of t)
1529
+ i.swatch && s.set(`${i.name}:${i.value}`, i.swatch);
1530
+ const u = /* @__PURE__ */ new Set();
1531
+ for (const i of r) u.add(`${i.name}:${i.value}`);
1532
+ const c = /* @__PURE__ */ new Map(), l = [...n, ...r];
1533
+ for (const i of t) {
1534
+ if (a.has(i.name) || !o.has(`${i.name}:${i.value}`)) continue;
1535
+ c.has(i.name) || c.set(i.name, []);
1536
+ const f = l.filter((I) => I.name !== i.name).concat({ name: i.name, value: i.value }), g = [...n, ...f.filter((I) => !a.has(I.name))], p = Ae(e, g);
1537
+ let v;
1538
+ p ? p.availableForSale ? v = "available" : p.inventoryPolicy === "CONTINUE" ? v = "backorderable" : v = "sold-out" : v = "unavailable", c.get(i.name).push({
1539
+ value: i.value,
1540
+ status: v,
1541
+ selected: u.has(`${i.name}:${i.value}`),
1542
+ swatch: s.get(`${i.name}:${i.value}`) ?? null
1543
+ });
1544
+ }
1545
+ return Array.from(c.entries()).map(([i, f]) => ({ name: i, values: f }));
2374
1546
  }
2375
- function cn(e, t) {
2376
- const n = /* @__PURE__ */ new Set();
2377
- for (const o of e) {
2378
- const r = o.selectedOptions.find((a) => a.name === t);
2379
- r && n.add(r.value);
1547
+ function Ot({
1548
+ images: e,
1549
+ swatchValues: t,
1550
+ variantSwatchMap: r,
1551
+ selectedVariantId: n
1552
+ }) {
1553
+ if (t.length === 0)
1554
+ return [...e].sort((c, l) => c.position - l.position);
1555
+ const a = n !== null ? r.get(n) ?? null : null, o = /* @__PURE__ */ new Map(), s = [];
1556
+ for (const c of e) {
1557
+ if (c.variantIds.length === 0) {
1558
+ s.push(c);
1559
+ continue;
1560
+ }
1561
+ let l = null;
1562
+ for (const i of c.variantIds) {
1563
+ const f = r.get(i);
1564
+ if (f) {
1565
+ l = f;
1566
+ break;
1567
+ }
1568
+ }
1569
+ if (l) {
1570
+ const i = o.get(l) ?? [];
1571
+ i.push(c), o.set(l, i);
1572
+ } else
1573
+ s.push(c);
2380
1574
  }
2381
- return [...n];
1575
+ for (const c of o.values())
1576
+ c.sort((l, i) => l.position - i.position);
1577
+ s.sort((c, l) => c.position - l.position);
1578
+ const u = [];
1579
+ a && o.has(a) && u.push(...o.get(a));
1580
+ for (const c of t)
1581
+ c !== a && o.has(c) && u.push(...o.get(c));
1582
+ return u.push(...s), u;
1583
+ }
1584
+ function Yt(e, t = {}) {
1585
+ return new Promise((r, n) => {
1586
+ const a = new XMLHttpRequest();
1587
+ if (a.open(t.method || "GET", e, !0), t.headers) {
1588
+ const o = t.headers;
1589
+ for (const s in o) a.setRequestHeader(s, o[s]);
1590
+ }
1591
+ if (t.signal && (t.signal.addEventListener("abort", () => a.abort()), t.signal.aborted)) {
1592
+ n(new DOMException("Aborted", "AbortError"));
1593
+ return;
1594
+ }
1595
+ a.onload = () => {
1596
+ const o = new Headers();
1597
+ a.getAllResponseHeaders().trim().split(`\r
1598
+ `).forEach((s) => {
1599
+ const [u, ...c] = s.split(": ");
1600
+ u && o.append(u, c.join(": "));
1601
+ }), r(
1602
+ new Response(a.response, {
1603
+ status: a.status,
1604
+ statusText: a.statusText,
1605
+ headers: o
1606
+ })
1607
+ );
1608
+ }, a.onerror = () => n(new TypeError("Network request failed")), a.ontimeout = () => n(new DOMException("Timeout", "TimeoutError")), a.onabort = () => n(new DOMException("Aborted", "AbortError")), a.send(t.body);
1609
+ });
2382
1610
  }
2383
1611
  export {
2384
- $t as and,
2385
- wn as batch,
2386
- On as computed,
2387
- An as createProductCard,
2388
- Pn as createSdk,
2389
- Cn as effect,
2390
- gn as eq,
2391
- En as exists,
2392
- Sn as filter,
2393
- zt as getSdk,
2394
- _n as gt,
2395
- vn as gte,
2396
- pn as inValues,
2397
- Mn as isInitialized,
2398
- dn as isRetryable,
2399
- un as isSdkError,
2400
- fn as jsonFileAdapter,
2401
- Pt as localStorageAdapter,
2402
- yn as lt,
2403
- In as lte,
2404
- mn as notEq,
2405
- bn as notExists,
2406
- hn as notIn,
2407
- Fn as or,
2408
- kn as signal
1612
+ nt as and,
1613
+ Wt as batch,
1614
+ Zt as computed,
1615
+ Kt as createClient,
1616
+ Jt as createProductCard,
1617
+ en as effect,
1618
+ Pt as eq,
1619
+ Bt as exists,
1620
+ Lt as fileStorage,
1621
+ Ht as filter,
1622
+ jt as getClient,
1623
+ Ut as gt,
1624
+ Ft as gte,
1625
+ Mt as inValues,
1626
+ Ct as isClientError,
1627
+ Qt as isInitialized,
1628
+ Ve as isRetryable,
1629
+ ze as localStorageAdapter,
1630
+ $t as lt,
1631
+ Vt as lte,
1632
+ Dt as notEq,
1633
+ xt as notExists,
1634
+ qt as notIn,
1635
+ Gt as or,
1636
+ tn as signal,
1637
+ $ as subscribe,
1638
+ Yt as xhrFetch
2409
1639
  };