bitsnap-react 1.19.0 → 1.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/BitsnapCart-V4S4EXYV.js +2 -0
- package/dist/BitsnapCart-V4S4EXYV.js.map +1 -0
- package/dist/BitsnapCart-Z6JFYNH2.mjs +2 -0
- package/dist/CartProvider-5NP4WACK.js +2 -0
- package/dist/CartProvider-5NP4WACK.js.map +1 -0
- package/dist/CartProvider-G7FQUPXL.mjs +2 -0
- package/dist/PanelModelFiles-EKQRLF46.js.map +1 -1
- package/dist/analytics.js +1 -1
- package/dist/analytics.js.map +1 -1
- package/dist/analytics.mjs +1 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/catalog.mjs +1 -1
- package/dist/chat.d.mts +10 -9
- package/dist/chat.d.ts +10 -9
- package/dist/chat.js +1 -1
- package/dist/chat.js.map +1 -1
- package/dist/chat.mjs +1 -1
- package/dist/chat.mjs.map +1 -1
- package/dist/{chunk-WG54EHST.mjs → chunk-2G46TAUX.mjs} +2 -2
- package/dist/chunk-2G46TAUX.mjs.map +1 -0
- package/dist/{chunk-DOJICJCQ.js → chunk-4Y233NII.js} +2 -2
- package/dist/chunk-4Y233NII.js.map +1 -0
- package/dist/chunk-5M3OUOMU.mjs +5 -0
- package/dist/chunk-5M3OUOMU.mjs.map +1 -0
- package/dist/chunk-6Q3VGPSF.js.map +1 -1
- package/dist/{chunk-DDIEFKNP.mjs → chunk-A2ZDFN3J.mjs} +2 -2
- package/dist/{chunk-GJOGATP6.js → chunk-AQYHQY2Y.js} +2 -2
- package/dist/chunk-AQYHQY2Y.js.map +1 -0
- package/dist/{chunk-N523LFAM.mjs → chunk-BTERIY6N.mjs} +2 -2
- package/dist/{chunk-MWWEPEU2.js → chunk-C736F727.js} +2 -2
- package/dist/chunk-C736F727.js.map +1 -0
- package/dist/{chunk-LGPNJ5XE.js → chunk-EFN4OW2C.js} +2 -2
- package/dist/chunk-EFN4OW2C.js.map +1 -0
- package/dist/{chunk-GQ5OKU74.js → chunk-GHBRR665.js} +2 -2
- package/dist/chunk-GHBRR665.js.map +1 -0
- package/dist/chunk-HKRH6FI6.mjs +2 -0
- package/dist/chunk-HKRH6FI6.mjs.map +1 -0
- package/dist/chunk-HP3I6D2R.js +2 -0
- package/dist/chunk-HP3I6D2R.js.map +1 -0
- package/dist/{chunk-D2ASWUXM.js → chunk-IRZJIPUF.js} +2 -2
- package/dist/chunk-IRZJIPUF.js.map +1 -0
- package/dist/{chunk-5M6M7FAR.mjs → chunk-IXQCN7MR.mjs} +2 -2
- package/dist/chunk-IXX6SUMB.mjs +2 -0
- package/dist/chunk-IXX6SUMB.mjs.map +1 -0
- package/dist/chunk-JSDGZ4NY.js.map +1 -1
- package/dist/chunk-KDL35KEI.js +2 -0
- package/dist/chunk-KDL35KEI.js.map +1 -0
- package/dist/{chunk-OR566YJI.mjs → chunk-KO7ZERN5.mjs} +2 -2
- package/dist/chunk-KO7ZERN5.mjs.map +1 -0
- package/dist/chunk-KOYBZORL.js.map +1 -1
- package/dist/chunk-KZWCVKLU.js +5 -0
- package/dist/chunk-KZWCVKLU.js.map +1 -0
- package/dist/{chunk-SCEWYZUZ.mjs → chunk-LHNTSQYO.mjs} +2 -2
- package/dist/{chunk-5JRUPLXY.mjs → chunk-LHQEM3CU.mjs} +2 -2
- package/dist/chunk-MDAFPGPA.js.map +1 -1
- package/dist/chunk-Q337IQNA.js.map +1 -1
- package/dist/{chunk-YV2C276H.js → chunk-RJPQMDIQ.js} +2 -2
- package/dist/chunk-RJPQMDIQ.js.map +1 -0
- package/dist/{chunk-SSSF64M7.mjs → chunk-TW25G7XX.mjs} +2 -2
- package/dist/{chunk-SSSF64M7.mjs.map → chunk-TW25G7XX.mjs.map} +1 -1
- package/dist/{chunk-MMLBQHBM.mjs → chunk-URQBHNJK.mjs} +2 -2
- package/dist/chunk-W3RGQYPD.js.map +1 -1
- package/dist/{chunk-2FD2QP4Y.js → chunk-YPA6MMGJ.js} +2 -2
- package/dist/chunk-YPA6MMGJ.js.map +1 -0
- package/dist/chunk-Z3YOJ6NZ.js +2 -0
- package/dist/chunk-Z3YOJ6NZ.js.map +1 -0
- package/dist/consent.js.map +1 -1
- package/dist/course.d.mts +1 -1
- package/dist/course.d.ts +1 -1
- package/dist/course.js +1 -1
- package/dist/course.js.map +1 -1
- package/dist/course.mjs +1 -1
- package/dist/embed/analytics.js +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.d.mts +37 -34
- package/dist/index.d.ts +37 -34
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/internal.js.map +1 -1
- package/dist/methods-33CWGKNA.mjs +2 -0
- package/dist/methods-4GB652MQ.js +2 -0
- package/dist/methods-4GB652MQ.js.map +1 -0
- package/dist/model-files-client-P4PORZJ6.js.map +1 -1
- package/dist/models.js.map +1 -1
- package/dist/returns.js +1 -1
- package/dist/returns.js.map +1 -1
- package/dist/returns.mjs +1 -1
- package/dist/{types-B-sjyZQs.d.mts → types-CjWyHunk.d.mts} +2 -0
- package/dist/{types-iRe6ix2y.d.ts → types-DfqzDP9k.d.ts} +2 -0
- package/dist/viewer3d.js.map +1 -1
- package/dist/viewer3d.mjs +2 -2
- package/dist/{widgets-BVOSj9fU.d.ts → widgets-Bsojw94g.d.ts} +10 -1
- package/dist/{widgets-BT2LN2Nq.d.mts → widgets-u7xMJbsY.d.mts} +10 -1
- package/package.json +2 -2
- package/dist/BitsnapCart-E72W5RRZ.mjs +0 -2
- package/dist/BitsnapCart-Q2HER6GU.js +0 -2
- package/dist/BitsnapCart-Q2HER6GU.js.map +0 -1
- package/dist/CartProvider-677CE2FI.js +0 -2
- package/dist/CartProvider-677CE2FI.js.map +0 -1
- package/dist/CartProvider-YPDOFSYC.mjs +0 -2
- package/dist/chunk-2FD2QP4Y.js.map +0 -1
- package/dist/chunk-AAC576BC.mjs +0 -5
- package/dist/chunk-AAC576BC.mjs.map +0 -1
- package/dist/chunk-AB37DWOK.mjs +0 -2
- package/dist/chunk-AB37DWOK.mjs.map +0 -1
- package/dist/chunk-BUYTK7KM.js +0 -2
- package/dist/chunk-BUYTK7KM.js.map +0 -1
- package/dist/chunk-D2ASWUXM.js.map +0 -1
- package/dist/chunk-DOJICJCQ.js.map +0 -1
- package/dist/chunk-GJOGATP6.js.map +0 -1
- package/dist/chunk-GQ5OKU74.js.map +0 -1
- package/dist/chunk-KHQEDQYF.js +0 -5
- package/dist/chunk-KHQEDQYF.js.map +0 -1
- package/dist/chunk-LGPNJ5XE.js.map +0 -1
- package/dist/chunk-MWWEPEU2.js.map +0 -1
- package/dist/chunk-NWXZ45TV.js +0 -2
- package/dist/chunk-NWXZ45TV.js.map +0 -1
- package/dist/chunk-OR566YJI.mjs.map +0 -1
- package/dist/chunk-WG54EHST.mjs.map +0 -1
- package/dist/chunk-YV2C276H.js.map +0 -1
- package/dist/methods-64D5DD6K.js +0 -2
- package/dist/methods-64D5DD6K.js.map +0 -1
- package/dist/methods-NQA3DFLE.mjs +0 -2
- /package/dist/{BitsnapCart-E72W5RRZ.mjs.map → BitsnapCart-Z6JFYNH2.mjs.map} +0 -0
- /package/dist/{CartProvider-YPDOFSYC.mjs.map → CartProvider-G7FQUPXL.mjs.map} +0 -0
- /package/dist/{chunk-DDIEFKNP.mjs.map → chunk-A2ZDFN3J.mjs.map} +0 -0
- /package/dist/{chunk-N523LFAM.mjs.map → chunk-BTERIY6N.mjs.map} +0 -0
- /package/dist/{chunk-5M6M7FAR.mjs.map → chunk-IXQCN7MR.mjs.map} +0 -0
- /package/dist/{chunk-SCEWYZUZ.mjs.map → chunk-LHNTSQYO.mjs.map} +0 -0
- /package/dist/{chunk-5JRUPLXY.mjs.map → chunk-LHQEM3CU.mjs.map} +0 -0
- /package/dist/{chunk-MMLBQHBM.mjs.map → chunk-URQBHNJK.mjs.map} +0 -0
- /package/dist/{methods-NQA3DFLE.mjs.map → methods-33CWGKNA.mjs.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-RJPQMDIQ.js","../src/components/checkout/BitsnapCart.tsx","../src/components/checkout/CartComponent.tsx","../src/components/checkout/appearance.ts","../src/components/checkout/appearance.context.tsx","../src/components/checkout/CartComponentContent.tsx","../src/ui/select.tsx","../src/components/checkout/CountrySelector.tsx"],"names":["CHECKOUT_SLOT_NAMES","CHECKOUT_TOKEN_VARIABLES","CHECKOUT_THEME_PRESETS","CHECKOUT_SHADCN_VARIABLES","resolveDropdownStyle","tokens","resolveCheckoutAppearance","appearance","resolved","resolveAppearanceCore","getCheckoutSlotAppearance","slot","getSlotAppearance","CheckoutAppearanceContext","createContext","CheckoutAppearanceProvider","children","useMemo","jsx","useCheckoutAppearance","useContext","useCheckoutSlot","Select","props","SelectValue","selectTriggerThemeClasses","SelectTrigger","className","size","theme","jsxs","cn","ChevronDownIcon","SelectContent","position","align","SelectScrollUpButton","SelectScrollDownButton","SelectItem","CheckIcon","ChevronUpIcon","CountrySelector","id","open","disabled","onToggle","onChange","selectedValue","countries","query","setQuery","useState","isCustomized","boundaryClassName","boundaryStyle","dropdownStyle","countryTrigger","countryDropdown","countrySearch","countryOption","searchCountryText","useCheckoutText","noCountriesFoundText","useEffect","filteredCountries","country","selectedCountry","el","value","isOpen","e"],"mappings":"AAAA,goDAAiT,sDAAiG,sDAAiD,sDAAgG,sDAAwD,sDAAiE,sDAAyD,4ECA5qB,oEACzB,qDCDe,qJACP,qCAEK,IC4DhBA,EAAAA,CAAsB,CACjC,MAAA,CACA,SAAA,CACA,OAAA,CACA,QAAA,CACA,OAAA,CACA,aAAA,CACA,aAAA,CACA,SAAA,CACA,cAAA,CACA,aAAA,CACA,cAAA,CACA,iBAAA,CACA,eAAA,CACA,gBAAA,CACA,cAAA,CACA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AAAA,CAAQ,IAAA,CACb,GAAA,CAAK,CAAA,4DAAA,EAA+DA,CAAAA,CAAQ,IAAI,CAAA,IAAA,CAAA,CAChF,SAAA,CAAU,4BAAA,CACZ,CAAA,CACA/C,6BAAAA,MAAC,CAAA,CAAK,SAAA,CAAU,sBAAA,CAAwB,QAAA,CAAA+C,CAAAA,CAAQ,IAAA,CAAK,CAAA,CAAA,CAAA,CAdhD,CAAA,EAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-RJPQMDIQ.js","sourcesContent":[null,"import { useEffect, useId, useRef } from \"react\";\nimport zod from \"zod\";\nimport {\n InstrumentProvider,\n useCartInstrument,\n useInstrument,\n type AnalyticsOption,\n} from \"@/src/analytics/instrument\";\nimport type { CheckoutAppearance } from \"./appearance\";\nimport type { CheckoutTexts } from \"./texts\";\nimport CartComponent from \"./CartComponent\";\nimport { getCheckoutMethods, getProjectID, setProjectID } from \"./CartProvider\";\nimport { sendAnalyticEvent } from \"./frontent.analytics\";\nimport { isErr } from \"./lib/err\";\nimport { useCheckoutStore } from \"./state\";\nimport { getLocale, setLocale } from \"./locale\";\nimport { getCheckoutText, type CheckoutTextKey } from \"./texts\";\n\nenum CartEvent {\n ADD_TO_CART = \"ADD_TO_CART\",\n}\n\nconst cartAddToCartSchema = zod.object({\n id: zod.string(),\n isSubscription: zod.boolean().default(false),\n quantity: zod.number(),\n metadata: zod.record(zod.string(), zod.string().optional()).optional(),\n url: zod.string().optional(),\n});\n\ntype CartAddToCartEvent = zod.infer<typeof cartAddToCartSchema>;\n\nexport type BitsnapCartProps = {\n projectID: string;\n locale?: string;\n children?: React.ReactNode;\n onVisibleChange?: (isVisible: boolean) => void;\n className?: string;\n numberOfProductsInCartOptions?: {\n style?: React.CSSProperties;\n isVisible?: boolean;\n };\n /**\n * Optional checkout appearance. Omitting it (or passing `{}`) keeps the\n * current presentation; every token and element slot is partial.\n */\n appearance?: CheckoutAppearance;\n /**\n * Optional text overrides. Any key given here replaces the built-in string\n * whatever the locale; omitted keys keep the `pl`/`en` defaults.\n */\n texts?: Partial<CheckoutTexts>;\n /**\n * Usage statistics for your Bitsnap dashboard (cart opened, checkout\n * started, add to cart). On by default; `false` turns it off. An object\n * lets you forward every event: `{ onEvent }`. Nothing is stored on the\n * visitor's device.\n */\n analytics?: AnalyticsOption;\n};\n\nconst visuallyHidden: React.CSSProperties = {\n position: \"absolute\",\n width: 1,\n height: 1,\n margin: -1,\n padding: 0,\n overflow: \"hidden\",\n clip: \"rect(0, 0, 0, 0)\",\n whiteSpace: \"nowrap\",\n border: 0,\n};\n\nfunction BitsnapCart({\n projectID,\n locale,\n children,\n onVisibleChange,\n className,\n numberOfProductsInCartOptions,\n appearance,\n texts,\n analytics,\n}: BitsnapCartProps) {\n const instrument = useInstrument(projectID, analytics, \"cart\");\n // Cart changes made outside of components (`Bitsnap.addProductToCart`) are reported here.\n useCartInstrument(instrument);\n const { isCartVisible, showCart, hideCart, numberOfProductsInCart } =\n useCheckoutStore();\n const panelId = `bitsnap-cart-${useId()}`;\n const text = (key: CheckoutTextKey) =>\n getCheckoutText(key, locale ?? getLocale(), texts);\n // The `window.cart` handlers are created once and must read the latest props.\n const textRef = useRef(text);\n textRef.current = text;\n\n /** Shows a message through the error area of the cart drawer. */\n function showCartNotice(key: CheckoutTextKey) {\n useCheckoutStore.getState().setNotice(textRef.current(key));\n showCart();\n }\n\n function sentPostMessageToIframe(msg: unknown) {\n const iframes = document.querySelectorAll(\"iframe\");\n\n iframes.forEach((iframe) => {\n iframe.contentWindow?.postMessage(msg, \"*\");\n });\n }\n\n useEffect(() => {\n onVisibleChange?.(isCartVisible);\n if (isCartVisible) {\n sendAnalyticEvent({\n event: \"viewCart\",\n });\n }\n }, [isCartVisible]);\n\n useEffect(() => {\n setProjectID(projectID);\n }, [projectID]);\n\n useEffect(() => {\n setLocale(locale);\n }, [locale]);\n\n useEffect(() => {\n if (!(\"cart\" in window)) {\n const projectID = getProjectID();\n if (projectID == null) {\n console.warn(\"There is no project ID configured.\");\n return;\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-expect-error\n window[\"cart\"] = {\n buyProduct: async (args: unknown) => {\n try {\n const payload = zod\n .object({\n productID: zod.string(),\n email: zod.string().optional(),\n name: zod.string().optional(),\n country: zod.string().optional(),\n marketingAgreement: zod.boolean().optional(),\n locale: zod.string().optional(),\n })\n .parse(args);\n const methods = getCheckoutMethods(projectID);\n try {\n const products = await methods.getProducts();\n if (isErr(products) == false) {\n sendAnalyticEvent({\n event: \"initiateCheckout\",\n items: products.map((el) => ({\n id: el.productID,\n name: el.details?.name ?? \"\",\n price: el.details?.price ?? 0,\n quantity: el.quantity,\n currency: el.details?.currency ?? \"PLN\",\n })),\n });\n }\n } catch (e) {}\n\n const result = await methods.justRedirectToPayment(payload);\n\n if (isErr(result) == false) {\n window.location.href = result.url;\n } else {\n showCartNotice(\"redirectFailed\");\n }\n } catch (e) {\n console.warn(e);\n }\n },\n };\n }\n }, []);\n\n async function handleAddingToCart(id: string, payload?: unknown) {\n const projectID = getProjectID();\n if (projectID == null) {\n console.warn(\"There is no project ID configured.\");\n return;\n }\n\n try {\n const data = cartAddToCartSchema.parse(payload);\n\n if (data.isSubscription) {\n await handleAddingSubscriptionToCart(projectID, data);\n return;\n }\n\n const methods = getCheckoutMethods(projectID);\n\n await methods.addProduct({\n productID: data.id,\n quantity: data.quantity,\n metadata: data.metadata,\n url: data.url,\n });\n\n sentPostMessageToIframe({\n id: id,\n type: CartEvent.ADD_TO_CART,\n success: true,\n });\n showCart();\n } catch (e) {\n console.warn(\"cannot add item to cart\", e);\n }\n }\n\n async function handleAddingSubscriptionToCart(\n projectID: string,\n event: CartAddToCartEvent,\n ) {\n console.warn(\n \"subscriptions cannot be added to the cart yet\",\n projectID,\n event.id,\n );\n showCartNotice(\"subscriptionUnsupported\");\n }\n\n function setupEventListener() {\n if (\"__cart_is_listening\" in window) {\n return;\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-expect-error\n window[\"__cart_is_listening\"] = true;\n window.addEventListener(\"message\", (event) => {\n if (\n typeof event.data[\"id\"] != \"undefined\" &&\n typeof event.data[\"type\"] != \"undefined\"\n ) {\n const { id, type } = event.data;\n switch (type) {\n case CartEvent.ADD_TO_CART.toString():\n handleAddingToCart(id, event.data[\"payload\"]).then().catch();\n break;\n default:\n break;\n }\n }\n });\n }\n\n useEffect(() => {\n setupEventListener();\n\n if (typeof window !== \"undefined\") {\n try {\n const parsedParams = new URLSearchParams(window.location.search);\n const refLink =\n parsedParams.get(\"ref\") ?? parsedParams.get(\"utm-source\");\n if (\n typeof localStorage != \"undefined\" &&\n refLink &&\n refLink.length > 0\n ) {\n localStorage.setItem(\"bitsnap-ref\", refLink);\n }\n } catch (e) {\n return;\n }\n }\n }, []);\n\n return (\n <>\n <button\n type=\"button\"\n onClick={() => (isCartVisible ? hideCart() : showCart())}\n aria-label={\n children\n ? undefined\n : numberOfProductsInCart > 0\n ? `${text(\"openCart\")}. ${text(\"cartItemsCount\")}: ${numberOfProductsInCart}`\n : text(\"openCart\")\n }\n aria-expanded={isCartVisible}\n aria-haspopup=\"dialog\"\n aria-controls={isCartVisible ? panelId : undefined}\n style={{ position: \"relative\" }}\n className={[\n \"bitsnap-react\",\n className ?? \"rounded-full hover:bg-neutral-300 transition p-1\",\n ].join(\" \")}\n >\n {children ? (\n <>{children}</>\n ) : (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"lucide lucide-shopping-cart\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n <circle cx=\"8\" cy=\"21\" r=\"1\" />\n <circle cx=\"19\" cy=\"21\" r=\"1\" />\n <path d=\"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12\" />\n </svg>\n )}\n {numberOfProductsInCart > 0 && (\n <span style={visuallyHidden}>\n {text(\"cartItemsCount\")}: {numberOfProductsInCart}\n </span>\n )}\n {numberOfProductsInCartOptions?.isVisible != false &&\n numberOfProductsInCart > 0 && (\n <div\n aria-hidden=\"true\"\n style={{\n position: \"absolute\",\n bottom: -5,\n right: -5,\n background: \"black\",\n color: \"white\",\n borderRadius: \"50%\",\n width: \"22px\",\n height: \"22px\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n fontSize: \"13px\",\n fontWeight: 600,\n boxShadow: \"0 2px 8px rgba(0, 0, 0, 0.25)\",\n ...numberOfProductsInCartOptions?.style,\n }}\n >\n {numberOfProductsInCart}\n </div>\n )}\n </button>\n <InstrumentProvider value={instrument}>\n <CartComponent\n isVisible={isCartVisible}\n locale={locale}\n appearance={appearance}\n texts={texts}\n panelId={panelId}\n shouldHide={() => {\n hideCart();\n }}\n />\n </InstrumentProvider>\n </>\n );\n}\n\nexport default BitsnapCart;\n","import { useAutoAnimate } from \"@formkit/auto-animate/react\";\nimport * as Dialog from \"@radix-ui/react-dialog\";\nimport { useCallback, useRef, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { cn } from \"@/src/lib/utils\";\nimport {\n CheckoutAppearanceProvider,\n useCheckoutAppearance,\n useCheckoutSlot,\n} from \"./appearance.context\";\nimport type { CheckoutAppearance } from \"./appearance\";\nimport CartComponentContent from \"./CartComponentContent\";\nimport CartProvider from \"./CartProvider\";\nimport { CheckoutTextsProvider, useCheckoutText } from \"./texts.context\";\nimport type { CheckoutTexts } from \"./texts\";\n\ninterface Props {\n isVisible: boolean;\n shouldHide: () => void;\n locale?: string;\n appearance?: CheckoutAppearance;\n texts?: Partial<CheckoutTexts>;\n /** DOM id of the panel, for `aria-controls` of the button that opens it. */\n panelId?: string;\n}\n\nfunction CartComponent({ isVisible, shouldHide, panelId, locale }: Props) {\n const [parent] = useAutoAnimate(/* optional config */);\n // The drawer renders inside the checkout root: the stylesheet is scoped to `.bitsnap-react`.\n const [rootElement, setRootElement] = useState<HTMLDivElement | null>(null);\n const rootRef = useCallback(\n (element: HTMLDivElement | null) => {\n parent(element);\n setRootElement(element);\n },\n [parent],\n );\n // The trigger lives outside of the dialog, so Radix does not know which element to give the focus back to.\n const returnFocusTo = useRef<HTMLElement | null>(null);\n const { boundaryClassName, boundaryStyle } = useCheckoutAppearance();\n const root = useCheckoutSlot(\"root\");\n const overlay = useCheckoutSlot(\"overlay\");\n const panel = useCheckoutSlot(\"panel\");\n const header = useCheckoutSlot(\"header\");\n const title = useCheckoutSlot(\"title\");\n const closeButton = useCheckoutSlot(\"closeButton\");\n const cartText = useCheckoutText(\"cart\");\n const closeText = useCheckoutText(\"close\");\n\n return (\n <div\n ref={rootRef}\n data-bitsnap-checkout=\"root\"\n data-bitsnap-checkout-slot=\"root\"\n className={cn(\"bitsnap-react\", boundaryClassName, root.className)}\n style={{ zIndex: 999999, ...boundaryStyle, ...root.style }}\n >\n {rootElement != null && (\n <Dialog.Root\n open={isVisible}\n onOpenChange={(open) => {\n if (!open) {\n shouldHide();\n }\n }}\n >\n <Dialog.Portal container={rootElement}>\n <Dialog.Overlay\n data-bitsnap-checkout-slot=\"overlay\"\n aria-hidden=\"true\"\n className={cn(\n \"fixed top-0 right-0 left-0 bottom-0 cursor-pointer z-10\",\n overlay.className,\n )}\n style={overlay.style}\n onClick={shouldHide}\n />\n <Dialog.Content\n id={panelId}\n data-bitsnap-checkout-slot=\"panel\"\n aria-modal=\"true\"\n aria-describedby={undefined}\n onOpenAutoFocus={() => {\n const active = document.activeElement;\n returnFocusTo.current = active instanceof HTMLElement ? active : null;\n }}\n onCloseAutoFocus={(event) => {\n event.preventDefault();\n returnFocusTo.current?.focus();\n returnFocusTo.current = null;\n }}\n className={cn(\n // Scrolls when the summary and the payment choice do not fit (small phones).\n \"fixed z-20 top-0 right-0 bottom-0 w-full md:w-[350px] xl:w-[420px] flex flex-col overflow-y-auto\",\n panel.className,\n )}\n style={panel.style}\n // The overlay closes the drawer on click; a close on pointer down would let the click through.\n onPointerDownOutside={(event) => event.preventDefault()}\n >\n <div\n data-bitsnap-checkout-slot=\"header\"\n className={cn(\n \"mx-3 mt-7 flex justify-between items-center\",\n header.className,\n )}\n style={header.style}\n >\n <Dialog.Title asChild>\n <h1\n data-bitsnap-checkout-slot=\"title\"\n className={cn(\"text-2xl font-medium\", title.className)}\n style={title.style}\n >\n {cartText}\n </h1>\n </Dialog.Title>\n <button\n type=\"button\"\n data-bitsnap-checkout-slot=\"closeButton\"\n className={cn(\n \"rounded-xl p-2 transition\",\n closeButton.className,\n )}\n style={closeButton.style}\n aria-label={closeText}\n onClick={shouldHide}\n >\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"lucide lucide-x\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\" />\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\" />\n </svg>\n </button>\n </div>\n\n <CartComponentContent className={\"grow\"} locale={locale} />\n </Dialog.Content>\n </Dialog.Portal>\n </Dialog.Root>\n )}\n </div>\n );\n}\n\nconst WrapperCartComponent = (props: Props) => {\n if (typeof window === \"undefined\") {\n return null;\n }\n\n return createPortal(\n <CheckoutAppearanceProvider appearance={props.appearance}>\n <CheckoutTextsProvider texts={props.texts} locale={props.locale}>\n <CartProvider locale={props.locale}>\n <CartComponent {...props} />\n </CartProvider>\n </CheckoutTextsProvider>\n </CheckoutAppearanceProvider>,\n document.body,\n );\n};\n\nexport default WrapperCartComponent;\n","import type { CSSProperties } from \"react\";\nimport {\n getSlotAppearance,\n resolveAppearanceCore,\n type AppearanceElements,\n type ShadcnVariableMapping,\n type SlotAppearance,\n} from \"@/src/lib/appearance-core\";\n\n/**\n * Checkout appearance API.\n *\n * `CheckoutAppearance` is resolved once per render into plain data: a theme\n * name, the tokens that are actually in effect, the per-slot overrides and the\n * inline style that both theme boundaries (the drawer root and the portalled\n * country dropdown) have to receive. Everything here is pure so it can be\n * tested without a DOM.\n *\n * Backward compatibility: the resolver never invents values. A token is only\n * present in the resolved output when the caller provided it or when the\n * caller explicitly selected a theme preset, so every unset token keeps falling\n * back to the value the checkout renders today (see `checkout.css`).\n */\n\nexport type CheckoutTheme = \"dark\" | \"light\";\n\nexport type CheckoutAppearanceTokens = {\n /** Checkout wide font family. The library never loads fonts. */\n fontFamily?: string;\n /** Base font size of the checkout. */\n fontSize?: string;\n /** Panel background. */\n background?: string;\n /** Raised surfaces: country dropdown, search bar, loading skeletons. */\n surface?: string;\n /** Main text color. */\n foreground?: string;\n /** Secondary text: empty cart, delivery info, country label, search input. */\n mutedForeground?: string;\n /** Borders: country trigger, dropdown, product separators. */\n border?: string;\n /** Checkout button background. */\n buttonBackground?: string;\n /** Checkout button text. */\n buttonForeground?: string;\n /** Checkout button background on hover. */\n buttonHoverBackground?: string;\n /** Hover and selected surfaces: close button, country options. */\n hoverSurface?: string;\n /** Focus ring color. Also applied to shared UI primitives through `--ring`. */\n focusRing?: string;\n /** Error and unavailable state color. */\n error?: string;\n /** Drawer backdrop color. */\n overlay?: string;\n /** Corner radius, applied through `--radius`. */\n radius?: string;\n};\n\n/**\n * Stable slot names. They are exposed as `data-bitsnap-checkout-slot`\n * attributes so they can also be targeted from plain CSS.\n */\nexport const CHECKOUT_SLOT_NAMES = [\n \"root\",\n \"overlay\",\n \"panel\",\n \"header\",\n \"title\",\n \"closeButton\",\n \"productList\",\n \"product\",\n \"productImage\",\n \"productName\",\n \"productPrice\",\n \"quantityControl\",\n \"quantityInput\",\n \"quantityButton\",\n \"removeButton\",\n \"summary\",\n \"totalLabel\",\n \"totalValue\",\n \"deliveryText\",\n \"summaryNote\",\n \"countryLabel\",\n \"countryTrigger\",\n \"countryDropdown\",\n \"countrySearch\",\n \"countryOption\",\n \"paymentButtons\",\n \"paymentMethods\",\n \"paymentMethodOption\",\n \"checkoutButton\",\n \"emptyState\",\n \"error\",\n \"skeleton\",\n] as const;\n\nexport type CheckoutSlotName = (typeof CHECKOUT_SLOT_NAMES)[number];\n\nexport type CheckoutSlotAppearance = SlotAppearance;\n\nexport type CheckoutAppearanceElements = AppearanceElements<CheckoutSlotName>;\n\nexport type CheckoutAppearance = {\n /**\n * `\"dark\"` keeps the current presentation, `\"light\"` applies the light preset.\n * Omitted means `\"dark\"`.\n */\n theme?: CheckoutTheme;\n /** Partial overrides. Anything omitted keeps today's value. */\n tokens?: CheckoutAppearanceTokens;\n /** Per element `className`/`style` overrides. */\n elements?: CheckoutAppearanceElements;\n};\n\nexport type ResolvedCheckoutAppearance = {\n theme: CheckoutTheme;\n /**\n * `true` as soon as the caller passed anything through `appearance`. The\n * country dropdown is portalled outside of the checkout root, so it only\n * receives the checkout boundary when the caller opted in - an omitted or\n * empty `appearance` keeps the previous (unthemed) dropdown untouched.\n */\n isCustomized: boolean;\n /** Tokens that are in effect. Empty entries were dropped. */\n tokens: CheckoutAppearanceTokens;\n elements: CheckoutAppearanceElements;\n /** Theme marker class for the theme boundaries. */\n boundaryClassName: string;\n /** Inline custom properties applied to the drawer root. */\n boundaryStyle: CSSProperties;\n /**\n * Extra properties for the portalled country dropdown. The shared select\n * content paints itself with `bg-popover`/`text-popover-foreground`, so those\n * variables have to carry the checkout colors over to the portal. They are\n * resolved eagerly because the dropdown is the only place where the built-in\n * defaults differ from the drawer.\n */\n dropdownStyle: CSSProperties;\n};\n\n/** CSS custom property used for each token. */\nexport const CHECKOUT_TOKEN_VARIABLES = {\n fontFamily: \"--bitsnap-checkout-font-family\",\n fontSize: \"--bitsnap-checkout-font-size\",\n background: \"--bitsnap-checkout-background\",\n surface: \"--bitsnap-checkout-surface\",\n foreground: \"--bitsnap-checkout-foreground\",\n mutedForeground: \"--bitsnap-checkout-muted-foreground\",\n border: \"--bitsnap-checkout-border\",\n buttonBackground: \"--bitsnap-checkout-button-background\",\n buttonForeground: \"--bitsnap-checkout-button-foreground\",\n buttonHoverBackground: \"--bitsnap-checkout-button-hover-background\",\n hoverSurface: \"--bitsnap-checkout-hover-surface\",\n focusRing: \"--bitsnap-checkout-focus-ring\",\n error: \"--bitsnap-checkout-error\",\n overlay: \"--bitsnap-checkout-overlay\",\n radius: \"--bitsnap-checkout-radius\",\n} as const;\n\nexport type CheckoutTokenName = keyof typeof CHECKOUT_TOKEN_VARIABLES;\n\n/**\n * Theme presets are intentionally partial. `\"dark\"` is empty because every\n * default already renders the current dark presentation; `\"light\"` only carries\n * the colors that have to change for a light checkout, so typography is never\n * reset implicitly.\n */\nexport const CHECKOUT_THEME_PRESETS: Record<\n CheckoutTheme,\n CheckoutAppearanceTokens\n> = {\n dark: {},\n light: {\n background: \"#ffffff\",\n surface: \"#f9fafb\",\n foreground: \"#18181b\",\n mutedForeground: \"#71717a\",\n border: \"#e4e4e7\",\n buttonBackground: \"#18181b\",\n buttonForeground: \"#fafafa\",\n buttonHoverBackground: \"#000000\",\n hoverSurface: \"#e4e4e7\",\n focusRing: \"#71717a\",\n error: \"#dc2626\",\n overlay: \"rgb(0 0 0 / 0.35)\",\n },\n};\n\n/**\n * Some shared UI primitives (`Button`, `SelectTrigger`, ...) read the shadcn\n * theme variables instead of checkout tokens. Those are remapped so a themed\n * dropdown and themed primitives stay consistent. They are only written when\n * the matching token is in effect, so untouched tokens change nothing.\n */\nconst CHECKOUT_SHADCN_VARIABLES: ShadcnVariableMapping<CheckoutTokenName> = [\n { token: \"background\", variable: \"--background\" },\n { token: \"foreground\", variable: \"--foreground\" },\n { token: \"surface\", variable: \"--card\" },\n { token: \"surface\", variable: \"--popover\" },\n { token: \"foreground\", variable: \"--popover-foreground\" },\n { token: \"mutedForeground\", variable: \"--muted-foreground\" },\n { token: \"border\", variable: \"--border\" },\n { token: \"border\", variable: \"--input\" },\n { token: \"focusRing\", variable: \"--ring\" },\n { token: \"error\", variable: \"--destructive\" },\n { token: \"radius\", variable: \"--radius\" },\n];\n\n/**\n * The portalled dropdown renders `bg-popover`/`text-popover-foreground` from the\n * shared primitives, so those two variables are resolved eagerly: without a\n * token they fall back to the dark values the checkout has always used.\n */\nfunction resolveDropdownStyle(tokens: CheckoutAppearanceTokens): CSSProperties {\n return {\n \"--popover\": tokens.surface ?? \"var(--color-neutral-800)\",\n \"--popover-foreground\": tokens.foreground ?? \"var(--color-neutral-200)\",\n } as CSSProperties;\n}\n\nexport function resolveCheckoutAppearance(\n appearance?: CheckoutAppearance,\n): ResolvedCheckoutAppearance {\n const resolved = resolveAppearanceCore<\n CheckoutTokenName,\n CheckoutTheme,\n CheckoutSlotName\n >(appearance, {\n defaultTheme: \"dark\",\n presets: CHECKOUT_THEME_PRESETS,\n variables: CHECKOUT_TOKEN_VARIABLES,\n shadcnVariables: CHECKOUT_SHADCN_VARIABLES,\n });\n\n return {\n theme: resolved.theme,\n isCustomized: resolved.isCustomized,\n tokens: resolved.tokens,\n elements: resolved.elements,\n boundaryClassName: resolved.theme,\n boundaryStyle: resolved.boundaryStyle,\n dropdownStyle: resolveDropdownStyle(resolved.tokens),\n };\n}\n\n/** Caller overrides for a single slot, if any were provided. */\nexport function getCheckoutSlotAppearance(\n resolved: ResolvedCheckoutAppearance,\n slot: CheckoutSlotName,\n): CheckoutSlotAppearance | undefined {\n return getSlotAppearance(resolved.elements, slot);\n}\n","import { createContext, useContext, useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n getCheckoutSlotAppearance,\n resolveCheckoutAppearance,\n type CheckoutAppearance,\n type CheckoutSlotAppearance,\n type CheckoutSlotName,\n type ResolvedCheckoutAppearance,\n} from \"./appearance\";\n\nconst CheckoutAppearanceContext = createContext<ResolvedCheckoutAppearance>(\n resolveCheckoutAppearance(),\n);\n\n/**\n * Checkout scoped appearance provider. It only wraps the checkout drawer, so\n * the configuration never leaks into the panel, the notifications or any\n * global state.\n */\nexport function CheckoutAppearanceProvider({\n appearance,\n children,\n}: {\n appearance?: CheckoutAppearance;\n children: ReactNode;\n}) {\n const resolved = useMemo(\n () => resolveCheckoutAppearance(appearance),\n [appearance],\n );\n\n return (\n <CheckoutAppearanceContext.Provider value={resolved}>\n {children}\n </CheckoutAppearanceContext.Provider>\n );\n}\n\nexport function useCheckoutAppearance(): ResolvedCheckoutAppearance {\n return useContext(CheckoutAppearanceContext);\n}\n\n/**\n * Returns the caller overrides for a slot. The values are meant to be merged\n * with the built-in presentation:\n *\n * ```tsx\n * const slot = useCheckoutSlot(\"title\");\n *\n * return <h1 className={cn(\"text-2xl font-medium\", slot.className)} style={slot.style} />;\n * ```\n */\nexport function useCheckoutSlot(\n slot: CheckoutSlotName,\n): CheckoutSlotAppearance {\n const resolved = useCheckoutAppearance();\n\n return getCheckoutSlotAppearance(resolved, slot) ?? {};\n}\n","import { useAutoAnimate } from \"@formkit/auto-animate/react\";\nimport React from \"react\";\nimport { useInstrumentContext } from \"@/src/analytics/instrument\";\nimport { getCartLines, getProjectID, useCartProvider } from \"./CartProvider\";\nimport CountrySelector from \"./CountrySelector\";\nimport { isErr } from \"./lib/err\";\nimport { formatCurrency } from \"./lib/round.number\";\nimport LoadingIndicator from \"./LoadingIndicator\";\nimport SingleProduct from \"./SingleProduct\";\nimport { Skeleton } from \"./Skeleton\";\nimport { ApplePayButton, GooglePayButton } from \"..\";\nimport { Spinner } from \"@/src/ui/spinner\";\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { cn } from \"@/src/lib/utils\";\nimport { sendAnalyticEvent } from \"./frontent.analytics\";\nimport { getLocale } from \"./locale\";\nimport { buyErrorText } from \"./buy-error\";\nimport { useCheckoutText, useCheckoutTextResolver } from \"./texts.context\";\nimport { useCheckoutSlot } from \"./appearance.context\";\nimport { rememberPendingOrder } from \"./pending-order\";\nimport { useCheckoutStore } from \"./state\";\nimport { PaymentMethodChoice } from \"./PaymentMethodChoice\";\nimport {\n effectivePaymentMethod,\n withoutCod,\n type PaymentMethod,\n type PaymentMethodChoice as Choice,\n} from \"./payment-method\";\nimport { InPostPayButtonInner } from \"../express/InPostPayButton\";\nimport { RevolutPayButtonInner } from \"../express/RevolutPayButton\";\n\nconst CartComponentContent = ({\n className,\n locale,\n}: {\n className: string;\n locale?: string;\n}) => {\n const provider = useCartProvider();\n const instrument = useInstrumentContext();\n const currentLocale = locale ?? getLocale();\n\n const productList = useCheckoutSlot(\"productList\");\n const summary = useCheckoutSlot(\"summary\");\n const totalLabel = useCheckoutSlot(\"totalLabel\");\n const totalValue = useCheckoutSlot(\"totalValue\");\n const deliveryText = useCheckoutSlot(\"deliveryText\");\n const summaryNote = useCheckoutSlot(\"summaryNote\");\n const countryLabel = useCheckoutSlot(\"countryLabel\");\n const paymentButtons = useCheckoutSlot(\"paymentButtons\");\n const checkoutButton = useCheckoutSlot(\"checkoutButton\");\n const emptyState = useCheckoutSlot(\"emptyState\");\n const error = useCheckoutSlot(\"error\");\n const skeleton = useCheckoutSlot(\"skeleton\");\n\n const unavailableProductsText = useCheckoutText(\"unavailableProducts\");\n const resolveCheckoutText = useCheckoutTextResolver();\n const emptyCartText = useCheckoutText(\"emptyCart\");\n const totalText = useCheckoutText(\"total\");\n const deliveryCopy = useCheckoutText(\"delivery\");\n const chooseCountryText = useCheckoutText(\"chooseCountry\");\n const nextStepText = useCheckoutText(\"nextStep\");\n const loadFailedText = useCheckoutText(\"loadFailed\");\n const retryText = useCheckoutText(\"retry\");\n const countryRequiredText = useCheckoutText(\"countryRequired\");\n const extrasCalculatedNextText = useCheckoutText(\"extrasCalculatedNext\");\n const countrySelectorId = React.useId();\n const countryHintId = React.useId();\n\n const { mutateAsync: removeProduct } = useMutation({\n mutationFn: provider.removeProductFromCart,\n });\n const { mutateAsync: updateQuantity } = useMutation({\n mutationFn: provider.updateQuantity,\n });\n const { mutateAsync: setCountryAsync } = useMutation({\n mutationFn: provider.setCountry,\n });\n const { mutateAsync: clearCart } = useMutation({\n mutationFn: provider.clearCart,\n });\n\n const [errMsg, setErrMsg] = React.useState(\"\");\n // Raised outside of the drawer (for example a failed redirect of `window.cart.buyProduct`).\n const notice = useCheckoutStore((state) => state.notice);\n React.useEffect(\n () => () => useCheckoutStore.getState().setNotice(undefined),\n [],\n );\n const shownError = errMsg.length > 0 ? errMsg : (notice ?? \"\");\n const [missingItemIds, setMissingItemIds] = React.useState<string[]>([]);\n\n const [isCountryOpen, setIsCountryOpen] = React.useState(false);\n\n const {\n mutateAsync: continueToCheckoutAsync,\n isPending: isContinueToCheckoutLoading,\n } = useMutation({\n mutationFn: provider.redirectToNextStep,\n });\n\n const { data: availableCountries } = useQuery({\n queryKey: [\"cart-available-countries\"],\n queryFn: provider.getAvailableCountries,\n });\n const { data: isApplePayAvailable } = useQuery({\n queryKey: [\"cart-one-click-payment\"],\n queryFn: provider.checkIfApplePayIsAvailable,\n });\n const { data, isLoading, isError, refetch } = useQuery({\n queryKey: [\"cart\", currentLocale],\n queryFn: provider.getProducts,\n });\n const { data: countryData, refetch: refetchCountry } = useQuery({\n queryKey: [\"cart-country\"],\n queryFn: provider.getCountry,\n });\n\n const [productsParent] = useAutoAnimate(/* optional config */);\n\n const products = isErr(data) ? undefined : data;\n\n const selectedCountry =\n countryData != null && !isErr(countryData) && countryData != \"\"\n ? countryData\n : undefined;\n\n // Whether the shop lets the buyer pay by hand (transfer / BLIK to a phone)\n // or on delivery for this cart. Asked once per cart content and country\n // (cash on delivery is for Poland only); any failure means \"no choice\".\n // Without a country \"Next step\" is disabled, so there is nothing to ask yet.\n // Until a new country or cart is answered, the last choice stays on screen\n // without cash on delivery, which the new answer may not offer.\n const queryClient = useQueryClient();\n const cartSignature =\n products == null || products.length === 0 || selectedCountry == null\n ? undefined\n : products\n .map((el) => `${el.productID}:${el.quantity}`)\n .sort()\n .join(\",\");\n const paymentMethodsQuery = {\n queryKey: [\n \"cart-payment-methods\",\n getProjectID(),\n currentLocale,\n selectedCountry,\n cartSignature,\n ],\n queryFn: async (): Promise<Choice | null> =>\n provider.getPaymentMethodChoice().catch(() => null),\n staleTime: 60_000,\n retry: false,\n } as const;\n const {\n data: paymentMethodChoiceData,\n isPlaceholderData: isPaymentMethodChoicePlaceholder,\n } = useQuery({\n ...paymentMethodsQuery,\n enabled: cartSignature != null,\n placeholderData: (previous: Choice | null | undefined) =>\n previous === undefined ? undefined : withoutCod(previous),\n });\n const paymentMethodChoice =\n cartSignature != null ? (paymentMethodChoiceData ?? null) : null;\n const [selectedPaymentMethod, setSelectedPaymentMethod] = React.useState<\n PaymentMethod | undefined\n >(undefined);\n const [isWaitingForChoice, setIsWaitingForChoice] = React.useState(false);\n const paymentMethodsRef = React.useRef<HTMLDivElement>(null);\n const hasLoadFailed = !isLoading && (isError || isErr(data));\n\n const countries = isErr(availableCountries) ? [] : availableCountries;\n\n const sumOfProducts =\n products?.reduce((prev, curr) => {\n if (curr.details == null) {\n return prev;\n }\n return prev + (curr.details.pricing?.effectivePrice ?? curr.details.price) * curr.quantity;\n }, 0) ?? 0;\n const currency = products?.[0]?.details?.currency ?? \"PLN\";\n\n const isSomeProductDeliverable =\n products?.some((product) => product.details?.isDeliverable === true) ??\n false;\n\n // The hint waits for the answer: the country is read asynchronously.\n const isCountryMissing = countryData !== undefined && selectedCountry == null;\n\n // A stored country the shop does not ship to (or none at all) would leave the checkout button disabled.\n const autoSelectedCountry = React.useRef(false);\n React.useEffect(() => {\n if (\n autoSelectedCountry.current ||\n countries == null ||\n countries.length === 0 ||\n countryData == null ||\n (selectedCountry != null &&\n countries.some((el) => el.code === selectedCountry))\n ) {\n return;\n }\n autoSelectedCountry.current = true;\n setCountryAsync(countries[0].code)\n .then(() => refetchCountry())\n .catch(() => {});\n }, [countries, countryData, selectedCountry]);\n\n // One `cart_opened` per opening of the drawer, once the cart is loaded.\n const opened = React.useRef(false);\n React.useEffect(() => {\n if (opened.current || isLoading) {\n return;\n }\n opened.current = true;\n instrument.track(\"cart_opened\", {\n item_count: products?.reduce((sum, el) => sum + el.quantity, 0) ?? 0,\n value_minor: sumOfProducts,\n currency,\n });\n }, [isLoading, instrument, products, sumOfProducts, currency]);\n\n const reportedQuantity = React.useRef(new Map<string, number>());\n React.useEffect(() => {\n reportedQuantity.current.clear();\n }, [products]);\n\n /** `add_to_cart` / `remove_from_cart` for a quantity change in the drawer. */\n function trackQuantityChange(id: string, newQuantity: number) {\n const line = products?.find((el) => el.id === id);\n if (line?.details == null) {\n return;\n }\n // Quick clicks arrive before the cart is reloaded: count from the last reported quantity.\n const delta = newQuantity - (reportedQuantity.current.get(id) ?? line.quantity);\n reportedQuantity.current.set(id, newQuantity);\n if (delta === 0) {\n return;\n }\n const price = line.details.pricing?.effectivePrice ?? line.details.price;\n const productID = line.catalogProductID ?? line.productID;\n instrument.track(\n delta > 0 ? \"add_to_cart\" : \"remove_from_cart\",\n {\n qty: Math.abs(delta),\n value_minor: Math.round(price * Math.abs(delta)),\n currency: line.details.currency,\n },\n {\n product_id: productID,\n variant_id: productID !== line.productID ? line.productID : null,\n },\n );\n }\n\n const startedCheckout = React.useRef(false);\n\n /** Rejects when the cart could not be changed; the cart is reloaded either way. */\n async function shouldUpdate(id: string, newQuantity?: number) {\n if (newQuantity == null) {\n return;\n }\n trackQuantityChange(id, Math.max(0, newQuantity));\n try {\n const result =\n newQuantity <= 0\n ? await removeProduct({ id: id })\n : await updateQuantity({ id: id, quantity: newQuantity });\n if (isErr(result)) {\n throw new Error(`cannot change the cart: ${result.error}`);\n }\n } finally {\n await refetch().catch(() => undefined);\n }\n }\n\n async function continueToCheckout() {\n try {\n setErrMsg(\"\");\n setMissingItemIds([]);\n useCheckoutStore.getState().setNotice(undefined);\n\n // A click before the choice arrived waits for it (at most the request\n // timeout); a choice the buyer has not seen yet is shown, not used. The\n // last choice shown in the meantime is used if the new one still offers\n // the selected method.\n let choice = paymentMethodChoice;\n let paymentMethod =\n choice != null\n ? effectivePaymentMethod(choice, selectedPaymentMethod)\n : undefined;\n if (\n cartSignature != null &&\n (paymentMethodChoiceData === undefined || isPaymentMethodChoicePlaceholder)\n ) {\n setIsWaitingForChoice(true);\n try {\n choice = await queryClient\n .fetchQuery(paymentMethodsQuery)\n .catch(() => null);\n } finally {\n setIsWaitingForChoice(false);\n }\n if (choice == null) {\n paymentMethod = undefined;\n } else if (paymentMethod == null || !choice.methods.includes(paymentMethod)) {\n // Let the buyer see the options first; focus moves to the selected one.\n window.setTimeout(() => {\n paymentMethodsRef.current\n ?.querySelector<HTMLInputElement>(\"input:checked\")\n ?.focus();\n }, 0);\n return;\n }\n }\n\n if (products != null) {\n if (!startedCheckout.current && products.length > 0) {\n startedCheckout.current = true;\n instrument.track(\"checkout_started\", {\n item_count: products.reduce((sum, el) => sum + el.quantity, 0),\n checkout_type: \"cart\",\n value_minor: sumOfProducts,\n currency,\n });\n }\n try {\n sendAnalyticEvent({\n event: \"initiateCheckout\",\n items: products?.map((el) => ({\n id: el.productID,\n name: el.details?.name ?? \"\",\n price: el.details?.price ?? 0,\n quantity: el.quantity,\n currency: el.details?.currency ?? \"PLN\",\n })),\n });\n } catch (e) {}\n }\n\n // What this order is made of; only these lines go once it is paid.\n const cartLinesBeforeBuy = getCartLines();\n const response = await continueToCheckoutAsync(\n paymentMethod != null ? { paymentMethod } : undefined,\n );\n\n if (isErr(response)) {\n // The seller may have changed the payment methods in the meantime.\n void queryClient.invalidateQueries({ queryKey: [\"cart-payment-methods\"] });\n if (response.error == \"item-ids-not-found\") {\n setErrMsg(unavailableProductsText);\n if (\"data\" in response && Array.isArray(response.data)) {\n setMissingItemIds(response.data as string[]);\n }\n } else if (\n paymentMethod === \"cod\" &&\n response.error == \"gateway-not-configured\"\n ) {\n // The shop turned cash on delivery off, or this cart does not qualify.\n setErrMsg(resolveCheckoutText(\"paymentMethodCodUnavailable\"));\n } else {\n setErrMsg(buyErrorText(response, resolveCheckoutText));\n }\n return;\n }\n\n // The cart stays until the order is paid (or placed, for cash on\n // delivery); without an order to ask about it is cleared now.\n if (\n !rememberPendingOrder(response, {\n cartProjectId: getProjectID(),\n lines: cartLinesBeforeBuy,\n })\n ) {\n await clearCart();\n }\n window.location.href = response.url;\n } catch (e: unknown) {\n console.warn(\"checkout failed\", e);\n setErrMsg(resolveCheckoutText(\"checkoutFailed\"));\n }\n }\n\n return (\n <div className={`${className} flex flex-col`} ref={productsParent}>\n {isLoading && (\n <div className={\"relative flex w-full justify-center flex-col gap-4\"}>\n <Skeleton\n data-bitsnap-checkout-slot=\"skeleton\"\n className={cn(\"w-full h-32\", skeleton.className)}\n style={skeleton.style}\n />\n <Skeleton\n data-bitsnap-checkout-slot=\"skeleton\"\n className={cn(\"w-full h-32\", skeleton.className)}\n style={skeleton.style}\n />\n </div>\n )}\n\n {hasLoadFailed && (\n <div className={\"flex flex-col items-start gap-3 p-4\"}>\n <p\n role=\"alert\"\n data-bitsnap-checkout-slot=\"error\"\n className={cn(error.className)}\n style={error.style}\n >\n {loadFailedText}\n </p>\n {notice != null && notice.length > 0 && (\n <p\n role=\"alert\"\n data-bitsnap-checkout-slot=\"error\"\n className={cn(\"text-sm\", error.className)}\n style={error.style}\n >\n {notice}\n </p>\n )}\n <button\n type=\"button\"\n data-bitsnap-checkout-slot=\"checkoutButton\"\n onClick={() => {\n refetch().then().catch();\n }}\n className={cn(\n \"px-3 py-2 rounded-md transition font-bold\",\n checkoutButton.className,\n )}\n style={checkoutButton.style}\n >\n {retryText}\n </button>\n </div>\n )}\n\n {!isLoading && !hasLoadFailed && (products == null || products.length == 0) && (\n <div className={\"flex flex-col gap-4 p-4\"}>\n <p\n data-bitsnap-checkout-slot=\"emptyState\"\n className={cn(emptyState.className)}\n style={emptyState.style}\n >\n {emptyCartText}\n </p>\n {notice != null && notice.length > 0 && (\n <p\n role=\"alert\"\n data-bitsnap-checkout-slot=\"error\"\n className={cn(\"text-sm\", error.className)}\n style={error.style}\n >\n {notice}\n </p>\n )}\n </div>\n )}\n\n <div\n data-bitsnap-checkout-slot=\"productList\"\n className={cn(\n \"max-h-[70vh] overflow-clip overflow-y-scroll\",\n productList.className,\n )}\n style={productList.style}\n >\n {products != null && products.length > 0 && (\n <ul className={\"mt-5\"}>\n {products.map((product) => (\n <React.Fragment key={product.id}>\n {product.details != null && (\n <li className={\"mb-3\"}>\n <SingleProduct\n isNotAvailable={missingItemIds.includes(\n product.productID,\n )}\n quantity={product.quantity}\n details={product.details}\n url={product.url}\n shouldUpdate={(newQuantity) =>\n shouldUpdate(product.id, newQuantity)\n }\n />\n <hr className=\"h-1\" />\n </li>\n )}\n </React.Fragment>\n ))}\n </ul>\n )}\n </div>\n\n <div className=\"grow\"></div>\n\n {sumOfProducts > 0 && currency != null && (\n <>\n <div\n data-bitsnap-checkout-slot=\"summary\"\n className={cn(\"mx-3 flex flex-col\", summary.className)}\n style={summary.style}\n >\n <div className={\"flex flex-row justify-between text-lg\"}>\n <p\n data-bitsnap-checkout-slot=\"totalLabel\"\n className={cn(\"text-xl\", totalLabel.className)}\n style={totalLabel.style}\n >\n {totalText}\n </p>\n <div className={\"flex flex-col items-end\"}>\n <p\n data-bitsnap-checkout-slot=\"totalValue\"\n className={cn(\"font-medium\", totalValue.className)}\n style={totalValue.style}\n >\n {formatCurrency(sumOfProducts, currency)}\n </p>\n {isSomeProductDeliverable && (\n <p\n data-bitsnap-checkout-slot=\"deliveryText\"\n className={cn(\n \"opacity-70 text-right text-base\",\n deliveryText.className,\n )}\n style={deliveryText.style}\n >\n {deliveryCopy}\n </p>\n )}\n </div>\n </div>\n <p\n data-bitsnap-checkout-slot=\"summaryNote\"\n className={cn(\"opacity-70 text-sm\", summaryNote.className)}\n style={summaryNote.style}\n >\n {extrasCalculatedNextText}\n </p>\n </div>\n\n {countries && countries?.length > 1 && (\n <div>\n <h4\n data-bitsnap-checkout-slot=\"countryLabel\"\n className={cn(\"ml-3 text-sm\", countryLabel.className)}\n style={countryLabel.style}\n >\n {chooseCountryText}\n </h4>\n <CountrySelector\n id={countrySelectorId}\n open={isCountryOpen}\n onToggle={() => {\n setIsCountryOpen(!isCountryOpen);\n }}\n onChange={(newValue) => {\n setCountryAsync(newValue).then(() => {\n refetchCountry().then().catch();\n });\n }}\n selectedValue={selectedCountry ?? \"\"}\n countries={countries}\n />\n </div>\n )}\n\n <div className={\"mb-3 flex flex-col\"}>\n {isApplePayAvailable && products != null && products.length > 0 && (\n <div\n data-bitsnap-checkout-slot=\"paymentButtons\"\n className={cn(\"w-full px-2\", paymentButtons.className)}\n style={paymentButtons.style}\n >\n <ApplePayButton\n colorType=\"white\"\n style={{ width: \"100%\" }}\n items={products?.map((el) => ({\n name: el.details?.name ?? \"\",\n id: el.productID,\n price: el.details?.pricing?.effectivePrice ?? el.details?.price ?? 0,\n currency: el.details?.currency,\n quantity: el.quantity,\n isDeliverable: el.details?.isDeliverable ?? false,\n metadata: el.metadata,\n }))}\n />\n </div>\n )}\n {products != null && products.length > 0 && (\n <div\n data-bitsnap-checkout-slot=\"paymentButtons\"\n className={cn(\"w-full px-2\", paymentButtons.className)}\n style={paymentButtons.style}\n >\n <GooglePayButton\n buttonSizeMode=\"fill\"\n buttonColor=\"white\"\n style={{ width: \"100%\" }}\n items={products?.map((el) => ({\n name: el.details?.name ?? \"\",\n id: el.productID,\n price: el.details?.pricing?.effectivePrice ?? el.details?.price ?? 0,\n quantity: el.quantity,\n isDeliverable: el.details?.isDeliverable ?? false,\n metadata: el.metadata,\n }))}\n />\n </div>\n )}\n {products != null && products.length > 0 && (\n <div\n data-bitsnap-checkout-slot=\"paymentButtons\"\n className={cn(\"w-full px-2\", paymentButtons.className)}\n style={paymentButtons.style}\n >\n <InPostPayButtonInner\n projectID={getProjectID() ?? \"\"}\n locale={currentLocale}\n />\n <RevolutPayButtonInner\n projectID={getProjectID() ?? \"\"}\n locale={currentLocale}\n />\n </div>\n )}\n {paymentMethodChoice != null && (\n <div ref={paymentMethodsRef} className=\"contents\">\n <PaymentMethodChoice\n choice={paymentMethodChoice}\n selected={effectivePaymentMethod(\n paymentMethodChoice,\n selectedPaymentMethod,\n )}\n onChange={setSelectedPaymentMethod}\n disabled={isContinueToCheckoutLoading}\n />\n </div>\n )}\n <button\n data-bitsnap-checkout-slot=\"checkoutButton\"\n onClick={continueToCheckout}\n disabled={\n isLoading ||\n isContinueToCheckoutLoading ||\n isWaitingForChoice ||\n selectedCountry == null\n }\n aria-describedby={isCountryMissing ? countryHintId : undefined}\n className={cn(\n \"px-3 py-2 my-2 mx-2 rounded-md disabled:opacity-40 disabled:cursor-not-allowed transition font-bold\",\n checkoutButton.className,\n )}\n style={checkoutButton.style}\n >\n {isContinueToCheckoutLoading || isWaitingForChoice ? (\n <Spinner />\n ) : (\n nextStepText\n )}\n </button>\n {isCountryMissing && (\n <p\n id={countryHintId}\n className={\"text-sm text-center opacity-70\"}\n >\n {countryRequiredText}\n </p>\n )}\n {shownError.length > 0 && (\n <p\n role=\"alert\"\n data-bitsnap-checkout-slot=\"error\"\n className={cn(\"text-sm text-center\", error.className)}\n style={error.style}\n >\n {shownError}\n </p>\n )}\n </div>\n </>\n )}\n </div>\n );\n};\n\nexport default CartComponentContent;\n","import * as React from \"react\"\nimport * as SelectPrimitive from \"@radix-ui/react-select\"\nimport { CheckIcon, ChevronDownIcon, ChevronUpIcon } from \"lucide-react\"\n\nimport { cn } from \"@/src/lib/utils\"\n\nfunction Select({\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Root>) {\n return <SelectPrimitive.Root data-slot=\"select\" {...props} />\n}\n\nfunction SelectGroup({\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Group>) {\n return <SelectPrimitive.Group data-slot=\"select-group\" {...props} />\n}\n\nfunction SelectValue({\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Value>) {\n return <SelectPrimitive.Value data-slot=\"select-value\" {...props} />\n}\n\n/**\n * Colors owned by the shared shadcn theme. They live in Tailwind's\n * `utilities` layer, so plain CSS can never win against them. Components that\n * theme themselves through their own stylesheet (the checkout and its\n * `appearance` tokens) opt out with `theme=\"bare\"`, which keeps the colors the\n * checkout owns (`background-color`, `border-color`) and leaves the rest alone.\n * The default is unchanged.\n */\nconst selectTriggerThemeClasses =\n \"border-input dark:bg-input/30 dark:hover:bg-input/50 bg-transparent\"\n\nfunction SelectTrigger({\n className,\n size = \"default\",\n theme = \"default\",\n children,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {\n size?: \"sm\" | \"default\"\n theme?: \"default\" | \"bare\"\n}) {\n return (\n <SelectPrimitive.Trigger\n data-slot=\"select-trigger\"\n data-size={size}\n className={cn(\n \"data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive flex w-fit items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n theme === \"bare\" ? \"\" : selectTriggerThemeClasses,\n className\n )}\n {...props}\n >\n {children}\n <SelectPrimitive.Icon asChild>\n <ChevronDownIcon className=\"size-4 opacity-50\" />\n </SelectPrimitive.Icon>\n </SelectPrimitive.Trigger>\n )\n}\n\nfunction SelectContent({\n className,\n children,\n position = \"popper\",\n align = \"center\",\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Content>) {\n return (\n <SelectPrimitive.Portal>\n <SelectPrimitive.Content\n data-slot=\"select-content\"\n className={cn(\n \"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md\",\n position === \"popper\" &&\n \"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1\",\n className\n )}\n position={position}\n align={align}\n {...props}\n >\n <SelectScrollUpButton />\n <SelectPrimitive.Viewport\n className={cn(\n \"p-1\",\n position === \"popper\" &&\n \"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1\"\n )}\n >\n {children}\n </SelectPrimitive.Viewport>\n <SelectScrollDownButton />\n </SelectPrimitive.Content>\n </SelectPrimitive.Portal>\n )\n}\n\nfunction SelectLabel({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Label>) {\n return (\n <SelectPrimitive.Label\n data-slot=\"select-label\"\n className={cn(\"text-muted-foreground px-2 py-1.5 text-xs\", className)}\n {...props}\n />\n )\n}\n\nfunction SelectItem({\n className,\n children,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Item>) {\n return (\n <SelectPrimitive.Item\n data-slot=\"select-item\"\n className={cn(\n \"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2\",\n className\n )}\n {...props}\n >\n <span className=\"absolute right-2 flex size-3.5 items-center justify-center\">\n <SelectPrimitive.ItemIndicator>\n <CheckIcon className=\"size-4\" />\n </SelectPrimitive.ItemIndicator>\n </span>\n <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>\n </SelectPrimitive.Item>\n )\n}\n\nfunction SelectSeparator({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Separator>) {\n return (\n <SelectPrimitive.Separator\n data-slot=\"select-separator\"\n className={cn(\"bg-border pointer-events-none -mx-1 my-1 h-px\", className)}\n {...props}\n />\n )\n}\n\nfunction SelectScrollUpButton({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {\n return (\n <SelectPrimitive.ScrollUpButton\n data-slot=\"select-scroll-up-button\"\n className={cn(\n \"flex cursor-default items-center justify-center py-1\",\n className\n )}\n {...props}\n >\n <ChevronUpIcon className=\"size-4\" />\n </SelectPrimitive.ScrollUpButton>\n )\n}\n\nfunction SelectScrollDownButton({\n className,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {\n return (\n <SelectPrimitive.ScrollDownButton\n data-slot=\"select-scroll-down-button\"\n className={cn(\n \"flex cursor-default items-center justify-center py-1\",\n className\n )}\n {...props}\n >\n <ChevronDownIcon className=\"size-4\" />\n </SelectPrimitive.ScrollDownButton>\n )\n}\n\nexport {\n Select,\n SelectContent,\n SelectGroup,\n SelectItem,\n SelectLabel,\n SelectScrollDownButton,\n SelectScrollUpButton,\n SelectSeparator,\n SelectTrigger,\n SelectValue,\n}\n","import { useEffect, useState } from \"react\";\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from \"@/src/ui/select\";\nimport { cn } from \"@/src/lib/utils\";\nimport { useCheckoutAppearance, useCheckoutSlot } from \"./appearance.context\";\nimport { useCheckoutText } from \"./texts.context\";\n\nexport interface CountrySelectorProps {\n id: string;\n open: boolean;\n disabled?: boolean;\n onToggle: () => void;\n onChange: (value: string) => void;\n selectedValue: string;\n countries: { name: string; code: string }[];\n}\n\nfunction CountrySelector({\n id,\n open,\n disabled = false,\n onToggle,\n onChange,\n selectedValue,\n countries,\n}: CountrySelectorProps) {\n const [query, setQuery] = useState(\"\");\n\n const {\n isCustomized,\n boundaryClassName,\n boundaryStyle,\n dropdownStyle,\n } = useCheckoutAppearance();\n const countryTrigger = useCheckoutSlot(\"countryTrigger\");\n const countryDropdown = useCheckoutSlot(\"countryDropdown\");\n const countrySearch = useCheckoutSlot(\"countrySearch\");\n const countryOption = useCheckoutSlot(\"countryOption\");\n const searchCountryText = useCheckoutText(\"searchCountry\");\n const noCountriesFoundText = useCheckoutText(\"noCountriesFound\");\n\n useEffect(() => {\n if (selectedValue == null && countries.length > 0) {\n onChange(countries[0].code);\n }\n }, []);\n\n const filteredCountries = countries.filter((country) =>\n country.name.toLowerCase().startsWith(query.toLowerCase()),\n );\n\n const selectedCountry = countries.find((el) => el.code === selectedValue);\n\n return (\n <Select\n value={selectedValue}\n onValueChange={(value) => {\n onChange(value);\n setQuery(\"\");\n }}\n open={open}\n onOpenChange={(isOpen) => {\n if (isOpen !== open) {\n onToggle();\n }\n if (!isOpen) {\n setQuery(\"\");\n }\n }}\n disabled={disabled}\n >\n <SelectTrigger\n data-bitsnap-checkout-slot=\"countryTrigger\"\n theme=\"bare\"\n className={cn(\n disabled\n ? \"bg-neutral-100 dark:bg-neutral-800 dark:border-neutral-700\"\n : \"\",\n \"w-full rounded-md\",\n countryTrigger.className,\n )}\n style={countryTrigger.style}\n >\n <SelectValue>\n {selectedCountry && (\n <span className=\"truncate flex items-center\">\n <img\n alt={selectedValue}\n src={`https://purecatamphetamine.github.io/country-flag-icons/3x2/${selectedValue}.svg`}\n className=\"inline mr-2 h-4 rounded-sm\"\n />\n {selectedCountry.name}\n </span>\n )}\n </SelectValue>\n </SelectTrigger>\n <SelectContent\n data-bitsnap-checkout={isCustomized ? \"dropdown\" : undefined}\n data-bitsnap-checkout-slot={isCustomized ? \"countryDropdown\" : undefined}\n className={cn(\n // The dropdown is portalled outside of the checkout root, so it only\n // joins the checkout theme boundary once the caller opts into an\n // appearance. Without it the content renders exactly as before.\n isCustomized ? \"bitsnap-react\" : \"\",\n boundaryClassName,\n \"w-full max-h-80 max-w-[350px] z-[999999]\",\n countryDropdown.className,\n )}\n style={{\n ...(isCustomized ? { ...boundaryStyle, ...dropdownStyle } : undefined),\n ...countryDropdown.style,\n }}\n position=\"popper\"\n >\n <div\n data-bitsnap-checkout-slot=\"countrySearch\"\n className={cn(\"sticky top-0 z-10 p-1 border-b\", countrySearch.className)}\n style={countrySearch.style}\n >\n <input\n type=\"search\"\n name=\"search\"\n autoComplete=\"off\"\n className=\"block w-full outline-none sm:text-body-regular bg-transparent rounded-md px-2 py-1.5\"\n placeholder={searchCountryText}\n aria-label={searchCountryText}\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n onClick={(e) => e.stopPropagation()}\n onKeyDown={(e) => e.stopPropagation()}\n />\n </div>\n <div className=\"max-h-64 overflow-y-auto\">\n {filteredCountries.length === 0 ? (\n <div className=\"cursor-default select-none relative py-2 pl-3 pr-9 text-sm\">\n {noCountriesFoundText}\n </div>\n ) : (\n filteredCountries.map((country) => (\n <SelectItem\n key={`${id}-${country.code}`}\n data-bitsnap-checkout-slot=\"countryOption\"\n value={country.code}\n className={cn(\n \"cursor-default select-none relative py-2 pl-3 pr-9 flex items-center transition\",\n countryOption.className,\n )}\n style={countryOption.style}\n >\n <img\n alt={country.code}\n src={`https://purecatamphetamine.github.io/country-flag-icons/3x2/${country.code}.svg`}\n className=\"inline mr-2 h-4 rounded-sm\"\n />\n <span className=\"font-normal truncate\">{country.name}</span>\n </SelectItem>\n ))\n )}\n </div>\n </SelectContent>\n </Select>\n );\n}\n\nexport default CountrySelector;\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as le,c as _,d as ue,e as z,f as de,g as V,h as fe,i as pe,o as Y,q as L}from"./chunk-MDCP5JNP.mjs";var Oe=Symbol.for("bitsnap.pageViews");function ye(e){let t=e;return t[Oe]??={path:null,starters:new Set,watching:!1}}function De(e,t){let n=()=>{try{t()}catch{}};for(let o of["pushState","replaceState"]){let a=e.history[o];e.history[o]=function(...i){let c=a.apply(this,i);return n(),c}}e.addEventListener("popstate",n)}function A(e,t=window){try{let n=ye(t),o=()=>e();n.watching||(n.watching=!0,De(t,()=>{let i=t.location.pathname;i===n.path||n.starters.size===0||(n.path=i,n.starters.values().next().value?.())})),n.starters.add(o);let a=t.location.pathname;return a!==n.path&&(n.path=a,o()),()=>void n.starters.delete(o)}catch{return()=>{}}}function ge(e=window){let t=ye(e);t.path=null,t.starters.clear()}var ve="1.19.0";function I(e){let t=new Uint8Array(e),n=typeof crypto<"u"?crypto:void 0;if(n&&typeof n.getRandomValues=="function")n.getRandomValues(t);else for(let o=0;o<e;o++)t[o]=Math.floor(Math.random()*256);return t}var me="X-Bitsnap-Visitor",$e=390*24*60*60,Me=/^[A-Za-z0-9_-]{22}$/;function R(e){return e.BitsnapConsent}function je(e,t){for(let n of e.cookie.split(";")){let o=n.indexOf("=");if(o!==-1&&n.slice(0,o).trim()===t)return n.slice(o+1).trim()}return null}function He(e){let t=e.toLowerCase();return t==="bitsnap.pl"||t.endsWith(".bitsnap.pl")}function F(e,t){try{let n=R(e);if(!n)return!1;if(n.scope==="project")return n.projectKey===t;let o=He(e.location.hostname);return n.scope==="global"?!o:!1}catch{return!1}}function J(e,t){try{return R(e)?.get()?.c.analytics===!0&&F(e,t)}catch{return!1}}function he(){let e="";return I(16).forEach(t=>e+=String.fromCharCode(t)),btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ee(e,t){try{return je(e,V(t))}catch{return null}}function B(e,t){let n=Ee(e,t);return n!==null&&Me.test(n)?n:null}function ke(e,t,n){try{let o=e.document,a=`${V(t)}=${n}; Max-Age=${$e}; Path=/; SameSite=Lax`+(e.location.protocol==="https:"?"; Secure":"");for(let i of Y(e.location.hostname).reverse())if(o.cookie=`${a}; Domain=${i}`,B(o,t)===n)return;o.cookie=a}catch{}}function be(e,t){try{let n=e.document;if(Ee(n,t)===null)return;let o=`${V(t)}=; Max-Age=0; Path=/; SameSite=Lax`+(e.location.protocol==="https:"?"; Secure":"");n.cookie=o;for(let a of Y(e.location.hostname))n.cookie=`${o}; Domain=${a}`}catch{}}function N(e,t){try{let n=e.navigator;return n?.globalPrivacyControl===!0||n?.webdriver===!0?null:J(e,t)?B(e.document,t):null}catch{return null}}var Ue="https://collect.bitsnap.pl",Ke=5e3,Ge=20,Te=32*1024,ze=60*1024,xe=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function _e(e){return typeof TextEncoder=="function"?new TextEncoder().encode(e).length:unescape(encodeURIComponent(e)).length}var y={track(){},page(){},clientId:()=>null,flush(){},setEnabled(){},onEvent:()=>()=>{},configure(){},destroy(){}};function Ye(e=Date.now()){let t=I(16),n=e;for(let a=5;a>=0;a--)t[a]=n%256,n=Math.floor(n/256);t[6]=t[6]&15|112,t[8]=t[8]&63|128;let o=Array.from(t,a=>a.toString(16).padStart(2,"0")).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}var Ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Fe(){return Array.from(I(16),e=>Ce[e%Ce.length]).join("")}function Je(e,t,n=!1){let o=_e(JSON.stringify({k:e,events:[]})),a=[],i=[],c=o,s=()=>{i.length>0&&a.push({body:JSON.stringify({k:e,events:i}),bytes:c,count:i.length}),i=[],c=o};for(let u of t){let l=_e(JSON.stringify(u));o+l>Te||((i.length>=le.maxBatchEvents||c+l+(i.length>0?1:0)>Te)&&s(),c+=l+(i.length>0?1:0),i.push(u))}if(s(),n){let u=0,l=a.length;for(;l>0&&u+a[l-1].bytes<=ze;)u+=a[l-1].bytes,l--;a=a.slice(l)}return a}function Xe(e){try{return typeof window>"u"||typeof document>"u"?y:qe(e,window)}catch{return y}}function qe(e,t){let n=_(e.projectKey??""),o=!!e.debug,a=(...r)=>{o&&console.warn("[bitsnap analytics]",...r)};if(!n)return a("invalid projectKey, tracking is off"),y;let i=n,c=r=>`${(r||Ue).replace(/\/+$/,"")}/e`,s=c(e.endpoint),u=e.source??"sdk_react",l=e.channel??"embed",b=`bitsnap-react@${ve}`,M=Fe(),T=z(t.location.href),j=e.env??"live";if(!e.env)try{new URLSearchParams(t.location.search).has("test")&&(j="test")}catch{}let Le=de(document.referrer),H=e.enabled!==!1,ee=null,Re=0,p=[],h=null,C=new Set;e.onEvent&&C.add(e.onEvent);let E=[],g,m=!0;function W(){let r=R(t);!r||r===g||(g=r,m=!r.ready,r.ready?.then(()=>{g===r&&(m=!0,re())},()=>{g===r&&(m=!0)}))}function te(){W();try{if(!g)return!1;let r=g.get();return!!g.denied&&g.denied("analytics")||!!r&&r.c.analytics===!1}catch{return!1}}function ne(r){C.forEach(f=>{try{f(r)}catch{}})}function U(r){try{if(W(),!g||!F(t,i))return;J(t,i)?P()&&B(t.document,i)===null&&ke(t,i,he()):r&&be(t,i)}catch{}}function re(){if(U(!0),te())p=[],E=[],w();else{if(m&&E.length>0){let r=E;E=[],r.forEach(ne)}p.length>0&&x()}}function P(){if(!H)return!1;let r=t.navigator;return r&&(r.globalPrivacyControl===!0||r.webdriver===!0)?!1:!te()}function w(){h!==null&&clearTimeout(h),h=null}function Be(){h===null&&(h=setTimeout(()=>{h=null,x()},Ke),h.unref?.())}function Ne(r){try{if(typeof fetch=="function"){fetch(s,{method:"POST",body:r,keepalive:!0,credentials:"omit",headers:{"Content-Type":"text/plain"}}).catch(()=>{});return}}catch{}try{let f=t.navigator;f&&typeof f.sendBeacon=="function"&&f.sendBeacon(s,new Blob([r],{type:"text/plain"}))}catch{}}function x(r=!1){try{if(w(),p.length===0)return;if(!P()){p=[];return}if(!m)return;U(m);let f=N(t,i),d=f?p.map(k=>({...k,client_id:f})):p;p=[],Je(i,d,r).forEach(k=>Ne(k.body))}catch{}}function oe(r,f,d){if(!P())return;let k=fe(r,f);if(!k.ok){a("dropped",r,k.reason);return}let se=z(t.location.href),K={event_id:d?.event_id&&xe.test(d.event_id)?d.event_id:Ye(),event:r,ts:Date.now(),schema_version:1,env:j,source:u,channel:l,sdk:b,page_id:M,page_type:d?.page_type!==void 0?d.page_type:ee,host:se?.host??null,path:d?.path?ue(d.path.split(/[?#]/)[0]):se?.path??null,referrer_host:Le,utm_source:T?.utm_source??null,utm_medium:T?.utm_medium??null,utm_campaign:T?.utm_campaign??null,utm_content:T?.utm_content??null,utm_term:T?.utm_term??null,ref_code:T?.ref_code??null,product_id:d?.product_id??null,variant_id:d?.variant_id??null,order_ref:d?.order_ref??null,props:k.props};d?.event_id&&!xe.test(d.event_id)&&a("ignored invalid event_id",r),u==="dashboard"&&e.visitorId&&(K.visitor_id=e.visitorId);let ce=pe(K);if(!ce.ok){a("dropped",r,ce.reason);return}let G=K;m?ne(G):E.push(G),p.push(G),p.length>=Ge?x():Be()}let ie=()=>x(!0),ae=()=>{document.visibilityState==="hidden"&&x(!0)},S=()=>re();return t.addEventListener("pagehide",ie),document.addEventListener("visibilitychange",ae),t.addEventListener("bitsnap:consent",S),t.addEventListener("bitsnap:consent:ready",S),W(),U(m),{track(r,f,d){try{oe(r,f,d)}catch{}},page(r,f){try{r!==void 0&&(ee=r),oe("page_view",{landing:Re++===0},f)}catch{}},clientId(r){try{return r!==void 0&&_(r)!==i?null:P()?N(t,i):null}catch{return null}},flush:()=>x(),setEnabled(r){H=!!r,H||(p=[],E=[],w())},configure(r){try{(r.env==="live"||r.env==="test")&&(j=r.env),typeof r.endpoint=="string"&&r.endpoint&&(s=c(r.endpoint))}catch{}},onEvent(r){return C.add(r),()=>void C.delete(r)},destroy(){p=[],E=[],w(),C.clear(),t.removeEventListener("pagehide",ie),document.removeEventListener("visibilitychange",ae),t.removeEventListener("bitsnap:consent",S),t.removeEventListener("bitsnap:consent:ready",S)}}}var v,O=null;function D(e){if(!v){let t=Xe(e);return t===y||(v=t,O=_(e.projectKey??"")),t}try{let t=_(e.projectKey??"");t!==O&&e.debug&&console.warn("[bitsnap analytics]","tracker already started for another projectKey, ignoring",e.projectKey),t===O&&((e.env||e.endpoint)&&v.configure({env:e.env,endpoint:e.endpoint}),e.enabled!=null&&v.setEnabled(e.enabled))}catch{}return v}function Ae(){return v}function xt(){typeof window<"u"&&ge(window),v?.destroy(),v=void 0,O=null}function _t(e){try{if(typeof window>"u")return{};let t=v,n=null;if(t)n=t.clientId(e);else{let o=e?_(e):null;n=o?N(window,o):null}return n?{[me]:n}:{}}catch{return{}}}import{createContext as Ze,createElement as Qe,useContext as et,useMemo as Ie,useRef as tt}from"react";var nt={track:y.track,page:y.page},Pe=Ze(nt);function St({projectKey:e,env:t,enabled:n,endpoint:o,onEvent:a,autoPageViews:i,children:c}){let s=Ie(()=>D({projectKey:e,env:t,endpoint:o,enabled:n}),[e,t,o]),u=tt(a);u.current=a,L(()=>{s.setEnabled(n!==!1)},[s,n]),L(()=>{if(!(i===!1||n===!1||s===y))return A(()=>s.page(null))},[s,i,n]),L(()=>s.onEvent(b=>u.current?.(b)),[s]);let l=Ie(()=>({track:s.track.bind(s),page:s.page.bind(s)}),[s]);return Qe(Pe.Provider,{value:l},c)}function we(){return et(Pe)}import{createContext as rt,createElement as ot,useContext as Ve,useEffect as it,useLayoutEffect as at,useMemo as st,useRef as ct}from"react";var $={track(){}},X=null;function lt(e){let t=Symbol("bitsnap-instrument");function n(){if(typeof window>"u")return null;let{projectKey:i,analytics:c,provided:s}=e();return c===!1?null:s||(i?D({projectKey:i,source:"sdk_react",channel:"embed",env:typeof c=="object"?c.env:void 0}):null)}let o={track(i,c,s){try{let u=n();if(!u)return;let{analytics:l,pageType:b}=e(),M=b&&s?.page_type===void 0?{...s,page_type:b}:s;X=typeof l=="object"&&l.onEvent?t:null,u.track(i,c,M)}catch{}finally{X=null}}};function a(){try{if(!n())return()=>{};let i=Ae();if(!i)return()=>{};let c=e().provided?()=>{}:A(()=>i.page(e().pageType??null)),s=i.onEvent(u=>{if(X===t)try{let{analytics:l}=e();typeof l=="object"&&l.onEvent?.(u)}catch{}});return()=>{c(),s()}}catch{return()=>{}}}return{instrument:o,attach:a}}var Z=rt(null);function Nt({value:e,children:t}){return ot(Z.Provider,{value:e},t)}function Ot(){return Ve(Z)??$}function Dt(e,t,n){let o=Ve(Z),a=we(),i=a.track===y.track?null:a,c=ct({projectKey:e,analytics:t,pageType:n,provided:i});c.current={projectKey:e,analytics:t,pageType:n,provided:i};let s=st(()=>lt(()=>c.current),[]),u=t===void 0&&o!==null,l=typeof t=="object"&&!!t.onEvent;return at(()=>{if(!u)return s.attach()},[s,u,l,e]),u?o:s.instrument}var Q=$;function Se(e){Q=e??$}var q=0;function $t(){return q>0?$:Q}async function Mt(e){q++;try{return await e()}finally{q--}}function jt(e){it(()=>(Se(e),()=>{Q===e&&Se(null)}),[e])}function Ht(e){let t=Number.isFinite(e)?Math.max(0,Math.min(100,e)):0;return t>=100?"100":t>=75?"75-99":t>=50?"50-74":t>=25?"25-49":"0-24"}function Wt(e,t){let n=[];for(let o of[25,50,75,100])e>=o&&!t.has(o)&&(t.add(o),n.push(o));return n}export{ve as a,A as b,Ue as c,Xe as d,D as e,Ae as f,xt as g,_t as h,St as i,we as j,$ as k,Nt as l,Ot as m,Dt as n,$t as o,Mt as p,jt as q,Ht as r,Wt as s};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as le,c as _,d as ue,e as z,f as de,g as V,h as fe,i as pe,o as Y,q as L}from"./chunk-MDCP5JNP.mjs";var Oe=Symbol.for("bitsnap.pageViews");function ye(e){let t=e;return t[Oe]??={path:null,starters:new Set,watching:!1}}function De(e,t){let n=()=>{try{t()}catch{}};for(let o of["pushState","replaceState"]){let a=e.history[o];e.history[o]=function(...i){let c=a.apply(this,i);return n(),c}}e.addEventListener("popstate",n)}function A(e,t=window){try{let n=ye(t),o=()=>e();n.watching||(n.watching=!0,De(t,()=>{let i=t.location.pathname;i===n.path||n.starters.size===0||(n.path=i,n.starters.values().next().value?.())})),n.starters.add(o);let a=t.location.pathname;return a!==n.path&&(n.path=a,o()),()=>void n.starters.delete(o)}catch{return()=>{}}}function ge(e=window){let t=ye(e);t.path=null,t.starters.clear()}var ve="1.20.0";function I(e){let t=new Uint8Array(e),n=typeof crypto<"u"?crypto:void 0;if(n&&typeof n.getRandomValues=="function")n.getRandomValues(t);else for(let o=0;o<e;o++)t[o]=Math.floor(Math.random()*256);return t}var me="X-Bitsnap-Visitor",$e=390*24*60*60,Me=/^[A-Za-z0-9_-]{22}$/;function R(e){return e.BitsnapConsent}function je(e,t){for(let n of e.cookie.split(";")){let o=n.indexOf("=");if(o!==-1&&n.slice(0,o).trim()===t)return n.slice(o+1).trim()}return null}function He(e){let t=e.toLowerCase();return t==="bitsnap.pl"||t.endsWith(".bitsnap.pl")}function F(e,t){try{let n=R(e);if(!n)return!1;if(n.scope==="project")return n.projectKey===t;let o=He(e.location.hostname);return n.scope==="global"?!o:!1}catch{return!1}}function J(e,t){try{return R(e)?.get()?.c.analytics===!0&&F(e,t)}catch{return!1}}function he(){let e="";return I(16).forEach(t=>e+=String.fromCharCode(t)),btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ee(e,t){try{return je(e,V(t))}catch{return null}}function B(e,t){let n=Ee(e,t);return n!==null&&Me.test(n)?n:null}function ke(e,t,n){try{let o=e.document,a=`${V(t)}=${n}; Max-Age=${$e}; Path=/; SameSite=Lax`+(e.location.protocol==="https:"?"; Secure":"");for(let i of Y(e.location.hostname).reverse())if(o.cookie=`${a}; Domain=${i}`,B(o,t)===n)return;o.cookie=a}catch{}}function be(e,t){try{let n=e.document;if(Ee(n,t)===null)return;let o=`${V(t)}=; Max-Age=0; Path=/; SameSite=Lax`+(e.location.protocol==="https:"?"; Secure":"");n.cookie=o;for(let a of Y(e.location.hostname))n.cookie=`${o}; Domain=${a}`}catch{}}function N(e,t){try{let n=e.navigator;return n?.globalPrivacyControl===!0||n?.webdriver===!0?null:J(e,t)?B(e.document,t):null}catch{return null}}var Ue="https://collect.bitsnap.pl",Ke=5e3,Ge=20,Te=32*1024,ze=60*1024,xe=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function _e(e){return typeof TextEncoder=="function"?new TextEncoder().encode(e).length:unescape(encodeURIComponent(e)).length}var y={track(){},page(){},clientId:()=>null,flush(){},setEnabled(){},onEvent:()=>()=>{},configure(){},destroy(){}};function Ye(e=Date.now()){let t=I(16),n=e;for(let a=5;a>=0;a--)t[a]=n%256,n=Math.floor(n/256);t[6]=t[6]&15|112,t[8]=t[8]&63|128;let o=Array.from(t,a=>a.toString(16).padStart(2,"0")).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}var Ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Fe(){return Array.from(I(16),e=>Ce[e%Ce.length]).join("")}function Je(e,t,n=!1){let o=_e(JSON.stringify({k:e,events:[]})),a=[],i=[],c=o,s=()=>{i.length>0&&a.push({body:JSON.stringify({k:e,events:i}),bytes:c,count:i.length}),i=[],c=o};for(let u of t){let l=_e(JSON.stringify(u));o+l>Te||((i.length>=le.maxBatchEvents||c+l+(i.length>0?1:0)>Te)&&s(),c+=l+(i.length>0?1:0),i.push(u))}if(s(),n){let u=0,l=a.length;for(;l>0&&u+a[l-1].bytes<=ze;)u+=a[l-1].bytes,l--;a=a.slice(l)}return a}function Xe(e){try{return typeof window>"u"||typeof document>"u"?y:qe(e,window)}catch{return y}}function qe(e,t){let n=_(e.projectKey??""),o=!!e.debug,a=(...r)=>{o&&console.warn("[bitsnap analytics]",...r)};if(!n)return a("invalid projectKey, tracking is off"),y;let i=n,c=r=>`${(r||Ue).replace(/\/+$/,"")}/e`,s=c(e.endpoint),u=e.source??"sdk_react",l=e.channel??"embed",b=`bitsnap-react@${ve}`,M=Fe(),T=z(t.location.href),j=e.env??"live";if(!e.env)try{new URLSearchParams(t.location.search).has("test")&&(j="test")}catch{}let Le=de(document.referrer),H=e.enabled!==!1,ee=null,Re=0,p=[],h=null,C=new Set;e.onEvent&&C.add(e.onEvent);let E=[],g,m=!0;function W(){let r=R(t);!r||r===g||(g=r,m=!r.ready,r.ready?.then(()=>{g===r&&(m=!0,re())},()=>{g===r&&(m=!0)}))}function te(){W();try{if(!g)return!1;let r=g.get();return!!g.denied&&g.denied("analytics")||!!r&&r.c.analytics===!1}catch{return!1}}function ne(r){C.forEach(f=>{try{f(r)}catch{}})}function U(r){try{if(W(),!g||!F(t,i))return;J(t,i)?P()&&B(t.document,i)===null&&ke(t,i,he()):r&&be(t,i)}catch{}}function re(){if(U(!0),te())p=[],E=[],w();else{if(m&&E.length>0){let r=E;E=[],r.forEach(ne)}p.length>0&&x()}}function P(){if(!H)return!1;let r=t.navigator;return r&&(r.globalPrivacyControl===!0||r.webdriver===!0)?!1:!te()}function w(){h!==null&&clearTimeout(h),h=null}function Be(){h===null&&(h=setTimeout(()=>{h=null,x()},Ke),h.unref?.())}function Ne(r){try{if(typeof fetch=="function"){fetch(s,{method:"POST",body:r,keepalive:!0,credentials:"omit",headers:{"Content-Type":"text/plain"}}).catch(()=>{});return}}catch{}try{let f=t.navigator;f&&typeof f.sendBeacon=="function"&&f.sendBeacon(s,new Blob([r],{type:"text/plain"}))}catch{}}function x(r=!1){try{if(w(),p.length===0)return;if(!P()){p=[];return}if(!m)return;U(m);let f=N(t,i),d=f?p.map(k=>({...k,client_id:f})):p;p=[],Je(i,d,r).forEach(k=>Ne(k.body))}catch{}}function oe(r,f,d){if(!P())return;let k=fe(r,f);if(!k.ok){a("dropped",r,k.reason);return}let se=z(t.location.href),K={event_id:d?.event_id&&xe.test(d.event_id)?d.event_id:Ye(),event:r,ts:Date.now(),schema_version:1,env:j,source:u,channel:l,sdk:b,page_id:M,page_type:d?.page_type!==void 0?d.page_type:ee,host:se?.host??null,path:d?.path?ue(d.path.split(/[?#]/)[0]):se?.path??null,referrer_host:Le,utm_source:T?.utm_source??null,utm_medium:T?.utm_medium??null,utm_campaign:T?.utm_campaign??null,utm_content:T?.utm_content??null,utm_term:T?.utm_term??null,ref_code:T?.ref_code??null,product_id:d?.product_id??null,variant_id:d?.variant_id??null,order_ref:d?.order_ref??null,props:k.props};d?.event_id&&!xe.test(d.event_id)&&a("ignored invalid event_id",r),u==="dashboard"&&e.visitorId&&(K.visitor_id=e.visitorId);let ce=pe(K);if(!ce.ok){a("dropped",r,ce.reason);return}let G=K;m?ne(G):E.push(G),p.push(G),p.length>=Ge?x():Be()}let ie=()=>x(!0),ae=()=>{document.visibilityState==="hidden"&&x(!0)},S=()=>re();return t.addEventListener("pagehide",ie),document.addEventListener("visibilitychange",ae),t.addEventListener("bitsnap:consent",S),t.addEventListener("bitsnap:consent:ready",S),W(),U(m),{track(r,f,d){try{oe(r,f,d)}catch{}},page(r,f){try{r!==void 0&&(ee=r),oe("page_view",{landing:Re++===0},f)}catch{}},clientId(r){try{return r!==void 0&&_(r)!==i?null:P()?N(t,i):null}catch{return null}},flush:()=>x(),setEnabled(r){H=!!r,H||(p=[],E=[],w())},configure(r){try{(r.env==="live"||r.env==="test")&&(j=r.env),typeof r.endpoint=="string"&&r.endpoint&&(s=c(r.endpoint))}catch{}},onEvent(r){return C.add(r),()=>void C.delete(r)},destroy(){p=[],E=[],w(),C.clear(),t.removeEventListener("pagehide",ie),document.removeEventListener("visibilitychange",ae),t.removeEventListener("bitsnap:consent",S),t.removeEventListener("bitsnap:consent:ready",S)}}}var v,O=null;function D(e){if(!v){let t=Xe(e);return t===y||(v=t,O=_(e.projectKey??"")),t}try{let t=_(e.projectKey??"");t!==O&&e.debug&&console.warn("[bitsnap analytics]","tracker already started for another projectKey, ignoring",e.projectKey),t===O&&((e.env||e.endpoint)&&v.configure({env:e.env,endpoint:e.endpoint}),e.enabled!=null&&v.setEnabled(e.enabled))}catch{}return v}function Ae(){return v}function xt(){typeof window<"u"&&ge(window),v?.destroy(),v=void 0,O=null}function _t(e){try{if(typeof window>"u")return{};let t=v,n=null;if(t)n=t.clientId(e);else{let o=e?_(e):null;n=o?N(window,o):null}return n?{[me]:n}:{}}catch{return{}}}import{createContext as Ze,createElement as Qe,useContext as et,useMemo as Ie,useRef as tt}from"react";var nt={track:y.track,page:y.page},Pe=Ze(nt);function St({projectKey:e,env:t,enabled:n,endpoint:o,onEvent:a,autoPageViews:i,children:c}){let s=Ie(()=>D({projectKey:e,env:t,endpoint:o,enabled:n}),[e,t,o]),u=tt(a);u.current=a,L(()=>{s.setEnabled(n!==!1)},[s,n]),L(()=>{if(!(i===!1||n===!1||s===y))return A(()=>s.page(null))},[s,i,n]),L(()=>s.onEvent(b=>u.current?.(b)),[s]);let l=Ie(()=>({track:s.track.bind(s),page:s.page.bind(s)}),[s]);return Qe(Pe.Provider,{value:l},c)}function we(){return et(Pe)}import{createContext as rt,createElement as ot,useContext as Ve,useEffect as it,useLayoutEffect as at,useMemo as st,useRef as ct}from"react";var $={track(){}},X=null;function lt(e){let t=Symbol("bitsnap-instrument");function n(){if(typeof window>"u")return null;let{projectKey:i,analytics:c,provided:s}=e();return c===!1?null:s||(i?D({projectKey:i,source:"sdk_react",channel:"embed",env:typeof c=="object"?c.env:void 0}):null)}let o={track(i,c,s){try{let u=n();if(!u)return;let{analytics:l,pageType:b}=e(),M=b&&s?.page_type===void 0?{...s,page_type:b}:s;X=typeof l=="object"&&l.onEvent?t:null,u.track(i,c,M)}catch{}finally{X=null}}};function a(){try{if(!n())return()=>{};let i=Ae();if(!i)return()=>{};let c=e().provided?()=>{}:A(()=>i.page(e().pageType??null)),s=i.onEvent(u=>{if(X===t)try{let{analytics:l}=e();typeof l=="object"&&l.onEvent?.(u)}catch{}});return()=>{c(),s()}}catch{return()=>{}}}return{instrument:o,attach:a}}var Z=rt(null);function Nt({value:e,children:t}){return ot(Z.Provider,{value:e},t)}function Ot(){return Ve(Z)??$}function Dt(e,t,n){let o=Ve(Z),a=we(),i=a.track===y.track?null:a,c=ct({projectKey:e,analytics:t,pageType:n,provided:i});c.current={projectKey:e,analytics:t,pageType:n,provided:i};let s=st(()=>lt(()=>c.current),[]),u=t===void 0&&o!==null,l=typeof t=="object"&&!!t.onEvent;return at(()=>{if(!u)return s.attach()},[s,u,l,e]),u?o:s.instrument}var Q=$;function Se(e){Q=e??$}var q=0;function $t(){return q>0?$:Q}async function Mt(e){q++;try{return await e()}finally{q--}}function jt(e){it(()=>(Se(e),()=>{Q===e&&Se(null)}),[e])}function Ht(e){let t=Number.isFinite(e)?Math.max(0,Math.min(100,e)):0;return t>=100?"100":t>=75?"75-99":t>=50?"50-74":t>=25?"25-49":"0-24"}function Wt(e,t){let n=[];for(let o of[25,50,75,100])e>=o&&!t.has(o)&&(t.add(o),n.push(o));return n}export{ve as a,A as b,Ue as c,Xe as d,D as e,Ae as f,xt as g,_t as h,St as i,we as j,$ as k,Nt as l,Ot as m,Dt as n,$t as o,Mt as p,jt as q,Ht as r,Wt as s};
|
|
2
|
+
//# sourceMappingURL=chunk-TW25G7XX.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/analytics/pageviews.ts","../src/version.ts","../src/analytics/random.ts","../src/analytics/visitor.ts","../src/analytics/core.ts","../src/analytics/react.tsx","../src/analytics/instrument.ts"],"sourcesContent":["/**\n * Page-wide state of the automatic page views. It lives on `window`, so the\n * npm package, a second copy of it and the `analytics.js` script agree on who\n * reports a path and the history is patched once.\n */\ntype Registry = {\n /** Last path some starter reported. */\n path: string | null;\n starters: Set<() => void>;\n watching: boolean;\n};\n\nconst REGISTRY = Symbol.for(\"bitsnap.pageViews\");\n\nfunction registry(win: Window): Registry {\n const holder = win as unknown as Record<symbol, Registry | undefined>;\n return (holder[REGISTRY] ??= { path: null, starters: new Set(), watching: false });\n}\n\n/** Calls `onChange` when the path changes through `history.pushState`/`replaceState` or Back/Forward. */\nfunction watchNavigation(win: Window, onChange: () => void) {\n const check = () => {\n try {\n onChange();\n } catch {}\n };\n for (const name of [\"pushState\", \"replaceState\"] as const) {\n const original = win.history[name];\n win.history[name] = function (this: History, ...args: Parameters<History[typeof name]>) {\n const result = original.apply(this, args);\n check();\n return result;\n };\n }\n win.addEventListener(\"popstate\", check);\n}\n\n/**\n * Calls `send` for the current path and again on every path change, unless\n * another starter on the page already reported that path: the page gets one\n * `page_view` per path change however many providers, components and embeds\n * start it. Returns the function that stops this starter.\n */\nexport function startAutoPageViews(send: () => void, win: Window = window): () => void {\n try {\n const reg = registry(win);\n const starter = () => send();\n if (!reg.watching) {\n reg.watching = true;\n watchNavigation(win, () => {\n const path = win.location.pathname;\n // Nobody listening: leave the path unreported so the next starter sends it.\n if (path === reg.path || reg.starters.size === 0) return;\n reg.path = path;\n reg.starters.values().next().value?.();\n });\n }\n reg.starters.add(starter);\n const path = win.location.pathname;\n if (path !== reg.path) {\n reg.path = path;\n starter();\n }\n return () => void reg.starters.delete(starter);\n } catch {\n return () => {};\n }\n}\n\n/** Forgets the reported path and the starters (tests, hot reload). The history patch stays. */\nexport function resetAutoPageViews(win: Window = window) {\n const reg = registry(win);\n reg.path = null;\n reg.starters.clear();\n}\n","// Generated by scripts/write-version.mjs from package.json. Do not edit.\nexport const SDK_VERSION = \"1.19.0\";\n","export function randomBytes(n: number): Uint8Array {\n const bytes = new Uint8Array(n);\n const c = typeof crypto !== \"undefined\" ? crypto : undefined;\n if (c && typeof c.getRandomValues === \"function\") c.getRandomValues(bytes);\n else for (let i = 0; i < n; i++) bytes[i] = Math.floor(Math.random() * 256);\n return bytes;\n}\n","import { domainCandidates } from \"../consent/core/cookie\";\nimport { clientIdCookieName } from \"./contract\";\nimport { randomBytes } from \"./random\";\n\n/** The part of `window.BitsnapConsent` (`bitsnap-react/consent`) the tracker reads. */\nexport type ConsentLike = {\n /** Absent on a consent script older than 1.9.0, which never counts as the project's banner. */\n scope?: \"global\" | \"project\";\n projectKey?: string | null;\n get(): { c: { analytics?: boolean } } | null;\n /** Also true for a refusal made on an older banner version, which `get()` no longer returns. */\n denied?(category: \"analytics\"): boolean;\n ready?: Promise<unknown>;\n};\n\n/** Sent to the Bitsnap server on the requests that create a checkout or payment link. */\nexport const VISITOR_HEADER = \"X-Bitsnap-Visitor\";\n// 390 days, under the 13 months CNIL allows. Set once, never extended.\nconst MAX_AGE_SECONDS = 390 * 24 * 60 * 60;\nconst VISITOR_ID_RE = /^[A-Za-z0-9_-]{22}$/;\n\nexport function consentApi(win: Window): ConsentLike | undefined {\n return (win as unknown as { BitsnapConsent?: ConsentLike }).BitsnapConsent;\n}\n\nfunction readCookie(doc: Document, name: string): string | null {\n for (const part of doc.cookie.split(\";\")) {\n const index = part.indexOf(\"=\");\n if (index !== -1 && part.slice(0, index).trim() === name) return part.slice(index + 1).trim();\n }\n return null;\n}\n\n/** bitsnap.pl and its subdomains: many merchants share them, and the site-wide choice is bitsnap's own. */\nfunction isBitsnapHost(hostname: string): boolean {\n const host = hostname.toLowerCase();\n return host === \"bitsnap.pl\" || host.endsWith(\".bitsnap.pl\");\n}\n\n/**\n * Whether the page's consent banner speaks for `projectKey`: a project-scope banner of that\n * key, or a site-scope banner on a merchant's own site. On bitsnap.pl a site-scope choice is\n * bitsnap's own, so only a project-scope one counts.\n */\nexport function consentBelongsTo(win: Window, projectKey: string): boolean {\n try {\n const api = consentApi(win);\n if (!api) return false;\n if (api.scope === \"project\") return api.projectKey === projectKey;\n const onBitsnap = isBitsnapHost(win.location.hostname);\n if (api.scope === \"global\") return !onBitsnap;\n // A consent script from before the scope info: it cannot be told apart from another project's banner.\n return false;\n } catch {\n return false;\n }\n}\n\n/** `true` only while a banner that speaks for `projectKey` holds a valid choice that grants `analytics`. */\nexport function analyticsGranted(win: Window, projectKey: string): boolean {\n try {\n return consentApi(win)?.get()?.c.analytics === true && consentBelongsTo(win, projectKey);\n } catch {\n return false;\n }\n}\n\n/** 16 random bytes as 22 base64url characters. */\nexport function newVisitorId(): string {\n let binary = \"\";\n randomBytes(16).forEach((byte) => (binary += String.fromCharCode(byte)));\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** Value of the `bs_vid_<projectKey>` cookie, whatever it holds; `null` when it is absent. */\nfunction rawVisitorCookie(doc: Document, projectKey: string): string | null {\n try {\n return readCookie(doc, clientIdCookieName(projectKey));\n } catch {\n return null;\n }\n}\n\n/** The project's client id from its first-party cookie (`bs_vid_<projectKey>`), or `null` if absent or malformed. */\nexport function readVisitorCookie(doc: Document, projectKey: string): string | null {\n const value = rawVisitorCookie(doc, projectKey);\n return value !== null && VISITOR_ID_RE.test(value) ? value : null;\n}\n\n/**\n * Sets the cookie on the widest registrable domain the browser accepts\n * (shortest suffix with two labels first, so `shop.example.co.uk` skips the\n * refused `co.uk`), host-only where no domain sticks (localhost, IP hosts).\n */\nexport function writeVisitorCookie(win: Window, projectKey: string, id: string): void {\n try {\n const doc = win.document;\n const base =\n `${clientIdCookieName(projectKey)}=${id}; Max-Age=${MAX_AGE_SECONDS}; Path=/; SameSite=Lax` +\n (win.location.protocol === \"https:\" ? \"; Secure\" : \"\");\n for (const domain of domainCandidates(win.location.hostname).reverse()) {\n doc.cookie = `${base}; Domain=${domain}`;\n if (readVisitorCookie(doc, projectKey) === id) return;\n }\n doc.cookie = base;\n } catch {\n // cookies blocked (sandboxed frame)\n }\n}\n\n/** Expires the cookie on the host and on every parent domain it may have been set on. */\nexport function deleteVisitorCookie(win: Window, projectKey: string): void {\n try {\n const doc = win.document;\n // Present under any value: a malformed one must go too.\n if (rawVisitorCookie(doc, projectKey) === null) return;\n const base =\n `${clientIdCookieName(projectKey)}=; Max-Age=0; Path=/; SameSite=Lax` +\n (win.location.protocol === \"https:\" ? \"; Secure\" : \"\");\n doc.cookie = base;\n for (const domain of domainCandidates(win.location.hostname)) doc.cookie = `${base}; Domain=${domain}`;\n } catch {\n // best effort\n }\n}\n\n/**\n * The project's client id to send, or `null`: analytics consent is granted,\n * Global Privacy Control is off, the browser is not automated and the cookie exists.\n */\nexport function readVisitorId(win: Window, projectKey: string): string | null {\n try {\n const nav = win.navigator as { globalPrivacyControl?: boolean; webdriver?: boolean } | undefined;\n if (nav?.globalPrivacyControl === true || nav?.webdriver === true) return null;\n return analyticsGranted(win, projectKey) ? readVisitorCookie(win.document, projectKey) : null;\n } catch {\n return null;\n }\n}\n","import {\n LIMITS,\n PAGE_TYPES,\n SCHEMA_VERSION,\n normalizeProjectKey,\n parseUrl,\n referrerHost,\n sanitizeProps,\n sanitizePath,\n validateEnvelope,\n type AppEventName,\n type Channel,\n type ClientEvent,\n type Env,\n type EventProps,\n type PageType,\n type Source,\n type StorefrontEventName,\n} from \"./contract\";\nimport { SDK_VERSION } from \"../version\";\nimport { resetAutoPageViews } from \"./pageviews\";\nimport { randomBytes } from \"./random\";\nimport {\n analyticsGranted,\n consentApi,\n consentBelongsTo,\n deleteVisitorCookie,\n newVisitorId,\n readVisitorCookie,\n readVisitorId,\n VISITOR_HEADER,\n writeVisitorCookie,\n type ConsentLike,\n} from \"./visitor\";\n\nexport { startAutoPageViews } from \"./pageviews\";\n\n/** Events a browser may send. `consent_updated` is written by the consent log only. */\nexport type BrowserEventName = Exclude<StorefrontEventName, \"consent_updated\"> | AppEventName;\n\nexport type TrackerOptions = {\n /** Public project key (the hashed project id). `pk_` prefix is accepted. */\n projectKey: string;\n /** Defaults to `live`, or `test` when the page URL has the `?test=` test-mode parameter. */\n env?: Env;\n /** Collector origin. Default `https://collect.bitsnap.pl`. */\n endpoint?: string;\n /** `false` turns tracking off. Default `true`. */\n enabled?: boolean;\n /** Default `embed`. */\n channel?: Channel;\n /** Default `sdk_react`. */\n source?: Source;\n /** Only honoured by the collector for `source: \"dashboard\"` (hashed user id). */\n visitorId?: string;\n /** Receives every valid envelope before it is queued, e.g. to forward it to the merchant's own tools. */\n onEvent?: (event: ClientEvent) => void;\n /** `console.warn` dropped events. */\n debug?: boolean;\n};\n\n/** Envelope fields a call site may set per event. */\nexport type TrackExtra = {\n page_type?: PageType | null;\n product_id?: string | null;\n variant_id?: string | null;\n order_ref?: string | null;\n /** Route template for pages whose URL path is not the path to report (the dashboard). */\n path?: string;\n /**\n * Deterministic UUIDv7 for events another system reports too (e.g. hosted\n * `payment_returned`), so the collector dedupes them. An invalid value is\n * ignored and a fresh id is used.\n */\n event_id?: string;\n};\n\nexport interface Tracker {\n track<E extends BrowserEventName>(event: E, props: EventProps<E>, extra?: TrackExtra): void;\n /**\n * Sends `page_view` and makes `pageType` the page type of the following events\n * (`null` clears it, `undefined` keeps the current one).\n */\n page(pageType?: PageType | null, extra?: TrackExtra): void;\n /**\n * The visitor's `bs_vid_<projectKey>` client id, only while this tracker is on\n * (enabled, no Global Privacy Control, not automated, analytics not denied) and\n * Bitsnap Consent grants analytics. `projectKey` must match the tracker's, if given.\n */\n clientId(projectKey?: string): string | null;\n /** Sends the queue now. */\n flush(): void;\n setEnabled(enabled: boolean): void;\n /** Returns an unsubscribe function. */\n onEvent(fn: (event: ClientEvent) => void): () => void;\n /** Updates `env` and `endpoint` of a running tracker. Other options are fixed at creation. */\n configure(patch: { env?: Env; endpoint?: string }): void;\n /** Removes the page listeners and drops the queue. */\n destroy(): void;\n}\n\nexport const DEFAULT_ENDPOINT = \"https://collect.bitsnap.pl\";\n\nconst FLUSH_INTERVAL_MS = 5000;\nconst FLUSH_AT = 20;\n// Half the collector's 64 KB body limit, measured in UTF-8 bytes of the whole body.\nconst MAX_BODY_BYTES = 32 * 1024;\n// Browsers share ~64 KB of in-flight keepalive requests; stay under it on pagehide.\nconst KEEPALIVE_BUDGET_BYTES = 60 * 1024;\nconst EVENT_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nfunction byteLength(text: string): number {\n if (typeof TextEncoder === \"function\") return new TextEncoder().encode(text).length;\n return unescape(encodeURIComponent(text)).length;\n}\n\nexport const noopTracker: Tracker = {\n track() {},\n page() {},\n clientId: () => null,\n flush() {},\n setEnabled() {},\n onEvent: () => () => {},\n configure() {},\n destroy() {},\n};\n\n/** UUIDv7: 48-bit unix ms, version 7, variant 10, 74 random bits. */\nexport function uuidv7(now = Date.now()): string {\n const b = randomBytes(16);\n let t = now;\n for (let i = 5; i >= 0; i--) {\n b[i] = t % 256;\n t = Math.floor(t / 256);\n }\n b[6] = (b[6] & 0x0f) | 0x70;\n b[8] = (b[8] & 0x3f) | 0x80;\n const hex = Array.from(b, (x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nconst PAGE_ID_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\nfunction newPageId(): string {\n return Array.from(randomBytes(16), (x) => PAGE_ID_ALPHABET[x % PAGE_ID_ALPHABET.length]).join(\"\");\n}\n\nexport function isPageType(value: unknown): value is PageType {\n return typeof value === \"string\" && (PAGE_TYPES as readonly string[]).includes(value);\n}\n\nexport type PackedBody = { body: string; bytes: number; count: number };\n\n/**\n * Splits events into `POST /e` bodies of at most `MAX_BODY_BYTES` UTF-8 bytes\n * (wrapper included) and `maxBatchEvents` events. With `leaving` (pagehide)\n * only the newest bodies that fit the shared keepalive quota are kept.\n */\nexport function packEvents(projectKey: string, events: ClientEvent[], leaving = false): PackedBody[] {\n const wrapper = byteLength(JSON.stringify({ k: projectKey, events: [] }));\n let bodies: PackedBody[] = [];\n let batch: ClientEvent[] = [];\n let size = wrapper;\n const close = () => {\n if (batch.length > 0) bodies.push({ body: JSON.stringify({ k: projectKey, events: batch }), bytes: size, count: batch.length });\n batch = [];\n size = wrapper;\n };\n for (const event of events) {\n const own = byteLength(JSON.stringify(event));\n if (wrapper + own > MAX_BODY_BYTES) continue; // a single event that can never fit\n // +1 for the comma that joins it to the previous event.\n if (batch.length >= LIMITS.maxBatchEvents || size + own + (batch.length > 0 ? 1 : 0) > MAX_BODY_BYTES) close();\n size += own + (batch.length > 0 ? 1 : 0);\n batch.push(event);\n }\n close();\n if (leaving) {\n let total = 0;\n let keep = bodies.length;\n while (keep > 0 && total + bodies[keep - 1].bytes <= KEEPALIVE_BUDGET_BYTES) {\n total += bodies[keep - 1].bytes;\n keep--;\n }\n bodies = bodies.slice(keep);\n }\n return bodies;\n}\n\n/**\n * In-memory event tracker. It never throws into the host page and touches no\n * cookie or Web Storage, except the `bs_vid_<projectKey>` client id cookie, which it keeps\n * only while Bitsnap Consent grants analytics. On the server it returns a no-op.\n */\nexport function createTracker(options: TrackerOptions): Tracker {\n try {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return noopTracker;\n return build(options, window);\n } catch {\n return noopTracker;\n }\n}\n\nfunction build(options: TrackerOptions, win: Window & typeof globalThis): Tracker {\n const projectKey = normalizeProjectKey(options.projectKey ?? \"\");\n const debug = !!options.debug;\n const warn = (...args: unknown[]) => {\n if (debug) console.warn(\"[bitsnap analytics]\", ...args);\n };\n if (!projectKey) {\n warn(\"invalid projectKey, tracking is off\");\n return noopTracker;\n }\n const key: string = projectKey;\n\n const endpointUrl = (endpoint: string | undefined) => `${(endpoint || DEFAULT_ENDPOINT).replace(/\\/+$/, \"\")}/e`;\n let url = endpointUrl(options.endpoint);\n const source = options.source ?? \"sdk_react\";\n const channel = options.channel ?? \"embed\";\n const sdk = `bitsnap-react@${SDK_VERSION}`;\n const pageId = newPageId();\n const landing = parseUrl(win.location.href);\n let env: Env = options.env ?? \"live\";\n if (!options.env) {\n try {\n if (new URLSearchParams(win.location.search).has(\"test\")) env = \"test\";\n } catch {}\n }\n const refHost = referrerHost(document.referrer);\n\n let enabled = options.enabled !== false;\n let pageType: PageType | null = null;\n let pageViews = 0;\n let queue: ClientEvent[] = [];\n let timer: ReturnType<typeof setTimeout> | null = null;\n const listeners = new Set<(event: ClientEvent) => void>();\n if (options.onEvent) listeners.add(options.onEvent);\n /** Events the listeners have not seen yet because consent was still loading. */\n let held: ClientEvent[] = [];\n\n // -- consent: respect a rejection, wait for the stored choice to load -----\n\n let attached: ConsentLike | undefined;\n let consentReady = true;\n\n function attachConsent() {\n const api = consentApi(win);\n if (!api || api === attached) return;\n attached = api;\n consentReady = !api.ready;\n api.ready?.then(\n () => {\n if (attached !== api) return;\n consentReady = true;\n afterConsentChange();\n },\n () => {\n if (attached === api) consentReady = true;\n },\n );\n }\n\n function consentDenied(): boolean {\n attachConsent();\n try {\n if (!attached) return false;\n const state = attached.get();\n return (!!attached.denied && attached.denied(\"analytics\")) || (!!state && state.c.analytics === false);\n } catch {\n return false;\n }\n }\n\n function notify(event: ClientEvent) {\n listeners.forEach((fn) => {\n try {\n fn(event);\n } catch {}\n });\n }\n\n /**\n * Keeps the `bs_vid_<projectKey>` cookie in line with the consent: set while analytics is granted, deleted once\n * it is not. Before the stored choice has loaded `get()` is empty, so nothing is deleted then.\n * Without Bitsnap Consent on the page the tracker is cookieless.\n */\n function syncVisitorCookie(final: boolean) {\n try {\n attachConsent();\n if (!attached) return;\n // A banner of another project, or bitsnap's own on bitsnap.pl, neither grants nor withdraws this id.\n if (!consentBelongsTo(win, key)) return;\n if (analyticsGranted(win, key)) {\n if (active() && readVisitorCookie(win.document, key) === null) writeVisitorCookie(win, key, newVisitorId());\n } else if (final) {\n deleteVisitorCookie(win, key);\n }\n } catch {}\n }\n\n function afterConsentChange() {\n syncVisitorCookie(true);\n if (consentDenied()) {\n queue = [];\n held = [];\n clearTimer();\n } else {\n if (consentReady && held.length > 0) {\n const release = held;\n held = [];\n release.forEach(notify);\n }\n if (queue.length > 0) flush();\n }\n }\n\n // -- state ----------------------------------------------------------------\n\n function active(): boolean {\n if (!enabled) return false;\n const nav = win.navigator;\n if (nav && ((nav as { globalPrivacyControl?: boolean }).globalPrivacyControl === true || nav.webdriver === true)) {\n return false;\n }\n return !consentDenied();\n }\n\n function clearTimer() {\n if (timer !== null) clearTimeout(timer);\n timer = null;\n }\n\n function schedule() {\n if (timer !== null) return;\n timer = setTimeout(() => {\n timer = null;\n flush();\n }, FLUSH_INTERVAL_MS);\n (timer as { unref?: () => void }).unref?.();\n }\n\n // -- sending --------------------------------------------------------------\n\n function send(body: string) {\n // fetch keepalive first (no size cap below the shared quota); sendBeacon only as a fallback.\n try {\n if (typeof fetch === \"function\") {\n fetch(url, {\n method: \"POST\",\n body,\n keepalive: true,\n credentials: \"omit\",\n headers: { \"Content-Type\": \"text/plain\" },\n }).catch(() => {});\n return;\n }\n } catch {}\n try {\n const nav = win.navigator;\n if (nav && typeof nav.sendBeacon === \"function\") {\n nav.sendBeacon(url, new Blob([body], { type: \"text/plain\" }));\n }\n } catch {}\n }\n\n function flush(leaving = false) {\n try {\n clearTimer();\n if (queue.length === 0) return;\n if (!active()) {\n queue = [];\n return;\n }\n // Hold events until Bitsnap Consent has loaded the stored choice.\n if (!consentReady) return;\n // The client id is added on the way out, so events held for the stored choice carry it too.\n syncVisitorCookie(consentReady);\n const clientId = readVisitorId(win, key);\n const pending = clientId ? queue.map((event) => ({ ...event, client_id: clientId })) : queue;\n queue = [];\n packEvents(key, pending, leaving).forEach((entry) => send(entry.body));\n } catch {}\n }\n\n // -- building -------------------------------------------------------------\n\n function emit(name: string, props: unknown, extra: TrackExtra | undefined) {\n if (!active()) return;\n const cleaned = sanitizeProps(name, props);\n if (!cleaned.ok) {\n warn(\"dropped\", name, cleaned.reason);\n return;\n }\n const here = parseUrl(win.location.href);\n const event: Record<string, unknown> = {\n event_id: extra?.event_id && EVENT_ID_RE.test(extra.event_id) ? extra.event_id : uuidv7(),\n event: name,\n ts: Date.now(),\n schema_version: SCHEMA_VERSION,\n env,\n source,\n channel,\n sdk,\n page_id: pageId,\n page_type: extra?.page_type !== undefined ? extra.page_type : pageType,\n host: here?.host ?? null,\n path: extra?.path ? sanitizePath(extra.path.split(/[?#]/)[0]) : (here?.path ?? null),\n referrer_host: refHost,\n utm_source: landing?.utm_source ?? null,\n utm_medium: landing?.utm_medium ?? null,\n utm_campaign: landing?.utm_campaign ?? null,\n utm_content: landing?.utm_content ?? null,\n utm_term: landing?.utm_term ?? null,\n ref_code: landing?.ref_code ?? null,\n product_id: extra?.product_id ?? null,\n variant_id: extra?.variant_id ?? null,\n order_ref: extra?.order_ref ?? null,\n props: cleaned.props,\n };\n if (extra?.event_id && !EVENT_ID_RE.test(extra.event_id)) warn(\"ignored invalid event_id\", name);\n if (source === \"dashboard\" && options.visitorId) event.visitor_id = options.visitorId;\n\n const verdict = validateEnvelope(event);\n if (!verdict.ok) {\n warn(\"dropped\", name, verdict.reason);\n return;\n }\n const valid = event as unknown as ClientEvent;\n // Listeners (the merchant's own tools) only see events once consent is known and not denied.\n if (consentReady) notify(valid);\n else held.push(valid);\n queue.push(valid);\n if (queue.length >= FLUSH_AT) flush();\n else schedule();\n }\n\n // -- page lifecycle -------------------------------------------------------\n\n const onHide = () => flush(true);\n const onVisibility = () => {\n if (document.visibilityState === \"hidden\") flush(true);\n };\n const onConsent = () => afterConsentChange();\n win.addEventListener(\"pagehide\", onHide);\n document.addEventListener(\"visibilitychange\", onVisibility);\n win.addEventListener(\"bitsnap:consent\", onConsent);\n win.addEventListener(\"bitsnap:consent:ready\", onConsent);\n attachConsent();\n syncVisitorCookie(consentReady);\n\n return {\n track(event, props, extra) {\n try {\n emit(event, props, extra);\n } catch {}\n },\n page(type, extra) {\n try {\n if (type !== undefined) pageType = type;\n emit(\"page_view\", { landing: pageViews++ === 0 }, extra);\n } catch {}\n },\n clientId(projectKey) {\n try {\n if (projectKey !== undefined && normalizeProjectKey(projectKey) !== key) return null;\n return active() ? readVisitorId(win, key) : null;\n } catch {\n return null;\n }\n },\n flush: () => flush(),\n setEnabled(value) {\n enabled = !!value;\n if (!enabled) {\n queue = [];\n held = [];\n clearTimer();\n }\n },\n configure(patch) {\n try {\n if (patch.env === \"live\" || patch.env === \"test\") env = patch.env;\n if (typeof patch.endpoint === \"string\" && patch.endpoint) url = endpointUrl(patch.endpoint);\n } catch {}\n },\n onEvent(fn) {\n listeners.add(fn);\n return () => void listeners.delete(fn);\n },\n destroy() {\n queue = [];\n held = [];\n clearTimer();\n listeners.clear();\n win.removeEventListener(\"pagehide\", onHide);\n document.removeEventListener(\"visibilitychange\", onVisibility);\n win.removeEventListener(\"bitsnap:consent\", onConsent);\n win.removeEventListener(\"bitsnap:consent:ready\", onConsent);\n },\n };\n}\n\n// -- singleton ----------------------------------------------------------------\n\nlet instance: Tracker | undefined;\nlet instanceKey: string | null = null;\n\n/**\n * Creates the page's tracker on the first call and returns that same tracker\n * afterwards. A later call with another `projectKey` is ignored (warns in\n * debug mode); a later call with `env`, `endpoint` or `enabled` updates the\n * running tracker. A malformed key is not remembered, so a later valid call still works.\n */\nexport function initTracker(options: TrackerOptions): Tracker {\n if (!instance) {\n const created = createTracker(options);\n if (created === noopTracker) return created;\n instance = created;\n instanceKey = normalizeProjectKey(options.projectKey ?? \"\");\n return created;\n }\n try {\n const key = normalizeProjectKey(options.projectKey ?? \"\");\n if (key !== instanceKey && options.debug) {\n console.warn(\"[bitsnap analytics]\", \"tracker already started for another projectKey, ignoring\", options.projectKey);\n }\n if (key === instanceKey) {\n if (options.env || options.endpoint) instance.configure({ env: options.env, endpoint: options.endpoint });\n if (options.enabled != null) instance.setEnabled(options.enabled);\n }\n } catch {}\n return instance;\n}\n\n/** The tracker made by `initTracker`, if any. */\nexport function getTracker(): Tracker | undefined {\n return instance;\n}\n\n/** Destroys the singleton so that `initTracker` can build a fresh one (tests, hot reload). */\nexport function resetTracker() {\n if (typeof window !== \"undefined\") resetAutoPageViews(window);\n instance?.destroy();\n instance = undefined;\n instanceKey = null;\n}\n\n/**\n * `X-Bitsnap-Visitor` for a request that creates a checkout or payment link:\n * the client id of `projectKey` (default: the running tracker's project), only\n * while tracking is on and Bitsnap Consent grants analytics. Empty otherwise.\n */\nexport function visitorHeaders(projectKey?: string): Record<string, string> {\n try {\n if (typeof window === \"undefined\") return {};\n const tracker = instance;\n let id: string | null = null;\n if (tracker) {\n id = tracker.clientId(projectKey);\n } else {\n // No tracker of this bundle (e.g. only the analytics.js script runs): read the cookie it set.\n const key = projectKey ? normalizeProjectKey(projectKey) : null;\n id = key ? readVisitorId(window, key) : null;\n }\n return id ? { [VISITOR_HEADER]: id } : {};\n } catch {\n return {};\n }\n}\n","import { createContext, createElement, useContext, useMemo, useRef, type ReactNode } from \"react\";\nimport { useIsomorphicLayoutEffect } from \"../lib/isomorphic-layout-effect\";\nimport { initTracker, noopTracker, startAutoPageViews, type Tracker, type TrackerOptions } from \"./core\";\nimport type { ClientEvent } from \"./contract\";\n\nexport type AnalyticsApi = Pick<Tracker, \"track\" | \"page\">;\n\nconst noop: AnalyticsApi = { track: noopTracker.track, page: noopTracker.page };\n\nconst AnalyticsContext = createContext<AnalyticsApi>(noop);\n\nexport type BitsnapAnalyticsProviderProps = {\n /** Public project key (the `projectID` the rest of the SDK uses). */\n projectKey: string;\n env?: TrackerOptions[\"env\"];\n /** `false` turns tracking off. */\n enabled?: boolean;\n endpoint?: string;\n /** Called with every event before it is sent, e.g. to forward it to the merchant's own tools. */\n onEvent?: (event: ClientEvent) => void;\n /**\n * Sends `page_view` on mount and on every path change (`pushState`, `replaceState`, Back/Forward).\n * Default `true`; set `false` to call `page()` yourself.\n */\n autoPageViews?: boolean;\n children?: ReactNode;\n};\n\n/**\n * Starts the page's tracker and hands `track` and `page` to `useAnalytics()`.\n * The tracker is a per-page singleton: the first valid `projectKey` wins, but\n * `env`, `endpoint` and `enabled` of any provider update the running tracker.\n * It sends a `page_view` for the current page and every path change, once per\n * path however many providers, instrumented components or `analytics.js`\n * embeds the page has.\n * Nothing is tracked on the server. The only thing stored on the visitor's\n * device is the `bs_vid_<projectKey>` cookie, and only while Bitsnap Consent grants analytics.\n */\nexport function BitsnapAnalyticsProvider({\n projectKey,\n env,\n enabled,\n endpoint,\n onEvent,\n autoPageViews,\n children,\n}: BitsnapAnalyticsProviderProps) {\n const tracker = useMemo(\n () => initTracker({ projectKey, env, endpoint, enabled }),\n // The tracker is a per-page singleton; `initTracker` applies env/endpoint/enabled changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [projectKey, env, endpoint],\n );\n const onEventRef = useRef(onEvent);\n onEventRef.current = onEvent;\n\n // Before the passive effects of the children, whose first events must already respect it.\n useIsomorphicLayoutEffect(() => {\n tracker.setEnabled(enabled !== false);\n }, [tracker, enabled]);\n\n // Also before the children's events, so the page view comes first. The page type is cleared:\n // an automatic view must not inherit the type of an earlier manual `page(type)`.\n useIsomorphicLayoutEffect(() => {\n if (autoPageViews === false || enabled === false || tracker === noopTracker) return;\n return startAutoPageViews(() => tracker.page(null));\n }, [tracker, autoPageViews, enabled]);\n\n // Layout effects run before the passive effects of the children, whose\n // first events (list viewed, cart opened) would otherwise be missed.\n useIsomorphicLayoutEffect(() => tracker.onEvent((event) => onEventRef.current?.(event)), [tracker]);\n\n const api = useMemo<AnalyticsApi>(\n () => ({ track: tracker.track.bind(tracker), page: tracker.page.bind(tracker) }),\n [tracker],\n );\n return createElement(AnalyticsContext.Provider, { value: api }, children);\n}\n\n/** `track` and `page`; no-ops outside a `<BitsnapAnalyticsProvider>`. */\nexport function useAnalytics(): AnalyticsApi {\n return useContext(AnalyticsContext);\n}\n","import { createContext, createElement, useContext, useEffect, useLayoutEffect, useMemo, useRef, type ReactNode } from \"react\";\nimport type { ClientEvent, Env, EventProps, PageType } from \"./contract\";\nimport { getTracker, initTracker, noopTracker, startAutoPageViews, type BrowserEventName, type TrackExtra } from \"./core\";\nimport { useAnalytics, type AnalyticsApi } from \"./react\";\n\n/**\n * The `analytics` prop of every instrumented bitsnap-react component.\n * `true` (the default) tracks, `false` opts out, an object tracks and can\n * forward each event to the merchant's own tools.\n */\nexport type AnalyticsOption =\n | boolean\n | {\n /** Called with every event this component emits, after Bitsnap Consent allows analytics. */\n onEvent?: (event: ClientEvent) => void;\n /** `test` events are stored but never reach the merchant's stats. */\n env?: Env;\n };\n\n/** What the components call. It never throws and does nothing on the server. */\nexport interface Instrument {\n track<E extends BrowserEventName>(event: E, props: EventProps<E>, extra?: TrackExtra): void;\n}\n\nexport const noopInstrument: Instrument = { track() {} };\n\ntype Latest = {\n projectKey: string | null | undefined;\n analytics: AnalyticsOption | undefined;\n pageType: PageType | undefined;\n provided: AnalyticsApi | null;\n};\n\n/** The instrument whose `track` call is running; lets `onEvent` listeners tell their own events apart. */\nlet emitting: symbol | null = null;\n\nfunction createInstrument(read: () => Latest) {\n const id = Symbol(\"bitsnap-instrument\");\n\n function target(): Pick<AnalyticsApi, \"track\"> | null {\n if (typeof window === \"undefined\") return null;\n const { projectKey, analytics, provided } = read();\n if (analytics === false) return null;\n // A <BitsnapAnalyticsProvider> owns the tracker.\n if (provided) return provided;\n if (!projectKey) return null;\n return initTracker({\n projectKey,\n source: \"sdk_react\",\n channel: \"embed\",\n env: typeof analytics === \"object\" ? analytics.env : undefined,\n });\n }\n\n const instrument: Instrument = {\n track(event, props, extra) {\n try {\n const tracker = target();\n if (!tracker) return;\n const { analytics, pageType } = read();\n const withPage = pageType && extra?.page_type === undefined ? { ...extra, page_type: pageType } : extra;\n emitting = typeof analytics === \"object\" && analytics.onEvent ? id : null;\n tracker.track(event, props, withPage);\n } catch {\n // Analytics never breaks the host page.\n } finally {\n emitting = null;\n }\n },\n };\n\n /** Starts the tracker on mount, wires `onEvent` and, without a provider, the automatic page views. Returns the cleanup. */\n function attach(): () => void {\n try {\n if (!target()) return () => {};\n const tracker = getTracker();\n if (!tracker) return () => {};\n // A <BitsnapAnalyticsProvider> decides on the page views itself (`autoPageViews`).\n const stopPageViews = read().provided ? () => {} : startAutoPageViews(() => tracker.page(read().pageType ?? null));\n const stopListening = tracker.onEvent((event) => {\n if (emitting !== id) return;\n try {\n const { analytics } = read();\n if (typeof analytics === \"object\") analytics.onEvent?.(event);\n } catch {}\n });\n return () => {\n stopPageViews();\n stopListening();\n };\n } catch {\n return () => {};\n }\n }\n\n return { instrument, attach };\n}\n\nconst InstrumentContext = createContext<Instrument | null>(null);\n\n/** Hands the instrument of a top-level component to the parts below it. */\nexport function InstrumentProvider({ value, children }: { value: Instrument; children?: ReactNode }) {\n return createElement(InstrumentContext.Provider, { value }, children);\n}\n\n/** The instrument of the closest instrumented ancestor, or a no-op. */\nexport function useInstrumentContext(): Instrument {\n return useContext(InstrumentContext) ?? noopInstrument;\n}\n\n/**\n * The instrument of a top-level component. `projectKey` is the public\n * project id the component already has. When `analytics` is not given and an\n * ancestor is instrumented, the ancestor's instrument is reused.\n */\nexport function useInstrument(\n projectKey: string | null | undefined,\n analytics?: AnalyticsOption,\n pageType?: PageType,\n): Instrument {\n const parent = useContext(InstrumentContext);\n const api = useAnalytics();\n const provided = api.track === noopTracker.track ? null : api;\n const latest = useRef<Latest>({ projectKey, analytics, pageType, provided });\n latest.current = { projectKey, analytics, pageType, provided };\n\n const own = useMemo(() => createInstrument(() => latest.current), []);\n const inherit = analytics === undefined && parent !== null;\n const hasListener = typeof analytics === \"object\" && !!analytics.onEvent;\n\n // A layout effect runs before the passive effects of the children, whose\n // first events (list viewed, cart opened) `onEvent` must not miss.\n useLayoutEffect(() => {\n if (inherit) return;\n return own.attach();\n }, [own, inherit, hasListener, projectKey]);\n\n return inherit ? parent : own.instrument;\n}\n\n// -- cart sink ---------------------------------------------------------------\n\nlet cartInstrument: Instrument = noopInstrument;\n\n/**\n * The instrument used for cart changes made outside of a component (the\n * `Bitsnap.addProductToCart` helper). `<BitsnapCheckout>` registers its own.\n */\nexport function setCartInstrument(instrument: Instrument | null) {\n cartInstrument = instrument ?? noopInstrument;\n}\n\nlet cartMuted = 0;\n\nexport function getCartInstrument(): Instrument {\n return cartMuted > 0 ? noopInstrument : cartInstrument;\n}\n\n/**\n * Runs `fn` with the cart sink muted, so a cart change made inside it (a custom\n * `onAddToCart` calling `Bitsnap.addProductToCart`) is not reported a second\n * time by the caller that reports it itself. Await the cart call inside `fn`.\n */\nexport async function withCartAnalyticsMuted<T>(fn: () => T | Promise<T>): Promise<T> {\n cartMuted++;\n try {\n return await fn();\n } finally {\n cartMuted--;\n }\n}\n\n/** Registers the instrument as the cart sink while the calling component is mounted. */\nexport function useCartInstrument(instrument: Instrument) {\n useEffect(() => {\n setCartInstrument(instrument);\n return () => {\n if (cartInstrument === instrument) setCartInstrument(null);\n };\n }, [instrument]);\n}\n\n// -- shared helpers ----------------------------------------------------------\n\n/** Score (0..100) → the contract's bucket. */\nexport function scoreBucket(percent: number): \"0-24\" | \"25-49\" | \"50-74\" | \"75-99\" | \"100\" {\n const value = Number.isFinite(percent) ? Math.max(0, Math.min(100, percent)) : 0;\n if (value >= 100) return \"100\";\n if (value >= 75) return \"75-99\";\n if (value >= 50) return \"50-74\";\n if (value >= 25) return \"25-49\";\n return \"0-24\";\n}\n\n/** Milestones (25/50/75/100) reached by `percent` that are not in `seen` yet. Adds them to `seen`. */\nexport function newMilestones(percent: number, seen: Set<number>): number[] {\n const reached: number[] = [];\n for (const milestone of [25, 50, 75, 100]) {\n if (percent >= milestone && !seen.has(milestone)) {\n seen.add(milestone);\n reached.push(milestone);\n }\n }\n return reached;\n}\n"],"mappings":"6GAYA,IAAMA,GAAW,OAAO,IAAI,mBAAmB,EAE/C,SAASC,GAASC,EAAuB,CACvC,IAAMC,EAASD,EACf,OAAQC,EAAOH,EAAQ,IAAM,CAAE,KAAM,KAAM,SAAU,IAAI,IAAO,SAAU,EAAM,CAClF,CAGA,SAASI,GAAgBF,EAAaG,EAAsB,CAC1D,IAAMC,EAAQ,IAAM,CAClB,GAAI,CACFD,EAAS,CACX,MAAQ,CAAC,CACX,EACA,QAAWE,IAAQ,CAAC,YAAa,cAAc,EAAY,CACzD,IAAMC,EAAWN,EAAI,QAAQK,CAAI,EACjCL,EAAI,QAAQK,CAAI,EAAI,YAA4BE,EAAwC,CACtF,IAAMC,EAASF,EAAS,MAAM,KAAMC,CAAI,EACxC,OAAAH,EAAM,EACCI,CACT,CACF,CACAR,EAAI,iBAAiB,WAAYI,CAAK,CACxC,CAQO,SAASK,EAAmBC,EAAkBV,EAAc,OAA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I,GAAG,EAClCJ,GAAWI,GAAa,CAACF,EAAK,IAAIE,CAAS,IAC7CF,EAAK,IAAIE,CAAS,EAClBD,EAAQ,KAAKC,CAAS,GAG1B,OAAOD,CACT","names":["REGISTRY","registry","win","holder","watchNavigation","onChange","check","name","original","args","result","startAutoPageViews","send","reg","starter","path","resetAutoPageViews","SDK_VERSION","randomBytes","n","bytes","c","i","VISITOR_HEADER","MAX_AGE_SECONDS","VISITOR_ID_RE","consentApi","win","readCookie","doc","name","part","index","isBitsnapHost","hostname","host","consentBelongsTo","projectKey","api","onBitsnap","analyticsGranted","newVisitorId","binary","randomBytes","byte","rawVisitorCookie","clientIdCookieName","readVisitorCookie","value","writeVisitorCookie","id","base","domain","domainCandidates","deleteVisitorCookie","readVisitorId","nav","DEFAULT_ENDPOINT","FLUSH_INTERVAL_MS","FLUSH_AT","MAX_BODY_BYTES","KEEPALIVE_BUDGET_BYTES","EVENT_ID_RE","byteLength","text","noopTracker","uuidv7","now","b","randomBytes","t","i","hex","x","PAGE_ID_ALPHABET","newPageId","packEvents","projectKey","events","leaving","wrapper","byteLength","bodies","batch","size","close","event","own","MAX_BODY_BYTES","LIMITS","total","keep","KEEPALIVE_BUDGET_BYTES","createTracker","options","noopTracker","build","win","normalizeProjectKey","debug","warn","args","key","endpointUrl","endpoint","DEFAULT_ENDPOINT","url","source","channel","sdk","SDK_VERSION","pageId","newPageId","landing","parseUrl","env","refHost","referrerHost","enabled","pageType","pageViews","queue","timer","listeners","held","attached","consentReady","attachConsent","api","consentApi","afterConsentChange","consentDenied","state","notify","fn","syncVisitorCookie","final","consentBelongsTo","analyticsGranted","active","readVisitorCookie","writeVisitorCookie","newVisitorId","deleteVisitorCookie","clearTimer","release","flush","nav","schedule","FLUSH_INTERVAL_MS","send","body","clientId","readVisitorId","pending","entry","emit","name","props","extra","cleaned","sanitizeProps","here","EVENT_ID_RE","uuidv7","sanitizePath","verdict","validateEnvelope","valid","FLUSH_AT","onHide","onVisibility","onConsent","type","value","patch","instance","instanceKey","initTracker","created","getTracker","resetTracker","resetAutoPageViews","visitorHeaders","tracker","id","VISITOR_HEADER","createContext","createElement","useContext","useMemo","useRef","noop","noopTracker","AnalyticsContext","createContext","BitsnapAnalyticsProvider","projectKey","env","enabled","endpoint","onEvent","autoPageViews","children","tracker","useMemo","initTracker","onEventRef","useRef","useIsomorphicLayoutEffect","startAutoPageViews","event","api","createElement","useAnalytics","useContext","createContext","createElement","useContext","useEffect","useLayoutEffect","useMemo","useRef","noopInstrument","emitting","createInstrument","read","id","target","projectKey","analytics","provided","initTracker","instrument","event","props","extra","tracker","pageType","withPage","attach","getTracker","stopPageViews","startAutoPageViews","stopListening","InstrumentContext","createContext","InstrumentProvider","value","children","createElement","useInstrumentContext","useContext","useInstrument","parent","api","useAnalytics","noopTracker","latest","useRef","own","useMemo","inherit","hasListener","useLayoutEffect","cartInstrument","setCartInstrument","cartMuted","getCartInstrument","withCartAnalyticsMuted","fn","useCartInstrument","useEffect","scoreBucket","percent","newMilestones","seen","reached","milestone"]}
|
|
1
|
+
{"version":3,"sources":["../src/analytics/pageviews.ts","../src/version.ts","../src/analytics/random.ts","../src/analytics/visitor.ts","../src/analytics/core.ts","../src/analytics/react.tsx","../src/analytics/instrument.ts"],"sourcesContent":["/**\n * Page-wide state of the automatic page views. It lives on `window`, so the\n * npm package, a second copy of it and the `analytics.js` script agree on who\n * reports a path and the history is patched once.\n */\ntype Registry = {\n /** Last path some starter reported. */\n path: string | null;\n starters: Set<() => void>;\n watching: boolean;\n};\n\nconst REGISTRY = Symbol.for(\"bitsnap.pageViews\");\n\nfunction registry(win: Window): Registry {\n const holder = win as unknown as Record<symbol, Registry | undefined>;\n return (holder[REGISTRY] ??= { path: null, starters: new Set(), watching: false });\n}\n\n/** Calls `onChange` when the path changes through `history.pushState`/`replaceState` or Back/Forward. */\nfunction watchNavigation(win: Window, onChange: () => void) {\n const check = () => {\n try {\n onChange();\n } catch {}\n };\n for (const name of [\"pushState\", \"replaceState\"] as const) {\n const original = win.history[name];\n win.history[name] = function (this: History, ...args: Parameters<History[typeof name]>) {\n const result = original.apply(this, args);\n check();\n return result;\n };\n }\n win.addEventListener(\"popstate\", check);\n}\n\n/**\n * Calls `send` for the current path and again on every path change, unless\n * another starter on the page already reported that path: the page gets one\n * `page_view` per path change however many providers, components and embeds\n * start it. Returns the function that stops this starter.\n */\nexport function startAutoPageViews(send: () => void, win: Window = window): () => void {\n try {\n const reg = registry(win);\n const starter = () => send();\n if (!reg.watching) {\n reg.watching = true;\n watchNavigation(win, () => {\n const path = win.location.pathname;\n // Nobody listening: leave the path unreported so the next starter sends it.\n if (path === reg.path || reg.starters.size === 0) return;\n reg.path = path;\n reg.starters.values().next().value?.();\n });\n }\n reg.starters.add(starter);\n const path = win.location.pathname;\n if (path !== reg.path) {\n reg.path = path;\n starter();\n }\n return () => void reg.starters.delete(starter);\n } catch {\n return () => {};\n }\n}\n\n/** Forgets the reported path and the starters (tests, hot reload). The history patch stays. */\nexport function resetAutoPageViews(win: Window = window) {\n const reg = registry(win);\n reg.path = null;\n reg.starters.clear();\n}\n","// Generated by scripts/write-version.mjs from package.json. Do not edit.\nexport const SDK_VERSION = \"1.20.0\";\n","export function randomBytes(n: number): Uint8Array {\n const bytes = new Uint8Array(n);\n const c = typeof crypto !== \"undefined\" ? crypto : undefined;\n if (c && typeof c.getRandomValues === \"function\") c.getRandomValues(bytes);\n else for (let i = 0; i < n; i++) bytes[i] = Math.floor(Math.random() * 256);\n return bytes;\n}\n","import { domainCandidates } from \"../consent/core/cookie\";\nimport { clientIdCookieName } from \"./contract\";\nimport { randomBytes } from \"./random\";\n\n/** The part of `window.BitsnapConsent` (`bitsnap-react/consent`) the tracker reads. */\nexport type ConsentLike = {\n /** Absent on a consent script older than 1.9.0, which never counts as the project's banner. */\n scope?: \"global\" | \"project\";\n projectKey?: string | null;\n get(): { c: { analytics?: boolean } } | null;\n /** Also true for a refusal made on an older banner version, which `get()` no longer returns. */\n denied?(category: \"analytics\"): boolean;\n ready?: Promise<unknown>;\n};\n\n/** Sent to the Bitsnap server on the requests that create a checkout or payment link. */\nexport const VISITOR_HEADER = \"X-Bitsnap-Visitor\";\n// 390 days, under the 13 months CNIL allows. Set once, never extended.\nconst MAX_AGE_SECONDS = 390 * 24 * 60 * 60;\nconst VISITOR_ID_RE = /^[A-Za-z0-9_-]{22}$/;\n\nexport function consentApi(win: Window): ConsentLike | undefined {\n return (win as unknown as { BitsnapConsent?: ConsentLike }).BitsnapConsent;\n}\n\nfunction readCookie(doc: Document, name: string): string | null {\n for (const part of doc.cookie.split(\";\")) {\n const index = part.indexOf(\"=\");\n if (index !== -1 && part.slice(0, index).trim() === name) return part.slice(index + 1).trim();\n }\n return null;\n}\n\n/** bitsnap.pl and its subdomains: many merchants share them, and the site-wide choice is bitsnap's own. */\nfunction isBitsnapHost(hostname: string): boolean {\n const host = hostname.toLowerCase();\n return host === \"bitsnap.pl\" || host.endsWith(\".bitsnap.pl\");\n}\n\n/**\n * Whether the page's consent banner speaks for `projectKey`: a project-scope banner of that\n * key, or a site-scope banner on a merchant's own site. On bitsnap.pl a site-scope choice is\n * bitsnap's own, so only a project-scope one counts.\n */\nexport function consentBelongsTo(win: Window, projectKey: string): boolean {\n try {\n const api = consentApi(win);\n if (!api) return false;\n if (api.scope === \"project\") return api.projectKey === projectKey;\n const onBitsnap = isBitsnapHost(win.location.hostname);\n if (api.scope === \"global\") return !onBitsnap;\n // A consent script from before the scope info: it cannot be told apart from another project's banner.\n return false;\n } catch {\n return false;\n }\n}\n\n/** `true` only while a banner that speaks for `projectKey` holds a valid choice that grants `analytics`. */\nexport function analyticsGranted(win: Window, projectKey: string): boolean {\n try {\n return consentApi(win)?.get()?.c.analytics === true && consentBelongsTo(win, projectKey);\n } catch {\n return false;\n }\n}\n\n/** 16 random bytes as 22 base64url characters. */\nexport function newVisitorId(): string {\n let binary = \"\";\n randomBytes(16).forEach((byte) => (binary += String.fromCharCode(byte)));\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** Value of the `bs_vid_<projectKey>` cookie, whatever it holds; `null` when it is absent. */\nfunction rawVisitorCookie(doc: Document, projectKey: string): string | null {\n try {\n return readCookie(doc, clientIdCookieName(projectKey));\n } catch {\n return null;\n }\n}\n\n/** The project's client id from its first-party cookie (`bs_vid_<projectKey>`), or `null` if absent or malformed. */\nexport function readVisitorCookie(doc: Document, projectKey: string): string | null {\n const value = rawVisitorCookie(doc, projectKey);\n return value !== null && VISITOR_ID_RE.test(value) ? value : null;\n}\n\n/**\n * Sets the cookie on the widest registrable domain the browser accepts\n * (shortest suffix with two labels first, so `shop.example.co.uk` skips the\n * refused `co.uk`), host-only where no domain sticks (localhost, IP hosts).\n */\nexport function writeVisitorCookie(win: Window, projectKey: string, id: string): void {\n try {\n const doc = win.document;\n const base =\n `${clientIdCookieName(projectKey)}=${id}; Max-Age=${MAX_AGE_SECONDS}; Path=/; SameSite=Lax` +\n (win.location.protocol === \"https:\" ? \"; Secure\" : \"\");\n for (const domain of domainCandidates(win.location.hostname).reverse()) {\n doc.cookie = `${base}; Domain=${domain}`;\n if (readVisitorCookie(doc, projectKey) === id) return;\n }\n doc.cookie = base;\n } catch {\n // cookies blocked (sandboxed frame)\n }\n}\n\n/** Expires the cookie on the host and on every parent domain it may have been set on. */\nexport function deleteVisitorCookie(win: Window, projectKey: string): void {\n try {\n const doc = win.document;\n // Present under any value: a malformed one must go too.\n if (rawVisitorCookie(doc, projectKey) === null) return;\n const base =\n `${clientIdCookieName(projectKey)}=; Max-Age=0; Path=/; SameSite=Lax` +\n (win.location.protocol === \"https:\" ? \"; Secure\" : \"\");\n doc.cookie = base;\n for (const domain of domainCandidates(win.location.hostname)) doc.cookie = `${base}; Domain=${domain}`;\n } catch {\n // best effort\n }\n}\n\n/**\n * The project's client id to send, or `null`: analytics consent is granted,\n * Global Privacy Control is off, the browser is not automated and the cookie exists.\n */\nexport function readVisitorId(win: Window, projectKey: string): string | null {\n try {\n const nav = win.navigator as { globalPrivacyControl?: boolean; webdriver?: boolean } | undefined;\n if (nav?.globalPrivacyControl === true || nav?.webdriver === true) return null;\n return analyticsGranted(win, projectKey) ? readVisitorCookie(win.document, projectKey) : null;\n } catch {\n return null;\n }\n}\n","import {\n LIMITS,\n PAGE_TYPES,\n SCHEMA_VERSION,\n normalizeProjectKey,\n parseUrl,\n referrerHost,\n sanitizeProps,\n sanitizePath,\n validateEnvelope,\n type AppEventName,\n type Channel,\n type ClientEvent,\n type Env,\n type EventProps,\n type PageType,\n type Source,\n type StorefrontEventName,\n} from \"./contract\";\nimport { SDK_VERSION } from \"../version\";\nimport { resetAutoPageViews } from \"./pageviews\";\nimport { randomBytes } from \"./random\";\nimport {\n analyticsGranted,\n consentApi,\n consentBelongsTo,\n deleteVisitorCookie,\n newVisitorId,\n readVisitorCookie,\n readVisitorId,\n VISITOR_HEADER,\n writeVisitorCookie,\n type ConsentLike,\n} from \"./visitor\";\n\nexport { startAutoPageViews } from \"./pageviews\";\n\n/** Events a browser may send. `consent_updated` is written by the consent log only. */\nexport type BrowserEventName = Exclude<StorefrontEventName, \"consent_updated\"> | AppEventName;\n\nexport type TrackerOptions = {\n /** Public project key (the hashed project id). `pk_` prefix is accepted. */\n projectKey: string;\n /** Defaults to `live`, or `test` when the page URL has the `?test=` test-mode parameter. */\n env?: Env;\n /** Collector origin. Default `https://collect.bitsnap.pl`. */\n endpoint?: string;\n /** `false` turns tracking off. Default `true`. */\n enabled?: boolean;\n /** Default `embed`. */\n channel?: Channel;\n /** Default `sdk_react`. */\n source?: Source;\n /** Only honoured by the collector for `source: \"dashboard\"` (hashed user id). */\n visitorId?: string;\n /** Receives every valid envelope before it is queued, e.g. to forward it to the merchant's own tools. */\n onEvent?: (event: ClientEvent) => void;\n /** `console.warn` dropped events. */\n debug?: boolean;\n};\n\n/** Envelope fields a call site may set per event. */\nexport type TrackExtra = {\n page_type?: PageType | null;\n product_id?: string | null;\n variant_id?: string | null;\n order_ref?: string | null;\n /** Route template for pages whose URL path is not the path to report (the dashboard). */\n path?: string;\n /**\n * Deterministic UUIDv7 for events another system reports too (e.g. hosted\n * `payment_returned`), so the collector dedupes them. An invalid value is\n * ignored and a fresh id is used.\n */\n event_id?: string;\n};\n\nexport interface Tracker {\n track<E extends BrowserEventName>(event: E, props: EventProps<E>, extra?: TrackExtra): void;\n /**\n * Sends `page_view` and makes `pageType` the page type of the following events\n * (`null` clears it, `undefined` keeps the current one).\n */\n page(pageType?: PageType | null, extra?: TrackExtra): void;\n /**\n * The visitor's `bs_vid_<projectKey>` client id, only while this tracker is on\n * (enabled, no Global Privacy Control, not automated, analytics not denied) and\n * Bitsnap Consent grants analytics. `projectKey` must match the tracker's, if given.\n */\n clientId(projectKey?: string): string | null;\n /** Sends the queue now. */\n flush(): void;\n setEnabled(enabled: boolean): void;\n /** Returns an unsubscribe function. */\n onEvent(fn: (event: ClientEvent) => void): () => void;\n /** Updates `env` and `endpoint` of a running tracker. Other options are fixed at creation. */\n configure(patch: { env?: Env; endpoint?: string }): void;\n /** Removes the page listeners and drops the queue. */\n destroy(): void;\n}\n\nexport const DEFAULT_ENDPOINT = \"https://collect.bitsnap.pl\";\n\nconst FLUSH_INTERVAL_MS = 5000;\nconst FLUSH_AT = 20;\n// Half the collector's 64 KB body limit, measured in UTF-8 bytes of the whole body.\nconst MAX_BODY_BYTES = 32 * 1024;\n// Browsers share ~64 KB of in-flight keepalive requests; stay under it on pagehide.\nconst KEEPALIVE_BUDGET_BYTES = 60 * 1024;\nconst EVENT_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nfunction byteLength(text: string): number {\n if (typeof TextEncoder === \"function\") return new TextEncoder().encode(text).length;\n return unescape(encodeURIComponent(text)).length;\n}\n\nexport const noopTracker: Tracker = {\n track() {},\n page() {},\n clientId: () => null,\n flush() {},\n setEnabled() {},\n onEvent: () => () => {},\n configure() {},\n destroy() {},\n};\n\n/** UUIDv7: 48-bit unix ms, version 7, variant 10, 74 random bits. */\nexport function uuidv7(now = Date.now()): string {\n const b = randomBytes(16);\n let t = now;\n for (let i = 5; i >= 0; i--) {\n b[i] = t % 256;\n t = Math.floor(t / 256);\n }\n b[6] = (b[6] & 0x0f) | 0x70;\n b[8] = (b[8] & 0x3f) | 0x80;\n const hex = Array.from(b, (x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nconst PAGE_ID_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\nfunction newPageId(): string {\n return Array.from(randomBytes(16), (x) => PAGE_ID_ALPHABET[x % PAGE_ID_ALPHABET.length]).join(\"\");\n}\n\nexport function isPageType(value: unknown): value is PageType {\n return typeof value === \"string\" && (PAGE_TYPES as readonly string[]).includes(value);\n}\n\nexport type PackedBody = { body: string; bytes: number; count: number };\n\n/**\n * Splits events into `POST /e` bodies of at most `MAX_BODY_BYTES` UTF-8 bytes\n * (wrapper included) and `maxBatchEvents` events. With `leaving` (pagehide)\n * only the newest bodies that fit the shared keepalive quota are kept.\n */\nexport function packEvents(projectKey: string, events: ClientEvent[], leaving = false): PackedBody[] {\n const wrapper = byteLength(JSON.stringify({ k: projectKey, events: [] }));\n let bodies: PackedBody[] = [];\n let batch: ClientEvent[] = [];\n let size = wrapper;\n const close = () => {\n if (batch.length > 0) bodies.push({ body: JSON.stringify({ k: projectKey, events: batch }), bytes: size, count: batch.length });\n batch = [];\n size = wrapper;\n };\n for (const event of events) {\n const own = byteLength(JSON.stringify(event));\n if (wrapper + own > MAX_BODY_BYTES) continue; // a single event that can never fit\n // +1 for the comma that joins it to the previous event.\n if (batch.length >= LIMITS.maxBatchEvents || size + own + (batch.length > 0 ? 1 : 0) > MAX_BODY_BYTES) close();\n size += own + (batch.length > 0 ? 1 : 0);\n batch.push(event);\n }\n close();\n if (leaving) {\n let total = 0;\n let keep = bodies.length;\n while (keep > 0 && total + bodies[keep - 1].bytes <= KEEPALIVE_BUDGET_BYTES) {\n total += bodies[keep - 1].bytes;\n keep--;\n }\n bodies = bodies.slice(keep);\n }\n return bodies;\n}\n\n/**\n * In-memory event tracker. It never throws into the host page and touches no\n * cookie or Web Storage, except the `bs_vid_<projectKey>` client id cookie, which it keeps\n * only while Bitsnap Consent grants analytics. On the server it returns a no-op.\n */\nexport function createTracker(options: TrackerOptions): Tracker {\n try {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return noopTracker;\n return build(options, window);\n } catch {\n return noopTracker;\n }\n}\n\nfunction build(options: TrackerOptions, win: Window & typeof globalThis): Tracker {\n const projectKey = normalizeProjectKey(options.projectKey ?? \"\");\n const debug = !!options.debug;\n const warn = (...args: unknown[]) => {\n if (debug) console.warn(\"[bitsnap analytics]\", ...args);\n };\n if (!projectKey) {\n warn(\"invalid projectKey, tracking is off\");\n return noopTracker;\n }\n const key: string = projectKey;\n\n const endpointUrl = (endpoint: string | undefined) => `${(endpoint || DEFAULT_ENDPOINT).replace(/\\/+$/, \"\")}/e`;\n let url = endpointUrl(options.endpoint);\n const source = options.source ?? \"sdk_react\";\n const channel = options.channel ?? \"embed\";\n const sdk = `bitsnap-react@${SDK_VERSION}`;\n const pageId = newPageId();\n const landing = parseUrl(win.location.href);\n let env: Env = options.env ?? \"live\";\n if (!options.env) {\n try {\n if (new URLSearchParams(win.location.search).has(\"test\")) env = \"test\";\n } catch {}\n }\n const refHost = referrerHost(document.referrer);\n\n let enabled = options.enabled !== false;\n let pageType: PageType | null = null;\n let pageViews = 0;\n let queue: ClientEvent[] = [];\n let timer: ReturnType<typeof setTimeout> | null = null;\n const listeners = new Set<(event: ClientEvent) => void>();\n if (options.onEvent) listeners.add(options.onEvent);\n /** Events the listeners have not seen yet because consent was still loading. */\n let held: ClientEvent[] = [];\n\n // -- consent: respect a rejection, wait for the stored choice to load -----\n\n let attached: ConsentLike | undefined;\n let consentReady = true;\n\n function attachConsent() {\n const api = consentApi(win);\n if (!api || api === attached) return;\n attached = api;\n consentReady = !api.ready;\n api.ready?.then(\n () => {\n if (attached !== api) return;\n consentReady = true;\n afterConsentChange();\n },\n () => {\n if (attached === api) consentReady = true;\n },\n );\n }\n\n function consentDenied(): boolean {\n attachConsent();\n try {\n if (!attached) return false;\n const state = attached.get();\n return (!!attached.denied && attached.denied(\"analytics\")) || (!!state && state.c.analytics === false);\n } catch {\n return false;\n }\n }\n\n function notify(event: ClientEvent) {\n listeners.forEach((fn) => {\n try {\n fn(event);\n } catch {}\n });\n }\n\n /**\n * Keeps the `bs_vid_<projectKey>` cookie in line with the consent: set while analytics is granted, deleted once\n * it is not. Before the stored choice has loaded `get()` is empty, so nothing is deleted then.\n * Without Bitsnap Consent on the page the tracker is cookieless.\n */\n function syncVisitorCookie(final: boolean) {\n try {\n attachConsent();\n if (!attached) return;\n // A banner of another project, or bitsnap's own on bitsnap.pl, neither grants nor withdraws this id.\n if (!consentBelongsTo(win, key)) return;\n if (analyticsGranted(win, key)) {\n if (active() && readVisitorCookie(win.document, key) === null) writeVisitorCookie(win, key, newVisitorId());\n } else if (final) {\n deleteVisitorCookie(win, key);\n }\n } catch {}\n }\n\n function afterConsentChange() {\n syncVisitorCookie(true);\n if (consentDenied()) {\n queue = [];\n held = [];\n clearTimer();\n } else {\n if (consentReady && held.length > 0) {\n const release = held;\n held = [];\n release.forEach(notify);\n }\n if (queue.length > 0) flush();\n }\n }\n\n // -- state ----------------------------------------------------------------\n\n function active(): boolean {\n if (!enabled) return false;\n const nav = win.navigator;\n if (nav && ((nav as { globalPrivacyControl?: boolean }).globalPrivacyControl === true || nav.webdriver === true)) {\n return false;\n }\n return !consentDenied();\n }\n\n function clearTimer() {\n if (timer !== null) clearTimeout(timer);\n timer = null;\n }\n\n function schedule() {\n if (timer !== null) return;\n timer = setTimeout(() => {\n timer = null;\n flush();\n }, FLUSH_INTERVAL_MS);\n (timer as { unref?: () => void }).unref?.();\n }\n\n // -- sending --------------------------------------------------------------\n\n function send(body: string) {\n // fetch keepalive first (no size cap below the shared quota); sendBeacon only as a fallback.\n try {\n if (typeof fetch === \"function\") {\n fetch(url, {\n method: \"POST\",\n body,\n keepalive: true,\n credentials: \"omit\",\n headers: { \"Content-Type\": \"text/plain\" },\n }).catch(() => {});\n return;\n }\n } catch {}\n try {\n const nav = win.navigator;\n if (nav && typeof nav.sendBeacon === \"function\") {\n nav.sendBeacon(url, new Blob([body], { type: \"text/plain\" }));\n }\n } catch {}\n }\n\n function flush(leaving = false) {\n try {\n clearTimer();\n if (queue.length === 0) return;\n if (!active()) {\n queue = [];\n return;\n }\n // Hold events until Bitsnap Consent has loaded the stored choice.\n if (!consentReady) return;\n // The client id is added on the way out, so events held for the stored choice carry it too.\n syncVisitorCookie(consentReady);\n const clientId = readVisitorId(win, key);\n const pending = clientId ? queue.map((event) => ({ ...event, client_id: clientId })) : queue;\n queue = [];\n packEvents(key, pending, leaving).forEach((entry) => send(entry.body));\n } catch {}\n }\n\n // -- building -------------------------------------------------------------\n\n function emit(name: string, props: unknown, extra: TrackExtra | undefined) {\n if (!active()) return;\n const cleaned = sanitizeProps(name, props);\n if (!cleaned.ok) {\n warn(\"dropped\", name, cleaned.reason);\n return;\n }\n const here = parseUrl(win.location.href);\n const event: Record<string, unknown> = {\n event_id: extra?.event_id && EVENT_ID_RE.test(extra.event_id) ? extra.event_id : uuidv7(),\n event: name,\n ts: Date.now(),\n schema_version: SCHEMA_VERSION,\n env,\n source,\n channel,\n sdk,\n page_id: pageId,\n page_type: extra?.page_type !== undefined ? extra.page_type : pageType,\n host: here?.host ?? null,\n path: extra?.path ? sanitizePath(extra.path.split(/[?#]/)[0]) : (here?.path ?? null),\n referrer_host: refHost,\n utm_source: landing?.utm_source ?? null,\n utm_medium: landing?.utm_medium ?? null,\n utm_campaign: landing?.utm_campaign ?? null,\n utm_content: landing?.utm_content ?? null,\n utm_term: landing?.utm_term ?? null,\n ref_code: landing?.ref_code ?? null,\n product_id: extra?.product_id ?? null,\n variant_id: extra?.variant_id ?? null,\n order_ref: extra?.order_ref ?? null,\n props: cleaned.props,\n };\n if (extra?.event_id && !EVENT_ID_RE.test(extra.event_id)) warn(\"ignored invalid event_id\", name);\n if (source === \"dashboard\" && options.visitorId) event.visitor_id = options.visitorId;\n\n const verdict = validateEnvelope(event);\n if (!verdict.ok) {\n warn(\"dropped\", name, verdict.reason);\n return;\n }\n const valid = event as unknown as ClientEvent;\n // Listeners (the merchant's own tools) only see events once consent is known and not denied.\n if (consentReady) notify(valid);\n else held.push(valid);\n queue.push(valid);\n if (queue.length >= FLUSH_AT) flush();\n else schedule();\n }\n\n // -- page lifecycle -------------------------------------------------------\n\n const onHide = () => flush(true);\n const onVisibility = () => {\n if (document.visibilityState === \"hidden\") flush(true);\n };\n const onConsent = () => afterConsentChange();\n win.addEventListener(\"pagehide\", onHide);\n document.addEventListener(\"visibilitychange\", onVisibility);\n win.addEventListener(\"bitsnap:consent\", onConsent);\n win.addEventListener(\"bitsnap:consent:ready\", onConsent);\n attachConsent();\n syncVisitorCookie(consentReady);\n\n return {\n track(event, props, extra) {\n try {\n emit(event, props, extra);\n } catch {}\n },\n page(type, extra) {\n try {\n if (type !== undefined) pageType = type;\n emit(\"page_view\", { landing: pageViews++ === 0 }, extra);\n } catch {}\n },\n clientId(projectKey) {\n try {\n if (projectKey !== undefined && normalizeProjectKey(projectKey) !== key) return null;\n return active() ? readVisitorId(win, key) : null;\n } catch {\n return null;\n }\n },\n flush: () => flush(),\n setEnabled(value) {\n enabled = !!value;\n if (!enabled) {\n queue = [];\n held = [];\n clearTimer();\n }\n },\n configure(patch) {\n try {\n if (patch.env === \"live\" || patch.env === \"test\") env = patch.env;\n if (typeof patch.endpoint === \"string\" && patch.endpoint) url = endpointUrl(patch.endpoint);\n } catch {}\n },\n onEvent(fn) {\n listeners.add(fn);\n return () => void listeners.delete(fn);\n },\n destroy() {\n queue = [];\n held = [];\n clearTimer();\n listeners.clear();\n win.removeEventListener(\"pagehide\", onHide);\n document.removeEventListener(\"visibilitychange\", onVisibility);\n win.removeEventListener(\"bitsnap:consent\", onConsent);\n win.removeEventListener(\"bitsnap:consent:ready\", onConsent);\n },\n };\n}\n\n// -- singleton ----------------------------------------------------------------\n\nlet instance: Tracker | undefined;\nlet instanceKey: string | null = null;\n\n/**\n * Creates the page's tracker on the first call and returns that same tracker\n * afterwards. A later call with another `projectKey` is ignored (warns in\n * debug mode); a later call with `env`, `endpoint` or `enabled` updates the\n * running tracker. A malformed key is not remembered, so a later valid call still works.\n */\nexport function initTracker(options: TrackerOptions): Tracker {\n if (!instance) {\n const created = createTracker(options);\n if (created === noopTracker) return created;\n instance = created;\n instanceKey = normalizeProjectKey(options.projectKey ?? \"\");\n return created;\n }\n try {\n const key = normalizeProjectKey(options.projectKey ?? \"\");\n if (key !== instanceKey && options.debug) {\n console.warn(\"[bitsnap analytics]\", \"tracker already started for another projectKey, ignoring\", options.projectKey);\n }\n if (key === instanceKey) {\n if (options.env || options.endpoint) instance.configure({ env: options.env, endpoint: options.endpoint });\n if (options.enabled != null) instance.setEnabled(options.enabled);\n }\n } catch {}\n return instance;\n}\n\n/** The tracker made by `initTracker`, if any. */\nexport function getTracker(): Tracker | undefined {\n return instance;\n}\n\n/** Destroys the singleton so that `initTracker` can build a fresh one (tests, hot reload). */\nexport function resetTracker() {\n if (typeof window !== \"undefined\") resetAutoPageViews(window);\n instance?.destroy();\n instance = undefined;\n instanceKey = null;\n}\n\n/**\n * `X-Bitsnap-Visitor` for a request that creates a checkout or payment link:\n * the client id of `projectKey` (default: the running tracker's project), only\n * while tracking is on and Bitsnap Consent grants analytics. Empty otherwise.\n */\nexport function visitorHeaders(projectKey?: string): Record<string, string> {\n try {\n if (typeof window === \"undefined\") return {};\n const tracker = instance;\n let id: string | null = null;\n if (tracker) {\n id = tracker.clientId(projectKey);\n } else {\n // No tracker of this bundle (e.g. only the analytics.js script runs): read the cookie it set.\n const key = projectKey ? normalizeProjectKey(projectKey) : null;\n id = key ? readVisitorId(window, key) : null;\n }\n return id ? { [VISITOR_HEADER]: id } : {};\n } catch {\n return {};\n }\n}\n","import { createContext, createElement, useContext, useMemo, useRef, type ReactNode } from \"react\";\nimport { useIsomorphicLayoutEffect } from \"../lib/isomorphic-layout-effect\";\nimport { initTracker, noopTracker, startAutoPageViews, type Tracker, type TrackerOptions } from \"./core\";\nimport type { ClientEvent } from \"./contract\";\n\nexport type AnalyticsApi = Pick<Tracker, \"track\" | \"page\">;\n\nconst noop: AnalyticsApi = { track: noopTracker.track, page: noopTracker.page };\n\nconst AnalyticsContext = createContext<AnalyticsApi>(noop);\n\nexport type BitsnapAnalyticsProviderProps = {\n /** Public project key (the `projectID` the rest of the SDK uses). */\n projectKey: string;\n env?: TrackerOptions[\"env\"];\n /** `false` turns tracking off. */\n enabled?: boolean;\n endpoint?: string;\n /** Called with every event before it is sent, e.g. to forward it to the merchant's own tools. */\n onEvent?: (event: ClientEvent) => void;\n /**\n * Sends `page_view` on mount and on every path change (`pushState`, `replaceState`, Back/Forward).\n * Default `true`; set `false` to call `page()` yourself.\n */\n autoPageViews?: boolean;\n children?: ReactNode;\n};\n\n/**\n * Starts the page's tracker and hands `track` and `page` to `useAnalytics()`.\n * The tracker is a per-page singleton: the first valid `projectKey` wins, but\n * `env`, `endpoint` and `enabled` of any provider update the running tracker.\n * It sends a `page_view` for the current page and every path change, once per\n * path however many providers, instrumented components or `analytics.js`\n * embeds the page has.\n * Nothing is tracked on the server. The only thing stored on the visitor's\n * device is the `bs_vid_<projectKey>` cookie, and only while Bitsnap Consent grants analytics.\n */\nexport function BitsnapAnalyticsProvider({\n projectKey,\n env,\n enabled,\n endpoint,\n onEvent,\n autoPageViews,\n children,\n}: BitsnapAnalyticsProviderProps) {\n const tracker = useMemo(\n () => initTracker({ projectKey, env, endpoint, enabled }),\n // The tracker is a per-page singleton; `initTracker` applies env/endpoint/enabled changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [projectKey, env, endpoint],\n );\n const onEventRef = useRef(onEvent);\n onEventRef.current = onEvent;\n\n // Before the passive effects of the children, whose first events must already respect it.\n useIsomorphicLayoutEffect(() => {\n tracker.setEnabled(enabled !== false);\n }, [tracker, enabled]);\n\n // Also before the children's events, so the page view comes first. The page type is cleared:\n // an automatic view must not inherit the type of an earlier manual `page(type)`.\n useIsomorphicLayoutEffect(() => {\n if (autoPageViews === false || enabled === false || tracker === noopTracker) return;\n return startAutoPageViews(() => tracker.page(null));\n }, [tracker, autoPageViews, enabled]);\n\n // Layout effects run before the passive effects of the children, whose\n // first events (list viewed, cart opened) would otherwise be missed.\n useIsomorphicLayoutEffect(() => tracker.onEvent((event) => onEventRef.current?.(event)), [tracker]);\n\n const api = useMemo<AnalyticsApi>(\n () => ({ track: tracker.track.bind(tracker), page: tracker.page.bind(tracker) }),\n [tracker],\n );\n return createElement(AnalyticsContext.Provider, { value: api }, children);\n}\n\n/** `track` and `page`; no-ops outside a `<BitsnapAnalyticsProvider>`. */\nexport function useAnalytics(): AnalyticsApi {\n return useContext(AnalyticsContext);\n}\n","import { createContext, createElement, useContext, useEffect, useLayoutEffect, useMemo, useRef, type ReactNode } from \"react\";\nimport type { ClientEvent, Env, EventProps, PageType } from \"./contract\";\nimport { getTracker, initTracker, noopTracker, startAutoPageViews, type BrowserEventName, type TrackExtra } from \"./core\";\nimport { useAnalytics, type AnalyticsApi } from \"./react\";\n\n/**\n * The `analytics` prop of every instrumented bitsnap-react component.\n * `true` (the default) tracks, `false` opts out, an object tracks and can\n * forward each event to the merchant's own tools.\n */\nexport type AnalyticsOption =\n | boolean\n | {\n /** Called with every event this component emits, after Bitsnap Consent allows analytics. */\n onEvent?: (event: ClientEvent) => void;\n /** `test` events are stored but never reach the merchant's stats. */\n env?: Env;\n };\n\n/** What the components call. It never throws and does nothing on the server. */\nexport interface Instrument {\n track<E extends BrowserEventName>(event: E, props: EventProps<E>, extra?: TrackExtra): void;\n}\n\nexport const noopInstrument: Instrument = { track() {} };\n\ntype Latest = {\n projectKey: string | null | undefined;\n analytics: AnalyticsOption | undefined;\n pageType: PageType | undefined;\n provided: AnalyticsApi | null;\n};\n\n/** The instrument whose `track` call is running; lets `onEvent` listeners tell their own events apart. */\nlet emitting: symbol | null = null;\n\nfunction createInstrument(read: () => Latest) {\n const id = Symbol(\"bitsnap-instrument\");\n\n function target(): Pick<AnalyticsApi, \"track\"> | null {\n if (typeof window === \"undefined\") return null;\n const { projectKey, analytics, provided } = read();\n if (analytics === false) return null;\n // A <BitsnapAnalyticsProvider> owns the tracker.\n if (provided) return provided;\n if (!projectKey) return null;\n return initTracker({\n projectKey,\n source: \"sdk_react\",\n channel: \"embed\",\n env: typeof analytics === \"object\" ? analytics.env : undefined,\n });\n }\n\n const instrument: Instrument = {\n track(event, props, extra) {\n try {\n const tracker = target();\n if (!tracker) return;\n const { analytics, pageType } = read();\n const withPage = pageType && extra?.page_type === undefined ? { ...extra, page_type: pageType } : extra;\n emitting = typeof analytics === \"object\" && analytics.onEvent ? id : null;\n tracker.track(event, props, withPage);\n } catch {\n // Analytics never breaks the host page.\n } finally {\n emitting = null;\n }\n },\n };\n\n /** Starts the tracker on mount, wires `onEvent` and, without a provider, the automatic page views. Returns the cleanup. */\n function attach(): () => void {\n try {\n if (!target()) return () => {};\n const tracker = getTracker();\n if (!tracker) return () => {};\n // A <BitsnapAnalyticsProvider> decides on the page views itself (`autoPageViews`).\n const stopPageViews = read().provided ? () => {} : startAutoPageViews(() => tracker.page(read().pageType ?? null));\n const stopListening = tracker.onEvent((event) => {\n if (emitting !== id) return;\n try {\n const { analytics } = read();\n if (typeof analytics === \"object\") analytics.onEvent?.(event);\n } catch {}\n });\n return () => {\n stopPageViews();\n stopListening();\n };\n } catch {\n return () => {};\n }\n }\n\n return { instrument, attach };\n}\n\nconst InstrumentContext = createContext<Instrument | null>(null);\n\n/** Hands the instrument of a top-level component to the parts below it. */\nexport function InstrumentProvider({ value, children }: { value: Instrument; children?: ReactNode }) {\n return createElement(InstrumentContext.Provider, { value }, children);\n}\n\n/** The instrument of the closest instrumented ancestor, or a no-op. */\nexport function useInstrumentContext(): Instrument {\n return useContext(InstrumentContext) ?? noopInstrument;\n}\n\n/**\n * The instrument of a top-level component. `projectKey` is the public\n * project id the component already has. When `analytics` is not given and an\n * ancestor is instrumented, the ancestor's instrument is reused.\n */\nexport function useInstrument(\n projectKey: string | null | undefined,\n analytics?: AnalyticsOption,\n pageType?: PageType,\n): Instrument {\n const parent = useContext(InstrumentContext);\n const api = useAnalytics();\n const provided = api.track === noopTracker.track ? null : api;\n const latest = useRef<Latest>({ projectKey, analytics, pageType, provided });\n latest.current = { projectKey, analytics, pageType, provided };\n\n const own = useMemo(() => createInstrument(() => latest.current), []);\n const inherit = analytics === undefined && parent !== null;\n const hasListener = typeof analytics === \"object\" && !!analytics.onEvent;\n\n // A layout effect runs before the passive effects of the children, whose\n // first events (list viewed, cart opened) `onEvent` must not miss.\n useLayoutEffect(() => {\n if (inherit) return;\n return own.attach();\n }, [own, inherit, hasListener, projectKey]);\n\n return inherit ? parent : own.instrument;\n}\n\n// -- cart sink ---------------------------------------------------------------\n\nlet cartInstrument: Instrument = noopInstrument;\n\n/**\n * The instrument used for cart changes made outside of a component (the\n * `Bitsnap.addProductToCart` helper). `<BitsnapCheckout>` registers its own.\n */\nexport function setCartInstrument(instrument: Instrument | null) {\n cartInstrument = instrument ?? noopInstrument;\n}\n\nlet cartMuted = 0;\n\nexport function getCartInstrument(): Instrument {\n return cartMuted > 0 ? noopInstrument : cartInstrument;\n}\n\n/**\n * Runs `fn` with the cart sink muted, so a cart change made inside it (a custom\n * `onAddToCart` calling `Bitsnap.addProductToCart`) is not reported a second\n * time by the caller that reports it itself. Await the cart call inside `fn`.\n */\nexport async function withCartAnalyticsMuted<T>(fn: () => T | Promise<T>): Promise<T> {\n cartMuted++;\n try {\n return await fn();\n } finally {\n cartMuted--;\n }\n}\n\n/** Registers the instrument as the cart sink while the calling component is mounted. */\nexport function useCartInstrument(instrument: Instrument) {\n useEffect(() => {\n setCartInstrument(instrument);\n return () => {\n if (cartInstrument === instrument) setCartInstrument(null);\n };\n }, [instrument]);\n}\n\n// -- shared helpers ----------------------------------------------------------\n\n/** Score (0..100) → the contract's bucket. */\nexport function scoreBucket(percent: number): \"0-24\" | \"25-49\" | \"50-74\" | \"75-99\" | \"100\" {\n const value = Number.isFinite(percent) ? Math.max(0, Math.min(100, percent)) : 0;\n if (value >= 100) return \"100\";\n if (value >= 75) return \"75-99\";\n if (value >= 50) return \"50-74\";\n if (value >= 25) return \"25-49\";\n return \"0-24\";\n}\n\n/** Milestones (25/50/75/100) reached by `percent` that are not in `seen` yet. Adds them to `seen`. */\nexport function newMilestones(percent: number, seen: Set<number>): number[] {\n const reached: number[] = [];\n for (const milestone of [25, 50, 75, 100]) {\n if (percent >= milestone && !seen.has(milestone)) {\n seen.add(milestone);\n reached.push(milestone);\n }\n }\n return reached;\n}\n"],"mappings":"6GAYA,IAAMA,GAAW,OAAO,IAAI,mBAAmB,EAE/C,SAASC,GAASC,EAAuB,CACvC,IAAMC,EAASD,EACf,OAAQC,EAAOH,EAAQ,IAAM,CAAE,KAAM,KAAM,SAAU,IAAI,IAAO,SAAU,EAAM,CAClF,CAGA,SAASI,GAAgBF,EAAaG,EAAsB,CAC1D,IAAMC,EAAQ,IAAM,CAClB,GAAI,CACFD,EAAS,CACX,MAAQ,CAAC,CACX,EACA,QAAWE,IAAQ,CAAC,YAAa,cAAc,EAAY,CACzD,IAAMC,EAAWN,EAAI,QAAQK,CAAI,EACjCL,EAAI,QAAQK,CAAI,EAAI,YAA4BE,EAAwC,CACtF,IAAMC,EAASF,EAAS,MAAM,KAAMC,CAAI,EACxC,OAAAH,EAAM,EACCI,CACT,CACF,CACAR,EAAI,iBAAiB,WAAYI,CAAK,CACxC,CAQO,SAASK,EAAmBC,EAAkBV,EAAc,OAAoB,CACrF,GAAI,CACF,IAAMW,EAAMZ,GAASC,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IAAIE,CAAS,IAC7CF,EAAK,IAAIE,CAAS,EAClBD,EAAQ,KAAKC,CAAS,GAG1B,OAAOD,CACT","names":["REGISTRY","registry","win","holder","watchNavigation","onChange","check","name","original","args","result","startAutoPageViews","send","reg","starter","path","resetAutoPageViews","SDK_VERSION","randomBytes","n","bytes","c","i","VISITOR_HEADER","MAX_AGE_SECONDS","VISITOR_ID_RE","consentApi","win","readCookie","doc","name","part","index","isBitsnapHost","hostname","host","consentBelongsTo","projectKey","api","onBitsnap","analyticsGranted","newVisitorId","binary","randomBytes","byte","rawVisitorCookie","clientIdCookieName","readVisitorCookie","value","writeVisitorCookie","id","base","domain","domainCandidates","deleteVisitorCookie","readVisitorId","nav","DEFAULT_ENDPOINT","FLUSH_INTERVAL_MS","FLUSH_AT","MAX_BODY_BYTES","KEEPALIVE_BUDGET_BYTES","EVENT_ID_RE","byteLength","text","noopTracker","uuidv7","now","b","randomBytes","t","i","hex","x","PAGE_ID_ALPHABET","newPageId","packEvents","projectKey","events","leaving","wrapper","byteLength","bodies","batch","size","close","event","own","MAX_BODY_BYTES","LIMITS","total","keep","KEEPALIVE_BUDGET_BYTES","createTracker","options","noopTracker","build","win","normalizeProjectKey","debug","warn","args","key","endpointUrl","endpoint","DEFAULT_ENDPOINT","url","source","channel","sdk","SDK_VERSION","pageId","newPageId","landing","parseUrl","env","refHost","referrerHost","enabled","pageType","pageViews","queue","timer","listeners","held","attached","consentReady","attachConsent","api","consentApi","afterConsentChange","consentDenied","state","notify","fn","syncVisitorCookie","final","consentBelongsTo","analyticsGranted","active","readVisitorCookie","writeVisitorCookie","newVisitorId","deleteVisitorCookie","clearTimer","release","flush","nav","schedule","FLUSH_INTERVAL_MS","send","body","clientId","readVisitorId","pending","entry","emit","name","props","extra","cleaned","sanitizeProps","here","EVENT_ID_RE","uuidv7","sanitizePath","verdict","validateEnvelope","valid","FLUSH_AT","onHide","onVisibility","onConsent","type","value","patch","instance","instanceKey","initTracker","created","getTracker","resetTracker","resetAutoPageViews","visitorHeaders","tracker","id","VISITOR_HEADER","createContext","createElement","useContext","useMemo","useRef","noop","noopTracker","AnalyticsContext","createContext","BitsnapAnalyticsProvider","projectKey","env","enabled","endpoint","onEvent","autoPageViews","children","tracker","useMemo","initTracker","onEventRef","useRef","useIsomorphicLayoutEffect","startAutoPageViews","event","api","createElement","useAnalytics","useContext","createContext","createElement","useContext","useEffect","useLayoutEffect","useMemo","useRef","noopInstrument","emitting","createInstrument","read","id","target","projectKey","analytics","provided","initTracker","instrument","event","props","extra","tracker","pageType","withPage","attach","getTracker","stopPageViews","startAutoPageViews","stopListening","InstrumentContext","createContext","InstrumentProvider","value","children","createElement","useInstrumentContext","useContext","useInstrument","parent","api","useAnalytics","noopTracker","latest","useRef","own","useMemo","inherit","hasListener","useLayoutEffect","cartInstrument","setCartInstrument","cartMuted","getCartInstrument","withCartAnalyticsMuted","fn","useCartInstrument","useEffect","scoreBucket","percent","newMilestones","seen","reached","milestone"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{C as y,D as I,E as T,F as N,G as f,H as g,I as C,J as O,K as _,c as R,o as c,r as p,s as l,t as E,u as S}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{C as y,D as I,E as T,F as N,G as f,H as g,I as C,J as O,K as _,c as R,o as c,r as p,s as l,t as E,u as S}from"./chunk-IXX6SUMB.mjs";import{a as d}from"./chunk-5R6AGO3Z.mjs";var M=["orders","order","confirmation","result","myReturns","myReturn"];function k(e){return M.includes(e)}function L(e){return e?{name:"orders"}:{name:"email"}}function U(e,s){switch(s.type){case"SESSION_EXPIRED":return k(e.name)?{name:"email"}:e;case"CODE_SENT":return e.name==="email"?{name:"code"}:e;case"AUTHENTICATED":return e.name==="email"||e.name==="code"?{name:"orders"}:e;case"SELECT_ORDER":return e.name==="orders"?{name:"order",orderId:s.orderId}:e;case"REVIEW":return e.name==="order"?{name:"confirmation",orderId:e.orderId,items:s.items,note:s.note}:e;case"SUBMITTED":return e.name==="confirmation"?{name:"result",returnId:s.returnId}:e;case"OPEN_MY_RETURNS":return e.name==="orders"||e.name==="result"?{name:"myReturns"}:e;case"SELECT_RETURN":return e.name==="myReturns"?{name:"myReturn",returnId:s.returnId}:e;case"CONTINUE":return e.name==="result"?{name:"orders"}:e;case"BACK":switch(e.name){case"code":return{name:"email"};case"order":case"myReturns":return{name:"orders"};case"confirmation":return{name:"order",orderId:e.orderId,items:e.items,note:e.note};case"myReturn":return{name:"myReturns"};default:return e}}}var K={email:1,code:2,orders:3,order:4,confirmation:5,result:6},B=6;function D(e){return K[e]}import{useEffect as P,useReducer as w,useRef as H}from"react";import{jsx as n,jsxs as Y}from"react/jsx-runtime";function V({current:e}){let s=p(),o=c("stepIndicator");return n("p",{"data-bitsnap-returns-slot":"stepIndicator",className:d("text-xs",o.className),style:o.style,children:s("stepIndicator",{current:e,total:B})})}function W({panelToken:e,logo:s}){let{status:o,challenge:a,projectID:x}=E("BitsnapReturns"),A=l(),[r,t]=w(U,L(!1));P(()=>{o==="authenticated"?t({type:"AUTHENTICATED"}):o==="anonymous"&&t({type:"SESSION_EXPIRED"})},[o]);let i=H(!1);if(P(()=>{i.current||o==="hydrating"||(i.current=!0,o==="anonymous"&&a!=null&&t({type:"CODE_SENT"}))},[o,a]),o==="exchanging"||o==="hydrating"&&e)return n(y,{});let m=D(r.name),b=r.name==="email"||r.name==="code";return Y("div",{className:"flex flex-col gap-4",children:[b&&n(R,{projectId:x,locale:A,...s}),m!=null&&n(V,{current:m}),r.name==="email"&&n(I,{showLogo:!1,onSubmitted:()=>t({type:"CODE_SENT"})}),r.name==="code"&&n(T,{showLogo:!1,onVerified:()=>t({type:"AUTHENTICATED"}),onBack:()=>t({type:"BACK"})}),r.name==="orders"&&n(N,{showLogout:!e,onSelectOrder:u=>t({type:"SELECT_ORDER",orderId:u}),onOpenMyReturns:()=>t({type:"OPEN_MY_RETURNS"})}),r.name==="order"&&n(f,{orderId:r.orderId,initialItems:r.items,initialNote:r.note,onBack:()=>t({type:"BACK"}),onContinue:({items:u,note:h})=>t({type:"REVIEW",items:u,note:h})}),r.name==="confirmation"&&n(g,{orderId:r.orderId,items:r.items,note:r.note,onBack:()=>t({type:"BACK"}),onSubmitted:u=>t({type:"SUBMITTED",returnId:u})}),r.name==="result"&&n(C,{returnId:r.returnId,onContinue:()=>t({type:"CONTINUE"}),onOpenMyReturns:()=>t({type:"OPEN_MY_RETURNS"})}),r.name==="myReturns"&&n(O,{onSelectReturn:u=>t({type:"SELECT_RETURN",returnId:u}),onBack:()=>t({type:"BACK"})}),r.name==="myReturn"&&n(_,{returnId:r.returnId,onBack:()=>t({type:"BACK"})})]})}function re({showLogo:e,logoUrl:s,logoDarkUrl:o,...a}){return n(S,{...a,children:n(W,{panelToken:a.panelAccessToken!=null&&a.panelAccessToken!=="",logo:{showLogo:e,logoUrl:s,logoDarkUrl:o}})})}export{re as a};
|
|
2
|
+
//# sourceMappingURL=chunk-URQBHNJK.mjs.map
|