@cimplify/sdk 0.6.5 → 0.6.7

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/react.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { createContext, useContext, useState, useEffect, useRef, useMemo, useCallback } from 'react';
1
+ import { createContext, useContext, useState, useEffect, useRef, useMemo, useCallback, useSyncExternalStore } from 'react';
2
2
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
3
3
 
4
4
  // src/react/index.tsx
@@ -9,6 +9,27 @@ var ELEMENT_TYPES = {
9
9
  ADDRESS: "address",
10
10
  PAYMENT: "payment"
11
11
  };
12
+ var MESSAGE_TYPES = {
13
+ // Parent → Iframe
14
+ INIT: "init",
15
+ SET_TOKEN: "set_token",
16
+ GET_DATA: "get_data",
17
+ PROCESS_CHECKOUT: "process_checkout",
18
+ ABORT_CHECKOUT: "abort_checkout",
19
+ // Iframe → Parent
20
+ READY: "ready",
21
+ HEIGHT_CHANGE: "height_change",
22
+ AUTHENTICATED: "authenticated",
23
+ REQUIRES_OTP: "requires_otp",
24
+ ERROR: "error",
25
+ ADDRESS_CHANGED: "address_changed",
26
+ ADDRESS_SELECTED: "address_selected",
27
+ PAYMENT_METHOD_SELECTED: "payment_method_selected",
28
+ TOKEN_REFRESHED: "token_refreshed",
29
+ LOGOUT_COMPLETE: "logout_complete",
30
+ CHECKOUT_STATUS: "checkout_status",
31
+ CHECKOUT_COMPLETE: "checkout_complete"
32
+ };
12
33
  var EVENT_TYPES = {
13
34
  READY: "ready",
14
35
  AUTHENTICATED: "authenticated",
@@ -362,6 +383,7 @@ function CimplifyCheckout({
362
383
  onError,
363
384
  onStatusChange,
364
385
  appearance,
386
+ demoMode,
365
387
  className
366
388
  }) {
367
389
  const resolvedOrderTypes = useMemo(
@@ -370,20 +392,131 @@ function CimplifyCheckout({
370
392
  );
371
393
  const [orderType, setOrderType] = useState(resolvedOrderTypes[0] || "pickup");
372
394
  const [status, setStatus] = useState(null);
395
+ const [statusText, setStatusText] = useState("");
373
396
  const [isSubmitting, setIsSubmitting] = useState(false);
397
+ const [isInitializing, setIsInitializing] = useState(false);
374
398
  const [errorMessage, setErrorMessage] = useState(null);
399
+ const [resolvedBusinessId, setResolvedBusinessId] = useState(businessId ?? null);
400
+ const [resolvedCartId, setResolvedCartId] = useState(cartId ?? null);
375
401
  const authMountRef = useRef(null);
376
402
  const addressMountRef = useRef(null);
377
403
  const paymentMountRef = useRef(null);
378
404
  const elementsRef = useRef(null);
379
405
  const activeCheckoutRef = useRef(null);
406
+ const initialAppearanceRef = useRef(appearance);
407
+ const hasWarnedInlineAppearanceRef = useRef(false);
408
+ const isMountedRef = useRef(true);
409
+ const demoRunRef = useRef(0);
410
+ const isDemoCheckout = demoMode ?? client.getPublicKey().trim().length === 0;
411
+ const isTestMode = client.isTestMode();
412
+ const emitStatus = useCallback(
413
+ (nextStatus, context = {}) => {
414
+ setStatus(nextStatus);
415
+ setStatusText(context.display_text || "");
416
+ onStatusChange?.(nextStatus, context);
417
+ },
418
+ [onStatusChange]
419
+ );
380
420
  useEffect(() => {
381
421
  if (!resolvedOrderTypes.includes(orderType)) {
382
422
  setOrderType(resolvedOrderTypes[0] || "pickup");
383
423
  }
384
424
  }, [resolvedOrderTypes, orderType]);
385
425
  useEffect(() => {
386
- const elements = client.elements(businessId, { appearance });
426
+ if (appearance && appearance !== initialAppearanceRef.current && !hasWarnedInlineAppearanceRef.current) {
427
+ hasWarnedInlineAppearanceRef.current = true;
428
+ console.warn(
429
+ "[Cimplify] `appearance` prop reference changed after mount. Elements keep the initial appearance to avoid iframe remount. Memoize appearance with useMemo() to remove this warning."
430
+ );
431
+ }
432
+ }, [appearance]);
433
+ useEffect(() => {
434
+ let cancelled = false;
435
+ async function bootstrap() {
436
+ if (isDemoCheckout) {
437
+ if (!cancelled) {
438
+ setResolvedBusinessId(businessId ?? null);
439
+ setResolvedCartId(cartId ?? "cart_demo");
440
+ setIsInitializing(false);
441
+ setErrorMessage(null);
442
+ }
443
+ return;
444
+ }
445
+ const needsBusinessResolve = !businessId;
446
+ const needsCartResolve = !cartId;
447
+ if (!needsBusinessResolve && !needsCartResolve) {
448
+ if (!cancelled) {
449
+ setResolvedBusinessId(businessId || null);
450
+ setResolvedCartId(cartId || null);
451
+ setIsInitializing(false);
452
+ setErrorMessage(null);
453
+ }
454
+ return;
455
+ }
456
+ if (!cancelled) {
457
+ setIsInitializing(true);
458
+ setErrorMessage(null);
459
+ }
460
+ let nextBusinessId = businessId ?? null;
461
+ if (!nextBusinessId) {
462
+ try {
463
+ nextBusinessId = await client.resolveBusinessId();
464
+ } catch {
465
+ if (!cancelled) {
466
+ const message = "Unable to initialize checkout business context.";
467
+ setResolvedBusinessId(null);
468
+ setResolvedCartId(null);
469
+ setErrorMessage(message);
470
+ setIsInitializing(false);
471
+ onError?.({ code: "BUSINESS_ID_REQUIRED", message });
472
+ }
473
+ return;
474
+ }
475
+ }
476
+ let nextCartId = cartId ?? null;
477
+ if (!nextCartId) {
478
+ const cartResult = await client.cart.get();
479
+ if (!cartResult.ok || !cartResult.value?.id || cartResult.value.items.length === 0) {
480
+ if (!cancelled) {
481
+ const message = "Your cart is empty. Add items before checkout.";
482
+ setResolvedBusinessId(nextBusinessId);
483
+ setResolvedCartId(null);
484
+ setErrorMessage(message);
485
+ setIsInitializing(false);
486
+ onError?.({ code: "CART_EMPTY", message });
487
+ }
488
+ return;
489
+ }
490
+ nextCartId = cartResult.value.id;
491
+ }
492
+ if (!cancelled) {
493
+ setResolvedBusinessId(nextBusinessId);
494
+ setResolvedCartId(nextCartId);
495
+ setIsInitializing(false);
496
+ setErrorMessage(null);
497
+ }
498
+ }
499
+ void bootstrap();
500
+ return () => {
501
+ cancelled = true;
502
+ };
503
+ }, [businessId, cartId, client, isDemoCheckout, onError]);
504
+ useEffect(() => {
505
+ return () => {
506
+ isMountedRef.current = false;
507
+ demoRunRef.current += 1;
508
+ activeCheckoutRef.current?.abort();
509
+ activeCheckoutRef.current = null;
510
+ };
511
+ }, []);
512
+ useEffect(() => {
513
+ if (isDemoCheckout || !resolvedBusinessId) {
514
+ elementsRef.current = null;
515
+ return;
516
+ }
517
+ const elements = client.elements(resolvedBusinessId, {
518
+ appearance: initialAppearanceRef.current
519
+ });
387
520
  elementsRef.current = elements;
388
521
  const auth = elements.create("auth");
389
522
  const address = elements.create("address", { mode: "shipping" });
@@ -403,27 +536,68 @@ function CimplifyCheckout({
403
536
  elements.destroy();
404
537
  elementsRef.current = null;
405
538
  };
406
- }, [client, businessId, appearance]);
407
- const handleStatusChange = useCallback(
408
- (nextStatus, context) => {
409
- setStatus(nextStatus);
410
- onStatusChange?.(nextStatus, context);
411
- },
412
- [onStatusChange]
413
- );
539
+ }, [client, resolvedBusinessId, isDemoCheckout]);
414
540
  const handleSubmit = useCallback(async () => {
415
- if (!elementsRef.current || isSubmitting) {
541
+ if (isSubmitting || isInitializing || !resolvedCartId) {
542
+ if (!resolvedCartId && !isInitializing) {
543
+ const message = "Your cart is empty. Add items before checkout.";
544
+ setErrorMessage(message);
545
+ onError?.({ code: "CART_EMPTY", message });
546
+ }
416
547
  return;
417
548
  }
418
549
  setErrorMessage(null);
419
550
  setIsSubmitting(true);
420
- setStatus("preparing");
551
+ emitStatus("preparing", { display_text: statusToLabel("preparing") });
552
+ if (isDemoCheckout) {
553
+ const runId = demoRunRef.current + 1;
554
+ demoRunRef.current = runId;
555
+ const wait = async (ms) => {
556
+ await new Promise((resolve) => setTimeout(resolve, ms));
557
+ return isMountedRef.current && runId === demoRunRef.current;
558
+ };
559
+ try {
560
+ if (!await wait(400)) return;
561
+ emitStatus("processing", { display_text: statusToLabel("processing") });
562
+ if (!await wait(900)) return;
563
+ emitStatus("polling", { display_text: statusToLabel("polling") });
564
+ if (!await wait(1200)) return;
565
+ const result = {
566
+ success: true,
567
+ order: {
568
+ id: `ord_demo_${Date.now()}`,
569
+ order_number: `DEMO-${Math.random().toString(36).slice(2, 8).toUpperCase()}`,
570
+ status: "confirmed",
571
+ total: "0.00",
572
+ currency: "USD"
573
+ }
574
+ };
575
+ emitStatus("success", {
576
+ order_id: result.order?.id,
577
+ order_number: result.order?.order_number,
578
+ display_text: statusToLabel("success")
579
+ });
580
+ onComplete(result);
581
+ } finally {
582
+ if (isMountedRef.current && runId === demoRunRef.current) {
583
+ setIsSubmitting(false);
584
+ }
585
+ }
586
+ return;
587
+ }
588
+ if (!elementsRef.current) {
589
+ const message = "Checkout is still initializing. Please try again.";
590
+ setErrorMessage(message);
591
+ onError?.({ code: "CHECKOUT_NOT_READY", message });
592
+ setIsSubmitting(false);
593
+ return;
594
+ }
421
595
  const checkout = elementsRef.current.processCheckout({
422
- cart_id: cartId,
423
- location_id: locationId,
596
+ cart_id: resolvedCartId,
597
+ location_id: locationId ?? client.getLocationId() ?? void 0,
424
598
  order_type: orderType,
425
599
  enroll_in_link: enrollInLink,
426
- on_status_change: handleStatusChange
600
+ on_status_change: emitStatus
427
601
  });
428
602
  activeCheckoutRef.current = checkout;
429
603
  try {
@@ -437,21 +611,45 @@ function CimplifyCheckout({
437
611
  setErrorMessage(message);
438
612
  onError?.({ code, message });
439
613
  } finally {
440
- activeCheckoutRef.current = null;
441
- setIsSubmitting(false);
614
+ if (isMountedRef.current) {
615
+ activeCheckoutRef.current = null;
616
+ setIsSubmitting(false);
617
+ }
442
618
  }
443
619
  }, [
444
- cartId,
620
+ resolvedCartId,
621
+ client,
445
622
  enrollInLink,
446
- handleStatusChange,
623
+ emitStatus,
624
+ isDemoCheckout,
625
+ isInitializing,
447
626
  isSubmitting,
448
627
  locationId,
449
628
  onComplete,
450
629
  onError,
451
630
  orderType
452
631
  ]);
632
+ if (isInitializing) {
633
+ return /* @__PURE__ */ jsx("div", { className, "data-cimplify-checkout": "", children: /* @__PURE__ */ jsx("p", { "data-cimplify-status": "", style: { fontSize: "14px", color: "#52525b" }, children: "Preparing checkout..." }) });
634
+ }
635
+ if (!isDemoCheckout && (!resolvedBusinessId || !resolvedCartId)) {
636
+ return /* @__PURE__ */ jsx("div", { className, "data-cimplify-checkout": "", children: /* @__PURE__ */ jsx("p", { "data-cimplify-error": "", style: { fontSize: "14px", color: "#b91c1c" }, children: errorMessage || "Unable to initialize checkout. Please refresh and try again." }) });
637
+ }
453
638
  return /* @__PURE__ */ jsxs("div", { className, "data-cimplify-checkout": "", children: [
454
- /* @__PURE__ */ jsx("div", { "data-cimplify-section": "auth", children: /* @__PURE__ */ jsx("div", { ref: authMountRef }) }),
639
+ isTestMode && !isDemoCheckout && /* @__PURE__ */ jsx(
640
+ "p",
641
+ {
642
+ "data-cimplify-test-mode": "",
643
+ style: {
644
+ marginBottom: "10px",
645
+ fontSize: "12px",
646
+ fontWeight: 600,
647
+ color: "#92400e"
648
+ },
649
+ children: "Test mode - no real charges"
650
+ }
651
+ ),
652
+ /* @__PURE__ */ jsx("div", { "data-cimplify-section": "auth", children: /* @__PURE__ */ jsx("div", { ref: isDemoCheckout ? void 0 : authMountRef }) }),
455
653
  /* @__PURE__ */ jsx("div", { "data-cimplify-section": "order-type", style: { marginTop: "12px" }, children: /* @__PURE__ */ jsx(
456
654
  "div",
457
655
  {
@@ -485,10 +683,10 @@ function CimplifyCheckout({
485
683
  {
486
684
  "data-cimplify-section": "address",
487
685
  style: { marginTop: "12px", display: orderType === "delivery" ? "block" : "none" },
488
- children: /* @__PURE__ */ jsx("div", { ref: addressMountRef })
686
+ children: /* @__PURE__ */ jsx("div", { ref: isDemoCheckout ? void 0 : addressMountRef })
489
687
  }
490
688
  ),
491
- /* @__PURE__ */ jsx("div", { "data-cimplify-section": "payment", style: { marginTop: "12px" }, children: /* @__PURE__ */ jsx("div", { ref: paymentMountRef }) }),
689
+ /* @__PURE__ */ jsx("div", { "data-cimplify-section": "payment", style: { marginTop: "12px" }, children: /* @__PURE__ */ jsx("div", { ref: isDemoCheckout ? void 0 : paymentMountRef }) }),
492
690
  /* @__PURE__ */ jsx("div", { style: { marginTop: "12px" }, children: /* @__PURE__ */ jsx(
493
691
  "button",
494
692
  {
@@ -507,34 +705,4433 @@ function CimplifyCheckout({
507
705
  children: isSubmitting ? "Processing..." : "Complete Order"
508
706
  }
509
707
  ) }),
510
- status && /* @__PURE__ */ jsx("p", { "data-cimplify-status": "", style: { marginTop: "10px", fontSize: "14px", color: "#52525b" }, children: statusToLabel(status) }),
708
+ status && /* @__PURE__ */ jsx("p", { "data-cimplify-status": "", style: { marginTop: "10px", fontSize: "14px", color: "#52525b" }, children: statusText || statusToLabel(status) }),
511
709
  errorMessage && /* @__PURE__ */ jsx("p", { "data-cimplify-error": "", style: { marginTop: "8px", fontSize: "14px", color: "#b91c1c" }, children: errorMessage })
512
710
  ] });
513
711
  }
514
- var ElementsContext = createContext({
515
- elements: null,
516
- isReady: false
517
- });
518
- function useElements() {
519
- return useContext(ElementsContext).elements;
712
+
713
+ // src/types/common.ts
714
+ var ErrorCode = {
715
+ // General
716
+ UNKNOWN_ERROR: "UNKNOWN_ERROR",
717
+ NETWORK_ERROR: "NETWORK_ERROR",
718
+ TIMEOUT: "TIMEOUT",
719
+ UNAUTHORIZED: "UNAUTHORIZED",
720
+ NOT_FOUND: "NOT_FOUND"};
721
+ var DOCS_ERROR_BASE_URL = "https://docs.cimplify.io/reference/error-codes";
722
+ function docsUrlForCode(code) {
723
+ return `${DOCS_ERROR_BASE_URL}#${code.toLowerCase().replace(/_/g, "-")}`;
520
724
  }
521
- function useElementsReady() {
522
- return useContext(ElementsContext).isReady;
725
+ var ERROR_SUGGESTIONS = {
726
+ UNKNOWN_ERROR: "An unexpected error occurred. Capture the request/response payload and retry with exponential backoff.",
727
+ NETWORK_ERROR: "Check the shopper's connection and retry. If this persists, inspect CORS, DNS, and API reachability.",
728
+ TIMEOUT: "The request exceeded the timeout. Retry once, then poll order status before charging again.",
729
+ UNAUTHORIZED: "Authentication is missing or expired. Ensure a valid access token is set and refresh the session if needed.",
730
+ FORBIDDEN: "The key/session lacks permission for this resource. Verify business ownership and API key scope.",
731
+ NOT_FOUND: "The requested resource does not exist or is not visible in this environment.",
732
+ VALIDATION_ERROR: "One or more fields are invalid. Validate required fields and enum values before retrying.",
733
+ CART_EMPTY: "The cart has no items. Redirect back to menu/catalogue and require at least one line item.",
734
+ CART_EXPIRED: "This cart is no longer active. Recreate a new cart and re-add shopper selections.",
735
+ CART_NOT_FOUND: "Cart could not be located. It may have expired or belongs to a different key/location.",
736
+ ITEM_UNAVAILABLE: "The selected item is unavailable at this location/time. Prompt the shopper to pick an alternative.",
737
+ VARIANT_NOT_FOUND: "The requested variant no longer exists. Refresh product data and require re-selection.",
738
+ VARIANT_OUT_OF_STOCK: "The selected variant is out of stock. Show in-stock variants and block checkout for this line.",
739
+ ADDON_REQUIRED: "A required add-on is missing. Ensure required modifier groups are completed before add-to-cart.",
740
+ ADDON_MAX_EXCEEDED: "Too many add-ons were selected. Enforce max selections client-side before submission.",
741
+ CHECKOUT_VALIDATION_FAILED: "Checkout payload failed validation. Verify customer, order type, and address fields are complete.",
742
+ DELIVERY_ADDRESS_REQUIRED: "Delivery orders require an address. Collect and pass address info before processing checkout.",
743
+ CUSTOMER_INFO_REQUIRED: "Customer details are required. Ensure name/email/phone are available before checkout.",
744
+ PAYMENT_FAILED: "Payment provider rejected or failed processing. Show retry/change-method options to the shopper.",
745
+ PAYMENT_CANCELLED: "Payment was cancelled by the shopper or provider flow. Allow a safe retry path.",
746
+ INSUFFICIENT_FUNDS: "Payment method has insufficient funds. Prompt shopper to use another method.",
747
+ CARD_DECLINED: "Card was declined. Ask shopper to retry or switch payment method.",
748
+ INVALID_OTP: "Authorization code is invalid. Let shopper re-enter OTP/PIN and retry.",
749
+ OTP_EXPIRED: "Authorization code expired. Request a new OTP and re-submit authorization.",
750
+ AUTHORIZATION_FAILED: "Additional payment authorization failed. Retry authorization or change payment method.",
751
+ PAYMENT_ACTION_NOT_COMPLETED: "Required payment action was not completed. Resume provider flow and poll for status.",
752
+ SLOT_UNAVAILABLE: "Selected schedule slot is unavailable. Refresh available slots and ask shopper to reselect.",
753
+ BOOKING_CONFLICT: "The requested booking conflicts with an existing reservation. Pick another slot/resource.",
754
+ SERVICE_NOT_FOUND: "Requested service no longer exists. Refresh service catalogue and retry selection.",
755
+ OUT_OF_STOCK: "Inventory is depleted for this item. Remove it or reduce quantity before checkout.",
756
+ INSUFFICIENT_QUANTITY: "Requested quantity exceeds available inventory. Reduce quantity and retry.",
757
+ BUSINESS_ID_REQUIRED: "Business context could not be resolved. Verify the public key and business bootstrap call.",
758
+ INVALID_CART: "Cart is invalid for checkout. Sync cart state, ensure items exist, then retry.",
759
+ ORDER_TYPE_REQUIRED: "Order type is required. Provide one of delivery, pickup, or dine_in before checkout.",
760
+ NO_PAYMENT_ELEMENT: "PaymentElement is required for processCheckout(). Mount it before triggering checkout.",
761
+ PAYMENT_NOT_MOUNTED: "PaymentElement iframe is not mounted. Mount it in the DOM before processCheckout().",
762
+ AUTH_INCOMPLETE: "AuthElement has not completed authentication. Wait for AUTHENTICATED before checkout.",
763
+ AUTH_LOST: "Session was cleared during checkout. Re-authenticate and restart checkout safely.",
764
+ ALREADY_PROCESSING: "Checkout is already in progress. Disable duplicate submits until completion.",
765
+ CHECKOUT_NOT_READY: "Checkout elements are still initializing. Wait for readiness before submit.",
766
+ CANCELLED: "Checkout was cancelled. Preserve cart state and allow shopper to retry.",
767
+ REQUEST_TIMEOUT: "Provider call timed out. Poll payment/order status before issuing another charge attempt.",
768
+ POPUP_BLOCKED: "Browser blocked provider popup. Ask shopper to enable popups and retry.",
769
+ FX_QUOTE_FAILED: "Failed to lock FX quote. Retry currency quote or fallback to base currency."
770
+ };
771
+ var ERROR_HINTS = Object.fromEntries(
772
+ Object.entries(ERROR_SUGGESTIONS).map(([code, suggestion]) => [
773
+ code,
774
+ {
775
+ docs_url: docsUrlForCode(code),
776
+ suggestion
777
+ }
778
+ ])
779
+ );
780
+ var CimplifyError = class extends Error {
781
+ constructor(code, message, retryable = false, docs_url, suggestion) {
782
+ super(message);
783
+ this.code = code;
784
+ this.retryable = retryable;
785
+ this.docs_url = docs_url;
786
+ this.suggestion = suggestion;
787
+ this.name = "CimplifyError";
788
+ }
789
+ /** User-friendly message safe to display */
790
+ get userMessage() {
791
+ return this.message;
792
+ }
793
+ };
794
+ function getErrorHint(code) {
795
+ return ERROR_HINTS[code];
523
796
  }
524
- function ElementsProvider({
525
- client,
526
- businessId,
527
- options,
528
- children
529
- }) {
530
- const [elements, setElements] = useState(null);
531
- const [isReady, setIsReady] = useState(false);
532
- useEffect(() => {
533
- const instance = client.elements(businessId, options);
534
- setElements(instance);
535
- setIsReady(true);
536
- return () => instance.destroy();
537
- }, [client, businessId, options]);
797
+ function enrichError(error, options = {}) {
798
+ const hint = getErrorHint(error.code);
799
+ if (hint) {
800
+ if (!error.docs_url) {
801
+ error.docs_url = hint.docs_url;
802
+ }
803
+ if (!error.suggestion) {
804
+ error.suggestion = hint.suggestion;
805
+ }
806
+ } else if (!error.docs_url) {
807
+ error.docs_url = docsUrlForCode(error.code || ErrorCode.UNKNOWN_ERROR);
808
+ }
809
+ if (options.isTestMode && !error.message.includes("pk_test_")) {
810
+ error.message = `${error.message}
811
+
812
+ \u2139 Your API key is a test-mode key (pk_test_...). Verify test data/session before retrying.`;
813
+ }
814
+ return error;
815
+ }
816
+
817
+ // src/types/result.ts
818
+ function ok(value) {
819
+ return { ok: true, value };
820
+ }
821
+ function err(error) {
822
+ return { ok: false, error };
823
+ }
824
+
825
+ // src/catalogue.ts
826
+ function toCimplifyError(error) {
827
+ if (error instanceof CimplifyError) return enrichError(error);
828
+ if (error instanceof Error) {
829
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
830
+ }
831
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
832
+ }
833
+ async function safe(promise) {
834
+ try {
835
+ return ok(await promise);
836
+ } catch (error) {
837
+ return err(toCimplifyError(error));
838
+ }
839
+ }
840
+ function isRecord(value) {
841
+ return typeof value === "object" && value !== null;
842
+ }
843
+ function readFinalPrice(value) {
844
+ if (!isRecord(value)) return void 0;
845
+ const finalPrice = value.final_price;
846
+ if (typeof finalPrice === "string" || typeof finalPrice === "number") {
847
+ return finalPrice;
848
+ }
849
+ return void 0;
850
+ }
851
+ function normalizeCatalogueProductPayload(product) {
852
+ const normalized = { ...product };
853
+ const defaultPrice = normalized["default_price"];
854
+ if (defaultPrice === void 0 || defaultPrice === null || defaultPrice === "") {
855
+ const derivedDefaultPrice = readFinalPrice(normalized["default_price_info"]) || readFinalPrice(normalized["price_info"]) || (typeof normalized["final_price"] === "string" || typeof normalized["final_price"] === "number" ? normalized["final_price"] : void 0);
856
+ normalized["default_price"] = derivedDefaultPrice ?? "0";
857
+ }
858
+ const variants = normalized["variants"];
859
+ if (Array.isArray(variants)) {
860
+ normalized["variants"] = variants.map((variant) => {
861
+ if (!isRecord(variant)) return variant;
862
+ const normalizedVariant = { ...variant };
863
+ const variantAdjustment = normalizedVariant["price_adjustment"];
864
+ if (variantAdjustment === void 0 || variantAdjustment === null || variantAdjustment === "") {
865
+ normalizedVariant["price_adjustment"] = readFinalPrice(normalizedVariant["price_info"]) ?? "0";
866
+ }
867
+ return normalizedVariant;
868
+ });
869
+ }
870
+ const addOns = normalized["add_ons"];
871
+ if (Array.isArray(addOns)) {
872
+ normalized["add_ons"] = addOns.map((addOn) => {
873
+ if (!isRecord(addOn)) return addOn;
874
+ const normalizedAddOn = { ...addOn };
875
+ const options = normalizedAddOn["options"];
876
+ if (!Array.isArray(options)) return normalizedAddOn;
877
+ normalizedAddOn["options"] = options.map((option) => {
878
+ if (!isRecord(option)) return option;
879
+ const normalizedOption = { ...option };
880
+ const optionPrice = normalizedOption["default_price"];
881
+ if (optionPrice === void 0 || optionPrice === null || optionPrice === "") {
882
+ normalizedOption["default_price"] = readFinalPrice(normalizedOption["default_price_info"]) || readFinalPrice(normalizedOption["price_info"]) || "0";
883
+ }
884
+ return normalizedOption;
885
+ });
886
+ return normalizedAddOn;
887
+ });
888
+ }
889
+ return normalized;
890
+ }
891
+ function findProductBySlug(products, slug) {
892
+ return products.find((product) => {
893
+ const value = product["slug"];
894
+ return typeof value === "string" && value === slug;
895
+ });
896
+ }
897
+ var CatalogueQueries = class {
898
+ constructor(client) {
899
+ this.client = client;
900
+ }
901
+ async getProducts(options) {
902
+ let query = "products";
903
+ const filters = [];
904
+ if (options?.category) {
905
+ filters.push(`@.category_id=='${options.category}'`);
906
+ }
907
+ if (options?.featured !== void 0) {
908
+ filters.push(`@.featured==${options.featured}`);
909
+ }
910
+ if (options?.in_stock !== void 0) {
911
+ filters.push(`@.in_stock==${options.in_stock}`);
912
+ }
913
+ if (options?.search) {
914
+ filters.push(`@.name contains '${options.search}'`);
915
+ }
916
+ if (options?.min_price !== void 0) {
917
+ filters.push(`@.price>=${options.min_price}`);
918
+ }
919
+ if (options?.max_price !== void 0) {
920
+ filters.push(`@.price<=${options.max_price}`);
921
+ }
922
+ if (filters.length > 0) {
923
+ query += `[?(${filters.join(" && ")})]`;
924
+ }
925
+ if (options?.sort_by) {
926
+ query += `#sort(${options.sort_by},${options.sort_order || "asc"})`;
927
+ }
928
+ if (options?.limit) {
929
+ query += `#limit(${options.limit})`;
930
+ }
931
+ if (options?.offset) {
932
+ query += `#offset(${options.offset})`;
933
+ }
934
+ const result = await safe(this.client.query(query));
935
+ if (!result.ok) return result;
936
+ return ok(result.value.map((product) => normalizeCatalogueProductPayload(product)));
937
+ }
938
+ async getProduct(id) {
939
+ const result = await safe(this.client.query(`products.${id}`));
940
+ if (!result.ok) return result;
941
+ return ok(normalizeCatalogueProductPayload(result.value));
942
+ }
943
+ async getProductBySlug(slug) {
944
+ const filteredResult = await safe(
945
+ this.client.query(`products[?(@.slug=='${slug}')]`)
946
+ );
947
+ if (!filteredResult.ok) return filteredResult;
948
+ const exactMatch = findProductBySlug(filteredResult.value, slug);
949
+ if (exactMatch) {
950
+ return ok(normalizeCatalogueProductPayload(exactMatch));
951
+ }
952
+ if (filteredResult.value.length === 1) {
953
+ return ok(normalizeCatalogueProductPayload(filteredResult.value[0]));
954
+ }
955
+ const unfilteredResult = await safe(this.client.query("products"));
956
+ if (!unfilteredResult.ok) return unfilteredResult;
957
+ const fallbackMatch = findProductBySlug(unfilteredResult.value, slug);
958
+ if (!fallbackMatch) {
959
+ return err(new CimplifyError("NOT_FOUND", `Product not found: ${slug}`, false));
960
+ }
961
+ return ok(normalizeCatalogueProductPayload(fallbackMatch));
962
+ }
963
+ async getVariants(productId) {
964
+ return safe(this.client.query(`products.${productId}.variants`));
965
+ }
966
+ async getVariantAxes(productId) {
967
+ return safe(this.client.query(`products.${productId}.variant_axes`));
968
+ }
969
+ /**
970
+ * Find a variant by axis selections (e.g., { "Size": "Large", "Color": "Red" })
971
+ * Returns the matching variant or null if no match found.
972
+ */
973
+ async getVariantByAxisSelections(productId, selections) {
974
+ return safe(
975
+ this.client.query(`products.${productId}.variant`, {
976
+ axis_selections: selections
977
+ })
978
+ );
979
+ }
980
+ /**
981
+ * Get a specific variant by its ID
982
+ */
983
+ async getVariantById(productId, variantId) {
984
+ return safe(this.client.query(`products.${productId}.variant.${variantId}`));
985
+ }
986
+ async getAddOns(productId) {
987
+ return safe(this.client.query(`products.${productId}.add_ons`));
988
+ }
989
+ async getCategories() {
990
+ return safe(this.client.query("categories"));
991
+ }
992
+ async getCategory(id) {
993
+ return safe(this.client.query(`categories.${id}`));
994
+ }
995
+ async getCategoryBySlug(slug) {
996
+ const result = await safe(
997
+ this.client.query(`categories[?(@.slug=='${slug}')]`)
998
+ );
999
+ if (!result.ok) return result;
1000
+ if (!result.value.length) {
1001
+ return err(new CimplifyError("NOT_FOUND", `Category not found: ${slug}`, false));
1002
+ }
1003
+ return ok(result.value[0]);
1004
+ }
1005
+ async getCategoryProducts(categoryId) {
1006
+ return safe(this.client.query(`products[?(@.category_id=='${categoryId}')]`));
1007
+ }
1008
+ async getCollections() {
1009
+ return safe(this.client.query("collections"));
1010
+ }
1011
+ async getCollection(id) {
1012
+ return safe(this.client.query(`collections.${id}`));
1013
+ }
1014
+ async getCollectionBySlug(slug) {
1015
+ const result = await safe(
1016
+ this.client.query(`collections[?(@.slug=='${slug}')]`)
1017
+ );
1018
+ if (!result.ok) return result;
1019
+ if (!result.value.length) {
1020
+ return err(new CimplifyError("NOT_FOUND", `Collection not found: ${slug}`, false));
1021
+ }
1022
+ return ok(result.value[0]);
1023
+ }
1024
+ async getCollectionProducts(collectionId) {
1025
+ return safe(this.client.query(`collections.${collectionId}.products`));
1026
+ }
1027
+ async searchCollections(query, limit = 20) {
1028
+ return safe(
1029
+ this.client.query(`collections[?(@.name contains '${query}')]#limit(${limit})`)
1030
+ );
1031
+ }
1032
+ async getBundles() {
1033
+ return safe(this.client.query("bundles"));
1034
+ }
1035
+ async getBundle(id) {
1036
+ return safe(this.client.query(`bundles.${id}`));
1037
+ }
1038
+ async getBundleBySlug(slug) {
1039
+ const result = await safe(
1040
+ this.client.query(`bundles[?(@.slug=='${slug}')]`)
1041
+ );
1042
+ if (!result.ok) return result;
1043
+ if (!result.value.length) {
1044
+ return err(new CimplifyError("NOT_FOUND", `Bundle not found: ${slug}`, false));
1045
+ }
1046
+ return ok(result.value[0]);
1047
+ }
1048
+ async searchBundles(query, limit = 20) {
1049
+ return safe(
1050
+ this.client.query(`bundles[?(@.name contains '${query}')]#limit(${limit})`)
1051
+ );
1052
+ }
1053
+ async getComposites(options) {
1054
+ let query = "composites";
1055
+ if (options?.limit) {
1056
+ query += `#limit(${options.limit})`;
1057
+ }
1058
+ return safe(this.client.query(query));
1059
+ }
1060
+ async getComposite(id) {
1061
+ return safe(this.client.query(`composites.${id}`));
1062
+ }
1063
+ async getCompositeByProductId(productId) {
1064
+ return safe(this.client.query(`composites.by_product.${productId}`));
1065
+ }
1066
+ async calculateCompositePrice(compositeId, selections, locationId) {
1067
+ return safe(
1068
+ this.client.call("composite.calculatePrice", {
1069
+ composite_id: compositeId,
1070
+ selections,
1071
+ location_id: locationId
1072
+ })
1073
+ );
1074
+ }
1075
+ async fetchQuote(input) {
1076
+ return safe(this.client.call("catalogue.createQuote", input));
1077
+ }
1078
+ async getQuote(quoteId) {
1079
+ return safe(
1080
+ this.client.call("catalogue.getQuote", {
1081
+ quote_id: quoteId
1082
+ })
1083
+ );
1084
+ }
1085
+ async refreshQuote(input) {
1086
+ return safe(this.client.call("catalogue.refreshQuote", input));
1087
+ }
1088
+ async search(query, options) {
1089
+ const limit = options?.limit ?? 20;
1090
+ let searchQuery = `products[?(@.name contains '${query}')]`;
1091
+ if (options?.category) {
1092
+ searchQuery = `products[?(@.name contains '${query}' && @.category_id=='${options.category}')]`;
1093
+ }
1094
+ searchQuery += `#limit(${limit})`;
1095
+ return safe(this.client.query(searchQuery));
1096
+ }
1097
+ async searchProducts(query, options) {
1098
+ return safe(
1099
+ this.client.call("catalogue.search", {
1100
+ query,
1101
+ limit: options?.limit ?? 20,
1102
+ category: options?.category
1103
+ })
1104
+ );
1105
+ }
1106
+ async getMenu(options) {
1107
+ let query = "menu";
1108
+ if (options?.category) {
1109
+ query = `menu[?(@.category=='${options.category}')]`;
1110
+ }
1111
+ if (options?.limit) {
1112
+ query += `#limit(${options.limit})`;
1113
+ }
1114
+ return safe(this.client.query(query));
1115
+ }
1116
+ async getMenuCategory(categoryId) {
1117
+ return safe(this.client.query(`menu.category.${categoryId}`));
1118
+ }
1119
+ async getMenuItem(itemId) {
1120
+ return safe(this.client.query(`menu.${itemId}`));
1121
+ }
1122
+ };
1123
+
1124
+ // src/cart.ts
1125
+ function toCimplifyError2(error) {
1126
+ if (error instanceof CimplifyError) return enrichError(error);
1127
+ if (error instanceof Error) {
1128
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
1129
+ }
1130
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
1131
+ }
1132
+ async function safe2(promise) {
1133
+ try {
1134
+ return ok(await promise);
1135
+ } catch (error) {
1136
+ return err(toCimplifyError2(error));
1137
+ }
1138
+ }
1139
+ function isUICartResponse(value) {
1140
+ return "cart" in value;
1141
+ }
1142
+ function unwrapEnrichedCart(value) {
1143
+ return isUICartResponse(value) ? value.cart : value;
1144
+ }
1145
+ var CartOperations = class {
1146
+ constructor(client) {
1147
+ this.client = client;
1148
+ }
1149
+ async get() {
1150
+ const result = await safe2(this.client.query("cart#enriched"));
1151
+ if (!result.ok) return result;
1152
+ return ok(unwrapEnrichedCart(result.value));
1153
+ }
1154
+ async getRaw() {
1155
+ return safe2(this.client.query("cart"));
1156
+ }
1157
+ async getItems() {
1158
+ return safe2(this.client.query("cart_items"));
1159
+ }
1160
+ async getCount() {
1161
+ return safe2(this.client.query("cart#count"));
1162
+ }
1163
+ async getTotal() {
1164
+ return safe2(this.client.query("cart#total"));
1165
+ }
1166
+ async getSummary() {
1167
+ const cartResult = await this.get();
1168
+ if (!cartResult.ok) return cartResult;
1169
+ const cart = cartResult.value;
1170
+ return ok({
1171
+ item_count: cart.items.length,
1172
+ total_items: cart.items.reduce((sum, item) => sum + item.quantity, 0),
1173
+ subtotal: cart.pricing.subtotal,
1174
+ discount_amount: cart.pricing.total_discounts,
1175
+ tax_amount: cart.pricing.tax_amount,
1176
+ total: cart.pricing.total_price,
1177
+ currency: cart.pricing.currency
1178
+ });
1179
+ }
1180
+ async addItem(input) {
1181
+ return safe2(this.client.call("cart.addItem", input));
1182
+ }
1183
+ async updateItem(cartItemId, updates) {
1184
+ return safe2(
1185
+ this.client.call("cart.updateItem", {
1186
+ cart_item_id: cartItemId,
1187
+ ...updates
1188
+ })
1189
+ );
1190
+ }
1191
+ async updateQuantity(cartItemId, quantity) {
1192
+ return safe2(
1193
+ this.client.call("cart.updateItemQuantity", {
1194
+ cart_item_id: cartItemId,
1195
+ quantity
1196
+ })
1197
+ );
1198
+ }
1199
+ async removeItem(cartItemId) {
1200
+ return safe2(
1201
+ this.client.call("cart.removeItem", {
1202
+ cart_item_id: cartItemId
1203
+ })
1204
+ );
1205
+ }
1206
+ async clear() {
1207
+ return safe2(this.client.call("cart.clearCart"));
1208
+ }
1209
+ async applyCoupon(code) {
1210
+ return safe2(
1211
+ this.client.call("cart.applyCoupon", {
1212
+ coupon_code: code
1213
+ })
1214
+ );
1215
+ }
1216
+ async removeCoupon() {
1217
+ return safe2(this.client.call("cart.removeCoupon"));
1218
+ }
1219
+ async isEmpty() {
1220
+ const countResult = await this.getCount();
1221
+ if (!countResult.ok) return countResult;
1222
+ return ok(countResult.value === 0);
1223
+ }
1224
+ async hasItem(productId, variantId) {
1225
+ const itemsResult = await this.getItems();
1226
+ if (!itemsResult.ok) return itemsResult;
1227
+ const found = itemsResult.value.some((item) => {
1228
+ const matchesProduct = item.item_id === productId;
1229
+ if (!variantId) return matchesProduct;
1230
+ const config = item.configuration;
1231
+ if ("variant" in config && config.variant) {
1232
+ return matchesProduct && config.variant.variant_id === variantId;
1233
+ }
1234
+ return matchesProduct;
1235
+ });
1236
+ return ok(found);
1237
+ }
1238
+ async findItem(productId, variantId) {
1239
+ const itemsResult = await this.getItems();
1240
+ if (!itemsResult.ok) return itemsResult;
1241
+ const found = itemsResult.value.find((item) => {
1242
+ const matchesProduct = item.item_id === productId;
1243
+ if (!variantId) return matchesProduct;
1244
+ const config = item.configuration;
1245
+ if ("variant" in config && config.variant) {
1246
+ return matchesProduct && config.variant.variant_id === variantId;
1247
+ }
1248
+ return matchesProduct;
1249
+ });
1250
+ return ok(found);
1251
+ }
1252
+ };
1253
+
1254
+ // src/constants.ts
1255
+ var LINK_QUERY = {
1256
+ DATA: "link.data",
1257
+ ADDRESSES: "link.addresses",
1258
+ MOBILE_MONEY: "link.mobile_money",
1259
+ PREFERENCES: "link.preferences"};
1260
+ var LINK_MUTATION = {
1261
+ CHECK_STATUS: "link.check_status",
1262
+ ENROLL: "link.enroll",
1263
+ ENROLL_AND_LINK_ORDER: "link.enroll_and_link_order",
1264
+ UPDATE_PREFERENCES: "link.update_preferences",
1265
+ CREATE_ADDRESS: "link.create_address",
1266
+ UPDATE_ADDRESS: "link.update_address",
1267
+ DELETE_ADDRESS: "link.delete_address",
1268
+ SET_DEFAULT_ADDRESS: "link.set_default_address",
1269
+ TRACK_ADDRESS_USAGE: "link.track_address_usage",
1270
+ CREATE_MOBILE_MONEY: "link.create_mobile_money",
1271
+ DELETE_MOBILE_MONEY: "link.delete_mobile_money",
1272
+ SET_DEFAULT_MOBILE_MONEY: "link.set_default_mobile_money",
1273
+ TRACK_MOBILE_MONEY_USAGE: "link.track_mobile_money_usage",
1274
+ VERIFY_MOBILE_MONEY: "link.verify_mobile_money"};
1275
+ var AUTH_MUTATION = {
1276
+ REQUEST_OTP: "auth.request_otp",
1277
+ VERIFY_OTP: "auth.verify_otp"
1278
+ };
1279
+ var CHECKOUT_MUTATION = {
1280
+ PROCESS: "checkout.process"
1281
+ };
1282
+ var PAYMENT_MUTATION = {
1283
+ SUBMIT_AUTHORIZATION: "payment.submit_authorization",
1284
+ CHECK_STATUS: "order.poll_payment_status"
1285
+ };
1286
+ var ORDER_MUTATION = {
1287
+ UPDATE_CUSTOMER: "order.update_order_customer"
1288
+ };
1289
+
1290
+ // src/utils/price.ts
1291
+ function parsePrice(value) {
1292
+ if (value === void 0 || value === null) {
1293
+ return 0;
1294
+ }
1295
+ if (typeof value === "number") {
1296
+ return isNaN(value) ? 0 : value;
1297
+ }
1298
+ const cleaned = value.replace(/[^\d.-]/g, "");
1299
+ const parsed = parseFloat(cleaned);
1300
+ return isNaN(parsed) ? 0 : parsed;
1301
+ }
1302
+
1303
+ // src/utils/payment.ts
1304
+ var PAYMENT_SUCCESS_STATUSES = /* @__PURE__ */ new Set([
1305
+ "success",
1306
+ "succeeded",
1307
+ "paid",
1308
+ "captured",
1309
+ "completed",
1310
+ "authorized"
1311
+ ]);
1312
+ var PAYMENT_FAILURE_STATUSES = /* @__PURE__ */ new Set([
1313
+ "failed",
1314
+ "declined",
1315
+ "cancelled",
1316
+ "voided",
1317
+ "error"
1318
+ ]);
1319
+ var PAYMENT_REQUIRES_ACTION_STATUSES = /* @__PURE__ */ new Set([
1320
+ "requires_action",
1321
+ "requires_payment_method",
1322
+ "requires_capture"
1323
+ ]);
1324
+ var PAYMENT_STATUS_ALIAS_MAP = {
1325
+ ok: "success",
1326
+ done: "success",
1327
+ paid: "paid",
1328
+ paid_in_full: "paid",
1329
+ paid_successfully: "paid",
1330
+ succeeded: "success",
1331
+ captured: "captured",
1332
+ completed: "completed",
1333
+ pending_confirmation: "pending_confirmation",
1334
+ requires_authorization: "requires_action",
1335
+ requires_action: "requires_action",
1336
+ requires_payment_method: "requires_payment_method",
1337
+ requires_capture: "requires_capture",
1338
+ partially_paid: "partially_paid",
1339
+ partially_refunded: "partially_refunded",
1340
+ card_declined: "declined",
1341
+ canceled: "cancelled",
1342
+ authorized: "authorized",
1343
+ cancelled: "cancelled",
1344
+ unresolved: "pending"
1345
+ };
1346
+ var KNOWN_PAYMENT_STATUSES = /* @__PURE__ */ new Set([
1347
+ "pending",
1348
+ "processing",
1349
+ "created",
1350
+ "pending_confirmation",
1351
+ "success",
1352
+ "succeeded",
1353
+ "failed",
1354
+ "declined",
1355
+ "authorized",
1356
+ "refunded",
1357
+ "partially_refunded",
1358
+ "partially_paid",
1359
+ "paid",
1360
+ "unpaid",
1361
+ "requires_action",
1362
+ "requires_payment_method",
1363
+ "requires_capture",
1364
+ "captured",
1365
+ "cancelled",
1366
+ "completed",
1367
+ "voided",
1368
+ "error",
1369
+ "unknown"
1370
+ ]);
1371
+ function normalizeStatusToken(status) {
1372
+ return status?.trim().toLowerCase().replace(/[\s-]+/g, "_") ?? "";
1373
+ }
1374
+ function normalizePaymentStatusValue(status) {
1375
+ const normalized = normalizeStatusToken(status);
1376
+ if (Object.prototype.hasOwnProperty.call(PAYMENT_STATUS_ALIAS_MAP, normalized)) {
1377
+ return PAYMENT_STATUS_ALIAS_MAP[normalized];
1378
+ }
1379
+ return KNOWN_PAYMENT_STATUSES.has(normalized) ? normalized : "unknown";
1380
+ }
1381
+ function isPaymentStatusSuccess(status) {
1382
+ const normalizedStatus = normalizePaymentStatusValue(status);
1383
+ return PAYMENT_SUCCESS_STATUSES.has(normalizedStatus);
1384
+ }
1385
+ function isPaymentStatusFailure(status) {
1386
+ const normalizedStatus = normalizePaymentStatusValue(status);
1387
+ return PAYMENT_FAILURE_STATUSES.has(normalizedStatus);
1388
+ }
1389
+ function isPaymentStatusRequiresAction(status) {
1390
+ const normalizedStatus = normalizePaymentStatusValue(status);
1391
+ return PAYMENT_REQUIRES_ACTION_STATUSES.has(normalizedStatus);
1392
+ }
1393
+ function normalizeStatusResponse(response) {
1394
+ if (!response || typeof response !== "object") {
1395
+ return {
1396
+ status: "pending",
1397
+ paid: false,
1398
+ message: "No status available"
1399
+ };
1400
+ }
1401
+ const res = response;
1402
+ const normalizedStatus = normalizePaymentStatusValue(res.status ?? void 0);
1403
+ const paidValue = res.paid === true;
1404
+ const derivedPaid = paidValue || [
1405
+ "success",
1406
+ "succeeded",
1407
+ "paid",
1408
+ "captured",
1409
+ "authorized",
1410
+ "completed"
1411
+ ].includes(normalizedStatus);
1412
+ return {
1413
+ status: normalizedStatus,
1414
+ paid: derivedPaid,
1415
+ amount: res.amount,
1416
+ currency: res.currency,
1417
+ reference: res.reference,
1418
+ message: res.message || ""
1419
+ };
1420
+ }
1421
+
1422
+ // src/utils/paystack.ts
1423
+ async function openPaystackPopup(options, signal) {
1424
+ if (typeof window === "undefined") {
1425
+ return { success: false, error: "PROVIDER_UNAVAILABLE" };
1426
+ }
1427
+ let PaystackPop;
1428
+ try {
1429
+ const imported = await import('@paystack/inline-js');
1430
+ PaystackPop = imported.default;
1431
+ } catch {
1432
+ return { success: false, error: "PROVIDER_UNAVAILABLE" };
1433
+ }
1434
+ return new Promise((resolve) => {
1435
+ let settled = false;
1436
+ const resolveOnce = (result) => {
1437
+ if (settled) {
1438
+ return;
1439
+ }
1440
+ settled = true;
1441
+ if (signal) {
1442
+ signal.removeEventListener("abort", onAbort);
1443
+ }
1444
+ resolve(result);
1445
+ };
1446
+ const onAbort = () => {
1447
+ resolveOnce({ success: false, error: "CANCELLED" });
1448
+ };
1449
+ if (signal?.aborted) {
1450
+ resolveOnce({ success: false, error: "CANCELLED" });
1451
+ return;
1452
+ }
1453
+ if (signal) {
1454
+ signal.addEventListener("abort", onAbort, { once: true });
1455
+ }
1456
+ try {
1457
+ const popup = new PaystackPop();
1458
+ popup.newTransaction({
1459
+ key: options.key,
1460
+ email: options.email,
1461
+ amount: options.amount,
1462
+ currency: options.currency,
1463
+ reference: options.reference,
1464
+ accessCode: options.accessCode,
1465
+ onSuccess: (transaction) => {
1466
+ resolveOnce({
1467
+ success: true,
1468
+ reference: transaction.reference ?? options.reference
1469
+ });
1470
+ },
1471
+ onCancel: () => {
1472
+ resolveOnce({ success: false, error: "PAYMENT_CANCELLED" });
1473
+ },
1474
+ onError: (error) => {
1475
+ resolveOnce({
1476
+ success: false,
1477
+ error: error?.message || "PAYMENT_FAILED"
1478
+ });
1479
+ }
1480
+ });
1481
+ } catch {
1482
+ resolveOnce({ success: false, error: "POPUP_BLOCKED" });
1483
+ }
1484
+ });
1485
+ }
1486
+
1487
+ // src/utils/checkout-resolver.ts
1488
+ var DEFAULT_POLL_INTERVAL_MS = 3e3;
1489
+ var DEFAULT_MAX_POLL_ATTEMPTS = 60;
1490
+ var MAX_CONSECUTIVE_NETWORK_ERRORS = 5;
1491
+ var CARD_PROVIDER_PAYSTACK = "paystack";
1492
+ function normalizeCardPopupError(error) {
1493
+ if (!error || error === "PAYMENT_CANCELLED" || error === "CANCELLED") {
1494
+ return "PAYMENT_CANCELLED";
1495
+ }
1496
+ if (error === "PROVIDER_UNAVAILABLE") {
1497
+ return "PROVIDER_UNAVAILABLE";
1498
+ }
1499
+ if (error === "POPUP_BLOCKED") {
1500
+ return "POPUP_BLOCKED";
1501
+ }
1502
+ return "PAYMENT_FAILED";
1503
+ }
1504
+ function normalizeCardProvider(value) {
1505
+ const normalized = value?.trim().toLowerCase();
1506
+ return normalized && normalized.length > 0 ? normalized : CARD_PROVIDER_PAYSTACK;
1507
+ }
1508
+ async function openCardPopup(provider, checkoutResult, email, currency, signal) {
1509
+ if (typeof window === "undefined") {
1510
+ return { success: false, error: "PROVIDER_UNAVAILABLE" };
1511
+ }
1512
+ if (provider === CARD_PROVIDER_PAYSTACK) {
1513
+ return openPaystackPopup(
1514
+ {
1515
+ key: checkoutResult.public_key || "",
1516
+ email,
1517
+ accessCode: checkoutResult.client_secret,
1518
+ reference: checkoutResult.payment_reference || checkoutResult.client_secret,
1519
+ currency
1520
+ },
1521
+ signal
1522
+ );
1523
+ }
1524
+ return { success: false, error: "PROVIDER_UNAVAILABLE" };
1525
+ }
1526
+ function normalizeAuthorizationType(value) {
1527
+ return value === "otp" || value === "pin" ? value : void 0;
1528
+ }
1529
+ function formatMoney2(value) {
1530
+ if (typeof value === "number" && Number.isFinite(value)) {
1531
+ return value.toFixed(2);
1532
+ }
1533
+ if (typeof value === "string" && value.trim().length > 0) {
1534
+ return value;
1535
+ }
1536
+ return "0.00";
1537
+ }
1538
+ function createAbortError() {
1539
+ const error = new Error("CANCELLED");
1540
+ error.name = "AbortError";
1541
+ return error;
1542
+ }
1543
+ function isAbortError(error) {
1544
+ if (error instanceof DOMException && error.name === "AbortError") {
1545
+ return true;
1546
+ }
1547
+ return error instanceof Error && (error.name === "AbortError" || error.message === "CANCELLED");
1548
+ }
1549
+ var CheckoutResolver = class {
1550
+ constructor(options) {
1551
+ this.client = options.client;
1552
+ this.checkoutData = options.checkoutData;
1553
+ this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
1554
+ this.maxPollAttempts = options.maxPollAttempts ?? DEFAULT_MAX_POLL_ATTEMPTS;
1555
+ this.onStatusChange = options.onStatusChange;
1556
+ this.onAuthorizationRequired = options.onAuthorizationRequired;
1557
+ this.signal = options.signal;
1558
+ this.returnUrl = options.returnUrl;
1559
+ this.enrollInLink = options.enrollInLink !== false;
1560
+ this.businessId = options.businessId;
1561
+ this.addressData = options.addressData;
1562
+ this.paymentData = options.paymentData;
1563
+ this.orderType = options.orderType;
1564
+ this.cartTotal = options.cartTotal;
1565
+ this.cartCurrency = options.cartCurrency;
1566
+ this.allowPopups = options.allowPopups ?? typeof window !== "undefined";
1567
+ }
1568
+ async resolve(checkoutResult) {
1569
+ try {
1570
+ this.ensureNotAborted();
1571
+ if (!checkoutResult.order_id) {
1572
+ return this.fail("CHECKOUT_FAILED", "Checkout did not return an order ID.", false);
1573
+ }
1574
+ let latestCheckoutResult = checkoutResult;
1575
+ let authorizationType = normalizeAuthorizationType(checkoutResult.authorization_type);
1576
+ let paymentReference = checkoutResult.payment_reference;
1577
+ if (this.isSuccessfulStatus(checkoutResult.payment_status)) {
1578
+ return this.finalizeSuccess(checkoutResult);
1579
+ }
1580
+ if (checkoutResult.client_secret && checkoutResult.public_key) {
1581
+ const provider = normalizeCardProvider(checkoutResult.provider);
1582
+ this.emit("awaiting_authorization", {
1583
+ display_text: "Complete payment in the card authorization popup.",
1584
+ order_id: checkoutResult.order_id,
1585
+ order_number: checkoutResult.order_number
1586
+ });
1587
+ if (!this.allowPopups) {
1588
+ return this.fail(
1589
+ "PROVIDER_UNAVAILABLE",
1590
+ "Card payment popup is unavailable in this environment.",
1591
+ false
1592
+ );
1593
+ }
1594
+ const popupResult = await openCardPopup(
1595
+ provider,
1596
+ checkoutResult,
1597
+ this.checkoutData.customer.email || "customer@cimplify.io",
1598
+ this.getOrderCurrency(checkoutResult),
1599
+ this.signal
1600
+ );
1601
+ if (!popupResult.success) {
1602
+ const popupError = normalizeCardPopupError(popupResult.error);
1603
+ if (popupError === "POPUP_BLOCKED") {
1604
+ return this.fail(
1605
+ "POPUP_BLOCKED",
1606
+ "Unable to open card payment popup. Please allow popups and try again.",
1607
+ true
1608
+ );
1609
+ }
1610
+ if (popupError === "PROVIDER_UNAVAILABLE") {
1611
+ return this.fail(
1612
+ "PROVIDER_UNAVAILABLE",
1613
+ "Card payment provider is unavailable.",
1614
+ false
1615
+ );
1616
+ }
1617
+ return this.fail(
1618
+ "PAYMENT_CANCELLED",
1619
+ "Card payment was cancelled before completion.",
1620
+ true
1621
+ );
1622
+ }
1623
+ paymentReference = popupResult.reference || paymentReference;
1624
+ }
1625
+ if (checkoutResult.authorization_url) {
1626
+ if (typeof window !== "undefined" && this.returnUrl) {
1627
+ window.location.assign(checkoutResult.authorization_url);
1628
+ return this.fail(
1629
+ "REDIRECT_REQUIRED",
1630
+ "Redirecting to complete payment authorization.",
1631
+ true
1632
+ );
1633
+ }
1634
+ if (typeof window !== "undefined") {
1635
+ const popup = window.open(
1636
+ checkoutResult.authorization_url,
1637
+ "cimplify-auth",
1638
+ "width=520,height=760,noopener,noreferrer"
1639
+ );
1640
+ if (!popup) {
1641
+ return this.fail(
1642
+ "POPUP_BLOCKED",
1643
+ "Authorization popup was blocked. Please allow popups and retry.",
1644
+ true
1645
+ );
1646
+ }
1647
+ }
1648
+ }
1649
+ if (checkoutResult.requires_authorization || isPaymentStatusRequiresAction(checkoutResult.payment_status)) {
1650
+ const authorization = await this.handleAuthorization({
1651
+ authorizationType,
1652
+ paymentReference,
1653
+ displayText: checkoutResult.display_text,
1654
+ provider: checkoutResult.provider
1655
+ });
1656
+ if (!authorization.ok) {
1657
+ return authorization.result;
1658
+ }
1659
+ if (authorization.value) {
1660
+ latestCheckoutResult = authorization.value;
1661
+ paymentReference = authorization.value.payment_reference || paymentReference;
1662
+ authorizationType = normalizeAuthorizationType(authorization.value.authorization_type) || authorizationType;
1663
+ if (this.isSuccessfulStatus(authorization.value.payment_status)) {
1664
+ return this.finalizeSuccess(authorization.value);
1665
+ }
1666
+ if (this.isFailureStatus(authorization.value.payment_status)) {
1667
+ return this.fail(
1668
+ "AUTHORIZATION_FAILED",
1669
+ authorization.value.display_text || "Payment authorization failed.",
1670
+ false
1671
+ );
1672
+ }
1673
+ }
1674
+ }
1675
+ return this.pollUntilTerminal({
1676
+ orderId: checkoutResult.order_id,
1677
+ latestCheckoutResult,
1678
+ paymentReference,
1679
+ authorizationType
1680
+ });
1681
+ } catch (error) {
1682
+ if (isAbortError(error)) {
1683
+ return this.fail("CANCELLED", "Checkout was cancelled.", true);
1684
+ }
1685
+ const message = error instanceof Error ? error.message : "Checkout failed unexpectedly.";
1686
+ return this.fail("CHECKOUT_FAILED", message, true);
1687
+ }
1688
+ }
1689
+ async pollUntilTerminal(input) {
1690
+ let consecutiveErrors = 0;
1691
+ let latestCheckoutResult = input.latestCheckoutResult;
1692
+ let paymentReference = input.paymentReference;
1693
+ let authorizationType = input.authorizationType;
1694
+ for (let attempt = 0; attempt < this.maxPollAttempts; attempt++) {
1695
+ this.ensureNotAborted();
1696
+ this.emit("polling", {
1697
+ poll_attempt: attempt,
1698
+ max_poll_attempts: this.maxPollAttempts,
1699
+ order_id: input.orderId,
1700
+ order_number: latestCheckoutResult.order_number
1701
+ });
1702
+ const statusResult = await this.client.checkout.pollPaymentStatus(input.orderId);
1703
+ if (!statusResult.ok) {
1704
+ consecutiveErrors += 1;
1705
+ if (consecutiveErrors >= MAX_CONSECUTIVE_NETWORK_ERRORS) {
1706
+ return this.fail(
1707
+ "NETWORK_ERROR",
1708
+ "Unable to confirm payment due to repeated network errors.",
1709
+ true
1710
+ );
1711
+ }
1712
+ await this.wait(this.pollIntervalMs);
1713
+ continue;
1714
+ }
1715
+ consecutiveErrors = 0;
1716
+ if (statusResult.value.reference) {
1717
+ paymentReference = statusResult.value.reference;
1718
+ }
1719
+ const normalized = normalizeStatusResponse(statusResult.value);
1720
+ if (normalized.paid || isPaymentStatusSuccess(normalized.status)) {
1721
+ return this.finalizeSuccess(latestCheckoutResult);
1722
+ }
1723
+ if (isPaymentStatusFailure(normalized.status)) {
1724
+ return this.fail(
1725
+ normalized.status ? normalized.status.toUpperCase() : "PAYMENT_FAILED",
1726
+ normalized.message || "Payment failed during confirmation.",
1727
+ false
1728
+ );
1729
+ }
1730
+ if (isPaymentStatusRequiresAction(normalized.status)) {
1731
+ const authorization = await this.handleAuthorization({
1732
+ authorizationType,
1733
+ paymentReference,
1734
+ displayText: normalized.message || latestCheckoutResult.display_text,
1735
+ provider: latestCheckoutResult.provider
1736
+ });
1737
+ if (!authorization.ok) {
1738
+ return authorization.result;
1739
+ }
1740
+ if (authorization.value) {
1741
+ latestCheckoutResult = authorization.value;
1742
+ paymentReference = authorization.value.payment_reference || paymentReference;
1743
+ authorizationType = normalizeAuthorizationType(authorization.value.authorization_type) || authorizationType;
1744
+ if (this.isSuccessfulStatus(authorization.value.payment_status)) {
1745
+ return this.finalizeSuccess(authorization.value);
1746
+ }
1747
+ if (this.isFailureStatus(authorization.value.payment_status)) {
1748
+ return this.fail(
1749
+ "AUTHORIZATION_FAILED",
1750
+ authorization.value.display_text || "Payment authorization failed.",
1751
+ false
1752
+ );
1753
+ }
1754
+ }
1755
+ }
1756
+ await this.wait(this.pollIntervalMs);
1757
+ }
1758
+ return this.fail(
1759
+ "PAYMENT_TIMEOUT",
1760
+ "Payment confirmation timed out. Please retry checkout.",
1761
+ true
1762
+ );
1763
+ }
1764
+ async handleAuthorization(input) {
1765
+ const authorizationType = input.authorizationType;
1766
+ const paymentReference = input.paymentReference;
1767
+ if (!authorizationType || !paymentReference) {
1768
+ return { ok: true };
1769
+ }
1770
+ this.emit("awaiting_authorization", {
1771
+ authorization_type: authorizationType,
1772
+ display_text: input.displayText,
1773
+ provider: input.provider
1774
+ });
1775
+ let authorizationResult;
1776
+ const submit = async (code) => {
1777
+ this.ensureNotAborted();
1778
+ const trimmedCode = code.trim();
1779
+ if (!trimmedCode) {
1780
+ throw new Error("Authorization code is required.");
1781
+ }
1782
+ const submitResult = await this.client.checkout.submitAuthorization({
1783
+ reference: paymentReference,
1784
+ auth_type: authorizationType,
1785
+ value: trimmedCode
1786
+ });
1787
+ if (!submitResult.ok) {
1788
+ throw new Error(submitResult.error.message || "Authorization failed.");
1789
+ }
1790
+ authorizationResult = submitResult.value;
1791
+ };
1792
+ try {
1793
+ if (this.onAuthorizationRequired) {
1794
+ await this.onAuthorizationRequired(authorizationType, submit);
1795
+ } else {
1796
+ return {
1797
+ ok: false,
1798
+ result: this.fail(
1799
+ "AUTHORIZATION_REQUIRED",
1800
+ "Authorization callback is required in headless checkout mode.",
1801
+ false
1802
+ )
1803
+ };
1804
+ }
1805
+ } catch (error) {
1806
+ if (isAbortError(error)) {
1807
+ return {
1808
+ ok: false,
1809
+ result: this.fail("CANCELLED", "Checkout was cancelled.", true)
1810
+ };
1811
+ }
1812
+ const message = error instanceof Error ? error.message : "Payment authorization failed.";
1813
+ return {
1814
+ ok: false,
1815
+ result: this.fail("AUTHORIZATION_FAILED", message, true)
1816
+ };
1817
+ }
1818
+ return {
1819
+ ok: true,
1820
+ value: authorizationResult
1821
+ };
1822
+ }
1823
+ async finalizeSuccess(checkoutResult) {
1824
+ this.emit("finalizing", {
1825
+ order_id: checkoutResult.order_id,
1826
+ order_number: checkoutResult.order_number
1827
+ });
1828
+ const enrolledInLink = await this.maybeEnrollInLink(checkoutResult.order_id);
1829
+ this.emit("success", {
1830
+ order_id: checkoutResult.order_id,
1831
+ order_number: checkoutResult.order_number
1832
+ });
1833
+ return {
1834
+ success: true,
1835
+ order: {
1836
+ id: checkoutResult.order_id,
1837
+ order_number: checkoutResult.order_number || checkoutResult.order_id,
1838
+ status: checkoutResult.payment_status || "paid",
1839
+ total: this.getOrderTotal(checkoutResult),
1840
+ currency: this.getOrderCurrency(checkoutResult)
1841
+ },
1842
+ enrolled_in_link: enrolledInLink
1843
+ };
1844
+ }
1845
+ async maybeEnrollInLink(orderId) {
1846
+ if (!this.enrollInLink || !orderId) {
1847
+ return false;
1848
+ }
1849
+ let businessId = this.businessId;
1850
+ if (!businessId) {
1851
+ const businessResult = await this.client.business.getInfo();
1852
+ if (!businessResult.ok || !businessResult.value?.id) {
1853
+ return false;
1854
+ }
1855
+ businessId = businessResult.value.id;
1856
+ }
1857
+ const address = this.getEnrollmentAddress();
1858
+ const mobileMoney = this.getEnrollmentMobileMoney();
1859
+ try {
1860
+ const enrollment = await this.client.link.enrollAndLinkOrder({
1861
+ order_id: orderId,
1862
+ business_id: businessId,
1863
+ order_type: this.orderType || this.checkoutData.order_type,
1864
+ address,
1865
+ mobile_money: mobileMoney
1866
+ });
1867
+ return enrollment.ok && enrollment.value.success;
1868
+ } catch {
1869
+ return false;
1870
+ }
1871
+ }
1872
+ getEnrollmentAddress() {
1873
+ const source = this.addressData ?? this.checkoutData.address_info;
1874
+ if (!source?.street_address) {
1875
+ return void 0;
1876
+ }
1877
+ return {
1878
+ label: "Default",
1879
+ street_address: source.street_address,
1880
+ apartment: source.apartment || void 0,
1881
+ city: source.city || "",
1882
+ region: source.region || "",
1883
+ delivery_instructions: source.delivery_instructions || void 0,
1884
+ phone_for_delivery: source.phone_for_delivery || void 0
1885
+ };
1886
+ }
1887
+ getEnrollmentMobileMoney() {
1888
+ if (this.paymentData?.type === "mobile_money" && this.paymentData.phone_number && this.paymentData.provider) {
1889
+ return {
1890
+ phone_number: this.paymentData.phone_number,
1891
+ provider: this.paymentData.provider,
1892
+ label: this.paymentData.label || "Mobile Money"
1893
+ };
1894
+ }
1895
+ if (this.checkoutData.mobile_money_details?.phone_number) {
1896
+ return {
1897
+ phone_number: this.checkoutData.mobile_money_details.phone_number,
1898
+ provider: this.checkoutData.mobile_money_details.provider,
1899
+ label: "Mobile Money"
1900
+ };
1901
+ }
1902
+ return void 0;
1903
+ }
1904
+ getOrderTotal(checkoutResult) {
1905
+ if (checkoutResult.fx?.pay_amount !== void 0) {
1906
+ return formatMoney2(checkoutResult.fx.pay_amount);
1907
+ }
1908
+ if (this.cartTotal !== void 0) {
1909
+ return formatMoney2(this.cartTotal);
1910
+ }
1911
+ return "0.00";
1912
+ }
1913
+ getOrderCurrency(checkoutResult) {
1914
+ if (checkoutResult.fx?.pay_currency) {
1915
+ return checkoutResult.fx.pay_currency;
1916
+ }
1917
+ if (this.cartCurrency) {
1918
+ return this.cartCurrency;
1919
+ }
1920
+ if (this.checkoutData.pay_currency) {
1921
+ return this.checkoutData.pay_currency;
1922
+ }
1923
+ return "GHS";
1924
+ }
1925
+ emit(status, context = {}) {
1926
+ if (!this.onStatusChange) {
1927
+ return;
1928
+ }
1929
+ try {
1930
+ this.onStatusChange(status, context);
1931
+ } catch {
1932
+ }
1933
+ }
1934
+ fail(code, message, recoverable) {
1935
+ this.emit("failed", {
1936
+ display_text: message
1937
+ });
1938
+ return {
1939
+ success: false,
1940
+ error: {
1941
+ code,
1942
+ message,
1943
+ recoverable
1944
+ }
1945
+ };
1946
+ }
1947
+ isSuccessfulStatus(status) {
1948
+ const normalized = normalizeStatusResponse({ status, paid: false });
1949
+ return normalized.paid || isPaymentStatusSuccess(normalized.status);
1950
+ }
1951
+ isFailureStatus(status) {
1952
+ const normalized = normalizeStatusResponse({ status, paid: false });
1953
+ return isPaymentStatusFailure(normalized.status);
1954
+ }
1955
+ ensureNotAborted() {
1956
+ if (this.signal?.aborted) {
1957
+ throw createAbortError();
1958
+ }
1959
+ }
1960
+ wait(ms) {
1961
+ this.ensureNotAborted();
1962
+ return new Promise((resolve, reject) => {
1963
+ const timer = setTimeout(() => {
1964
+ if (this.signal) {
1965
+ this.signal.removeEventListener("abort", onAbort);
1966
+ }
1967
+ resolve();
1968
+ }, ms);
1969
+ const onAbort = () => {
1970
+ clearTimeout(timer);
1971
+ reject(createAbortError());
1972
+ };
1973
+ if (this.signal) {
1974
+ this.signal.addEventListener("abort", onAbort, { once: true });
1975
+ }
1976
+ });
1977
+ }
1978
+ };
1979
+
1980
+ // src/checkout.ts
1981
+ function toCimplifyError3(error) {
1982
+ if (error instanceof CimplifyError) return enrichError(error);
1983
+ if (error instanceof Error) {
1984
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
1985
+ }
1986
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
1987
+ }
1988
+ async function safe3(promise) {
1989
+ try {
1990
+ return ok(await promise);
1991
+ } catch (error) {
1992
+ return err(toCimplifyError3(error));
1993
+ }
1994
+ }
1995
+ function toTerminalFailure(code, message, recoverable) {
1996
+ return {
1997
+ success: false,
1998
+ error: {
1999
+ code,
2000
+ message,
2001
+ recoverable
2002
+ }
2003
+ };
2004
+ }
2005
+ function generateIdempotencyKey() {
2006
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
2007
+ return `idem_${crypto.randomUUID()}`;
2008
+ }
2009
+ const timestamp = Date.now().toString(36);
2010
+ const random = Math.random().toString(36).substring(2, 15);
2011
+ return `idem_${timestamp}_${random}`;
2012
+ }
2013
+ var CheckoutService = class {
2014
+ constructor(client) {
2015
+ this.client = client;
2016
+ }
2017
+ async process(data) {
2018
+ const checkoutData = {
2019
+ ...data,
2020
+ idempotency_key: data.idempotency_key || generateIdempotencyKey()
2021
+ };
2022
+ return safe3(
2023
+ this.client.call(CHECKOUT_MUTATION.PROCESS, {
2024
+ checkout_data: checkoutData
2025
+ })
2026
+ );
2027
+ }
2028
+ async initializePayment(orderId, method) {
2029
+ return safe3(
2030
+ this.client.call("order.initializePayment", {
2031
+ order_id: orderId,
2032
+ payment_method: method
2033
+ })
2034
+ );
2035
+ }
2036
+ async submitAuthorization(input) {
2037
+ return safe3(
2038
+ this.client.call(PAYMENT_MUTATION.SUBMIT_AUTHORIZATION, input)
2039
+ );
2040
+ }
2041
+ async pollPaymentStatus(orderId) {
2042
+ return safe3(
2043
+ this.client.call(PAYMENT_MUTATION.CHECK_STATUS, orderId)
2044
+ );
2045
+ }
2046
+ async updateOrderCustomer(orderId, customer) {
2047
+ return safe3(
2048
+ this.client.call(ORDER_MUTATION.UPDATE_CUSTOMER, {
2049
+ order_id: orderId,
2050
+ ...customer
2051
+ })
2052
+ );
2053
+ }
2054
+ async verifyPayment(orderId) {
2055
+ return safe3(
2056
+ this.client.call("order.verifyPayment", {
2057
+ order_id: orderId
2058
+ })
2059
+ );
2060
+ }
2061
+ async processAndResolve(data) {
2062
+ data.on_status_change?.("preparing", {});
2063
+ if (!data.cart_id) {
2064
+ return ok(
2065
+ toTerminalFailure(
2066
+ "INVALID_CART",
2067
+ "A valid cart is required before checkout can start.",
2068
+ false
2069
+ )
2070
+ );
2071
+ }
2072
+ const cartResult = await this.client.cart.get();
2073
+ if (!cartResult.ok || !cartResult.value?.id) {
2074
+ return ok(
2075
+ toTerminalFailure(
2076
+ "INVALID_CART",
2077
+ "Unable to load cart for checkout.",
2078
+ false
2079
+ )
2080
+ );
2081
+ }
2082
+ const cart = cartResult.value;
2083
+ if (cart.id !== data.cart_id || cart.items.length === 0) {
2084
+ return ok(
2085
+ toTerminalFailure(
2086
+ "INVALID_CART",
2087
+ "Cart is empty or no longer valid. Please refresh and try again.",
2088
+ false
2089
+ )
2090
+ );
2091
+ }
2092
+ const checkoutData = {
2093
+ cart_id: data.cart_id,
2094
+ location_id: data.location_id,
2095
+ customer: data.customer,
2096
+ order_type: data.order_type,
2097
+ address_info: data.address_info,
2098
+ payment_method: data.payment_method,
2099
+ mobile_money_details: data.mobile_money_details,
2100
+ special_instructions: data.special_instructions,
2101
+ link_address_id: data.link_address_id,
2102
+ link_payment_method_id: data.link_payment_method_id,
2103
+ idempotency_key: data.idempotency_key || generateIdempotencyKey(),
2104
+ metadata: data.metadata,
2105
+ pay_currency: data.pay_currency,
2106
+ fx_quote_id: data.fx_quote_id
2107
+ };
2108
+ const baseCurrency = (cart.pricing.currency || checkoutData.pay_currency || "GHS").toUpperCase();
2109
+ const payCurrency = data.pay_currency?.trim().toUpperCase();
2110
+ const cartTotalAmount = Number.parseFloat(cart.pricing.total_price || "0");
2111
+ if (payCurrency && payCurrency !== baseCurrency && !checkoutData.fx_quote_id && Number.isFinite(cartTotalAmount) && cartTotalAmount > 0) {
2112
+ const fxQuoteResult = await this.client.fx.lockQuote({
2113
+ from: baseCurrency,
2114
+ to: payCurrency,
2115
+ amount: cartTotalAmount
2116
+ });
2117
+ if (!fxQuoteResult.ok) {
2118
+ return ok(
2119
+ toTerminalFailure(
2120
+ "FX_QUOTE_FAILED",
2121
+ fxQuoteResult.error.message || "Unable to lock FX quote for checkout.",
2122
+ true
2123
+ )
2124
+ );
2125
+ }
2126
+ checkoutData.pay_currency = payCurrency;
2127
+ checkoutData.fx_quote_id = fxQuoteResult.value.id;
2128
+ }
2129
+ data.on_status_change?.("processing", {});
2130
+ const processResult = await this.process(checkoutData);
2131
+ if (!processResult.ok) {
2132
+ return ok(
2133
+ toTerminalFailure(
2134
+ processResult.error.code || "CHECKOUT_FAILED",
2135
+ processResult.error.message || "Unable to process checkout.",
2136
+ processResult.error.retryable ?? true
2137
+ )
2138
+ );
2139
+ }
2140
+ const resolver = new CheckoutResolver({
2141
+ client: this.client,
2142
+ checkoutData,
2143
+ pollIntervalMs: data.poll_interval_ms,
2144
+ maxPollAttempts: data.max_poll_attempts,
2145
+ onStatusChange: data.on_status_change,
2146
+ onAuthorizationRequired: data.on_authorization_required,
2147
+ signal: data.signal,
2148
+ returnUrl: data.return_url,
2149
+ enrollInLink: data.enroll_in_link,
2150
+ cartTotal: cart.pricing.total_price,
2151
+ cartCurrency: checkoutData.pay_currency || cart.pricing.currency || "GHS",
2152
+ orderType: checkoutData.order_type,
2153
+ allowPopups: data.allow_popups
2154
+ });
2155
+ const resolved = await resolver.resolve(processResult.value);
2156
+ return ok(resolved);
2157
+ }
2158
+ };
2159
+
2160
+ // src/orders.ts
2161
+ function toCimplifyError4(error) {
2162
+ if (error instanceof CimplifyError) return enrichError(error);
2163
+ if (error instanceof Error) {
2164
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
2165
+ }
2166
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
2167
+ }
2168
+ async function safe4(promise) {
2169
+ try {
2170
+ return ok(await promise);
2171
+ } catch (error) {
2172
+ return err(toCimplifyError4(error));
2173
+ }
2174
+ }
2175
+ var OrderQueries = class {
2176
+ constructor(client) {
2177
+ this.client = client;
2178
+ }
2179
+ async list(options) {
2180
+ let query = "orders";
2181
+ if (options?.status) {
2182
+ query += `[?(@.status=='${options.status}')]`;
2183
+ }
2184
+ query += "#sort(created_at,desc)";
2185
+ if (options?.limit) {
2186
+ query += `#limit(${options.limit})`;
2187
+ }
2188
+ if (options?.offset) {
2189
+ query += `#offset(${options.offset})`;
2190
+ }
2191
+ return safe4(this.client.query(query));
2192
+ }
2193
+ async get(orderId) {
2194
+ return safe4(this.client.query(`orders.${orderId}`));
2195
+ }
2196
+ async getRecent(limit = 5) {
2197
+ return safe4(this.client.query(`orders#sort(created_at,desc)#limit(${limit})`));
2198
+ }
2199
+ async getByStatus(status) {
2200
+ return safe4(this.client.query(`orders[?(@.status=='${status}')]`));
2201
+ }
2202
+ async cancel(orderId, reason) {
2203
+ return safe4(
2204
+ this.client.call("order.cancelOrder", {
2205
+ order_id: orderId,
2206
+ reason
2207
+ })
2208
+ );
2209
+ }
2210
+ };
2211
+
2212
+ // src/link.ts
2213
+ function toCimplifyError5(error) {
2214
+ if (error instanceof CimplifyError) return error;
2215
+ if (error instanceof Error) {
2216
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
2217
+ }
2218
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
2219
+ }
2220
+ async function safe5(promise) {
2221
+ try {
2222
+ return ok(await promise);
2223
+ } catch (error) {
2224
+ return err(toCimplifyError5(error));
2225
+ }
2226
+ }
2227
+ var LinkService = class {
2228
+ constructor(client) {
2229
+ this.client = client;
2230
+ }
2231
+ async requestOtp(input) {
2232
+ return safe5(this.client.linkPost("/v1/link/auth/request-otp", input));
2233
+ }
2234
+ async verifyOtp(input) {
2235
+ const result = await safe5(
2236
+ this.client.linkPost("/v1/link/auth/verify-otp", input)
2237
+ );
2238
+ if (result.ok && result.value.session_token) {
2239
+ this.client.setSessionToken(result.value.session_token);
2240
+ }
2241
+ return result;
2242
+ }
2243
+ async logout() {
2244
+ const result = await safe5(this.client.linkPost("/v1/link/auth/logout"));
2245
+ if (result.ok) {
2246
+ this.client.clearSession();
2247
+ }
2248
+ return result;
2249
+ }
2250
+ async checkStatus(contact) {
2251
+ return safe5(
2252
+ this.client.call(LINK_MUTATION.CHECK_STATUS, {
2253
+ contact
2254
+ })
2255
+ );
2256
+ }
2257
+ async getLinkData() {
2258
+ return safe5(this.client.query(LINK_QUERY.DATA));
2259
+ }
2260
+ async getAddresses() {
2261
+ return safe5(this.client.query(LINK_QUERY.ADDRESSES));
2262
+ }
2263
+ async getMobileMoney() {
2264
+ return safe5(this.client.query(LINK_QUERY.MOBILE_MONEY));
2265
+ }
2266
+ async getPreferences() {
2267
+ return safe5(this.client.query(LINK_QUERY.PREFERENCES));
2268
+ }
2269
+ async enroll(data) {
2270
+ return safe5(this.client.call(LINK_MUTATION.ENROLL, data));
2271
+ }
2272
+ async enrollAndLinkOrder(data) {
2273
+ return safe5(
2274
+ this.client.call(LINK_MUTATION.ENROLL_AND_LINK_ORDER, data)
2275
+ );
2276
+ }
2277
+ async updatePreferences(preferences) {
2278
+ return safe5(this.client.call(LINK_MUTATION.UPDATE_PREFERENCES, preferences));
2279
+ }
2280
+ async createAddress(input) {
2281
+ return safe5(this.client.call(LINK_MUTATION.CREATE_ADDRESS, input));
2282
+ }
2283
+ async updateAddress(input) {
2284
+ return safe5(this.client.call(LINK_MUTATION.UPDATE_ADDRESS, input));
2285
+ }
2286
+ async deleteAddress(addressId) {
2287
+ return safe5(this.client.call(LINK_MUTATION.DELETE_ADDRESS, addressId));
2288
+ }
2289
+ async setDefaultAddress(addressId) {
2290
+ return safe5(this.client.call(LINK_MUTATION.SET_DEFAULT_ADDRESS, addressId));
2291
+ }
2292
+ async trackAddressUsage(addressId) {
2293
+ return safe5(
2294
+ this.client.call(LINK_MUTATION.TRACK_ADDRESS_USAGE, {
2295
+ address_id: addressId
2296
+ })
2297
+ );
2298
+ }
2299
+ async createMobileMoney(input) {
2300
+ return safe5(this.client.call(LINK_MUTATION.CREATE_MOBILE_MONEY, input));
2301
+ }
2302
+ async deleteMobileMoney(mobileMoneyId) {
2303
+ return safe5(this.client.call(LINK_MUTATION.DELETE_MOBILE_MONEY, mobileMoneyId));
2304
+ }
2305
+ async setDefaultMobileMoney(mobileMoneyId) {
2306
+ return safe5(
2307
+ this.client.call(LINK_MUTATION.SET_DEFAULT_MOBILE_MONEY, mobileMoneyId)
2308
+ );
2309
+ }
2310
+ async trackMobileMoneyUsage(mobileMoneyId) {
2311
+ return safe5(
2312
+ this.client.call(LINK_MUTATION.TRACK_MOBILE_MONEY_USAGE, {
2313
+ mobile_money_id: mobileMoneyId
2314
+ })
2315
+ );
2316
+ }
2317
+ async verifyMobileMoney(mobileMoneyId) {
2318
+ return safe5(
2319
+ this.client.call(LINK_MUTATION.VERIFY_MOBILE_MONEY, mobileMoneyId)
2320
+ );
2321
+ }
2322
+ async getSessions() {
2323
+ return safe5(this.client.linkGet("/v1/link/sessions"));
2324
+ }
2325
+ async revokeSession(sessionId) {
2326
+ return safe5(this.client.linkDelete(`/v1/link/sessions/${sessionId}`));
2327
+ }
2328
+ async revokeAllSessions() {
2329
+ return safe5(this.client.linkDelete("/v1/link/sessions"));
2330
+ }
2331
+ async getAddressesRest() {
2332
+ return safe5(this.client.linkGet("/v1/link/addresses"));
2333
+ }
2334
+ async createAddressRest(input) {
2335
+ return safe5(this.client.linkPost("/v1/link/addresses", input));
2336
+ }
2337
+ async deleteAddressRest(addressId) {
2338
+ return safe5(this.client.linkDelete(`/v1/link/addresses/${addressId}`));
2339
+ }
2340
+ async setDefaultAddressRest(addressId) {
2341
+ return safe5(this.client.linkPost(`/v1/link/addresses/${addressId}/default`));
2342
+ }
2343
+ async getMobileMoneyRest() {
2344
+ return safe5(this.client.linkGet("/v1/link/mobile-money"));
2345
+ }
2346
+ async createMobileMoneyRest(input) {
2347
+ return safe5(this.client.linkPost("/v1/link/mobile-money", input));
2348
+ }
2349
+ async deleteMobileMoneyRest(mobileMoneyId) {
2350
+ return safe5(this.client.linkDelete(`/v1/link/mobile-money/${mobileMoneyId}`));
2351
+ }
2352
+ async setDefaultMobileMoneyRest(mobileMoneyId) {
2353
+ return safe5(
2354
+ this.client.linkPost(`/v1/link/mobile-money/${mobileMoneyId}/default`)
2355
+ );
2356
+ }
2357
+ };
2358
+
2359
+ // src/auth.ts
2360
+ function toCimplifyError6(error) {
2361
+ if (error instanceof CimplifyError) return error;
2362
+ if (error instanceof Error) {
2363
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
2364
+ }
2365
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
2366
+ }
2367
+ async function safe6(promise) {
2368
+ try {
2369
+ return ok(await promise);
2370
+ } catch (error) {
2371
+ return err(toCimplifyError6(error));
2372
+ }
2373
+ }
2374
+ var AuthService = class {
2375
+ constructor(client) {
2376
+ this.client = client;
2377
+ }
2378
+ async getStatus() {
2379
+ return safe6(this.client.query("auth"));
2380
+ }
2381
+ async getCurrentUser() {
2382
+ const result = await this.getStatus();
2383
+ if (!result.ok) return result;
2384
+ return ok(result.value.customer || null);
2385
+ }
2386
+ async isAuthenticated() {
2387
+ const result = await this.getStatus();
2388
+ if (!result.ok) return result;
2389
+ return ok(result.value.is_authenticated);
2390
+ }
2391
+ async requestOtp(contact, contactType) {
2392
+ return safe6(
2393
+ this.client.call(AUTH_MUTATION.REQUEST_OTP, {
2394
+ contact,
2395
+ contact_type: contactType
2396
+ })
2397
+ );
2398
+ }
2399
+ async verifyOtp(code, contact) {
2400
+ return safe6(
2401
+ this.client.call(AUTH_MUTATION.VERIFY_OTP, {
2402
+ otp_code: code,
2403
+ contact
2404
+ })
2405
+ );
2406
+ }
2407
+ async logout() {
2408
+ return safe6(this.client.call("auth.logout"));
2409
+ }
2410
+ async updateProfile(input) {
2411
+ return safe6(this.client.call("auth.update_profile", input));
2412
+ }
2413
+ async changePassword(input) {
2414
+ return safe6(this.client.call("auth.change_password", input));
2415
+ }
2416
+ async resetPassword(email) {
2417
+ return safe6(this.client.call("auth.reset_password", { email }));
2418
+ }
2419
+ };
2420
+
2421
+ // src/business.ts
2422
+ function toCimplifyError7(error) {
2423
+ if (error instanceof CimplifyError) return enrichError(error);
2424
+ if (error instanceof Error) {
2425
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
2426
+ }
2427
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
2428
+ }
2429
+ async function safe7(promise) {
2430
+ try {
2431
+ return ok(await promise);
2432
+ } catch (error) {
2433
+ return err(toCimplifyError7(error));
2434
+ }
2435
+ }
2436
+ var BusinessService = class {
2437
+ constructor(client) {
2438
+ this.client = client;
2439
+ }
2440
+ async getInfo() {
2441
+ return safe7(this.client.query("business.info"));
2442
+ }
2443
+ async getByHandle(handle) {
2444
+ return safe7(this.client.query(`business.handle.${handle}`));
2445
+ }
2446
+ async getByDomain(domain) {
2447
+ return safe7(this.client.query("business.domain", { domain }));
2448
+ }
2449
+ async getSettings() {
2450
+ return safe7(this.client.query("business.settings"));
2451
+ }
2452
+ async getTheme() {
2453
+ return safe7(this.client.query("business.theme"));
2454
+ }
2455
+ async getLocations() {
2456
+ return safe7(this.client.query("business.locations"));
2457
+ }
2458
+ async getLocation(locationId) {
2459
+ return safe7(this.client.query(`business.locations.${locationId}`));
2460
+ }
2461
+ async getHours() {
2462
+ return safe7(this.client.query("business.hours"));
2463
+ }
2464
+ async getLocationHours(locationId) {
2465
+ return safe7(this.client.query(`business.locations.${locationId}.hours`));
2466
+ }
2467
+ async getBootstrap() {
2468
+ const [businessResult, locationsResult, categoriesResult] = await Promise.all([
2469
+ this.getInfo(),
2470
+ this.getLocations(),
2471
+ safe7(this.client.query("categories#select(id,name,slug)"))
2472
+ ]);
2473
+ if (!businessResult.ok) return businessResult;
2474
+ if (!locationsResult.ok) return locationsResult;
2475
+ if (!categoriesResult.ok) return categoriesResult;
2476
+ const business = businessResult.value;
2477
+ const locations = locationsResult.value;
2478
+ const categories = categoriesResult.value;
2479
+ const defaultLocation = locations[0];
2480
+ return ok({
2481
+ business,
2482
+ location: defaultLocation,
2483
+ locations,
2484
+ categories,
2485
+ currency: business.default_currency,
2486
+ is_open: defaultLocation?.accepts_online_orders ?? false,
2487
+ accepts_orders: defaultLocation?.accepts_online_orders ?? false
2488
+ });
2489
+ }
2490
+ };
2491
+
2492
+ // src/inventory.ts
2493
+ function toCimplifyError8(error) {
2494
+ if (error instanceof CimplifyError) return error;
2495
+ if (error instanceof Error) {
2496
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
2497
+ }
2498
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
2499
+ }
2500
+ async function safe8(promise) {
2501
+ try {
2502
+ return ok(await promise);
2503
+ } catch (error) {
2504
+ return err(toCimplifyError8(error));
2505
+ }
2506
+ }
2507
+ var InventoryService = class {
2508
+ constructor(client) {
2509
+ this.client = client;
2510
+ }
2511
+ async getStockLevels() {
2512
+ return safe8(this.client.query("inventory.stock_levels"));
2513
+ }
2514
+ async getProductStock(productId, locationId) {
2515
+ if (locationId) {
2516
+ return safe8(
2517
+ this.client.query("inventory.product", {
2518
+ product_id: productId,
2519
+ location_id: locationId
2520
+ })
2521
+ );
2522
+ }
2523
+ return safe8(
2524
+ this.client.query("inventory.product", {
2525
+ product_id: productId
2526
+ })
2527
+ );
2528
+ }
2529
+ async getVariantStock(variantId, locationId) {
2530
+ return safe8(
2531
+ this.client.query("inventory.variant", {
2532
+ variant_id: variantId,
2533
+ location_id: locationId
2534
+ })
2535
+ );
2536
+ }
2537
+ async checkProductAvailability(productId, quantity, locationId) {
2538
+ return safe8(
2539
+ this.client.query("inventory.check_availability", {
2540
+ product_id: productId,
2541
+ quantity,
2542
+ location_id: locationId
2543
+ })
2544
+ );
2545
+ }
2546
+ async checkVariantAvailability(variantId, quantity, locationId) {
2547
+ return safe8(
2548
+ this.client.query("inventory.check_availability", {
2549
+ variant_id: variantId,
2550
+ quantity,
2551
+ location_id: locationId
2552
+ })
2553
+ );
2554
+ }
2555
+ async checkMultipleAvailability(items, locationId) {
2556
+ const results = await Promise.all(
2557
+ items.map(
2558
+ (item) => item.variant_id ? this.checkVariantAvailability(item.variant_id, item.quantity, locationId) : this.checkProductAvailability(item.product_id, item.quantity, locationId)
2559
+ )
2560
+ );
2561
+ for (const result of results) {
2562
+ if (!result.ok) return result;
2563
+ }
2564
+ return ok(results.map((r) => r.value));
2565
+ }
2566
+ async getSummary() {
2567
+ return safe8(this.client.query("inventory.summary"));
2568
+ }
2569
+ async isInStock(productId, locationId) {
2570
+ const result = await this.checkProductAvailability(productId, 1, locationId);
2571
+ if (!result.ok) return result;
2572
+ return ok(result.value.is_available);
2573
+ }
2574
+ async getAvailableQuantity(productId, locationId) {
2575
+ const result = await this.getProductStock(productId, locationId);
2576
+ if (!result.ok) return result;
2577
+ return ok(result.value.available_quantity);
2578
+ }
2579
+ };
2580
+
2581
+ // src/scheduling.ts
2582
+ function toVariables(input) {
2583
+ return Object.fromEntries(Object.entries(input));
2584
+ }
2585
+ function toCimplifyError9(error) {
2586
+ if (error instanceof CimplifyError) return error;
2587
+ if (error instanceof Error) {
2588
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
2589
+ }
2590
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
2591
+ }
2592
+ async function safe9(promise) {
2593
+ try {
2594
+ return ok(await promise);
2595
+ } catch (error) {
2596
+ return err(toCimplifyError9(error));
2597
+ }
2598
+ }
2599
+ var SchedulingService = class {
2600
+ constructor(client) {
2601
+ this.client = client;
2602
+ }
2603
+ async getServices() {
2604
+ return safe9(this.client.query("scheduling.services"));
2605
+ }
2606
+ /**
2607
+ * Get a specific service by ID
2608
+ * Note: Filters from all services client-side (no single-service endpoint)
2609
+ */
2610
+ async getService(serviceId) {
2611
+ const result = await this.getServices();
2612
+ if (!result.ok) return result;
2613
+ return ok(result.value.find((s) => s.id === serviceId) || null);
2614
+ }
2615
+ async getAvailableSlots(input) {
2616
+ return safe9(
2617
+ this.client.query("scheduling.slots", toVariables(input))
2618
+ );
2619
+ }
2620
+ async checkSlotAvailability(input) {
2621
+ return safe9(
2622
+ this.client.query(
2623
+ "scheduling.check_availability",
2624
+ toVariables(input)
2625
+ )
2626
+ );
2627
+ }
2628
+ async getServiceAvailability(params) {
2629
+ return safe9(
2630
+ this.client.query(
2631
+ "scheduling.availability",
2632
+ toVariables(params)
2633
+ )
2634
+ );
2635
+ }
2636
+ async getBooking(bookingId) {
2637
+ return safe9(this.client.query(`scheduling.${bookingId}`));
2638
+ }
2639
+ async getCustomerBookings() {
2640
+ return safe9(this.client.query("scheduling"));
2641
+ }
2642
+ async getUpcomingBookings() {
2643
+ return safe9(
2644
+ this.client.query(
2645
+ "scheduling[?(@.status!='completed' && @.status!='cancelled')]#sort(start_time,asc)"
2646
+ )
2647
+ );
2648
+ }
2649
+ async getPastBookings(limit = 10) {
2650
+ return safe9(
2651
+ this.client.query(
2652
+ `scheduling[?(@.status=='completed')]#sort(start_time,desc)#limit(${limit})`
2653
+ )
2654
+ );
2655
+ }
2656
+ async cancelBooking(input) {
2657
+ return safe9(this.client.call("scheduling.cancel_booking", input));
2658
+ }
2659
+ async rescheduleBooking(input) {
2660
+ return safe9(this.client.call("scheduling.reschedule_booking", input));
2661
+ }
2662
+ async getNextAvailableSlot(serviceId, fromDate) {
2663
+ const date = fromDate || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
2664
+ const result = await this.getAvailableSlots({
2665
+ service_id: serviceId,
2666
+ date
2667
+ });
2668
+ if (!result.ok) return result;
2669
+ return ok(result.value.find((slot) => slot.is_available) || null);
2670
+ }
2671
+ async hasAvailabilityOn(serviceId, date) {
2672
+ const result = await this.getAvailableSlots({
2673
+ service_id: serviceId,
2674
+ date
2675
+ });
2676
+ if (!result.ok) return result;
2677
+ return ok(result.value.some((slot) => slot.is_available));
2678
+ }
2679
+ };
2680
+
2681
+ // src/lite.ts
2682
+ function toCimplifyError10(error) {
2683
+ if (error instanceof CimplifyError) return error;
2684
+ if (error instanceof Error) {
2685
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
2686
+ }
2687
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
2688
+ }
2689
+ async function safe10(promise) {
2690
+ try {
2691
+ return ok(await promise);
2692
+ } catch (error) {
2693
+ return err(toCimplifyError10(error));
2694
+ }
2695
+ }
2696
+ var LiteService = class {
2697
+ constructor(client) {
2698
+ this.client = client;
2699
+ }
2700
+ async getBootstrap() {
2701
+ return safe10(this.client.query("lite.bootstrap"));
2702
+ }
2703
+ async getTable(tableId) {
2704
+ return safe10(this.client.query(`lite.table.${tableId}`));
2705
+ }
2706
+ async getTableByNumber(tableNumber, locationId) {
2707
+ return safe10(
2708
+ this.client.query("lite.table_by_number", {
2709
+ table_number: tableNumber,
2710
+ location_id: locationId
2711
+ })
2712
+ );
2713
+ }
2714
+ async sendToKitchen(tableId, items) {
2715
+ return safe10(
2716
+ this.client.call("lite.send_to_kitchen", {
2717
+ table_id: tableId,
2718
+ items
2719
+ })
2720
+ );
2721
+ }
2722
+ async callWaiter(tableId, reason) {
2723
+ return safe10(
2724
+ this.client.call("lite.call_waiter", {
2725
+ table_id: tableId,
2726
+ reason
2727
+ })
2728
+ );
2729
+ }
2730
+ async requestBill(tableId) {
2731
+ return safe10(
2732
+ this.client.call("lite.request_bill", {
2733
+ table_id: tableId
2734
+ })
2735
+ );
2736
+ }
2737
+ async getMenu() {
2738
+ return safe10(this.client.query("lite.menu"));
2739
+ }
2740
+ async getMenuByCategory(categoryId) {
2741
+ return safe10(this.client.query(`lite.menu.category.${categoryId}`));
2742
+ }
2743
+ };
2744
+
2745
+ // src/fx.ts
2746
+ function toCimplifyError11(error) {
2747
+ if (error instanceof CimplifyError) return error;
2748
+ if (error instanceof Error) {
2749
+ return new CimplifyError("UNKNOWN_ERROR", error.message, false);
2750
+ }
2751
+ return new CimplifyError("UNKNOWN_ERROR", String(error), false);
2752
+ }
2753
+ async function safe11(promise) {
2754
+ try {
2755
+ return ok(await promise);
2756
+ } catch (error) {
2757
+ return err(toCimplifyError11(error));
2758
+ }
2759
+ }
2760
+ var FxService = class {
2761
+ constructor(client) {
2762
+ this.client = client;
2763
+ }
2764
+ async getRate(from, to) {
2765
+ return safe11(this.client.call("fx.getRate", { from, to }));
2766
+ }
2767
+ async lockQuote(request) {
2768
+ return safe11(this.client.call("fx.lockQuote", request));
2769
+ }
2770
+ };
2771
+
2772
+ // src/elements.ts
2773
+ function toCheckoutError(code, message, recoverable) {
2774
+ const hint = getErrorHint(code);
2775
+ return {
2776
+ success: false,
2777
+ error: {
2778
+ code,
2779
+ message,
2780
+ recoverable,
2781
+ docs_url: hint?.docs_url,
2782
+ suggestion: hint?.suggestion
2783
+ }
2784
+ };
2785
+ }
2786
+ var DEFAULT_LINK_URL = "https://link.cimplify.io";
2787
+ function isAllowedOrigin(origin) {
2788
+ try {
2789
+ const url = new URL(origin);
2790
+ const hostname = url.hostname;
2791
+ if (hostname === "localhost" || hostname === "127.0.0.1") {
2792
+ return true;
2793
+ }
2794
+ if (url.protocol !== "https:") {
2795
+ return false;
2796
+ }
2797
+ return hostname === "cimplify.io" || hostname.endsWith(".cimplify.io");
2798
+ } catch {
2799
+ return false;
2800
+ }
2801
+ }
2802
+ function parseIframeMessage(data) {
2803
+ if (!data || typeof data !== "object") {
2804
+ return null;
2805
+ }
2806
+ const maybeType = data.type;
2807
+ if (typeof maybeType !== "string") {
2808
+ return null;
2809
+ }
2810
+ return data;
2811
+ }
2812
+ var CimplifyElements = class {
2813
+ constructor(client, businessId, options = {}) {
2814
+ this.elements = /* @__PURE__ */ new Map();
2815
+ this.accessToken = null;
2816
+ this.accountId = null;
2817
+ this.customerId = null;
2818
+ this.customerData = null;
2819
+ this.addressData = null;
2820
+ this.paymentData = null;
2821
+ this.checkoutInProgress = false;
2822
+ this.activeCheckoutAbort = null;
2823
+ this.hasWarnedMissingAuthElement = false;
2824
+ this.businessIdResolvePromise = null;
2825
+ this.client = client;
2826
+ this.businessId = businessId ?? null;
2827
+ this.linkUrl = options.linkUrl || DEFAULT_LINK_URL;
2828
+ this.options = options;
2829
+ this.boundHandleMessage = this.handleMessage.bind(this);
2830
+ if (typeof window !== "undefined") {
2831
+ window.addEventListener("message", this.boundHandleMessage);
2832
+ }
2833
+ }
2834
+ create(type, options = {}) {
2835
+ const existing = this.elements.get(type);
2836
+ if (existing) return existing;
2837
+ const element = new CimplifyElement(type, this.businessId, this.linkUrl, options, this);
2838
+ this.elements.set(type, element);
2839
+ return element;
2840
+ }
2841
+ getElement(type) {
2842
+ return this.elements.get(type);
2843
+ }
2844
+ destroy() {
2845
+ this.elements.forEach((element) => element.destroy());
2846
+ this.elements.clear();
2847
+ if (typeof window !== "undefined") {
2848
+ window.removeEventListener("message", this.boundHandleMessage);
2849
+ }
2850
+ }
2851
+ async submitCheckout(data) {
2852
+ const result = await this.processCheckout({
2853
+ cart_id: data.cart_id,
2854
+ order_type: data.order_type ?? "delivery",
2855
+ location_id: data.location_id,
2856
+ notes: data.notes,
2857
+ scheduled_time: data.scheduled_time,
2858
+ tip_amount: data.tip_amount,
2859
+ enroll_in_link: true
2860
+ });
2861
+ if (result.success) {
2862
+ return {
2863
+ success: true,
2864
+ order: {
2865
+ id: result.order?.id || "",
2866
+ status: result.order?.status || "unknown",
2867
+ total: result.order?.total || ""
2868
+ }
2869
+ };
2870
+ }
2871
+ return {
2872
+ success: false,
2873
+ error: {
2874
+ code: result.error?.code || "CHECKOUT_FAILED",
2875
+ message: result.error?.message || "Checkout failed"
2876
+ }
2877
+ };
2878
+ }
2879
+ processCheckout(options) {
2880
+ let abortFn = null;
2881
+ const task = (async () => {
2882
+ if (this.checkoutInProgress) {
2883
+ return toCheckoutError(
2884
+ "ALREADY_PROCESSING",
2885
+ "Checkout is already in progress.",
2886
+ false
2887
+ );
2888
+ }
2889
+ if (!options.cart_id) {
2890
+ return toCheckoutError(
2891
+ "INVALID_CART",
2892
+ "A valid cart is required before checkout can start.",
2893
+ false
2894
+ );
2895
+ }
2896
+ if (!options.order_type) {
2897
+ return toCheckoutError(
2898
+ "ORDER_TYPE_REQUIRED",
2899
+ "Order type is required before checkout can start.",
2900
+ false
2901
+ );
2902
+ }
2903
+ const paymentElement = this.elements.get(ELEMENT_TYPES.PAYMENT);
2904
+ if (!paymentElement) {
2905
+ return toCheckoutError(
2906
+ "NO_PAYMENT_ELEMENT",
2907
+ "Payment element must be mounted before checkout.",
2908
+ false
2909
+ );
2910
+ }
2911
+ if (!paymentElement.isMounted()) {
2912
+ return toCheckoutError(
2913
+ "PAYMENT_NOT_MOUNTED",
2914
+ "Payment element must be mounted before checkout.",
2915
+ false
2916
+ );
2917
+ }
2918
+ const authElement = this.elements.get(ELEMENT_TYPES.AUTH);
2919
+ if (!authElement && !this.hasWarnedMissingAuthElement) {
2920
+ this.hasWarnedMissingAuthElement = true;
2921
+ console.warn(
2922
+ "[Cimplify] processCheckout() called without AuthElement mounted. For best conversion and Link enrollment, mount <AuthElement> before checkout."
2923
+ );
2924
+ }
2925
+ if (authElement && !this.accessToken) {
2926
+ return toCheckoutError(
2927
+ "AUTH_INCOMPLETE",
2928
+ "Authentication must complete before checkout can start.",
2929
+ true
2930
+ );
2931
+ }
2932
+ const addressElement = this.elements.get(ELEMENT_TYPES.ADDRESS);
2933
+ if (addressElement) {
2934
+ await addressElement.getData();
2935
+ }
2936
+ await this.hydrateCustomerData();
2937
+ const processMessage = {
2938
+ type: MESSAGE_TYPES.PROCESS_CHECKOUT,
2939
+ cart_id: options.cart_id,
2940
+ order_type: options.order_type,
2941
+ location_id: options.location_id,
2942
+ notes: options.notes,
2943
+ scheduled_time: options.scheduled_time,
2944
+ tip_amount: options.tip_amount,
2945
+ pay_currency: options.pay_currency,
2946
+ enroll_in_link: options.enroll_in_link ?? true,
2947
+ address: this.addressData ?? void 0,
2948
+ customer: this.customerData ? {
2949
+ name: this.customerData.name,
2950
+ email: this.customerData.email,
2951
+ phone: this.customerData.phone
2952
+ } : null,
2953
+ account_id: this.accountId ?? void 0,
2954
+ customer_id: this.customerId ?? void 0
2955
+ };
2956
+ const timeoutMs = options.timeout_ms ?? 18e4;
2957
+ const paymentWindow = paymentElement.getContentWindow();
2958
+ this.checkoutInProgress = true;
2959
+ return new Promise((resolve) => {
2960
+ let settled = false;
2961
+ const cleanup = () => {
2962
+ if (typeof window !== "undefined") {
2963
+ window.removeEventListener("message", handleCheckoutMessage);
2964
+ }
2965
+ clearTimeout(timeout);
2966
+ this.checkoutInProgress = false;
2967
+ this.activeCheckoutAbort = null;
2968
+ };
2969
+ const settle = (result) => {
2970
+ if (settled) {
2971
+ return;
2972
+ }
2973
+ settled = true;
2974
+ cleanup();
2975
+ resolve(result);
2976
+ };
2977
+ const timeout = setTimeout(() => {
2978
+ settle(
2979
+ toCheckoutError(
2980
+ "TIMEOUT",
2981
+ "Checkout timed out before receiving a terminal response.",
2982
+ true
2983
+ )
2984
+ );
2985
+ }, timeoutMs);
2986
+ const handleCheckoutMessage = (event) => {
2987
+ if (!isAllowedOrigin(event.origin)) {
2988
+ return;
2989
+ }
2990
+ const message = parseIframeMessage(event.data);
2991
+ if (!message) {
2992
+ return;
2993
+ }
2994
+ if (message.type === MESSAGE_TYPES.LOGOUT_COMPLETE) {
2995
+ paymentElement.sendMessage({ type: MESSAGE_TYPES.ABORT_CHECKOUT });
2996
+ settle(
2997
+ toCheckoutError(
2998
+ "AUTH_LOST",
2999
+ "Authentication was cleared during checkout.",
3000
+ true
3001
+ )
3002
+ );
3003
+ return;
3004
+ }
3005
+ if (paymentWindow && event.source && event.source !== paymentWindow) {
3006
+ return;
3007
+ }
3008
+ if (message.type === MESSAGE_TYPES.CHECKOUT_STATUS) {
3009
+ options.on_status_change?.(message.status, message.context);
3010
+ return;
3011
+ }
3012
+ if (message.type === MESSAGE_TYPES.CHECKOUT_COMPLETE) {
3013
+ settle({
3014
+ success: message.success,
3015
+ order: message.order,
3016
+ error: message.error,
3017
+ enrolled_in_link: message.enrolled_in_link
3018
+ });
3019
+ }
3020
+ };
3021
+ if (typeof window !== "undefined") {
3022
+ window.addEventListener("message", handleCheckoutMessage);
3023
+ }
3024
+ abortFn = () => {
3025
+ paymentElement.sendMessage({ type: MESSAGE_TYPES.ABORT_CHECKOUT });
3026
+ settle(
3027
+ toCheckoutError(
3028
+ "CANCELLED",
3029
+ "Checkout was cancelled.",
3030
+ true
3031
+ )
3032
+ );
3033
+ };
3034
+ this.activeCheckoutAbort = abortFn;
3035
+ paymentElement.sendMessage(processMessage);
3036
+ });
3037
+ })();
3038
+ const abortable = task;
3039
+ abortable.abort = () => {
3040
+ if (abortFn) {
3041
+ abortFn();
3042
+ }
3043
+ };
3044
+ return abortable;
3045
+ }
3046
+ isAuthenticated() {
3047
+ return this.accessToken !== null;
3048
+ }
3049
+ getAccessToken() {
3050
+ return this.accessToken;
3051
+ }
3052
+ getPublicKey() {
3053
+ return this.client.getPublicKey();
3054
+ }
3055
+ getBusinessId() {
3056
+ return this.businessId;
3057
+ }
3058
+ async resolveBusinessId() {
3059
+ if (this.businessId) {
3060
+ return this.businessId;
3061
+ }
3062
+ if (this.businessIdResolvePromise) {
3063
+ return this.businessIdResolvePromise;
3064
+ }
3065
+ this.businessIdResolvePromise = this.client.resolveBusinessId().then((resolvedBusinessId) => {
3066
+ this.businessId = resolvedBusinessId;
3067
+ return resolvedBusinessId;
3068
+ }).catch(() => null).finally(() => {
3069
+ this.businessIdResolvePromise = null;
3070
+ });
3071
+ return this.businessIdResolvePromise;
3072
+ }
3073
+ getAppearance() {
3074
+ return this.options.appearance;
3075
+ }
3076
+ async hydrateCustomerData() {
3077
+ if (!this.accessToken || this.customerData) {
3078
+ return;
3079
+ }
3080
+ if (!this.client.getAccessToken()) {
3081
+ this.client.setAccessToken(this.accessToken);
3082
+ }
3083
+ const linkDataResult = await this.client.link.getLinkData();
3084
+ if (!linkDataResult.ok || !linkDataResult.value?.customer) {
3085
+ return;
3086
+ }
3087
+ const customer = linkDataResult.value.customer;
3088
+ this.customerData = {
3089
+ name: customer.name || "",
3090
+ email: customer.email || null,
3091
+ phone: customer.phone || null
3092
+ };
3093
+ }
3094
+ handleMessage(event) {
3095
+ if (!isAllowedOrigin(event.origin)) {
3096
+ return;
3097
+ }
3098
+ const message = parseIframeMessage(event.data);
3099
+ if (!message) return;
3100
+ switch (message.type) {
3101
+ case MESSAGE_TYPES.AUTHENTICATED:
3102
+ const customer = message.customer ?? {
3103
+ name: "",
3104
+ email: null,
3105
+ phone: null
3106
+ };
3107
+ this.accessToken = message.token;
3108
+ this.accountId = message.accountId;
3109
+ this.customerId = message.customerId;
3110
+ this.customerData = customer;
3111
+ this.client.setAccessToken(message.token);
3112
+ this.elements.forEach((element, type) => {
3113
+ if (type !== ELEMENT_TYPES.AUTH) {
3114
+ element.sendMessage({ type: MESSAGE_TYPES.SET_TOKEN, token: message.token });
3115
+ }
3116
+ });
3117
+ break;
3118
+ case MESSAGE_TYPES.TOKEN_REFRESHED:
3119
+ this.accessToken = message.token;
3120
+ break;
3121
+ case MESSAGE_TYPES.ADDRESS_CHANGED:
3122
+ case MESSAGE_TYPES.ADDRESS_SELECTED:
3123
+ this.addressData = message.address;
3124
+ break;
3125
+ case MESSAGE_TYPES.PAYMENT_METHOD_SELECTED:
3126
+ this.paymentData = message.method;
3127
+ break;
3128
+ case MESSAGE_TYPES.LOGOUT_COMPLETE:
3129
+ if (this.checkoutInProgress && this.activeCheckoutAbort) {
3130
+ this.activeCheckoutAbort();
3131
+ }
3132
+ this.accessToken = null;
3133
+ this.accountId = null;
3134
+ this.customerId = null;
3135
+ this.customerData = null;
3136
+ this.addressData = null;
3137
+ this.paymentData = null;
3138
+ this.client.clearSession();
3139
+ break;
3140
+ }
3141
+ }
3142
+ _setAddressData(data) {
3143
+ this.addressData = data;
3144
+ }
3145
+ _setPaymentData(data) {
3146
+ this.paymentData = data;
3147
+ }
3148
+ };
3149
+ var CimplifyElement = class {
3150
+ constructor(type, businessId, linkUrl, options, parent) {
3151
+ this.iframe = null;
3152
+ this.container = null;
3153
+ this.mounted = false;
3154
+ this.eventHandlers = /* @__PURE__ */ new Map();
3155
+ this.resolvers = /* @__PURE__ */ new Map();
3156
+ this.type = type;
3157
+ this.businessId = businessId;
3158
+ this.linkUrl = linkUrl;
3159
+ this.options = options;
3160
+ this.parent = parent;
3161
+ this.boundHandleMessage = this.handleMessage.bind(this);
3162
+ if (typeof window !== "undefined") {
3163
+ window.addEventListener("message", this.boundHandleMessage);
3164
+ }
3165
+ }
3166
+ mount(container) {
3167
+ if (this.mounted) {
3168
+ console.warn(`Element ${this.type} is already mounted`);
3169
+ return;
3170
+ }
3171
+ const target = typeof container === "string" ? document.querySelector(container) : container;
3172
+ if (!target) {
3173
+ console.error(`Container not found: ${container}`);
3174
+ return;
3175
+ }
3176
+ this.container = target;
3177
+ this.mounted = true;
3178
+ void this.createIframe();
3179
+ }
3180
+ destroy() {
3181
+ if (this.iframe) {
3182
+ this.iframe.remove();
3183
+ this.iframe = null;
3184
+ }
3185
+ this.container = null;
3186
+ this.mounted = false;
3187
+ this.eventHandlers.clear();
3188
+ this.resolvers.forEach((entry) => clearTimeout(entry.timeoutId));
3189
+ this.resolvers.clear();
3190
+ if (typeof window !== "undefined") {
3191
+ window.removeEventListener("message", this.boundHandleMessage);
3192
+ }
3193
+ }
3194
+ on(event, handler) {
3195
+ if (!this.eventHandlers.has(event)) {
3196
+ this.eventHandlers.set(event, /* @__PURE__ */ new Set());
3197
+ }
3198
+ this.eventHandlers.get(event).add(handler);
3199
+ }
3200
+ off(event, handler) {
3201
+ this.eventHandlers.get(event)?.delete(handler);
3202
+ }
3203
+ async getData() {
3204
+ if (!this.isMounted()) {
3205
+ return null;
3206
+ }
3207
+ return new Promise((resolve) => {
3208
+ const id = Math.random().toString(36).slice(2);
3209
+ const timeoutId = setTimeout(() => {
3210
+ const entry = this.resolvers.get(id);
3211
+ if (!entry) {
3212
+ return;
3213
+ }
3214
+ this.resolvers.delete(id);
3215
+ entry.resolve(null);
3216
+ }, 5e3);
3217
+ this.resolvers.set(id, { resolve, timeoutId });
3218
+ this.sendMessage({ type: MESSAGE_TYPES.GET_DATA });
3219
+ });
3220
+ }
3221
+ sendMessage(message) {
3222
+ if (this.iframe?.contentWindow) {
3223
+ this.iframe.contentWindow.postMessage(message, this.linkUrl);
3224
+ }
3225
+ }
3226
+ getContentWindow() {
3227
+ return this.iframe?.contentWindow ?? null;
3228
+ }
3229
+ isMounted() {
3230
+ return this.mounted && Boolean(this.iframe) && this.iframe?.isConnected === true;
3231
+ }
3232
+ async createIframe() {
3233
+ if (!this.container) return;
3234
+ const resolvedBusinessId = this.businessId ?? await this.parent.resolveBusinessId();
3235
+ if (!resolvedBusinessId || !this.container || !this.mounted) {
3236
+ console.error("Unable to mount element without a resolved business ID");
3237
+ this.emit(EVENT_TYPES.ERROR, {
3238
+ code: "BUSINESS_ID_REQUIRED",
3239
+ message: "Unable to initialize checkout without a business ID."
3240
+ });
3241
+ return;
3242
+ }
3243
+ this.businessId = resolvedBusinessId;
3244
+ const iframe = document.createElement("iframe");
3245
+ const url = new URL(`${this.linkUrl}/elements/${this.type}`);
3246
+ url.searchParams.set("businessId", resolvedBusinessId);
3247
+ if (this.options.prefillEmail) url.searchParams.set("email", this.options.prefillEmail);
3248
+ if (this.options.mode) url.searchParams.set("mode", this.options.mode);
3249
+ iframe.src = url.toString();
3250
+ iframe.style.border = "none";
3251
+ iframe.style.width = "100%";
3252
+ iframe.style.display = "block";
3253
+ iframe.style.overflow = "hidden";
3254
+ iframe.setAttribute("allowtransparency", "true");
3255
+ iframe.setAttribute("frameborder", "0");
3256
+ iframe.setAttribute(
3257
+ "sandbox",
3258
+ "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"
3259
+ );
3260
+ this.iframe = iframe;
3261
+ this.container.appendChild(iframe);
3262
+ iframe.onload = () => {
3263
+ const publicKey = this.parent.getPublicKey();
3264
+ this.sendMessage({
3265
+ type: MESSAGE_TYPES.INIT,
3266
+ businessId: resolvedBusinessId,
3267
+ publicKey,
3268
+ demoMode: publicKey.length === 0,
3269
+ prefillEmail: this.options.prefillEmail,
3270
+ appearance: this.parent.getAppearance()
3271
+ });
3272
+ const token = this.parent.getAccessToken();
3273
+ if (token && this.type !== ELEMENT_TYPES.AUTH) {
3274
+ this.sendMessage({ type: MESSAGE_TYPES.SET_TOKEN, token });
3275
+ }
3276
+ };
3277
+ }
3278
+ handleMessage(event) {
3279
+ if (!isAllowedOrigin(event.origin)) {
3280
+ return;
3281
+ }
3282
+ const message = parseIframeMessage(event.data);
3283
+ if (!message) return;
3284
+ switch (message.type) {
3285
+ case MESSAGE_TYPES.READY:
3286
+ this.emit(EVENT_TYPES.READY, { height: message.height });
3287
+ break;
3288
+ case MESSAGE_TYPES.HEIGHT_CHANGE:
3289
+ if (this.iframe) this.iframe.style.height = `${message.height}px`;
3290
+ break;
3291
+ case MESSAGE_TYPES.AUTHENTICATED:
3292
+ const customer = message.customer ?? {
3293
+ name: "",
3294
+ email: null,
3295
+ phone: null
3296
+ };
3297
+ this.emit(EVENT_TYPES.AUTHENTICATED, {
3298
+ accountId: message.accountId,
3299
+ customerId: message.customerId,
3300
+ token: message.token,
3301
+ customer
3302
+ });
3303
+ break;
3304
+ case MESSAGE_TYPES.REQUIRES_OTP:
3305
+ this.emit(EVENT_TYPES.REQUIRES_OTP, { contactMasked: message.contactMasked });
3306
+ break;
3307
+ case MESSAGE_TYPES.ERROR:
3308
+ this.emit(EVENT_TYPES.ERROR, { code: message.code, message: message.message });
3309
+ break;
3310
+ case MESSAGE_TYPES.ADDRESS_CHANGED:
3311
+ case MESSAGE_TYPES.ADDRESS_SELECTED:
3312
+ this.parent._setAddressData(message.address);
3313
+ this.emit(EVENT_TYPES.CHANGE, { address: message.address });
3314
+ this.resolveData(message.address);
3315
+ break;
3316
+ case MESSAGE_TYPES.PAYMENT_METHOD_SELECTED:
3317
+ this.parent._setPaymentData(message.method);
3318
+ this.emit(EVENT_TYPES.CHANGE, { paymentMethod: message.method });
3319
+ this.resolveData(message.method);
3320
+ break;
3321
+ }
3322
+ }
3323
+ emit(event, data) {
3324
+ this.eventHandlers.get(event)?.forEach((handler) => handler(data));
3325
+ }
3326
+ resolveData(data) {
3327
+ this.resolvers.forEach((entry) => {
3328
+ clearTimeout(entry.timeoutId);
3329
+ entry.resolve(data);
3330
+ });
3331
+ this.resolvers.clear();
3332
+ }
3333
+ };
3334
+ function createElements(client, businessId, options) {
3335
+ return new CimplifyElements(client, businessId, options);
3336
+ }
3337
+
3338
+ // src/client.ts
3339
+ var ACCESS_TOKEN_STORAGE_KEY = "cimplify_access_token";
3340
+ var DEFAULT_TIMEOUT_MS = 3e4;
3341
+ var DEFAULT_MAX_RETRIES = 3;
3342
+ var DEFAULT_RETRY_DELAY_MS = 1e3;
3343
+ function sleep(ms) {
3344
+ return new Promise((resolve) => setTimeout(resolve, ms));
3345
+ }
3346
+ function isRetryable(error) {
3347
+ if (error instanceof TypeError && error.message.includes("fetch")) {
3348
+ return true;
3349
+ }
3350
+ if (error instanceof DOMException && error.name === "AbortError") {
3351
+ return true;
3352
+ }
3353
+ if (error instanceof CimplifyError) {
3354
+ return error.retryable;
3355
+ }
3356
+ if (error instanceof CimplifyError && error.code === "SERVER_ERROR") {
3357
+ return true;
3358
+ }
3359
+ return false;
3360
+ }
3361
+ function toNetworkError(error, isTestMode) {
3362
+ if (error instanceof DOMException && error.name === "AbortError") {
3363
+ return enrichError(
3364
+ new CimplifyError(
3365
+ ErrorCode.TIMEOUT,
3366
+ "Request timed out. Please check your connection and try again.",
3367
+ true
3368
+ ),
3369
+ { isTestMode }
3370
+ );
3371
+ }
3372
+ if (error instanceof TypeError && error.message.includes("fetch")) {
3373
+ return enrichError(
3374
+ new CimplifyError(
3375
+ ErrorCode.NETWORK_ERROR,
3376
+ "Network error. Please check your internet connection.",
3377
+ true
3378
+ ),
3379
+ { isTestMode }
3380
+ );
3381
+ }
3382
+ if (error instanceof CimplifyError) {
3383
+ return enrichError(error, { isTestMode });
3384
+ }
3385
+ return enrichError(
3386
+ new CimplifyError(
3387
+ ErrorCode.UNKNOWN_ERROR,
3388
+ error instanceof Error ? error.message : "An unknown error occurred",
3389
+ false
3390
+ ),
3391
+ { isTestMode }
3392
+ );
3393
+ }
3394
+ function deriveUrls() {
3395
+ const hostname = typeof window !== "undefined" ? window.location.hostname : "";
3396
+ if (hostname === "localhost" || hostname === "127.0.0.1") {
3397
+ const protocol = window.location.protocol;
3398
+ return {
3399
+ baseUrl: `${protocol}//${hostname}:8082`,
3400
+ linkApiUrl: `${protocol}//${hostname}:8080`
3401
+ };
3402
+ }
3403
+ return {
3404
+ baseUrl: "https://storefronts.cimplify.io",
3405
+ linkApiUrl: "https://api.cimplify.io"
3406
+ };
3407
+ }
3408
+ function getEnvPublicKey() {
3409
+ try {
3410
+ const env = globalThis.process;
3411
+ return env?.env.NEXT_PUBLIC_CIMPLIFY_PUBLIC_KEY || void 0;
3412
+ } catch {
3413
+ return void 0;
3414
+ }
3415
+ }
3416
+ var CimplifyClient = class {
3417
+ constructor(config = {}) {
3418
+ this.accessToken = null;
3419
+ this.context = {};
3420
+ this.businessId = null;
3421
+ this.businessIdResolvePromise = null;
3422
+ this.inflightRequests = /* @__PURE__ */ new Map();
3423
+ this.publicKey = config.publicKey || getEnvPublicKey() || "";
3424
+ const urls = deriveUrls();
3425
+ this.baseUrl = urls.baseUrl;
3426
+ this.linkApiUrl = urls.linkApiUrl;
3427
+ this.credentials = config.credentials || "include";
3428
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;
3429
+ this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
3430
+ this.retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;
3431
+ this.hooks = config.hooks ?? {};
3432
+ this.accessToken = this.loadAccessToken();
3433
+ if (!this.publicKey) {
3434
+ console.warn(
3435
+ '[Cimplify] No public key found. Set NEXT_PUBLIC_CIMPLIFY_PUBLIC_KEY in your environment, or pass { publicKey: "pk_..." } to createCimplifyClient().'
3436
+ );
3437
+ }
3438
+ }
3439
+ /** @deprecated Use getAccessToken() instead */
3440
+ getSessionToken() {
3441
+ return this.accessToken;
3442
+ }
3443
+ /** @deprecated Use setAccessToken() instead */
3444
+ setSessionToken(token) {
3445
+ this.setAccessToken(token);
3446
+ }
3447
+ getAccessToken() {
3448
+ return this.accessToken;
3449
+ }
3450
+ getPublicKey() {
3451
+ return this.publicKey;
3452
+ }
3453
+ isTestMode() {
3454
+ return this.publicKey.trim().startsWith("pk_test_");
3455
+ }
3456
+ setAccessToken(token) {
3457
+ const previous = this.accessToken;
3458
+ this.accessToken = token;
3459
+ this.saveAccessToken(token);
3460
+ this.hooks.onSessionChange?.({
3461
+ previousToken: previous,
3462
+ newToken: token,
3463
+ source: "manual"
3464
+ });
3465
+ }
3466
+ clearSession() {
3467
+ const previous = this.accessToken;
3468
+ this.accessToken = null;
3469
+ this.saveAccessToken(null);
3470
+ this.hooks.onSessionChange?.({
3471
+ previousToken: previous,
3472
+ newToken: null,
3473
+ source: "clear"
3474
+ });
3475
+ }
3476
+ /** Set the active location/branch for all subsequent requests */
3477
+ setLocationId(locationId) {
3478
+ if (locationId) {
3479
+ this.context.location_id = locationId;
3480
+ } else {
3481
+ delete this.context.location_id;
3482
+ }
3483
+ }
3484
+ /** Get the currently active location ID */
3485
+ getLocationId() {
3486
+ return this.context.location_id ?? null;
3487
+ }
3488
+ /** Cache a resolved business ID for future element/checkouts initialization. */
3489
+ setBusinessId(businessId) {
3490
+ const normalized = businessId.trim();
3491
+ if (!normalized) {
3492
+ return;
3493
+ }
3494
+ this.businessId = normalized;
3495
+ }
3496
+ /** Get cached business ID if available. */
3497
+ getBusinessId() {
3498
+ return this.businessId;
3499
+ }
3500
+ /**
3501
+ * Resolve business ID from public key once and cache it.
3502
+ * Subsequent calls return the cached value (or shared in-flight promise).
3503
+ */
3504
+ async resolveBusinessId() {
3505
+ if (this.businessId) {
3506
+ return this.businessId;
3507
+ }
3508
+ if (this.businessIdResolvePromise) {
3509
+ return this.businessIdResolvePromise;
3510
+ }
3511
+ this.businessIdResolvePromise = (async () => {
3512
+ const result = await this.business.getInfo();
3513
+ if (!result.ok || !result.value?.id) {
3514
+ throw new CimplifyError(
3515
+ ErrorCode.NOT_FOUND,
3516
+ "Unable to resolve business ID from the current public key.",
3517
+ true
3518
+ );
3519
+ }
3520
+ this.businessId = result.value.id;
3521
+ return result.value.id;
3522
+ })();
3523
+ try {
3524
+ return await this.businessIdResolvePromise;
3525
+ } finally {
3526
+ this.businessIdResolvePromise = null;
3527
+ }
3528
+ }
3529
+ loadAccessToken() {
3530
+ if (typeof window !== "undefined" && window.localStorage) {
3531
+ return localStorage.getItem(ACCESS_TOKEN_STORAGE_KEY);
3532
+ }
3533
+ return null;
3534
+ }
3535
+ saveAccessToken(token) {
3536
+ if (typeof window !== "undefined" && window.localStorage) {
3537
+ if (token) {
3538
+ localStorage.setItem(ACCESS_TOKEN_STORAGE_KEY, token);
3539
+ } else {
3540
+ localStorage.removeItem(ACCESS_TOKEN_STORAGE_KEY);
3541
+ }
3542
+ }
3543
+ }
3544
+ getHeaders() {
3545
+ const headers = {
3546
+ "Content-Type": "application/json",
3547
+ "X-API-Key": this.publicKey
3548
+ };
3549
+ if (this.accessToken) {
3550
+ headers["Authorization"] = `Bearer ${this.accessToken}`;
3551
+ }
3552
+ return headers;
3553
+ }
3554
+ async resilientFetch(url, options) {
3555
+ const method = options.method || "GET";
3556
+ const path = url.replace(this.baseUrl, "").replace(this.linkApiUrl, "");
3557
+ const startTime = Date.now();
3558
+ let retryCount = 0;
3559
+ const context = {
3560
+ method,
3561
+ path,
3562
+ url,
3563
+ body: options.body ? JSON.parse(options.body) : void 0,
3564
+ startTime
3565
+ };
3566
+ this.hooks.onRequestStart?.(context);
3567
+ let lastError;
3568
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
3569
+ try {
3570
+ const controller = new AbortController();
3571
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
3572
+ const response = await fetch(url, {
3573
+ ...options,
3574
+ signal: controller.signal
3575
+ });
3576
+ clearTimeout(timeoutId);
3577
+ if (response.ok || response.status >= 400 && response.status < 500) {
3578
+ this.hooks.onRequestSuccess?.({
3579
+ ...context,
3580
+ status: response.status,
3581
+ durationMs: Date.now() - startTime
3582
+ });
3583
+ return response;
3584
+ }
3585
+ if (response.status >= 500 && attempt < this.maxRetries) {
3586
+ retryCount++;
3587
+ const delay = this.retryDelay * Math.pow(2, attempt);
3588
+ this.hooks.onRetry?.({
3589
+ ...context,
3590
+ attempt: retryCount,
3591
+ delayMs: delay,
3592
+ error: new Error(`Server error: ${response.status}`)
3593
+ });
3594
+ await sleep(delay);
3595
+ continue;
3596
+ }
3597
+ this.hooks.onRequestSuccess?.({
3598
+ ...context,
3599
+ status: response.status,
3600
+ durationMs: Date.now() - startTime
3601
+ });
3602
+ return response;
3603
+ } catch (error) {
3604
+ lastError = error;
3605
+ const networkError = toNetworkError(error, this.isTestMode());
3606
+ const errorRetryable = isRetryable(error);
3607
+ if (!errorRetryable || attempt >= this.maxRetries) {
3608
+ this.hooks.onRequestError?.({
3609
+ ...context,
3610
+ error: networkError,
3611
+ durationMs: Date.now() - startTime,
3612
+ retryCount,
3613
+ retryable: errorRetryable
3614
+ });
3615
+ throw networkError;
3616
+ }
3617
+ retryCount++;
3618
+ const delay = this.retryDelay * Math.pow(2, attempt);
3619
+ this.hooks.onRetry?.({
3620
+ ...context,
3621
+ attempt: retryCount,
3622
+ delayMs: delay,
3623
+ error: networkError
3624
+ });
3625
+ await sleep(delay);
3626
+ }
3627
+ }
3628
+ const finalError = toNetworkError(lastError, this.isTestMode());
3629
+ this.hooks.onRequestError?.({
3630
+ ...context,
3631
+ error: finalError,
3632
+ durationMs: Date.now() - startTime,
3633
+ retryCount,
3634
+ retryable: false
3635
+ });
3636
+ throw finalError;
3637
+ }
3638
+ getDedupeKey(type, payload) {
3639
+ return `${type}:${JSON.stringify(payload)}`;
3640
+ }
3641
+ async deduplicatedRequest(key, requestFn) {
3642
+ const existing = this.inflightRequests.get(key);
3643
+ if (existing) {
3644
+ return existing;
3645
+ }
3646
+ const request = requestFn().finally(() => {
3647
+ this.inflightRequests.delete(key);
3648
+ });
3649
+ this.inflightRequests.set(key, request);
3650
+ return request;
3651
+ }
3652
+ async query(query, variables) {
3653
+ const body = { query };
3654
+ if (variables) {
3655
+ body.variables = variables;
3656
+ }
3657
+ if (Object.keys(this.context).length > 0) {
3658
+ body.context = this.context;
3659
+ }
3660
+ const key = this.getDedupeKey("query", body);
3661
+ return this.deduplicatedRequest(key, async () => {
3662
+ const response = await this.resilientFetch(`${this.baseUrl}/api/q`, {
3663
+ method: "POST",
3664
+ credentials: this.credentials,
3665
+ headers: this.getHeaders(),
3666
+ body: JSON.stringify(body)
3667
+ });
3668
+ return this.handleResponse(response);
3669
+ });
3670
+ }
3671
+ async call(method, args) {
3672
+ const body = {
3673
+ method,
3674
+ args: args !== void 0 ? [args] : []
3675
+ };
3676
+ if (Object.keys(this.context).length > 0) {
3677
+ body.context = this.context;
3678
+ }
3679
+ const response = await this.resilientFetch(`${this.baseUrl}/api/m`, {
3680
+ method: "POST",
3681
+ credentials: this.credentials,
3682
+ headers: this.getHeaders(),
3683
+ body: JSON.stringify(body)
3684
+ });
3685
+ return this.handleResponse(response);
3686
+ }
3687
+ async get(path) {
3688
+ const key = this.getDedupeKey("get", path);
3689
+ return this.deduplicatedRequest(key, async () => {
3690
+ const response = await this.resilientFetch(`${this.baseUrl}${path}`, {
3691
+ method: "GET",
3692
+ credentials: this.credentials,
3693
+ headers: this.getHeaders()
3694
+ });
3695
+ return this.handleRestResponse(response);
3696
+ });
3697
+ }
3698
+ async post(path, body) {
3699
+ const response = await this.resilientFetch(`${this.baseUrl}${path}`, {
3700
+ method: "POST",
3701
+ credentials: this.credentials,
3702
+ headers: this.getHeaders(),
3703
+ body: body ? JSON.stringify(body) : void 0
3704
+ });
3705
+ return this.handleRestResponse(response);
3706
+ }
3707
+ async delete(path) {
3708
+ const response = await this.resilientFetch(`${this.baseUrl}${path}`, {
3709
+ method: "DELETE",
3710
+ credentials: this.credentials,
3711
+ headers: this.getHeaders()
3712
+ });
3713
+ return this.handleRestResponse(response);
3714
+ }
3715
+ async linkGet(path) {
3716
+ const key = this.getDedupeKey("linkGet", path);
3717
+ return this.deduplicatedRequest(key, async () => {
3718
+ const response = await this.resilientFetch(`${this.linkApiUrl}${path}`, {
3719
+ method: "GET",
3720
+ credentials: this.credentials,
3721
+ headers: this.getHeaders()
3722
+ });
3723
+ return this.handleRestResponse(response);
3724
+ });
3725
+ }
3726
+ async linkPost(path, body) {
3727
+ const response = await this.resilientFetch(`${this.linkApiUrl}${path}`, {
3728
+ method: "POST",
3729
+ credentials: this.credentials,
3730
+ headers: this.getHeaders(),
3731
+ body: body ? JSON.stringify(body) : void 0
3732
+ });
3733
+ return this.handleRestResponse(response);
3734
+ }
3735
+ async linkDelete(path) {
3736
+ const response = await this.resilientFetch(`${this.linkApiUrl}${path}`, {
3737
+ method: "DELETE",
3738
+ credentials: this.credentials,
3739
+ headers: this.getHeaders()
3740
+ });
3741
+ return this.handleRestResponse(response);
3742
+ }
3743
+ async handleRestResponse(response) {
3744
+ const json = await response.json();
3745
+ if (!response.ok) {
3746
+ const error = enrichError(
3747
+ new CimplifyError(
3748
+ json.error?.error_code || "API_ERROR",
3749
+ json.error?.error_message || "An error occurred",
3750
+ false
3751
+ ),
3752
+ { isTestMode: this.isTestMode() }
3753
+ );
3754
+ if (response.status === 401 || error.code === ErrorCode.UNAUTHORIZED) {
3755
+ console.warn(
3756
+ "[Cimplify] Received 401 Unauthorized. Access token may be missing/expired. Refresh authentication and retry the request."
3757
+ );
3758
+ }
3759
+ throw error;
3760
+ }
3761
+ return json.data;
3762
+ }
3763
+ async handleResponse(response) {
3764
+ const json = await response.json();
3765
+ if (!json.success || json.error) {
3766
+ const error = enrichError(
3767
+ new CimplifyError(
3768
+ json.error?.code || "UNKNOWN_ERROR",
3769
+ json.error?.message || "An unknown error occurred",
3770
+ json.error?.retryable || false
3771
+ ),
3772
+ { isTestMode: this.isTestMode() }
3773
+ );
3774
+ if (response.status === 401 || error.code === ErrorCode.UNAUTHORIZED) {
3775
+ console.warn(
3776
+ "[Cimplify] Received 401 Unauthorized. Access token may be missing/expired. Refresh authentication and retry the request."
3777
+ );
3778
+ }
3779
+ throw error;
3780
+ }
3781
+ return json.data;
3782
+ }
3783
+ get catalogue() {
3784
+ if (!this._catalogue) {
3785
+ this._catalogue = new CatalogueQueries(this);
3786
+ }
3787
+ return this._catalogue;
3788
+ }
3789
+ get cart() {
3790
+ if (!this._cart) {
3791
+ this._cart = new CartOperations(this);
3792
+ }
3793
+ return this._cart;
3794
+ }
3795
+ get checkout() {
3796
+ if (!this._checkout) {
3797
+ this._checkout = new CheckoutService(this);
3798
+ }
3799
+ return this._checkout;
3800
+ }
3801
+ get orders() {
3802
+ if (!this._orders) {
3803
+ this._orders = new OrderQueries(this);
3804
+ }
3805
+ return this._orders;
3806
+ }
3807
+ get link() {
3808
+ if (!this._link) {
3809
+ this._link = new LinkService(this);
3810
+ }
3811
+ return this._link;
3812
+ }
3813
+ get auth() {
3814
+ if (!this._auth) {
3815
+ this._auth = new AuthService(this);
3816
+ }
3817
+ return this._auth;
3818
+ }
3819
+ get business() {
3820
+ if (!this._business) {
3821
+ this._business = new BusinessService(this);
3822
+ }
3823
+ return this._business;
3824
+ }
3825
+ get inventory() {
3826
+ if (!this._inventory) {
3827
+ this._inventory = new InventoryService(this);
3828
+ }
3829
+ return this._inventory;
3830
+ }
3831
+ get scheduling() {
3832
+ if (!this._scheduling) {
3833
+ this._scheduling = new SchedulingService(this);
3834
+ }
3835
+ return this._scheduling;
3836
+ }
3837
+ get lite() {
3838
+ if (!this._lite) {
3839
+ this._lite = new LiteService(this);
3840
+ }
3841
+ return this._lite;
3842
+ }
3843
+ get fx() {
3844
+ if (!this._fx) {
3845
+ this._fx = new FxService(this);
3846
+ }
3847
+ return this._fx;
3848
+ }
3849
+ /**
3850
+ * Create a CimplifyElements instance for embedding checkout components.
3851
+ * Like Stripe's stripe.elements().
3852
+ *
3853
+ * @param businessId - The business ID for checkout context
3854
+ * @param options - Optional configuration for elements
3855
+ *
3856
+ * @example
3857
+ * ```ts
3858
+ * const elements = client.elements('bus_xxx');
3859
+ * const authElement = elements.create('auth');
3860
+ * authElement.mount('#auth-container');
3861
+ * ```
3862
+ */
3863
+ elements(businessId, options) {
3864
+ if (businessId) {
3865
+ this.setBusinessId(businessId);
3866
+ }
3867
+ return createElements(this, businessId ?? this.businessId ?? void 0, options);
3868
+ }
3869
+ };
3870
+ function createCimplifyClient(config = {}) {
3871
+ return new CimplifyClient(config);
3872
+ }
3873
+ var LOCATION_STORAGE_KEY = "cimplify_location_id";
3874
+ var DEFAULT_CURRENCY = "USD";
3875
+ var DEFAULT_COUNTRY = "US";
3876
+ function createDefaultClient() {
3877
+ const processRef = globalThis.process;
3878
+ const envPublicKey = processRef?.env?.NEXT_PUBLIC_CIMPLIFY_PUBLIC_KEY || "";
3879
+ return createCimplifyClient({ publicKey: envPublicKey });
3880
+ }
3881
+ function getStoredLocationId() {
3882
+ if (typeof window === "undefined" || !window.localStorage) {
3883
+ return null;
3884
+ }
3885
+ const value = window.localStorage.getItem(LOCATION_STORAGE_KEY);
3886
+ if (!value) {
3887
+ return null;
3888
+ }
3889
+ const normalized = value.trim();
3890
+ return normalized.length > 0 ? normalized : null;
3891
+ }
3892
+ function setStoredLocationId(locationId) {
3893
+ if (typeof window === "undefined" || !window.localStorage) {
3894
+ return;
3895
+ }
3896
+ if (!locationId) {
3897
+ window.localStorage.removeItem(LOCATION_STORAGE_KEY);
3898
+ return;
3899
+ }
3900
+ window.localStorage.setItem(LOCATION_STORAGE_KEY, locationId);
3901
+ }
3902
+ function resolveInitialLocation(locations) {
3903
+ if (locations.length === 0) {
3904
+ return null;
3905
+ }
3906
+ const storedId = getStoredLocationId();
3907
+ if (storedId) {
3908
+ const matched = locations.find((location) => location.id === storedId);
3909
+ if (matched) {
3910
+ return matched;
3911
+ }
3912
+ }
3913
+ return locations[0];
3914
+ }
3915
+ var CimplifyContext = createContext(null);
3916
+ function CimplifyProvider({
3917
+ client,
3918
+ children,
3919
+ onLocationChange
3920
+ }) {
3921
+ const resolvedClient = useMemo(() => client ?? createDefaultClient(), [client]);
3922
+ const onLocationChangeRef = useRef(onLocationChange);
3923
+ const [business, setBusiness] = useState(null);
3924
+ const [locations, setLocations] = useState([]);
3925
+ const [currentLocation, setCurrentLocationState] = useState(null);
3926
+ const [isReady, setIsReady] = useState(false);
3927
+ useEffect(() => {
3928
+ onLocationChangeRef.current = onLocationChange;
3929
+ }, [onLocationChange]);
3930
+ const isDemoMode = resolvedClient.getPublicKey().trim().length === 0;
3931
+ const setCurrentLocation = useCallback(
3932
+ (location) => {
3933
+ setCurrentLocationState(location);
3934
+ resolvedClient.setLocationId(location.id);
3935
+ setStoredLocationId(location.id);
3936
+ onLocationChangeRef.current?.(location);
3937
+ },
3938
+ [resolvedClient]
3939
+ );
3940
+ useEffect(() => {
3941
+ let cancelled = false;
3942
+ async function bootstrap() {
3943
+ setIsReady(false);
3944
+ if (isDemoMode) {
3945
+ if (!cancelled) {
3946
+ setBusiness(null);
3947
+ setLocations([]);
3948
+ setCurrentLocationState(null);
3949
+ resolvedClient.setLocationId(null);
3950
+ setStoredLocationId(null);
3951
+ setIsReady(true);
3952
+ }
3953
+ return;
3954
+ }
3955
+ const [businessResult, locationsResult] = await Promise.all([
3956
+ resolvedClient.business.getInfo(),
3957
+ resolvedClient.business.getLocations()
3958
+ ]);
3959
+ if (cancelled) {
3960
+ return;
3961
+ }
3962
+ const nextBusiness = businessResult.ok ? businessResult.value : null;
3963
+ const nextLocations = locationsResult.ok && Array.isArray(locationsResult.value) ? locationsResult.value : [];
3964
+ const initialLocation = resolveInitialLocation(nextLocations);
3965
+ setBusiness(nextBusiness);
3966
+ if (nextBusiness?.id) {
3967
+ resolvedClient.setBusinessId(nextBusiness.id);
3968
+ }
3969
+ setLocations(nextLocations);
3970
+ if (initialLocation) {
3971
+ setCurrentLocationState(initialLocation);
3972
+ resolvedClient.setLocationId(initialLocation.id);
3973
+ setStoredLocationId(initialLocation.id);
3974
+ } else {
3975
+ setCurrentLocationState(null);
3976
+ resolvedClient.setLocationId(null);
3977
+ setStoredLocationId(null);
3978
+ }
3979
+ setIsReady(true);
3980
+ }
3981
+ bootstrap().catch(() => {
3982
+ if (cancelled) {
3983
+ return;
3984
+ }
3985
+ setBusiness(null);
3986
+ setLocations([]);
3987
+ setCurrentLocationState(null);
3988
+ resolvedClient.setLocationId(null);
3989
+ setStoredLocationId(null);
3990
+ setIsReady(true);
3991
+ });
3992
+ return () => {
3993
+ cancelled = true;
3994
+ };
3995
+ }, [resolvedClient, isDemoMode]);
3996
+ const contextValue = useMemo(
3997
+ () => ({
3998
+ client: resolvedClient,
3999
+ business,
4000
+ currency: business?.default_currency || DEFAULT_CURRENCY,
4001
+ country: business?.country_code || DEFAULT_COUNTRY,
4002
+ locations,
4003
+ currentLocation,
4004
+ setCurrentLocation,
4005
+ isReady,
4006
+ isDemoMode
4007
+ }),
4008
+ [
4009
+ resolvedClient,
4010
+ business,
4011
+ locations,
4012
+ currentLocation,
4013
+ setCurrentLocation,
4014
+ isReady,
4015
+ isDemoMode
4016
+ ]
4017
+ );
4018
+ return /* @__PURE__ */ jsx(CimplifyContext.Provider, { value: contextValue, children });
4019
+ }
4020
+ function useCimplify() {
4021
+ const context = useContext(CimplifyContext);
4022
+ if (!context) {
4023
+ throw new Error("useCimplify must be used within CimplifyProvider");
4024
+ }
4025
+ return context;
4026
+ }
4027
+ function useOptionalCimplify() {
4028
+ return useContext(CimplifyContext);
4029
+ }
4030
+ var productsCache = /* @__PURE__ */ new Map();
4031
+ var productsInflight = /* @__PURE__ */ new Map();
4032
+ function buildProductsCacheKey(client, locationId, options) {
4033
+ return JSON.stringify({
4034
+ key: client.getPublicKey(),
4035
+ location_id: locationId || "__none__",
4036
+ options
4037
+ });
4038
+ }
4039
+ function useProducts(options = {}) {
4040
+ const context = useOptionalCimplify();
4041
+ const client = options.client ?? context?.client;
4042
+ if (!client) {
4043
+ throw new Error("useProducts must be used within CimplifyProvider or passed { client }.");
4044
+ }
4045
+ const enabled = options.enabled ?? true;
4046
+ const locationId = client.getLocationId();
4047
+ const previousLocationIdRef = useRef(locationId);
4048
+ const requestIdRef = useRef(0);
4049
+ const queryOptions = useMemo(
4050
+ () => ({
4051
+ category: options.category,
4052
+ collection: options.collection,
4053
+ search: options.search,
4054
+ featured: options.featured,
4055
+ limit: options.limit
4056
+ }),
4057
+ [options.category, options.collection, options.featured, options.limit, options.search]
4058
+ );
4059
+ const cacheKey = useMemo(
4060
+ () => buildProductsCacheKey(client, locationId, queryOptions),
4061
+ [client, locationId, queryOptions]
4062
+ );
4063
+ const cached = productsCache.get(cacheKey);
4064
+ const [products, setProducts] = useState(cached?.products ?? []);
4065
+ const [isLoading, setIsLoading] = useState(enabled && !cached);
4066
+ const [error, setError] = useState(null);
4067
+ useEffect(() => {
4068
+ if (previousLocationIdRef.current !== locationId) {
4069
+ productsCache.clear();
4070
+ productsInflight.clear();
4071
+ previousLocationIdRef.current = locationId;
4072
+ }
4073
+ }, [locationId]);
4074
+ const load = useCallback(
4075
+ async (force = false) => {
4076
+ if (!enabled) {
4077
+ setIsLoading(false);
4078
+ return;
4079
+ }
4080
+ const nextRequestId = ++requestIdRef.current;
4081
+ setError(null);
4082
+ if (!force) {
4083
+ const cacheEntry = productsCache.get(cacheKey);
4084
+ if (cacheEntry) {
4085
+ setProducts(cacheEntry.products);
4086
+ setIsLoading(false);
4087
+ return;
4088
+ }
4089
+ }
4090
+ setIsLoading(true);
4091
+ try {
4092
+ const existing = productsInflight.get(cacheKey);
4093
+ const promise = existing ?? (async () => {
4094
+ const result = await client.catalogue.getProducts(queryOptions);
4095
+ if (!result.ok) {
4096
+ throw result.error;
4097
+ }
4098
+ return result.value;
4099
+ })();
4100
+ if (!existing) {
4101
+ productsInflight.set(
4102
+ cacheKey,
4103
+ promise.finally(() => {
4104
+ productsInflight.delete(cacheKey);
4105
+ })
4106
+ );
4107
+ }
4108
+ const value = await promise;
4109
+ productsCache.set(cacheKey, { products: value });
4110
+ if (nextRequestId === requestIdRef.current) {
4111
+ setProducts(value);
4112
+ setError(null);
4113
+ }
4114
+ } catch (loadError) {
4115
+ if (nextRequestId === requestIdRef.current) {
4116
+ setError(loadError);
4117
+ }
4118
+ } finally {
4119
+ if (nextRequestId === requestIdRef.current) {
4120
+ setIsLoading(false);
4121
+ }
4122
+ }
4123
+ },
4124
+ [cacheKey, client, enabled, queryOptions]
4125
+ );
4126
+ useEffect(() => {
4127
+ void load(false);
4128
+ }, [load]);
4129
+ const refetch = useCallback(async () => {
4130
+ productsCache.delete(cacheKey);
4131
+ await load(true);
4132
+ }, [cacheKey, load]);
4133
+ return { products, isLoading, error, refetch };
4134
+ }
4135
+ var productCache = /* @__PURE__ */ new Map();
4136
+ var productInflight = /* @__PURE__ */ new Map();
4137
+ function isLikelySlug(value) {
4138
+ return /^[a-z0-9-]+$/.test(value);
4139
+ }
4140
+ function buildProductCacheKey(client, locationId, slugOrId) {
4141
+ return JSON.stringify({
4142
+ key: client.getPublicKey(),
4143
+ location_id: locationId || "__none__",
4144
+ slug_or_id: slugOrId
4145
+ });
4146
+ }
4147
+ function useProduct(slugOrId, options = {}) {
4148
+ const context = useOptionalCimplify();
4149
+ const client = options.client ?? context?.client;
4150
+ if (!client) {
4151
+ throw new Error("useProduct must be used within CimplifyProvider or passed { client }.");
4152
+ }
4153
+ const enabled = options.enabled ?? true;
4154
+ const locationId = client.getLocationId();
4155
+ const previousLocationIdRef = useRef(locationId);
4156
+ const requestIdRef = useRef(0);
4157
+ const normalizedSlugOrId = useMemo(() => (slugOrId || "").trim(), [slugOrId]);
4158
+ const cacheKey = useMemo(
4159
+ () => buildProductCacheKey(client, locationId, normalizedSlugOrId),
4160
+ [client, locationId, normalizedSlugOrId]
4161
+ );
4162
+ const cached = productCache.get(cacheKey);
4163
+ const [product, setProduct] = useState(cached?.product ?? null);
4164
+ const [isLoading, setIsLoading] = useState(
4165
+ enabled && normalizedSlugOrId.length > 0 && !cached
4166
+ );
4167
+ const [error, setError] = useState(null);
4168
+ useEffect(() => {
4169
+ if (previousLocationIdRef.current !== locationId) {
4170
+ productCache.clear();
4171
+ productInflight.clear();
4172
+ previousLocationIdRef.current = locationId;
4173
+ }
4174
+ }, [locationId]);
4175
+ const load = useCallback(
4176
+ async (force = false) => {
4177
+ if (!enabled || normalizedSlugOrId.length === 0) {
4178
+ setProduct(null);
4179
+ setIsLoading(false);
4180
+ return;
4181
+ }
4182
+ const nextRequestId = ++requestIdRef.current;
4183
+ setError(null);
4184
+ if (!force) {
4185
+ const cacheEntry = productCache.get(cacheKey);
4186
+ if (cacheEntry) {
4187
+ setProduct(cacheEntry.product);
4188
+ setIsLoading(false);
4189
+ return;
4190
+ }
4191
+ }
4192
+ setIsLoading(true);
4193
+ try {
4194
+ const existing = productInflight.get(cacheKey);
4195
+ const promise = existing ?? (async () => {
4196
+ const result = isLikelySlug(normalizedSlugOrId) ? await client.catalogue.getProductBySlug(normalizedSlugOrId) : await client.catalogue.getProduct(normalizedSlugOrId);
4197
+ if (!result.ok) {
4198
+ throw result.error;
4199
+ }
4200
+ return result.value;
4201
+ })();
4202
+ if (!existing) {
4203
+ productInflight.set(
4204
+ cacheKey,
4205
+ promise.finally(() => {
4206
+ productInflight.delete(cacheKey);
4207
+ })
4208
+ );
4209
+ }
4210
+ const value = await promise;
4211
+ productCache.set(cacheKey, { product: value });
4212
+ if (nextRequestId === requestIdRef.current) {
4213
+ setProduct(value);
4214
+ setError(null);
4215
+ }
4216
+ } catch (loadError) {
4217
+ if (nextRequestId === requestIdRef.current) {
4218
+ setError(loadError);
4219
+ }
4220
+ } finally {
4221
+ if (nextRequestId === requestIdRef.current) {
4222
+ setIsLoading(false);
4223
+ }
4224
+ }
4225
+ },
4226
+ [cacheKey, client, enabled, normalizedSlugOrId]
4227
+ );
4228
+ useEffect(() => {
4229
+ void load(false);
4230
+ }, [load]);
4231
+ const refetch = useCallback(async () => {
4232
+ productCache.delete(cacheKey);
4233
+ await load(true);
4234
+ }, [cacheKey, load]);
4235
+ return { product, isLoading, error, refetch };
4236
+ }
4237
+ var categoriesCache = /* @__PURE__ */ new Map();
4238
+ var categoriesInflight = /* @__PURE__ */ new Map();
4239
+ function buildCategoriesCacheKey(client) {
4240
+ return client.getPublicKey() || "__demo__";
4241
+ }
4242
+ function useCategories(options = {}) {
4243
+ const context = useOptionalCimplify();
4244
+ const client = options.client ?? context?.client;
4245
+ if (!client) {
4246
+ throw new Error("useCategories must be used within CimplifyProvider or passed { client }.");
4247
+ }
4248
+ const enabled = options.enabled ?? true;
4249
+ const cacheKey = useMemo(() => buildCategoriesCacheKey(client), [client]);
4250
+ const cached = categoriesCache.get(cacheKey);
4251
+ const [categories, setCategories] = useState(cached ?? []);
4252
+ const [isLoading, setIsLoading] = useState(enabled && !cached);
4253
+ const [error, setError] = useState(null);
4254
+ const load = useCallback(
4255
+ async (force = false) => {
4256
+ if (!enabled) {
4257
+ setIsLoading(false);
4258
+ return;
4259
+ }
4260
+ setError(null);
4261
+ if (!force) {
4262
+ const cachedCategories = categoriesCache.get(cacheKey);
4263
+ if (cachedCategories) {
4264
+ setCategories(cachedCategories);
4265
+ setIsLoading(false);
4266
+ return;
4267
+ }
4268
+ }
4269
+ setIsLoading(true);
4270
+ try {
4271
+ const existing = categoriesInflight.get(cacheKey);
4272
+ const promise = existing ?? (async () => {
4273
+ const result = await client.catalogue.getCategories();
4274
+ if (!result.ok) {
4275
+ throw result.error;
4276
+ }
4277
+ return result.value;
4278
+ })();
4279
+ if (!existing) {
4280
+ categoriesInflight.set(
4281
+ cacheKey,
4282
+ promise.finally(() => {
4283
+ categoriesInflight.delete(cacheKey);
4284
+ })
4285
+ );
4286
+ }
4287
+ const value = await promise;
4288
+ categoriesCache.set(cacheKey, value);
4289
+ setCategories(value);
4290
+ } catch (loadError) {
4291
+ setError(loadError);
4292
+ } finally {
4293
+ setIsLoading(false);
4294
+ }
4295
+ },
4296
+ [cacheKey, client, enabled]
4297
+ );
4298
+ useEffect(() => {
4299
+ void load(false);
4300
+ }, [load]);
4301
+ const refetch = useCallback(async () => {
4302
+ categoriesCache.delete(cacheKey);
4303
+ await load(true);
4304
+ }, [cacheKey, load]);
4305
+ return { categories, isLoading, error, refetch };
4306
+ }
4307
+ var CART_STORAGE_PREFIX = "cimplify:cart:v2";
4308
+ var DEFAULT_TAX_RATE = 0.08875;
4309
+ var cartStores = /* @__PURE__ */ new Map();
4310
+ function toNumber(value) {
4311
+ if (typeof value === "number" && Number.isFinite(value)) {
4312
+ return value;
4313
+ }
4314
+ if (typeof value === "string") {
4315
+ const parsed = Number.parseFloat(value);
4316
+ return Number.isFinite(parsed) ? parsed : 0;
4317
+ }
4318
+ return 0;
4319
+ }
4320
+ function roundMoney(value) {
4321
+ return Math.max(0, Number(value.toFixed(2)));
4322
+ }
4323
+ function clampQuantity(quantity) {
4324
+ if (!Number.isFinite(quantity)) {
4325
+ return 1;
4326
+ }
4327
+ return Math.max(1, Math.floor(quantity));
4328
+ }
4329
+ function normalizeOptionIds(value) {
4330
+ if (!value || value.length === 0) {
4331
+ return void 0;
4332
+ }
4333
+ const normalized = Array.from(
4334
+ new Set(
4335
+ value.map((entry) => entry.trim()).filter((entry) => entry.length > 0)
4336
+ )
4337
+ ).sort();
4338
+ return normalized.length > 0 ? normalized : void 0;
4339
+ }
4340
+ function buildLineKey(productId, options) {
4341
+ const parts = [productId];
4342
+ if (options.locationId) {
4343
+ parts.push(`l:${options.locationId}`);
4344
+ }
4345
+ if (options.variantId) {
4346
+ parts.push(`v:${options.variantId}`);
4347
+ }
4348
+ const addOnOptionIds = normalizeOptionIds(options.addOnOptionIds);
4349
+ if (addOnOptionIds && addOnOptionIds.length > 0) {
4350
+ parts.push(`a:${addOnOptionIds.join(",")}`);
4351
+ }
4352
+ if (options.bundleSelections && options.bundleSelections.length > 0) {
4353
+ parts.push(`b:${JSON.stringify(options.bundleSelections)}`);
4354
+ }
4355
+ if (options.compositeSelections && options.compositeSelections.length > 0) {
4356
+ parts.push(`c:${JSON.stringify(options.compositeSelections)}`);
4357
+ }
4358
+ if (options.quoteId) {
4359
+ parts.push(`q:${options.quoteId}`);
4360
+ }
4361
+ return parts.join("|");
4362
+ }
4363
+ function calculateLineSubtotal(item) {
4364
+ let unitPrice = parsePrice(item.product.default_price);
4365
+ if (item.variant?.price_adjustment) {
4366
+ unitPrice += parsePrice(item.variant.price_adjustment);
4367
+ }
4368
+ for (const option of item.addOnOptions || []) {
4369
+ if (option.default_price) {
4370
+ unitPrice += parsePrice(option.default_price);
4371
+ }
4372
+ }
4373
+ return roundMoney(unitPrice * item.quantity);
4374
+ }
4375
+ function calculateSummary(items) {
4376
+ const subtotal = roundMoney(items.reduce((sum, item) => sum + calculateLineSubtotal(item), 0));
4377
+ const tax = roundMoney(subtotal * DEFAULT_TAX_RATE);
4378
+ return {
4379
+ subtotal,
4380
+ tax,
4381
+ total: roundMoney(subtotal + tax)
4382
+ };
4383
+ }
4384
+ function toProductFromServerItem(item, businessId) {
4385
+ return {
4386
+ id: item.item_id,
4387
+ business_id: businessId,
4388
+ category_id: item.category_id,
4389
+ name: item.name,
4390
+ slug: item.item_id,
4391
+ description: item.description,
4392
+ image_url: item.image_url,
4393
+ default_price: item.base_price,
4394
+ product_type: "product",
4395
+ inventory_type: "none",
4396
+ variant_strategy: "fetch_all",
4397
+ is_active: item.is_available,
4398
+ created_at: item.created_at,
4399
+ updated_at: item.updated_at,
4400
+ metadata: {
4401
+ from_sdk: true
4402
+ }
4403
+ };
4404
+ }
4405
+ function mapServerCart(serverCart) {
4406
+ const items = serverCart.items.map((item) => {
4407
+ const variant = item.variant_info || item.variant_name ? {
4408
+ id: item.variant_info?.id || item.variant_id || "",
4409
+ name: item.variant_info?.name || item.variant_name || "Variant",
4410
+ price_adjustment: item.variant_info?.price_adjustment
4411
+ } : void 0;
4412
+ const quoteId = typeof item.metadata?.quote_id === "string" ? item.metadata.quote_id : void 0;
4413
+ return {
4414
+ id: item.id,
4415
+ product: toProductFromServerItem(item, serverCart.business_id),
4416
+ quantity: clampQuantity(item.quantity),
4417
+ locationId: serverCart.location_id,
4418
+ variantId: item.variant_id,
4419
+ variant,
4420
+ quoteId,
4421
+ addOnOptionIds: item.add_on_option_ids || void 0,
4422
+ addOnOptions: (item.add_on_options || []).map((option) => ({
4423
+ id: option.id,
4424
+ name: option.name,
4425
+ default_price: option.price
4426
+ })),
4427
+ bundleSelections: item.bundle_selections || void 0,
4428
+ compositeSelections: item.composite_selections || void 0,
4429
+ specialInstructions: item.special_instructions
4430
+ };
4431
+ });
4432
+ return {
4433
+ items,
4434
+ subtotal: roundMoney(toNumber(serverCart.pricing.subtotal)),
4435
+ tax: roundMoney(toNumber(serverCart.pricing.tax_amount)),
4436
+ total: roundMoney(toNumber(serverCart.pricing.total_price)),
4437
+ currency: serverCart.pricing.currency || "USD"
4438
+ };
4439
+ }
4440
+ function buildStorageKey(storeKey) {
4441
+ return `${CART_STORAGE_PREFIX}:${storeKey}`;
4442
+ }
4443
+ function createEmptySnapshot(currency) {
4444
+ return {
4445
+ items: [],
4446
+ subtotal: 0,
4447
+ tax: 0,
4448
+ total: 0,
4449
+ currency,
4450
+ isLoading: true
4451
+ };
4452
+ }
4453
+ function createCartStore(params) {
4454
+ const { client, storeKey, locationId, isDemoMode, currency } = params;
4455
+ const storageKey = buildStorageKey(storeKey);
4456
+ const listeners = /* @__PURE__ */ new Set();
4457
+ let snapshot = createEmptySnapshot(currency);
4458
+ let initialized = false;
4459
+ let initializePromise = null;
4460
+ function emit() {
4461
+ listeners.forEach((listener) => {
4462
+ listener();
4463
+ });
4464
+ }
4465
+ function setSnapshot(nextSnapshot) {
4466
+ snapshot = nextSnapshot;
4467
+ persistSnapshot();
4468
+ emit();
4469
+ }
4470
+ function updateSnapshot(updater) {
4471
+ setSnapshot(updater(snapshot));
4472
+ }
4473
+ function persistSnapshot() {
4474
+ if (typeof window === "undefined" || !window.localStorage) {
4475
+ return;
4476
+ }
4477
+ try {
4478
+ window.localStorage.setItem(
4479
+ storageKey,
4480
+ JSON.stringify({
4481
+ items: snapshot.items,
4482
+ subtotal: snapshot.subtotal,
4483
+ tax: snapshot.tax,
4484
+ total: snapshot.total,
4485
+ currency: snapshot.currency
4486
+ })
4487
+ );
4488
+ } catch {
4489
+ }
4490
+ }
4491
+ function hydrateFromStorage() {
4492
+ if (typeof window === "undefined" || !window.localStorage) {
4493
+ return;
4494
+ }
4495
+ try {
4496
+ const raw = window.localStorage.getItem(storageKey);
4497
+ if (!raw) {
4498
+ return;
4499
+ }
4500
+ const parsed = JSON.parse(raw);
4501
+ if (!parsed || !Array.isArray(parsed.items)) {
4502
+ return;
4503
+ }
4504
+ snapshot = {
4505
+ items: parsed.items,
4506
+ subtotal: toNumber(parsed.subtotal),
4507
+ tax: toNumber(parsed.tax),
4508
+ total: toNumber(parsed.total),
4509
+ currency: typeof parsed.currency === "string" && parsed.currency ? parsed.currency : currency,
4510
+ isLoading: !isDemoMode
4511
+ };
4512
+ emit();
4513
+ } catch {
4514
+ }
4515
+ }
4516
+ async function sync() {
4517
+ if (isDemoMode) {
4518
+ updateSnapshot((current) => ({
4519
+ ...current,
4520
+ isLoading: false
4521
+ }));
4522
+ return;
4523
+ }
4524
+ updateSnapshot((current) => ({
4525
+ ...current,
4526
+ isLoading: true
4527
+ }));
4528
+ const result = await client.cart.get();
4529
+ if (!result.ok) {
4530
+ updateSnapshot((current) => ({
4531
+ ...current,
4532
+ isLoading: false
4533
+ }));
4534
+ throw result.error;
4535
+ }
4536
+ const next = mapServerCart(result.value);
4537
+ setSnapshot({
4538
+ ...next,
4539
+ isLoading: false
4540
+ });
4541
+ }
4542
+ async function maybeResolveQuoteId(product, quantity, options) {
4543
+ if (options.quoteId) {
4544
+ return options.quoteId;
4545
+ }
4546
+ const addOnOptionIds = normalizeOptionIds(options.addOnOptionIds);
4547
+ const requiresQuote = Boolean(
4548
+ options.variantId || addOnOptionIds && addOnOptionIds.length > 0 || options.bundleSelections && options.bundleSelections.length > 0 || options.compositeSelections && options.compositeSelections.length > 0
4549
+ );
4550
+ if (!requiresQuote || isDemoMode) {
4551
+ return void 0;
4552
+ }
4553
+ const quoteResult = await client.catalogue.fetchQuote({
4554
+ product_id: product.id,
4555
+ quantity,
4556
+ location_id: options.locationId || locationId || void 0,
4557
+ variant_id: options.variantId,
4558
+ add_on_option_ids: addOnOptionIds,
4559
+ bundle_selections: options.bundleSelections,
4560
+ composite_selections: options.compositeSelections
4561
+ });
4562
+ if (!quoteResult.ok) {
4563
+ throw quoteResult.error;
4564
+ }
4565
+ return quoteResult.value.quote_id;
4566
+ }
4567
+ async function addItem(product, quantity = 1, options = {}) {
4568
+ const resolvedQuantity = clampQuantity(quantity);
4569
+ const normalizedOptions = {
4570
+ ...options,
4571
+ locationId: options.locationId || locationId || void 0,
4572
+ addOnOptionIds: normalizeOptionIds(options.addOnOptionIds)
4573
+ };
4574
+ const maybeProductWithVariants = product;
4575
+ if (Array.isArray(maybeProductWithVariants.variants) && maybeProductWithVariants.variants.length > 0 && !normalizedOptions.variantId) {
4576
+ console.warn(
4577
+ "[Cimplify] addItem() called without variantId for a product that has variants. Default variant pricing will be used."
4578
+ );
4579
+ }
4580
+ const previousSnapshot = snapshot;
4581
+ const lineKey = buildLineKey(product.id, normalizedOptions);
4582
+ const optimisticItem = {
4583
+ id: `tmp_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,
4584
+ product,
4585
+ quantity: resolvedQuantity,
4586
+ locationId: normalizedOptions.locationId,
4587
+ variantId: normalizedOptions.variantId,
4588
+ variant: normalizedOptions.variant,
4589
+ quoteId: normalizedOptions.quoteId,
4590
+ addOnOptionIds: normalizedOptions.addOnOptionIds,
4591
+ addOnOptions: normalizedOptions.addOnOptions,
4592
+ bundleSelections: normalizedOptions.bundleSelections,
4593
+ compositeSelections: normalizedOptions.compositeSelections,
4594
+ specialInstructions: normalizedOptions.specialInstructions
4595
+ };
4596
+ updateSnapshot((current) => {
4597
+ const existingIndex = current.items.findIndex((item) => {
4598
+ const itemKey = buildLineKey(item.product.id, {
4599
+ locationId: item.locationId,
4600
+ variantId: item.variantId,
4601
+ quoteId: item.quoteId,
4602
+ addOnOptionIds: item.addOnOptionIds,
4603
+ bundleSelections: item.bundleSelections,
4604
+ compositeSelections: item.compositeSelections
4605
+ });
4606
+ return itemKey === lineKey;
4607
+ });
4608
+ const nextItems = [...current.items];
4609
+ if (existingIndex >= 0) {
4610
+ const existing = nextItems[existingIndex];
4611
+ nextItems[existingIndex] = {
4612
+ ...existing,
4613
+ quantity: existing.quantity + resolvedQuantity
4614
+ };
4615
+ } else {
4616
+ nextItems.push(optimisticItem);
4617
+ }
4618
+ const summary = calculateSummary(nextItems);
4619
+ return {
4620
+ ...current,
4621
+ items: nextItems,
4622
+ subtotal: summary.subtotal,
4623
+ tax: summary.tax,
4624
+ total: summary.total
4625
+ };
4626
+ });
4627
+ if (isDemoMode) {
4628
+ return;
4629
+ }
4630
+ try {
4631
+ const quoteId = await maybeResolveQuoteId(product, resolvedQuantity, normalizedOptions);
4632
+ const result = await client.cart.addItem({
4633
+ item_id: product.id,
4634
+ quantity: resolvedQuantity,
4635
+ variant_id: normalizedOptions.variantId,
4636
+ quote_id: quoteId,
4637
+ add_on_options: normalizedOptions.addOnOptionIds,
4638
+ special_instructions: normalizedOptions.specialInstructions,
4639
+ bundle_selections: normalizedOptions.bundleSelections,
4640
+ composite_selections: normalizedOptions.compositeSelections
4641
+ });
4642
+ if (!result.ok) {
4643
+ throw result.error;
4644
+ }
4645
+ await sync();
4646
+ } catch (error) {
4647
+ snapshot = previousSnapshot;
4648
+ persistSnapshot();
4649
+ emit();
4650
+ throw error;
4651
+ }
4652
+ }
4653
+ async function removeItem(itemId) {
4654
+ const previousSnapshot = snapshot;
4655
+ updateSnapshot((current) => {
4656
+ const nextItems = current.items.filter((item) => item.id !== itemId);
4657
+ const summary = calculateSummary(nextItems);
4658
+ return {
4659
+ ...current,
4660
+ items: nextItems,
4661
+ subtotal: summary.subtotal,
4662
+ tax: summary.tax,
4663
+ total: summary.total
4664
+ };
4665
+ });
4666
+ if (isDemoMode) {
4667
+ return;
4668
+ }
4669
+ try {
4670
+ const result = await client.cart.removeItem(itemId);
4671
+ if (!result.ok) {
4672
+ throw result.error;
4673
+ }
4674
+ await sync();
4675
+ } catch (error) {
4676
+ snapshot = previousSnapshot;
4677
+ persistSnapshot();
4678
+ emit();
4679
+ throw error;
4680
+ }
4681
+ }
4682
+ async function updateQuantity(itemId, quantity) {
4683
+ if (quantity <= 0) {
4684
+ await removeItem(itemId);
4685
+ return;
4686
+ }
4687
+ const resolvedQuantity = clampQuantity(quantity);
4688
+ const previousSnapshot = snapshot;
4689
+ updateSnapshot((current) => {
4690
+ const nextItems = current.items.map(
4691
+ (item) => item.id === itemId ? {
4692
+ ...item,
4693
+ quantity: resolvedQuantity
4694
+ } : item
4695
+ );
4696
+ const summary = calculateSummary(nextItems);
4697
+ return {
4698
+ ...current,
4699
+ items: nextItems,
4700
+ subtotal: summary.subtotal,
4701
+ tax: summary.tax,
4702
+ total: summary.total
4703
+ };
4704
+ });
4705
+ if (isDemoMode) {
4706
+ return;
4707
+ }
4708
+ try {
4709
+ const result = await client.cart.updateQuantity(itemId, resolvedQuantity);
4710
+ if (!result.ok) {
4711
+ throw result.error;
4712
+ }
4713
+ await sync();
4714
+ } catch (error) {
4715
+ snapshot = previousSnapshot;
4716
+ persistSnapshot();
4717
+ emit();
4718
+ throw error;
4719
+ }
4720
+ }
4721
+ async function clearCart() {
4722
+ const previousSnapshot = snapshot;
4723
+ updateSnapshot((current) => ({
4724
+ ...current,
4725
+ items: [],
4726
+ subtotal: 0,
4727
+ tax: 0,
4728
+ total: 0
4729
+ }));
4730
+ if (isDemoMode) {
4731
+ return;
4732
+ }
4733
+ try {
4734
+ const result = await client.cart.clear();
4735
+ if (!result.ok) {
4736
+ throw result.error;
4737
+ }
4738
+ await sync();
4739
+ } catch (error) {
4740
+ snapshot = previousSnapshot;
4741
+ persistSnapshot();
4742
+ emit();
4743
+ throw error;
4744
+ }
4745
+ }
4746
+ async function initialize() {
4747
+ if (initialized) {
4748
+ if (initializePromise) {
4749
+ await initializePromise;
4750
+ }
4751
+ return;
4752
+ }
4753
+ initialized = true;
4754
+ hydrateFromStorage();
4755
+ if (isDemoMode) {
4756
+ updateSnapshot((current) => ({
4757
+ ...current,
4758
+ isLoading: false
4759
+ }));
4760
+ return;
4761
+ }
4762
+ initializePromise = sync().catch(() => {
4763
+ updateSnapshot((current) => ({
4764
+ ...current,
4765
+ isLoading: false
4766
+ }));
4767
+ });
4768
+ await initializePromise;
4769
+ initializePromise = null;
4770
+ }
4771
+ return {
4772
+ subscribe(listener) {
4773
+ listeners.add(listener);
4774
+ return () => {
4775
+ listeners.delete(listener);
4776
+ };
4777
+ },
4778
+ getSnapshot() {
4779
+ return snapshot;
4780
+ },
4781
+ initialize,
4782
+ addItem,
4783
+ removeItem,
4784
+ updateQuantity,
4785
+ clearCart,
4786
+ sync
4787
+ };
4788
+ }
4789
+ function getStoreKey(client, locationId, isDemoMode) {
4790
+ return [
4791
+ client.getPublicKey() || "__demo__",
4792
+ locationId || "__no_location__",
4793
+ isDemoMode ? "demo" : "live"
4794
+ ].join(":");
4795
+ }
4796
+ function getOrCreateStore(params) {
4797
+ const { client, locationId, isDemoMode, currency } = params;
4798
+ const storeKey = getStoreKey(client, locationId, isDemoMode);
4799
+ const existing = cartStores.get(storeKey);
4800
+ if (existing) {
4801
+ return existing;
4802
+ }
4803
+ const created = createCartStore({
4804
+ client,
4805
+ storeKey,
4806
+ locationId,
4807
+ isDemoMode,
4808
+ currency
4809
+ });
4810
+ cartStores.set(storeKey, created);
4811
+ return created;
4812
+ }
4813
+ function useCart(options = {}) {
4814
+ const context = useOptionalCimplify();
4815
+ const client = options.client ?? context?.client;
4816
+ if (!client) {
4817
+ throw new Error("useCart must be used within CimplifyProvider or passed { client }.");
4818
+ }
4819
+ const locationId = options.locationId ?? client.getLocationId();
4820
+ const isDemoMode = options.demoMode ?? context?.isDemoMode ?? client.getPublicKey().trim().length === 0;
4821
+ const currency = options.currency ?? context?.currency ?? "USD";
4822
+ const store = useMemo(
4823
+ () => getOrCreateStore({
4824
+ client,
4825
+ locationId,
4826
+ isDemoMode,
4827
+ currency
4828
+ }),
4829
+ [client, currency, isDemoMode, locationId]
4830
+ );
4831
+ const snapshot = useSyncExternalStore(
4832
+ store.subscribe,
4833
+ store.getSnapshot,
4834
+ store.getSnapshot
4835
+ );
4836
+ useEffect(() => {
4837
+ void store.initialize();
4838
+ }, [store]);
4839
+ const addItem = useCallback(
4840
+ async (product, quantity, addOptions) => {
4841
+ await store.addItem(product, quantity, addOptions);
4842
+ },
4843
+ [store]
4844
+ );
4845
+ const removeItem = useCallback(
4846
+ async (itemId) => {
4847
+ await store.removeItem(itemId);
4848
+ },
4849
+ [store]
4850
+ );
4851
+ const updateQuantity = useCallback(
4852
+ async (itemId, quantity) => {
4853
+ await store.updateQuantity(itemId, quantity);
4854
+ },
4855
+ [store]
4856
+ );
4857
+ const clearCart = useCallback(async () => {
4858
+ await store.clearCart();
4859
+ }, [store]);
4860
+ const sync = useCallback(async () => {
4861
+ try {
4862
+ await store.sync();
4863
+ } catch (syncError) {
4864
+ throw syncError;
4865
+ }
4866
+ }, [store]);
4867
+ const itemCount = useMemo(
4868
+ () => snapshot.items.reduce((sum, item) => sum + item.quantity, 0),
4869
+ [snapshot.items]
4870
+ );
4871
+ return {
4872
+ items: snapshot.items,
4873
+ itemCount,
4874
+ subtotal: snapshot.subtotal,
4875
+ tax: snapshot.tax,
4876
+ total: snapshot.total,
4877
+ currency: snapshot.currency,
4878
+ isEmpty: itemCount === 0,
4879
+ isLoading: snapshot.isLoading,
4880
+ addItem,
4881
+ removeItem,
4882
+ updateQuantity,
4883
+ clearCart,
4884
+ sync
4885
+ };
4886
+ }
4887
+ var orderCache = /* @__PURE__ */ new Map();
4888
+ var orderInflight = /* @__PURE__ */ new Map();
4889
+ function buildOrderCacheKey(client, orderId) {
4890
+ return `${client.getPublicKey() || "__demo__"}:${orderId}`;
4891
+ }
4892
+ function useOrder(orderId, options = {}) {
4893
+ const context = useOptionalCimplify();
4894
+ const client = options.client ?? context?.client;
4895
+ if (!client) {
4896
+ throw new Error("useOrder must be used within CimplifyProvider or passed { client }.");
4897
+ }
4898
+ const normalizedOrderId = useMemo(() => (orderId || "").trim(), [orderId]);
4899
+ const enabled = options.enabled ?? true;
4900
+ const poll = options.poll ?? false;
4901
+ const pollInterval = options.pollInterval ?? 5e3;
4902
+ const requestIdRef = useRef(0);
4903
+ const cacheKey = useMemo(
4904
+ () => buildOrderCacheKey(client, normalizedOrderId),
4905
+ [client, normalizedOrderId]
4906
+ );
4907
+ const cached = orderCache.get(cacheKey);
4908
+ const [order, setOrder] = useState(cached?.order ?? null);
4909
+ const [isLoading, setIsLoading] = useState(
4910
+ enabled && normalizedOrderId.length > 0 && !cached
4911
+ );
4912
+ const [error, setError] = useState(null);
4913
+ const load = useCallback(
4914
+ async (force = false) => {
4915
+ if (!enabled || normalizedOrderId.length === 0) {
4916
+ setOrder(null);
4917
+ setIsLoading(false);
4918
+ return;
4919
+ }
4920
+ const nextRequestId = ++requestIdRef.current;
4921
+ setError(null);
4922
+ if (!force) {
4923
+ const cacheEntry = orderCache.get(cacheKey);
4924
+ if (cacheEntry) {
4925
+ setOrder(cacheEntry.order);
4926
+ setIsLoading(false);
4927
+ return;
4928
+ }
4929
+ }
4930
+ setIsLoading(true);
4931
+ try {
4932
+ const existing = orderInflight.get(cacheKey);
4933
+ const promise = existing ?? (async () => {
4934
+ const result = await client.orders.get(normalizedOrderId);
4935
+ if (!result.ok) {
4936
+ throw result.error;
4937
+ }
4938
+ return result.value;
4939
+ })();
4940
+ if (!existing) {
4941
+ orderInflight.set(
4942
+ cacheKey,
4943
+ promise.finally(() => {
4944
+ orderInflight.delete(cacheKey);
4945
+ })
4946
+ );
4947
+ }
4948
+ const value = await promise;
4949
+ orderCache.set(cacheKey, { order: value });
4950
+ if (nextRequestId === requestIdRef.current) {
4951
+ setOrder(value);
4952
+ setError(null);
4953
+ }
4954
+ } catch (loadError) {
4955
+ if (nextRequestId === requestIdRef.current) {
4956
+ setError(loadError);
4957
+ }
4958
+ } finally {
4959
+ if (nextRequestId === requestIdRef.current) {
4960
+ setIsLoading(false);
4961
+ }
4962
+ }
4963
+ },
4964
+ [cacheKey, client, enabled, normalizedOrderId]
4965
+ );
4966
+ useEffect(() => {
4967
+ void load(false);
4968
+ }, [load]);
4969
+ useEffect(() => {
4970
+ if (!poll || !enabled || normalizedOrderId.length === 0) {
4971
+ return;
4972
+ }
4973
+ const timer = window.setInterval(() => {
4974
+ void load(true);
4975
+ }, Math.max(1e3, pollInterval));
4976
+ return () => {
4977
+ window.clearInterval(timer);
4978
+ };
4979
+ }, [enabled, load, normalizedOrderId.length, poll, pollInterval]);
4980
+ const refetch = useCallback(async () => {
4981
+ orderCache.delete(cacheKey);
4982
+ await load(true);
4983
+ }, [cacheKey, load]);
4984
+ return { order, isLoading, error, refetch };
4985
+ }
4986
+ var LOCATION_STORAGE_KEY2 = "cimplify_location_id";
4987
+ function readStoredLocationId() {
4988
+ if (typeof window === "undefined" || !window.localStorage) {
4989
+ return null;
4990
+ }
4991
+ const value = window.localStorage.getItem(LOCATION_STORAGE_KEY2);
4992
+ if (!value) {
4993
+ return null;
4994
+ }
4995
+ const normalized = value.trim();
4996
+ return normalized.length > 0 ? normalized : null;
4997
+ }
4998
+ function writeStoredLocationId(locationId) {
4999
+ if (typeof window === "undefined" || !window.localStorage) {
5000
+ return;
5001
+ }
5002
+ if (!locationId) {
5003
+ window.localStorage.removeItem(LOCATION_STORAGE_KEY2);
5004
+ return;
5005
+ }
5006
+ window.localStorage.setItem(LOCATION_STORAGE_KEY2, locationId);
5007
+ }
5008
+ function resolveLocation(locations, preferredId) {
5009
+ if (locations.length === 0) {
5010
+ return null;
5011
+ }
5012
+ if (preferredId) {
5013
+ const found = locations.find((location) => location.id === preferredId);
5014
+ if (found) {
5015
+ return found;
5016
+ }
5017
+ }
5018
+ return locations[0];
5019
+ }
5020
+ function useLocations(options = {}) {
5021
+ const context = useOptionalCimplify();
5022
+ if (context && (!options.client || context.client === options.client)) {
5023
+ return {
5024
+ locations: context.locations,
5025
+ currentLocation: context.currentLocation,
5026
+ setCurrentLocation: context.setCurrentLocation,
5027
+ isLoading: !context.isReady
5028
+ };
5029
+ }
5030
+ const client = options.client;
5031
+ const [locations, setLocations] = useState([]);
5032
+ const [currentLocation, setCurrentLocationState] = useState(null);
5033
+ const [isLoading, setIsLoading] = useState(true);
5034
+ const setCurrentLocation = useCallback(
5035
+ (location) => {
5036
+ setCurrentLocationState(location);
5037
+ if (client) {
5038
+ client.setLocationId(location.id);
5039
+ }
5040
+ writeStoredLocationId(location.id);
5041
+ },
5042
+ [client]
5043
+ );
5044
+ useEffect(() => {
5045
+ if (!client) {
5046
+ setLocations([]);
5047
+ setCurrentLocationState(null);
5048
+ setIsLoading(false);
5049
+ return;
5050
+ }
5051
+ const activeClient = client;
5052
+ let cancelled = false;
5053
+ async function loadLocations() {
5054
+ setIsLoading(true);
5055
+ const result = await activeClient.business.getLocations();
5056
+ if (cancelled) {
5057
+ return;
5058
+ }
5059
+ if (!result.ok) {
5060
+ setLocations([]);
5061
+ setCurrentLocationState(null);
5062
+ setIsLoading(false);
5063
+ return;
5064
+ }
5065
+ const nextLocations = result.value;
5066
+ const preferredId = activeClient.getLocationId() ?? readStoredLocationId();
5067
+ const resolved = resolveLocation(nextLocations, preferredId);
5068
+ setLocations(nextLocations);
5069
+ setCurrentLocationState(resolved);
5070
+ activeClient.setLocationId(resolved?.id || null);
5071
+ writeStoredLocationId(resolved?.id || null);
5072
+ setIsLoading(false);
5073
+ }
5074
+ void loadLocations();
5075
+ return () => {
5076
+ cancelled = true;
5077
+ };
5078
+ }, [client]);
5079
+ return {
5080
+ locations,
5081
+ currentLocation,
5082
+ setCurrentLocation,
5083
+ isLoading
5084
+ };
5085
+ }
5086
+ var ElementsContext = createContext({
5087
+ elements: null,
5088
+ isReady: false
5089
+ });
5090
+ function useElements() {
5091
+ return useContext(ElementsContext).elements;
5092
+ }
5093
+ function useElementsReady() {
5094
+ return useContext(ElementsContext).isReady;
5095
+ }
5096
+ function ElementsProvider({
5097
+ client,
5098
+ businessId,
5099
+ options,
5100
+ children
5101
+ }) {
5102
+ const [elements, setElements] = useState(null);
5103
+ const [isReady, setIsReady] = useState(false);
5104
+ const initialOptionsRef = useRef(options);
5105
+ useEffect(() => {
5106
+ let cancelled = false;
5107
+ let instance = null;
5108
+ setIsReady(false);
5109
+ setElements(null);
5110
+ async function bootstrap() {
5111
+ const resolvedBusinessId = businessId ?? await client.resolveBusinessId().catch(() => null);
5112
+ if (!resolvedBusinessId) {
5113
+ if (!cancelled) {
5114
+ setIsReady(false);
5115
+ setElements(null);
5116
+ }
5117
+ return;
5118
+ }
5119
+ instance = client.elements(resolvedBusinessId, initialOptionsRef.current);
5120
+ if (cancelled) {
5121
+ instance.destroy();
5122
+ return;
5123
+ }
5124
+ setElements(instance);
5125
+ setIsReady(true);
5126
+ }
5127
+ void bootstrap();
5128
+ return () => {
5129
+ cancelled = true;
5130
+ if (instance) {
5131
+ instance.destroy();
5132
+ }
5133
+ };
5134
+ }, [client, businessId]);
538
5135
  return /* @__PURE__ */ jsx(ElementsContext.Provider, { value: { elements, isReady }, children });
539
5136
  }
540
5137
  function AuthElement({
@@ -646,4 +5243,4 @@ function useCheckout() {
646
5243
  return { submit, process, isLoading };
647
5244
  }
648
5245
 
649
- export { Ad, AdProvider, AddressElement, AuthElement, CimplifyCheckout, ElementsProvider, PaymentElement, useAds, useCheckout, useElements, useElementsReady };
5246
+ export { Ad, AdProvider, AddressElement, AuthElement, CimplifyCheckout, CimplifyProvider, ElementsProvider, PaymentElement, useAds, useCart, useCategories, useCheckout, useCimplify, useElements, useElementsReady, useLocations, useOptionalCimplify, useOrder, useProduct, useProducts };