@konfiqo/storefront-sdk 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,711 @@
1
+ // src/errors.ts
2
+ var API_CODES = /* @__PURE__ */ new Set([
3
+ "store_not_found",
4
+ "origin_not_allowed",
5
+ "invalid_request",
6
+ "invalid_buyer_ip",
7
+ "catalog_unavailable",
8
+ "product_not_found",
9
+ "content_not_found",
10
+ "cart_not_found",
11
+ "variant_not_found",
12
+ "line_not_found",
13
+ "insufficient_stock",
14
+ "quantity_out_of_range",
15
+ "too_many_lines",
16
+ "invalid_shipping_option",
17
+ "cart_read_only",
18
+ "checkout_in_progress",
19
+ "checkout_incomplete",
20
+ "cart_changed",
21
+ "out_of_stock",
22
+ "amount_out_of_range",
23
+ "nothing_to_pay",
24
+ "invalid_buyer_details",
25
+ "payment_unavailable",
26
+ "checkout_unavailable",
27
+ "order_not_found",
28
+ "order_unavailable",
29
+ "media_not_found",
30
+ "media_unavailable",
31
+ "challenge_required",
32
+ "challenge_failed",
33
+ "challenge_unavailable",
34
+ "too_many_open_orders",
35
+ "not_signed_in",
36
+ "invalid_code",
37
+ "profile_required",
38
+ "too_many_code_requests",
39
+ "invalid_recovery_token",
40
+ "cart_not_recoverable",
41
+ "unavailable"
42
+ ]);
43
+ var ERROR_BRAND = /* @__PURE__ */ Symbol.for("@konfiqo/storefront-sdk/error");
44
+ var StorefrontError = class extends Error {
45
+ /** The API `error` code, or one of the SDK's own codes. */
46
+ code;
47
+ /** HTTP status; `0` when no response arrived (`network_error`, `timeout`). */
48
+ status;
49
+ /** The code's extras (see {@link StorefrontErrorDetailsMap}). */
50
+ details;
51
+ /**
52
+ * @param code - the error code
53
+ * @param status - the HTTP status (`0` without a response)
54
+ * @param message - a human-readable description (not for display logic)
55
+ * @param details - the code's extras
56
+ * @param options - `cause`: the underlying error, if any
57
+ */
58
+ constructor(code, status, message, details, options) {
59
+ super(message, options);
60
+ this.name = "StorefrontError";
61
+ this.code = code;
62
+ this.status = status;
63
+ this.details = details;
64
+ Object.defineProperty(this, ERROR_BRAND, { value: true });
65
+ }
66
+ /** Whether this error has `code`; narrows `details` to that code's extras. */
67
+ is(code) {
68
+ return this.code === code;
69
+ }
70
+ };
71
+ function isStorefrontError(e) {
72
+ return e instanceof StorefrontError || typeof e === "object" && e !== null && e[ERROR_BRAND] === true;
73
+ }
74
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
75
+ function parseRetryAfter(value) {
76
+ if (value === null) return void 0;
77
+ const trimmed = value.trim();
78
+ if (/^\d+$/.test(trimmed)) return Number(trimmed);
79
+ const at = Date.parse(trimmed);
80
+ if (Number.isNaN(at)) return void 0;
81
+ return Math.max(0, Math.ceil((at - Date.now()) / 1e3));
82
+ }
83
+ function errorFromResponse(status, body, headers) {
84
+ const b = isObject(body) ? body : {};
85
+ const message = typeof b.message === "string" && b.message !== "" ? b.message : `Storefront API request failed (HTTP ${status})`;
86
+ const error = typeof b.error === "string" ? b.error : null;
87
+ if (status === 429 && (error === null || !API_CODES.has(error))) {
88
+ const waits = [
89
+ parseRetryAfter(headers.get("retry-after")),
90
+ parseRetryAfter(headers.get("retry-after-ip"))
91
+ ].filter((w) => w !== void 0);
92
+ const retryAfter = waits.length > 0 ? Math.max(...waits) : void 0;
93
+ return new StorefrontError(
94
+ "rate_limited",
95
+ status,
96
+ message,
97
+ retryAfter === void 0 ? {} : { retryAfter }
98
+ );
99
+ }
100
+ if (error === null) {
101
+ if (status === 401)
102
+ return new StorefrontError("unauthorized", status, message, void 0);
103
+ return new StorefrontError("http_error", status, message, void 0);
104
+ }
105
+ if (!API_CODES.has(error)) {
106
+ return new StorefrontError("unknown_error", status, message, { error });
107
+ }
108
+ const code = error;
109
+ return apiError(code, status, message, b);
110
+ }
111
+ var arr = (v) => Array.isArray(v) ? v : [];
112
+ var n = (v) => typeof v === "number" ? v : 0;
113
+ function apiError(code, status, message, b) {
114
+ switch (code) {
115
+ case "cart_changed":
116
+ return new StorefrontError(code, status, message, {
117
+ lines: arr(b.lines),
118
+ subtotalMinor: n(b.subtotalMinor),
119
+ shippingMinor: n(b.shippingMinor),
120
+ totalMinor: n(b.totalMinor),
121
+ shippingOptions: arr(b.shippingOptions)
122
+ });
123
+ case "out_of_stock":
124
+ return new StorefrontError(code, status, message, {
125
+ variantIds: arr(b.variantIds)
126
+ });
127
+ case "checkout_incomplete":
128
+ return new StorefrontError(code, status, message, {
129
+ missing: arr(b.missing)
130
+ });
131
+ case "invalid_buyer_details":
132
+ return new StorefrontError(code, status, message, {
133
+ field: String(b.field ?? "")
134
+ });
135
+ case "insufficient_stock":
136
+ return new StorefrontError(code, status, message, {
137
+ available: n(b.available)
138
+ });
139
+ case "invalid_request":
140
+ return new StorefrontError(code, status, message, {
141
+ issues: arr(b.issues)
142
+ });
143
+ case "cart_read_only":
144
+ return new StorefrontError(code, status, message, {
145
+ status: b.status === "ordered" ? "ordered" : "expired"
146
+ });
147
+ default:
148
+ return new StorefrontError(
149
+ code,
150
+ status,
151
+ message,
152
+ void 0
153
+ );
154
+ }
155
+ }
156
+
157
+ // src/client.ts
158
+ var DEFAULT_TIMEOUT_MS = 15e3;
159
+ var PUBLISHABLE_KEY_HEADER = "x-konfiqo-publishable-key";
160
+ var STOREFRONT_KEY_HEADER = "x-konfiqo-storefront-key";
161
+ var SERVER_KEY_HEADER = "x-konfiqo-server-key";
162
+ var TURNSTILE_TOKEN_HEADER = "x-konfiqo-turnstile-token";
163
+ var BUYER_IP_HEADER = "x-konfiqo-buyer-ip";
164
+ function seg(v) {
165
+ if (typeof v !== "string" || v === "" || v === "." || v === "..") {
166
+ throw new TypeError(
167
+ `invalid_path_segment: ${JSON.stringify(v)} is not a valid path segment`
168
+ );
169
+ }
170
+ return encodeURIComponent(v);
171
+ }
172
+ function isBrowserLike() {
173
+ const g = globalThis;
174
+ return typeof window !== "undefined" || typeof document !== "undefined" || typeof self !== "undefined" && typeof g.importScripts === "function";
175
+ }
176
+ function createStorefrontClient(options) {
177
+ const baseUrl = options.baseUrl?.trim().replace(/\/+$/, "");
178
+ if (!baseUrl)
179
+ throw new TypeError("createStorefrontClient: baseUrl is required");
180
+ const publishableKey = options.publishableKey?.trim();
181
+ if (!publishableKey)
182
+ throw new TypeError("createStorefrontClient: publishableKey is required");
183
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
184
+ if (!(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {
185
+ throw new TypeError(
186
+ "createStorefrontClient: timeoutMs must be a positive number"
187
+ );
188
+ }
189
+ const baseHeaders = {
190
+ [PUBLISHABLE_KEY_HEADER]: publishableKey
191
+ };
192
+ if (options.serverKey !== void 0 && options.trustedStorefrontKey !== void 0) {
193
+ throw new TypeError(
194
+ "createStorefrontClient: serverKey and trustedStorefrontKey cannot be used together"
195
+ );
196
+ }
197
+ if (options.serverKey !== void 0) {
198
+ if (isBrowserLike()) {
199
+ throw new TypeError(
200
+ "createStorefrontClient: serverKey must never be used in a browser"
201
+ );
202
+ }
203
+ const buyerIp = options.buyerIp?.trim();
204
+ if (!buyerIp) {
205
+ throw new TypeError(
206
+ "createStorefrontClient: buyerIp is required with serverKey"
207
+ );
208
+ }
209
+ baseHeaders[SERVER_KEY_HEADER] = options.serverKey;
210
+ baseHeaders[BUYER_IP_HEADER] = buyerIp;
211
+ }
212
+ if (options.trustedStorefrontKey !== void 0) {
213
+ if (isBrowserLike()) {
214
+ throw new TypeError(
215
+ "createStorefrontClient: trustedStorefrontKey is server-only and must never be used in a browser"
216
+ );
217
+ }
218
+ const buyerIp = options.buyerIp?.trim();
219
+ if (!buyerIp) {
220
+ throw new TypeError(
221
+ "createStorefrontClient: buyerIp is required with trustedStorefrontKey"
222
+ );
223
+ }
224
+ baseHeaders[STOREFRONT_KEY_HEADER] = options.trustedStorefrontKey;
225
+ baseHeaders[BUYER_IP_HEADER] = buyerIp;
226
+ }
227
+ async function request(method, path, body, callOptions, extraHeaders = {}, flags = {}) {
228
+ const url = `${baseUrl}${path()}`;
229
+ const callerSignal = callOptions?.signal;
230
+ if (callerSignal?.aborted) throw abortError(callerSignal);
231
+ const doFetch = options.fetch ?? globalThis.fetch;
232
+ const headers = {
233
+ ...baseHeaders,
234
+ ...extraHeaders
235
+ };
236
+ if (callOptions?.cookie) headers.cookie = callOptions.cookie;
237
+ const init = { method, headers };
238
+ if (flags.credentials) init.credentials = "include";
239
+ if (body !== void 0) {
240
+ headers["content-type"] = "application/json";
241
+ init.body = JSON.stringify(body);
242
+ }
243
+ const controller = new AbortController();
244
+ init.signal = controller.signal;
245
+ let timedOut = false;
246
+ let onTimeout = () => {
247
+ };
248
+ const deadline = new Promise((_, reject) => {
249
+ onTimeout = reject;
250
+ });
251
+ deadline.catch(() => {
252
+ });
253
+ const timer = setTimeout(() => {
254
+ timedOut = true;
255
+ onTimeout(transportError(void 0, true, timeoutMs));
256
+ controller.abort();
257
+ }, timeoutMs);
258
+ const onCallerAbort = () => {
259
+ onTimeout(abortError(callerSignal));
260
+ controller.abort();
261
+ };
262
+ callerSignal?.addEventListener("abort", onCallerAbort, { once: true });
263
+ try {
264
+ let res;
265
+ let text;
266
+ try {
267
+ res = await Promise.race([doFetch(url, init), deadline]);
268
+ text = await Promise.race([res.text(), deadline]);
269
+ } catch (e) {
270
+ if (e instanceof StorefrontError) throw e;
271
+ throw transportError(e, timedOut, timeoutMs);
272
+ }
273
+ let parsed;
274
+ let isJson = false;
275
+ if (text !== "") {
276
+ try {
277
+ parsed = JSON.parse(text);
278
+ isJson = true;
279
+ } catch {
280
+ parsed = void 0;
281
+ }
282
+ }
283
+ if (!res.ok) throw errorFromResponse(res.status, parsed, res.headers);
284
+ if (!isJson && flags.emptyOk && text === "") return void 0;
285
+ if (!isJson) {
286
+ throw new StorefrontError(
287
+ "invalid_response",
288
+ res.status,
289
+ "Storefront API answered a non-JSON body",
290
+ void 0
291
+ );
292
+ }
293
+ return parsed;
294
+ } finally {
295
+ clearTimeout(timer);
296
+ callerSignal?.removeEventListener("abort", onCallerAbort);
297
+ }
298
+ }
299
+ const get = (path, options2) => request("GET", path, void 0, options2);
300
+ const acct = { credentials: true };
301
+ const send = (method, path, body, o, extra = {}, emptyOk = false) => request(method, () => path, body, o, extra, { ...acct, emptyOk });
302
+ const cart = (id) => `/v1/carts/${seg(id)}`;
303
+ return {
304
+ getContent: (key, o) => get(() => `/v1/content/${seg(key)}`, o),
305
+ store: {
306
+ get: (o) => get(() => "/v1/store", o)
307
+ },
308
+ categories: {
309
+ list: (o) => get(() => "/v1/categories", o)
310
+ },
311
+ products: {
312
+ list: (query = {}, o) => get(() => {
313
+ const params = new URLSearchParams();
314
+ if (query.category !== void 0)
315
+ params.set("category", query.category);
316
+ if (query.q !== void 0) params.set("q", query.q);
317
+ if (query.page !== void 0) params.set("page", String(query.page));
318
+ if (query.pageSize !== void 0)
319
+ params.set("pageSize", String(query.pageSize));
320
+ const qs = params.toString();
321
+ return `/v1/products${qs ? `?${qs}` : ""}`;
322
+ }, o),
323
+ get: (slug, o) => get(() => `/v1/products/${seg(slug)}`, o)
324
+ },
325
+ carts: {
326
+ create: (o) => request("POST", () => "/v1/carts", void 0, o),
327
+ recover: (token, o) => request(
328
+ "POST",
329
+ () => "/v1/carts/recover",
330
+ { token },
331
+ o
332
+ ),
333
+ get: (cartId, o) => get(() => cart(cartId), o),
334
+ addLine: (cartId, input, o) => request(
335
+ "POST",
336
+ () => `${cart(cartId)}/lines`,
337
+ { variantId: input.variantId, quantity: input.quantity },
338
+ o
339
+ ),
340
+ updateLine: (cartId, variantId, input, o) => request(
341
+ "PATCH",
342
+ () => `${cart(cartId)}/lines/${seg(variantId)}`,
343
+ { quantity: input.quantity },
344
+ o
345
+ ),
346
+ removeLine: (cartId, variantId, o) => request(
347
+ "DELETE",
348
+ () => `${cart(cartId)}/lines/${seg(variantId)}`,
349
+ void 0,
350
+ o
351
+ ),
352
+ setCustomer: (cartId, input, o) => request("PUT", () => `${cart(cartId)}/customer`, input, o),
353
+ setAddress: (cartId, input, o) => request("PUT", () => `${cart(cartId)}/address`, input, o),
354
+ shippingOptions: (cartId, o) => get(() => `${cart(cartId)}/shipping-options`, o),
355
+ setShippingOption: (cartId, optionId, o) => request(
356
+ "PUT",
357
+ () => `${cart(cartId)}/shipping-option`,
358
+ { id: optionId },
359
+ o
360
+ ),
361
+ checkout: (cartId, o) => request(
362
+ "POST",
363
+ () => `${cart(cartId)}/checkout`,
364
+ void 0,
365
+ o,
366
+ o?.turnstileToken ? { [TURNSTILE_TOKEN_HEADER]: o.turnstileToken } : {}
367
+ )
368
+ },
369
+ orders: {
370
+ get: (orderId, token, o) => get(
371
+ () => `/v1/orders/${seg(orderId)}?token=${encodeURIComponent(token)}`,
372
+ o
373
+ )
374
+ },
375
+ account: {
376
+ requestCode: (email, o) => send(
377
+ "POST",
378
+ "/v1/account/code",
379
+ { email },
380
+ o,
381
+ o?.turnstileToken ? { [TURNSTILE_TOKEN_HEADER]: o.turnstileToken } : {},
382
+ true
383
+ ),
384
+ signIn: (email, code, o) => send("POST", "/v1/account/session", { email, code }, o),
385
+ signOut: (o) => send("DELETE", "/v1/account/session", void 0, o, {}, true),
386
+ get: (page, o) => send(
387
+ "GET",
388
+ page === void 0 ? "/v1/account" : `/v1/account?page=${encodeURIComponent(String(page))}`,
389
+ void 0,
390
+ o
391
+ ),
392
+ updateProfile: (profile, o) => send(
393
+ "PUT",
394
+ "/v1/account/profile",
395
+ {
396
+ name: profile.name,
397
+ surname: profile.surname,
398
+ phone: profile.phone
399
+ },
400
+ o,
401
+ {},
402
+ true
403
+ ),
404
+ saveAddresses: async (addresses, o) => (await send(
405
+ "PUT",
406
+ "/v1/account/addresses",
407
+ { addresses },
408
+ o
409
+ )).addresses
410
+ },
411
+ media: {
412
+ url: (key) => `${baseUrl}/v1/media/${key.split("/").map(seg).join("/")}?pk=${encodeURIComponent(publishableKey)}`
413
+ }
414
+ };
415
+ }
416
+ function abortError(signal) {
417
+ return new StorefrontError(
418
+ "aborted",
419
+ 0,
420
+ "Storefront API request was aborted",
421
+ void 0,
422
+ { cause: signal.reason }
423
+ );
424
+ }
425
+ function transportError(e, timedOut, timeoutMs) {
426
+ if (timedOut) {
427
+ return new StorefrontError(
428
+ "timeout",
429
+ 0,
430
+ `Storefront API did not answer within ${timeoutMs} ms`,
431
+ { timeoutMs },
432
+ { cause: e }
433
+ );
434
+ }
435
+ return new StorefrontError(
436
+ "network_error",
437
+ 0,
438
+ "Storefront API could not be reached",
439
+ void 0,
440
+ {
441
+ cause: e
442
+ }
443
+ );
444
+ }
445
+
446
+ // src/theme.ts
447
+ var THEME_FONTS = [
448
+ "inter",
449
+ "roboto",
450
+ "open-sans",
451
+ "lato",
452
+ "poppins"
453
+ ];
454
+ var KNOWN_SECTION_TYPES = /* @__PURE__ */ new Set([
455
+ "hero",
456
+ "featuredProducts",
457
+ "categoryGrid",
458
+ "richText"
459
+ ]);
460
+ function isKnownThemeSection(section) {
461
+ return typeof section === "object" && section !== null && typeof section.type === "string" && KNOWN_SECTION_TYPES.has(section.type);
462
+ }
463
+
464
+ // src/payment.ts
465
+ var mounted = /* @__PURE__ */ new WeakMap();
466
+ function mountPayment(element, presentation, options = {}) {
467
+ switch (presentation.presentation) {
468
+ case "embedded":
469
+ return mountEmbedded(element, presentation.embed);
470
+ case "redirect": {
471
+ const url = presentation.url;
472
+ let protocol;
473
+ try {
474
+ protocol = new URL(url).protocol;
475
+ } catch {
476
+ protocol = "";
477
+ }
478
+ if (protocol !== "https:" && protocol !== "http:") {
479
+ throw new TypeError("mountPayment: redirect URL must be http(s)");
480
+ }
481
+ const view = element.ownerDocument.defaultView;
482
+ if (!view) throw new TypeError("mountPayment: element has no window");
483
+ view.location.assign(url);
484
+ return { kind: "redirect", url };
485
+ }
486
+ case "closed":
487
+ options.onClosed?.(presentation.page);
488
+ return { kind: "closed", page: presentation.page };
489
+ }
490
+ }
491
+ function mountEmbedded(element, embed) {
492
+ if (embed.kind !== "iyzico-checkout-form" || typeof embed.content !== "string") {
493
+ return { kind: "unsupported", embedKind: String(embed.kind) };
494
+ }
495
+ const content = embed.content;
496
+ const current = mounted.get(element);
497
+ if (current && current.content === content && current.nodes.every((n2) => n2.parentNode === element)) {
498
+ return { kind: "embedded", unmount: current.unmount };
499
+ }
500
+ element.replaceChildren();
501
+ element.innerHTML = content;
502
+ const doc = element.ownerDocument;
503
+ for (const inert of Array.from(element.querySelectorAll("script"))) {
504
+ const live = doc.createElement("script");
505
+ for (const attr of Array.from(inert.attributes)) {
506
+ live.setAttribute(attr.name, attr.value);
507
+ }
508
+ if (live.hasAttribute("src")) live.async = false;
509
+ live.text = inert.text;
510
+ inert.replaceWith(live);
511
+ }
512
+ const entry = {
513
+ content,
514
+ nodes: Array.from(element.childNodes),
515
+ unmount: () => {
516
+ if (mounted.get(element) !== entry) return;
517
+ for (const node of entry.nodes) node.parentNode?.removeChild(node);
518
+ mounted.delete(element);
519
+ }
520
+ };
521
+ mounted.set(element, entry);
522
+ return { kind: "embedded", unmount: entry.unmount };
523
+ }
524
+
525
+ // src/money.ts
526
+ function formatMoney(minor, currency, locale) {
527
+ if (typeof minor !== "number" || !Number.isFinite(minor)) {
528
+ throw new TypeError("formatMoney: minor must be a finite number");
529
+ }
530
+ const format = new Intl.NumberFormat(locale, { style: "currency", currency });
531
+ const digits = format.resolvedOptions().maximumFractionDigits ?? 2;
532
+ return format.format(minor / 10 ** digits);
533
+ }
534
+
535
+ // src/cart-storage.ts
536
+ function cartIdKey(storeId) {
537
+ return `storefront:cart:${storeId}`;
538
+ }
539
+ function loadCartId(storage, storeId) {
540
+ try {
541
+ const v = storage?.getItem(cartIdKey(storeId));
542
+ return typeof v === "string" && v.trim() !== "" ? v.trim() : null;
543
+ } catch {
544
+ return null;
545
+ }
546
+ }
547
+ function saveCartId(storage, storeId, cartId) {
548
+ if (!storage) return false;
549
+ try {
550
+ storage.setItem(cartIdKey(storeId), cartId);
551
+ return true;
552
+ } catch {
553
+ return false;
554
+ }
555
+ }
556
+ function clearCartId(storage, storeId) {
557
+ if (!storage) return false;
558
+ try {
559
+ storage.removeItem(cartIdKey(storeId));
560
+ return true;
561
+ } catch {
562
+ return false;
563
+ }
564
+ }
565
+ var CART_COOKIE = "__Host-konfiqo_cart";
566
+ var MAX_COOKIE_VALUE = 3500;
567
+ var COOKIE_MAX_AGE = 31536e3;
568
+ function readMap(doc) {
569
+ try {
570
+ for (const part of doc.cookie.split(";")) {
571
+ const p = part.trim();
572
+ if (!p.startsWith(`${CART_COOKIE}=`)) continue;
573
+ const parsed = JSON.parse(
574
+ decodeURIComponent(p.slice(CART_COOKIE.length + 1))
575
+ );
576
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
577
+ return {};
578
+ }
579
+ const out = {};
580
+ for (const [k, v] of Object.entries(parsed)) {
581
+ if (typeof v === "string") out[k] = v;
582
+ }
583
+ return out;
584
+ }
585
+ } catch {
586
+ }
587
+ return {};
588
+ }
589
+ function writeMap(doc, map) {
590
+ const attrs = "; Path=/; SameSite=Lax; Secure";
591
+ const keys = Object.keys(map);
592
+ if (keys.length === 0) {
593
+ doc.cookie = `${CART_COOKIE}=; Max-Age=0${attrs}`;
594
+ return true;
595
+ }
596
+ const value = encodeURIComponent(JSON.stringify(map));
597
+ if (value.length > MAX_COOKIE_VALUE) return false;
598
+ doc.cookie = `${CART_COOKIE}=${value}; Max-Age=${COOKIE_MAX_AGE}${attrs}`;
599
+ return true;
600
+ }
601
+ function cookieCartStorage(doc) {
602
+ const jar = () => doc === void 0 ? globalThis.document ?? null : doc;
603
+ return {
604
+ getItem(key) {
605
+ const d = jar();
606
+ if (!d) return null;
607
+ return readMap(d)[key] ?? null;
608
+ },
609
+ setItem(key, value) {
610
+ const d = jar();
611
+ if (!d) throw new Error("no document");
612
+ const map = readMap(d);
613
+ map[key] = value;
614
+ if (!writeMap(d, map)) throw new Error("cart cookie too large");
615
+ },
616
+ removeItem(key) {
617
+ const d = jar();
618
+ if (!d) return;
619
+ const map = readMap(d);
620
+ if (!(key in map)) return;
621
+ delete map[key];
622
+ writeMap(d, map);
623
+ }
624
+ };
625
+ }
626
+
627
+ // src/turnstile.ts
628
+ var TURNSTILE_SCRIPT_URL = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
629
+ var loading = /* @__PURE__ */ new WeakMap();
630
+ function loadTurnstile(document2) {
631
+ const view = document2.defaultView;
632
+ if (!view)
633
+ return Promise.reject(
634
+ new TypeError("loadTurnstile: document has no window")
635
+ );
636
+ if (view.turnstile) return Promise.resolve(view.turnstile);
637
+ const pending = loading.get(document2);
638
+ if (pending) return pending;
639
+ const promise = new Promise((resolve, reject) => {
640
+ let script = Array.from(document2.scripts).find(
641
+ (s) => s.src === TURNSTILE_SCRIPT_URL
642
+ );
643
+ if (!script) {
644
+ script = document2.createElement("script");
645
+ script.src = TURNSTILE_SCRIPT_URL;
646
+ script.async = true;
647
+ (document2.head ?? document2.documentElement).appendChild(script);
648
+ }
649
+ script.addEventListener("load", () => {
650
+ if (view.turnstile) resolve(view.turnstile);
651
+ else
652
+ reject(
653
+ new Error("loadTurnstile: script loaded without window.turnstile")
654
+ );
655
+ });
656
+ const tag = script;
657
+ tag.addEventListener("error", () => {
658
+ tag.remove();
659
+ reject(new Error("loadTurnstile: script failed to load"));
660
+ });
661
+ });
662
+ loading.set(document2, promise);
663
+ promise.catch(() => {
664
+ if (loading.get(document2) === promise) loading.delete(document2);
665
+ });
666
+ return promise;
667
+ }
668
+ async function renderTurnstile(element, siteKey, options) {
669
+ if (!siteKey) throw new TypeError("renderTurnstile: siteKey is required");
670
+ const turnstile = await loadTurnstile(element.ownerDocument);
671
+ const params = {
672
+ sitekey: siteKey,
673
+ callback: (token) => options.onToken(token),
674
+ "expired-callback": () => options.onExpired?.(),
675
+ "error-callback": (code) => options.onError?.(code)
676
+ };
677
+ const widgetId = turnstile.render(element, params);
678
+ if (!widgetId) throw new Error("renderTurnstile: the widget did not render");
679
+ return {
680
+ widgetId,
681
+ reset: () => turnstile.reset(widgetId),
682
+ remove: () => turnstile.remove(widgetId)
683
+ };
684
+ }
685
+
686
+ // src/index.ts
687
+ var SDK_VERSION = "0.4.0";
688
+ export {
689
+ BUYER_IP_HEADER,
690
+ DEFAULT_TIMEOUT_MS,
691
+ PUBLISHABLE_KEY_HEADER,
692
+ SDK_VERSION,
693
+ STOREFRONT_KEY_HEADER,
694
+ StorefrontError,
695
+ THEME_FONTS,
696
+ TURNSTILE_SCRIPT_URL,
697
+ TURNSTILE_TOKEN_HEADER,
698
+ cartIdKey,
699
+ clearCartId,
700
+ cookieCartStorage,
701
+ createStorefrontClient,
702
+ formatMoney,
703
+ isKnownThemeSection,
704
+ isStorefrontError,
705
+ loadCartId,
706
+ loadTurnstile,
707
+ mountPayment,
708
+ renderTurnstile,
709
+ saveCartId
710
+ };
711
+ //# sourceMappingURL=index.js.map