bitsnap-react 1.17.0 → 1.18.1
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/AGENTS.md +85 -0
- package/README.md +84 -0
- package/dist/CartProvider-CC6YIZVS.js +2 -0
- package/dist/CartProvider-CC6YIZVS.js.map +1 -0
- package/dist/CartProvider-ECQQH3PS.css +2 -0
- package/dist/CartProvider-ECQQH3PS.css.map +1 -0
- package/dist/CartProvider-ZL65WZN6.mjs +2 -0
- package/dist/PanelModelFiles-4B2HYGIE.mjs +2 -0
- package/dist/PanelModelFiles-4B2HYGIE.mjs.map +1 -0
- package/dist/PanelModelFiles-EKQRLF46.js +2 -0
- package/dist/PanelModelFiles-EKQRLF46.js.map +1 -0
- package/dist/analytics.js +1 -1
- package/dist/analytics.js.map +1 -1
- package/dist/analytics.mjs +1 -1
- package/dist/catalog.css +1 -1
- package/dist/catalog.css.map +1 -1
- package/dist/catalog.d.mts +2 -0
- package/dist/catalog.d.ts +2 -0
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/catalog.mjs +1 -1
- package/dist/{chunk-4BL7TLK3.js → chunk-2XSLIZ27.js} +2 -2
- package/dist/chunk-2XSLIZ27.js.map +1 -0
- package/dist/{chunk-SYN5KU3O.js → chunk-5OCGXVLC.js} +2 -2
- package/dist/chunk-5OCGXVLC.js.map +1 -0
- package/dist/{chunk-A6VCP3A4.mjs → chunk-5YN752OV.mjs} +2 -2
- package/dist/{chunk-X3LVYIJR.mjs → chunk-62WDFH7K.mjs} +2 -2
- package/dist/chunk-6Q3VGPSF.js.map +1 -1
- package/dist/chunk-7BG22YBF.js +5 -0
- package/dist/chunk-7BG22YBF.js.map +1 -0
- package/dist/{chunk-5FZAROP6.js → chunk-AHISXVEE.js} +2 -2
- package/dist/chunk-AHISXVEE.js.map +1 -0
- package/dist/{chunk-MIMQTH2G.js → chunk-DR7WYI37.js} +2 -2
- package/dist/chunk-DR7WYI37.js.map +1 -0
- package/dist/chunk-EOFJAQPT.js +2 -0
- package/dist/chunk-EOFJAQPT.js.map +1 -0
- package/dist/{chunk-C3BBJOVV.js → chunk-G4SEOVLD.js} +2 -2
- package/dist/chunk-G4SEOVLD.js.map +1 -0
- package/dist/{chunk-2UDAB2C5.mjs → chunk-GKJURMDO.mjs} +2 -2
- package/dist/{chunk-2UDAB2C5.mjs.map → chunk-GKJURMDO.mjs.map} +1 -1
- package/dist/{chunk-M2G74N43.mjs → chunk-IGQZP4YR.mjs} +2 -2
- package/dist/chunk-JSDGZ4NY.js.map +1 -1
- package/dist/chunk-KOYBZORL.js.map +1 -1
- package/dist/{chunk-ESF5ZVVF.js → chunk-N3B25GTY.js} +2 -2
- package/dist/chunk-N3B25GTY.js.map +1 -0
- package/dist/chunk-OFPRIENJ.mjs +2 -0
- package/dist/chunk-OFPRIENJ.mjs.map +1 -0
- package/dist/chunk-Q337IQNA.js +2 -0
- package/dist/chunk-Q337IQNA.js.map +1 -0
- package/dist/{chunk-BZXV77PT.mjs → chunk-UTUPPMLK.mjs} +2 -2
- package/dist/{chunk-L7Q7OKM5.mjs → chunk-VWA3ZCNI.mjs} +2 -2
- package/dist/chunk-W3RGQYPD.js.map +1 -1
- package/dist/chunk-YGE2223J.mjs +5 -0
- package/dist/chunk-YGE2223J.mjs.map +1 -0
- package/dist/{chunk-HKNWW37T.mjs → chunk-ZKT4N553.mjs} +2 -2
- package/dist/chunk-ZM5T4TQW.mjs +2 -0
- package/dist/chunk-ZM5T4TQW.mjs.map +1 -0
- package/dist/consent.js.map +1 -1
- package/dist/course.d.mts +10 -0
- package/dist/course.d.ts +10 -0
- package/dist/course.js +1 -1
- package/dist/course.js.map +1 -1
- package/dist/course.mjs +1 -1
- package/dist/course.mjs.map +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 +272 -2
- package/dist/index.d.ts +272 -2
- 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-7DWKFCPK.js +2 -0
- package/dist/methods-7DWKFCPK.js.map +1 -0
- package/dist/methods-DQTADIN4.mjs +2 -0
- package/dist/methods-OJEZREBK.css +2 -0
- package/dist/methods-OJEZREBK.css.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/viewer3d.css +1 -1
- package/dist/viewer3d.css.map +1 -1
- package/dist/viewer3d.js.map +1 -1
- package/dist/viewer3d.mjs +1 -1
- package/package.json +4 -3
- package/dist/CartProvider-DGRZDTYC.mjs +0 -2
- package/dist/CartProvider-PDEV6GCV.css +0 -2
- package/dist/CartProvider-PDEV6GCV.css.map +0 -1
- package/dist/CartProvider-YVOHSMPE.js +0 -2
- package/dist/CartProvider-YVOHSMPE.js.map +0 -1
- package/dist/PanelModelFiles-NYCOFPLY.js +0 -2
- package/dist/PanelModelFiles-NYCOFPLY.js.map +0 -1
- package/dist/PanelModelFiles-RV7OHUUZ.mjs +0 -2
- package/dist/PanelModelFiles-RV7OHUUZ.mjs.map +0 -1
- package/dist/chunk-2NL5FCXC.mjs +0 -4
- package/dist/chunk-2NL5FCXC.mjs.map +0 -1
- package/dist/chunk-4BL7TLK3.js.map +0 -1
- package/dist/chunk-4ETIDGYZ.mjs +0 -2
- package/dist/chunk-4ETIDGYZ.mjs.map +0 -1
- package/dist/chunk-555KFWGY.js +0 -4
- package/dist/chunk-555KFWGY.js.map +0 -1
- package/dist/chunk-5FZAROP6.js.map +0 -1
- package/dist/chunk-6GCCNBEU.js +0 -2
- package/dist/chunk-6GCCNBEU.js.map +0 -1
- package/dist/chunk-7RXW6XFY.js +0 -2
- package/dist/chunk-7RXW6XFY.js.map +0 -1
- package/dist/chunk-C3BBJOVV.js.map +0 -1
- package/dist/chunk-ESF5ZVVF.js.map +0 -1
- package/dist/chunk-MIMQTH2G.js.map +0 -1
- package/dist/chunk-SYN5KU3O.js.map +0 -1
- package/dist/chunk-VNYHJT6V.mjs +0 -2
- package/dist/chunk-VNYHJT6V.mjs.map +0 -1
- package/dist/methods-3W34GRYL.js +0 -2
- package/dist/methods-3W34GRYL.js.map +0 -1
- package/dist/methods-LUJSKSQ4.mjs +0 -2
- package/dist/methods-QAZED7TJ.css +0 -2
- package/dist/methods-QAZED7TJ.css.map +0 -1
- /package/dist/{CartProvider-DGRZDTYC.mjs.map → CartProvider-ZL65WZN6.mjs.map} +0 -0
- /package/dist/{chunk-A6VCP3A4.mjs.map → chunk-5YN752OV.mjs.map} +0 -0
- /package/dist/{chunk-X3LVYIJR.mjs.map → chunk-62WDFH7K.mjs.map} +0 -0
- /package/dist/{chunk-M2G74N43.mjs.map → chunk-IGQZP4YR.mjs.map} +0 -0
- /package/dist/{chunk-BZXV77PT.mjs.map → chunk-UTUPPMLK.mjs.map} +0 -0
- /package/dist/{chunk-L7Q7OKM5.mjs.map → chunk-VWA3ZCNI.mjs.map} +0 -0
- /package/dist/{chunk-HKNWW37T.mjs.map → chunk-ZKT4N553.mjs.map} +0 -0
- /package/dist/{methods-LUJSKSQ4.mjs.map → methods-DQTADIN4.mjs.map} +0 -0
|
@@ -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.17.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,C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S,IAAY,MACrBA,GAAS,GAAW,QACpBA,GAAS,GAAW,QACpBA,GAAS,GAAW,QACjB,MACT,CAGO,SAAS2B,GAAcD,EAAiBE,EAA6B,CAC1E,IAAMC,EAAoB,CAAC,EAC3B,QAAWC,IAAa,CAAC,GAAI,GAAI,GAAI,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.18.1\";\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,EA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AAW,QACpBA,GAAS,GAAW,QACjB,MACT,CAGO,SAAS2B,GAAcD,EAAiBE,EAA6B,CAC1E,IAAMC,EAAoB,CAAC,EAC3B,QAAWC,IAAa,CAAC,GAAI,GAAI,GAAI,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,2 +1,2 @@
|
|
|
1
|
-
import{c as u,d,e as p,f as m}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{c as u,d,e as p,f as m}from"./chunk-62WDFH7K.mjs";import{k as l}from"./chunk-GKJURMDO.mjs";import{d as c}from"./chunk-OFPRIENJ.mjs";function f(t,r){try{return new Intl.NumberFormat(t,{style:"currency",currency:r,currencyDisplay:"symbol"})}catch{return}}function L(t,r,o=c){let e=t/100,n=f(o,r)??f(c,r);return n!=null?n.format(e):`${e.toFixed(2)} ${r}`}var P=24,g=48,i=class extends Error{status;constructor(r,o){super(r),this.name="ProductListError",this.status=o}};function T(t){return t==null||!Number.isFinite(t)?P:Math.min(g,Math.max(1,Math.floor(t)))}function A(t,r){return Math.max(1,Math.ceil(t/r))}function a(t){return t.replace(/\/+$/,"")}function I(t){let r=new URLSearchParams;r.set("limit",String(t.limit)),r.set("offset",String(t.offset)),t.locale&&r.set("locale",t.locale);let o=t.search?.trim();return o&&r.set("search",o),`${a(t.host)}/api/integrations/${encodeURIComponent(t.projectID)}/public-commerce/product-list?${r.toString()}`}function y(t){return typeof t=="object"&&t!=null&&Array.isArray(t.items)&&typeof t.totalCount=="number"}async function H(t,r){let o=await fetch(u(I(t)),{method:"GET",credentials:"omit",headers:{Accept:"application/json"},signal:r});if(!o.ok)throw new i(`Could not load products (${o.status})`,o.status);let e=await o.json();if(!y(e))throw new i("Unexpected product list response");return e}function h(t,r){if(t.projectID!=null&&t.projectID!==r.projectID)return{ok:!1,reason:`the page cart already belongs to project "${t.projectID}"`};let o=null,e=r.host?a(r.host):"",n=a(t.host);if(e&&e!==n){if(n!==a(t.defaultHost))return{ok:!1,reason:`the page cart already uses the host "${t.host}"`};o=e}return{ok:!0,setProjectID:t.projectID==null?r.projectID:null,setHost:o}}function b(t,r){let o=r.cartItemId!=null&&r.cartItemId!==r.id?r.cartItemId:null;t.track("add_to_cart",{qty:1,value_minor:r.price,currency:r.currency},{product_id:r.id,variant_id:o})}async function M(t,r){let[{Bitsnap:o},{getProjectID:e,setProjectID:n}]=await Promise.all([import("./methods-DQTADIN4.mjs"),import("./CartProvider-ZL65WZN6.mjs")]),s=h({projectID:e(),host:p,defaultHost:d},r);if(!s.ok)return C(s.reason);if(s.setProjectID!=null&&n(s.setProjectID),s.setHost!=null&&m(s.setHost),await o.addProductToCart(t.cartItemId??t.id,1,void 0,{url:r.url,name:t.name,price:t.price,currency:t.currency,analytics:l})!=null)throw new Error("Could not add the product to the cart");r.analytics!=null&&b(r.analytics,t),r.showCart&&o.showCart()}function C(t){throw console.warn(`bitsnap-react: ProductList did not add to the cart because ${t}. Pass onAddToCart to use another cart.`),new Error("The page cart belongs to another project or host")}export{T as a,A as b,H as c,b as d,M as e,L as f};
|
|
2
|
+
//# sourceMappingURL=chunk-IGQZP4YR.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/
|
|
1
|
+
{"version":3,"sources":["/home/user/bitsnap-react-payment-release/dist/chunk-JSDGZ4NY.js"],"names":[],"mappings":"AAAA,6EAAI,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,aAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,6BAAqB","file":"/home/user/bitsnap-react-payment-release/dist/chunk-JSDGZ4NY.js"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/appearance-core.ts"],"names":["omitUndefined","tokens","result","key","value","hasAnyElement","elements","element","resolveBoundaryStyle","variables","shadcnVariables","style","token","variable","resolveAppearanceCore","appearance","config","theme","getSlotAppearance","slot"],"mappings":"AA8DO,0rBAASA,CAAAA,CACdC,CAAAA,CACgC,CAChC,IAAMC,CAAAA,CAAkC,CAAC,CAAA,CAEzC,GAAA,CAAA,GAAW,CAACC,CAAAA,CAAKC,CAAK,CAAA,GAAK,MAAA,CAAO,OAAA,CAAQH,CAAM,CAAA,CAC1CG,CAAAA,EAAS,IAAA,EAAA,CACXF,CAAAA,CAAOC,CAAG,CAAA,CAAIC,CAAAA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A,CAAAE,CAAAA,CACA,YAAA,iBACEF,CAAAA,6BAAY,OAAA,EAAS,IAAA,EACrB,MAAA,CAAO,IAAA,CAAKd,CAAM,CAAA,CAAE,MAAA,CAAS,CAAA,EAC7BI,CAAAA,CAAcC,CAAQ,CAAA,CACxB,MAAA,CAAAL,CAAAA,CACA,QAAA,CAAAK,CAAAA,CACA,aAAA,CAAeE,CAAAA,CACbP,CAAAA,CACAe,CAAAA,CAAO,SAAA,CACPA,CAAAA,CAAO,eACT,CACF,CACF,CAGO,SAASE,CAAAA,CACdZ,CAAAA,CACAa,CAAAA,CAC4B,CAC5B,OAAOb,CAAAA,CAASa,CAAI,CACtB,CAAA,6BAAA","file":"/home/
|
|
1
|
+
{"version":3,"sources":["../src/lib/appearance-core.ts"],"names":["omitUndefined","tokens","result","key","value","hasAnyElement","elements","element","resolveBoundaryStyle","variables","shadcnVariables","style","token","variable","resolveAppearanceCore","appearance","config","theme","getSlotAppearance","slot"],"mappings":"AA8DO,0rBAASA,CAAAA,CACdC,CAAAA,CACgC,CAChC,IAAMC,CAAAA,CAAkC,CAAC,CAAA,CAEzC,GAAA,CAAA,GAAW,CAACC,CAAAA,CAAKC,CAAK,CAAA,GAAK,MAAA,CAAO,OAAA,CAAQH,CAAM,CAAA,CAC1CG,CAAAA,EAAS,IAAA,EAAA,CACXF,CAAAA,CAAOC,CAAG,CAAA,CAAIC,CAAAA,CAAAA,CAIlB,OAAOF,CACT,CAEO,SAASG,CAAAA,CACdC,CAAAA,CACS,CACT,OAAO,MAAA,CAAO,MAAA,CAAmCA,CAAQ,CAAA,CAAE,IAAA,CACxDC,CAAAA,EACCA,CAAAA,EAAW,IAAA,EAAA,CAASA,CAAAA,CAAQ,SAAA,EAAa,IAAA,EAAQA,CAAAA,CAAQ,KAAA,EAAS,IAAA,CACtE,CACF,CAMO,SAASC,CAAAA,CACdP,CAAAA,CACAQ,CAAAA,CACAC,CAAAA,CACe,CACf,IAAMC,CAAAA,CAAgC,CAAC,CAAA,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,CAC4B,CAC5B,OAAOb,CAAAA,CAASa,CAAI,CACtB,CAAA,6BAAA","file":"/home/user/bitsnap-react-payment-release/dist/chunk-KOYBZORL.js","sourcesContent":["import type { CSSProperties } from \"react\";\n\n/**\n * Generic building blocks shared by the appearance modules (checkout, and\n * later returns). Each module supplies its own token to CSS variable map, theme\n * presets and shadcn mapping, and keeps its own public types. Everything here\n * is pure so it can be tested without a DOM.\n */\n\n/** Caller overrides for a single slot. */\nexport type SlotAppearance = {\n /** Merged after the built-in classes with `cn`, so Tailwind conflicts resolve. */\n className?: string;\n /** Merged after the built-in inline styles. */\n style?: CSSProperties;\n};\n\n/** Typed partial map of slot name to its overrides. */\nexport type AppearanceElements<Slot extends string> = Partial<\n Record<Slot, SlotAppearance>\n>;\n\n/** CSS custom property used for each token. */\nexport type TokenVariables<Token extends string> = Readonly<\n Record<Token, string>\n>;\n\n/**\n * Remaps a token onto a shadcn theme variable (`--background`, `--ring`, ...)\n * so shared UI primitives follow the module's tokens. Only written when the\n * token is in effect.\n */\nexport type ShadcnVariableMapping<Token extends string> = readonly {\n token: Token;\n variable: string;\n}[];\n\nexport type AppearanceCoreConfig<Token extends string, Theme extends string> = {\n /** Theme used when the caller does not select one. */\n defaultTheme: Theme;\n /** Partial token sets applied underneath the caller tokens. */\n presets: Record<Theme, Partial<Record<Token, string>>>;\n variables: TokenVariables<Token>;\n shadcnVariables: ShadcnVariableMapping<Token>;\n};\n\nexport type ResolvedAppearanceCore<\n Token extends string,\n Theme extends string,\n Slot extends string,\n> = {\n theme: Theme;\n /** `true` as soon as the caller passed a theme, a token or a slot override. */\n isCustomized: boolean;\n /** Tokens that are in effect. Empty entries were dropped. */\n tokens: Partial<Record<Token, string>>;\n elements: AppearanceElements<Slot>;\n /** Inline custom properties for the theme boundary. */\n boundaryStyle: CSSProperties;\n};\n\n/** Drops `undefined`/`null` tokens so unset values keep the stylesheet default. */\nexport function omitUndefined<Token extends string>(\n tokens: Partial<Record<Token, string>>,\n): Partial<Record<Token, string>> {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(tokens)) {\n if (value != null) {\n result[key] = value;\n }\n }\n\n return result as Partial<Record<Token, string>>;\n}\n\nexport function hasAnyElement<Slot extends string>(\n elements: AppearanceElements<Slot>,\n): boolean {\n return Object.values<SlotAppearance | undefined>(elements).some(\n (element) =>\n element != null && (element.className != null || element.style != null),\n );\n}\n\n/**\n * Token to CSS variable resolution, followed by the shadcn remapping. Only\n * tokens that are in effect produce a variable.\n */\nexport function resolveBoundaryStyle<Token extends string>(\n tokens: Partial<Record<Token, string>>,\n variables: TokenVariables<Token>,\n shadcnVariables: ShadcnVariableMapping<Token>,\n): CSSProperties {\n const style: Record<string, string> = {};\n\n for (const [token, variable] of Object.entries<string>(variables)) {\n const value = tokens[token as Token];\n if (value != null) {\n style[variable] = value;\n }\n }\n\n for (const { token, variable } of shadcnVariables) {\n const value = tokens[token];\n if (value != null) {\n style[variable] = value;\n }\n }\n\n return style as CSSProperties;\n}\n\n/**\n * Resolves theme, tokens, slot overrides and the boundary style. The resolver\n * never invents values: a token is only present when the caller provided it or\n * selected a theme preset that carries it.\n */\nexport function resolveAppearanceCore<\n Token extends string,\n Theme extends string,\n Slot extends string,\n>(\n appearance:\n | {\n theme?: Theme;\n tokens?: Partial<Record<Token, string>>;\n elements?: AppearanceElements<Slot>;\n }\n | undefined,\n config: AppearanceCoreConfig<Token, Theme>,\n): ResolvedAppearanceCore<Token, Theme, Slot> {\n const theme: Theme = appearance?.theme ?? config.defaultTheme;\n\n const tokens = omitUndefined<Token>({\n ...config.presets[theme],\n ...appearance?.tokens,\n });\n\n const elements = appearance?.elements ?? {};\n\n return {\n theme,\n isCustomized:\n appearance?.theme != null ||\n Object.keys(tokens).length > 0 ||\n hasAnyElement(elements),\n tokens,\n elements,\n boundaryStyle: resolveBoundaryStyle(\n tokens,\n config.variables,\n config.shadcnVariables,\n ),\n };\n}\n\n/** Caller overrides for a slot, if any were provided. */\nexport function getSlotAppearance<Slot extends string>(\n elements: AppearanceElements<Slot>,\n slot: Slot,\n): SlotAppearance | undefined {\n return elements[slot];\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkG4SEOVLDjs = require('./chunk-G4SEOVLD.js');var s="X-Bitsnap-Client",n=`bitsnap-react@${_chunkG4SEOVLDjs.a}`,i="bs_client",E= exports.a ={[s]:n},T= exports.b =t=>e=>(e.header.set(s,n),t(e));function C(t){let e=t.indexOf("#"),o=e===-1?t:t.slice(0,e),c=e===-1?"":t.slice(e),p=o.includes("?")?/[?&]$/.test(o)?"":"&":"?";return`${o}${p}${i}=${encodeURIComponent(n)}${c}`}var a="https://bitsnap.pl",l= exports.e =a;function _(t){console.log("setCustomHost",t),l= exports.e =t}var _clsx = require('clsx');var _tailwindmerge = require('tailwind-merge');function H(...t){return _tailwindmerge.twMerge.call(void 0, _clsx.clsx.call(void 0, t))}exports.a = E; exports.b = T; exports.c = C; exports.d = a; exports.e = l; exports.f = _; exports.g = H;
|
|
2
|
+
//# sourceMappingURL=chunk-N3B25GTY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/user/bitsnap-react-payment-release/dist/chunk-N3B25GTY.js","../src/lib/client-header.ts"],"names":["CLIENT_HEADER_NAME","CLIENT_HEADER_VALUE","SDK_VERSION"],"mappings":"AAAA,+HAAuC,ICG1BA,CAAAA,CAAqB,kBAAA,CACrBC,CAAAA,CAAsB,CAAA,cAAA,EAAiBC,kBAAW,CAAA,CAAA","file":"/home/user/bitsnap-react-payment-release/dist/chunk-N3B25GTY.js","sourcesContent":[null,"import type { Interceptor } from \"@connectrpc/connect\";\nimport { SDK_VERSION } from \"../version\";\n\nexport const CLIENT_HEADER_NAME = \"X-Bitsnap-Client\";\nexport const CLIENT_HEADER_VALUE = `bitsnap-react@${SDK_VERSION}`;\n\nexport const CLIENT_QUERY_PARAM = \"bs_client\";\n\n/**\n * Spread into the `headers` of a fetch that already triggers a CORS preflight\n * (JSON POST, Connect RPC). Never use it on a simple cross-origin GET: the\n * custom header would force a preflight that older servers and merchant\n * proxies do not allow. Use `withClientParam` there.\n */\nexport const clientHeaders: Record<string, string> = {\n [CLIENT_HEADER_NAME]: CLIENT_HEADER_VALUE,\n};\n\n/** Connect interceptor adding the client header to every RPC. */\nexport const clientHeaderInterceptor: Interceptor = (next) => (req) => {\n req.header.set(CLIENT_HEADER_NAME, CLIENT_HEADER_VALUE);\n return next(req);\n};\n\n/** Adds `bs_client=<pkg>@<ver>` to a URL, for simple GETs that must stay preflight-free. */\nexport function withClientParam(url: string): string {\n const hash = url.indexOf(\"#\");\n const base = hash === -1 ? url : url.slice(0, hash);\n const fragment = hash === -1 ? \"\" : url.slice(hash);\n const separator = base.includes(\"?\") ? (/[?&]$/.test(base) ? \"\" : \"&\") : \"?\";\n return `${base}${separator}${CLIENT_QUERY_PARAM}=${encodeURIComponent(CLIENT_HEADER_VALUE)}${fragment}`;\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function l(t,e){return e.toLowerCase().startsWith("en")?t.en:t.pl}function d(t,e){let n={...t};if(e!=null)for(let[c,i]of Object.entries(e))i!=null&&(n[c]=i);return n}function s(t,e,n){return d(l(t,e),n)}function p(t,e){return t[e]??e}var u={en:{cart:"Cart",emptyCart:"Your cart is empty.",total:"Total:",delivery:"+ delivery",chooseCountry:"Choose a country",nextStep:"Next step",unavailableProducts:"Not all products are available.",checkoutFailed:"Something went wrong. Please try again later.",noPaymentGateway:"This shop doesn't accept online payments yet. Try again later or contact the seller.",gatewayNotConfigured:"Payments in this shop are not set up correctly. Try again later or contact the seller.",shippingNotConfigured:"Delivery in this shop is not configured yet. Try again later or contact the seller.",mixedRecurring:"Subscriptions and one-time products cannot be paid for together. Pay for them in separate orders.",currencyUnsupported:"The shop doesn't accept payments in this currency. Contact the seller.",priceChanged:"The product price has changed. Refresh the page to see the current price.",close:"Close cart",remove:"Remove",quantity:"Quantity",increaseQuantity:"Increase quantity",decreaseQuantity:"Decrease quantity",openCart:"Open cart",cartItemsCount:"Items in cart",lowestPrice30Days:"Lowest price in the last 30 days:",noPriceHistory:"No price data for the last 30 days",redirectFailed:"Could not redirect to the payment. Please try again later.",subscriptionUnsupported:"Subscriptions cannot be added to the cart yet.",searchCountry:"Find a country",noCountriesFound:"No countries found",countryRequired:"Choose a country to continue.",paymentForCart:"Cart payment",coupon:"Coupon",extrasCalculatedNext:"Discounts, shipping and taxes are calculated at the next step",loadFailed:"Could not load your cart.",retry:"Try again",paymentMethodLegend:"How would you like to pay?",paymentMethodOnline:"Pay online",paymentMethodOnlineDescription:"Card, BLIK code or instant bank payment. You pay right away.",paymentMethodManualTransfer:"Bank transfer",paymentMethodManualBlik:"BLIK \u2013 transfer to a phone number",paymentMethodManualBoth:"Bank transfer or BLIK to a phone number",paymentMethodManualDescription:"You pay in your bank's app. We show the payment details after you place the order, and the order waits for your payment.",paymentMethodManualBlikNote:"This is not a BLIK code payment \u2013 you do not enter a 6\u2011digit code.",paymentMethodCod:"Cash on delivery",paymentMethodCodDescription:"You pay the courier in cash or by card when you receive the parcel.",paymentMethodCodUnavailable:"Cash on delivery is not available for this order. Choose another way to pay.",expressPending:"Confirming your payment\u2026",expressConfirmed:"Payment confirmed. Thank you!",expressFailed:"The payment failed. Your cart is unchanged.",expressCancelled:"Payment cancelled. Your cart is unchanged.",expressPendingLong:"We are still confirming your payment. We will check again when you come back to this page.",expressLoadFailed:"Could not load this payment button. Try again later or use the regular checkout.",expressCartUnavailable:"This cart cannot be paid with this method right now. Try again later.",expressCartConflict:"Your cart changed in another tab or in the provider's app. Review the quantities and try again.",expressPriceChanged:"Your cart total changed. Check the new total and try again.",expressProductUnavailable:"This product cannot be paid for right now. Try again later."},pl:{cart:"Koszyk",emptyCart:"Brak produkt\xF3w w koszyku.",total:"Suma:",delivery:"+ dostawa",chooseCountry:"Wybierz kraj",nextStep:"Nast\u0119pny krok",unavailableProducts:"Nie wszystkie produkty s\u0105 dost\u0119pne w magazynie.",checkoutFailed:"Co\u015B posz\u0142o nie tak. Spr\xF3buj ponownie p\xF3\u017Aniej.",noPaymentGateway:"Ten sklep nie przyjmuje jeszcze p\u0142atno\u015Bci online. Spr\xF3buj ponownie p\xF3\u017Aniej lub skontaktuj si\u0119 ze sprzedawc\u0105.",gatewayNotConfigured:"P\u0142atno\u015Bci w tym sklepie nie s\u0105 poprawnie skonfigurowane. Spr\xF3buj ponownie p\xF3\u017Aniej lub skontaktuj si\u0119 ze sprzedawc\u0105.",shippingNotConfigured:"Dostawa w tym sklepie nie jest jeszcze skonfigurowana. Spr\xF3buj ponownie p\xF3\u017Aniej lub skontaktuj si\u0119 ze sprzedawc\u0105.",mixedRecurring:"Subskrypcji i produkt\xF3w jednorazowych nie mo\u017Cna op\u0142aci\u0107 razem. Op\u0142a\u0107 je w osobnych zam\xF3wieniach.",currencyUnsupported:"Sklep nie przyjmuje p\u0142atno\u015Bci w tej walucie. Skontaktuj si\u0119 ze sprzedawc\u0105.",priceChanged:"Cena produktu si\u0119 zmieni\u0142a. Od\u015Bwie\u017C stron\u0119, aby zobaczy\u0107 aktualn\u0105 cen\u0119.",close:"Zamknij koszyk",remove:"Usu\u0144",quantity:"Ilo\u015B\u0107",increaseQuantity:"Zwi\u0119ksz ilo\u015B\u0107",decreaseQuantity:"Zmniejsz ilo\u015B\u0107",openCart:"Otw\xF3rz koszyk",cartItemsCount:"Produkt\xF3w w koszyku",lowestPrice30Days:"Najni\u017Csza cena z 30 dni:",noPriceHistory:"Brak danych o cenie z ostatnich 30 dni",redirectFailed:"Nie uda\u0142o si\u0119 przekierowa\u0107 do p\u0142atno\u015Bci. Spr\xF3buj ponownie p\xF3\u017Aniej.",subscriptionUnsupported:"Subskrypcji nie mo\u017Cna jeszcze doda\u0107 do koszyka.",searchCountry:"Znajd\u017A kraj",noCountriesFound:"Nie znaleziono kraj\xF3w",countryRequired:"Wybierz kraj, aby przej\u015B\u0107 dalej.",paymentForCart:"P\u0142atno\u015B\u0107 za koszyk",coupon:"Kupon",extrasCalculatedNext:"Rabaty, dostawa i podatki w nast\u0119pnym kroku",loadFailed:"Nie uda\u0142o si\u0119 wczyta\u0107 koszyka.",retry:"Spr\xF3buj ponownie",paymentMethodLegend:"Jak chcesz zap\u0142aci\u0107?",paymentMethodOnline:"Zap\u0142a\u0107 online",paymentMethodOnlineDescription:"Karta, kod BLIK lub szybki przelew. P\u0142acisz od razu.",paymentMethodManualTransfer:"Przelew bankowy",paymentMethodManualBlik:"BLIK \u2013 przelew na telefon",paymentMethodManualBoth:"Przelew lub BLIK na telefon",paymentMethodManualDescription:"Zap\u0142acisz w aplikacji swojego banku. Dane do p\u0142atno\u015Bci poka\u017Cemy po z\u0142o\u017Ceniu zam\xF3wienia, a zam\xF3wienie poczeka na Twoj\u0105 wp\u0142at\u0119.",paymentMethodManualBlikNote:"To nie jest p\u0142atno\u015B\u0107 kodem BLIK \u2013 nie wpisujesz 6\u2011cyfrowego kodu.",paymentMethodCod:"P\u0142atno\u015B\u0107 przy odbiorze",paymentMethodCodDescription:"Zap\u0142acisz kurierowi got\xF3wk\u0105 lub kart\u0105, gdy odbierzesz przesy\u0142k\u0119.",paymentMethodCodUnavailable:"P\u0142atno\u015B\u0107 przy odbiorze nie jest dost\u0119pna dla tego zam\xF3wienia. Wybierz inn\u0105 form\u0119 p\u0142atno\u015Bci.",expressPending:"Potwierdzamy p\u0142atno\u015B\u0107\u2026",expressConfirmed:"P\u0142atno\u015B\u0107 potwierdzona. Dzi\u0119kujemy!",expressFailed:"P\u0142atno\u015B\u0107 si\u0119 nie uda\u0142a. Koszyk pozosta\u0142 bez zmian.",expressCancelled:"P\u0142atno\u015B\u0107 zosta\u0142a anulowana. Koszyk pozosta\u0142 bez zmian.",expressPendingLong:"Nadal potwierdzamy Twoj\u0105 p\u0142atno\u015B\u0107. Sprawdzimy ponownie, gdy wr\xF3cisz na t\u0119 stron\u0119.",expressLoadFailed:"Nie uda\u0142o si\u0119 wczyta\u0107 przycisku p\u0142atno\u015Bci. Spr\xF3buj ponownie p\xF3\u017Aniej lub skorzystaj ze zwyk\u0142ego koszyka.",expressCartUnavailable:"Tego koszyka nie mo\u017Cna teraz op\u0142aci\u0107 t\u0105 metod\u0105. Spr\xF3buj ponownie p\xF3\u017Aniej.",expressCartConflict:"Koszyk zmieni\u0142 si\u0119 w innej karcie lub w aplikacji przewo\u017Anika. Sprawd\u017A ilo\u015Bci i spr\xF3buj ponownie.",expressPriceChanged:"Suma koszyka si\u0119 zmieni\u0142a. Sprawd\u017A now\u0105 sum\u0119 i spr\xF3buj ponownie.",expressProductUnavailable:"Nie mo\u017Cna teraz zap\u0142aci\u0107 za ten produkt. Spr\xF3buj ponownie p\xF3\u017Aniej."}};function y(t,e){return s(u,t,e)}function m(t,e,n){return p(y(e,n),t)}var o="pl-PL",r="bitsnap-locale",a;function w(t){let e=t?.trim();a=e?e.toLowerCase()==="en"?"en-US":e.toLowerCase()==="pl"?o:e:void 0,typeof localStorage<"u"&&(a==null?localStorage.removeItem(r):localStorage.setItem(r,a))}function z(){return a??(typeof localStorage<"u"?localStorage.getItem(r)??o:o)}export{l as a,s as b,m as c,o as d,w as e,z as f};
|
|
2
|
+
//# sourceMappingURL=chunk-OFPRIENJ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/texts.ts","../src/components/checkout/texts.ts","../src/components/checkout/locale.ts"],"sourcesContent":["/**\n * Shared text machinery: typed string tables per locale, the locale fallback\n * and a merge with caller overrides. Each module (checkout, later returns)\n * supplies its own key type and default tables.\n */\n\n/** Strings of one locale, keyed by text key. */\nexport type TextTable<Key extends string> = Record<Key, string>;\n\n/** Default tables for the supported locales. */\nexport type LocaleTables<Key extends string> = {\n en: TextTable<Key>;\n pl: TextTable<Key>;\n};\n\n/**\n * Picks the table for a locale. Any locale starting with `en` (case\n * insensitive, so `en`, `en-US`, `EN-gb`) gets English; everything else,\n * including unknown locales, gets the Polish default.\n */\nexport function pickLocaleTable<Key extends string>(\n tables: LocaleTables<Key>,\n locale: string,\n): TextTable<Key> {\n return locale.toLowerCase().startsWith(\"en\") ? tables.en : tables.pl;\n}\n\n/**\n * Merges caller overrides over a table. Overrides apply regardless of the\n * locale; `undefined`/`null` entries are ignored so the default stays.\n */\nexport function mergeTexts<Key extends string>(\n table: TextTable<Key>,\n overrides?: Partial<TextTable<Key>>,\n): TextTable<Key> {\n const result: Record<string, string> = { ...table };\n\n if (overrides != null) {\n for (const [key, value] of Object.entries<string | undefined>(overrides)) {\n if (value != null) {\n result[key] = value;\n }\n }\n }\n\n return result as TextTable<Key>;\n}\n\n/** Locale table merged with the caller overrides. */\nexport function resolveTexts<Key extends string>(\n tables: LocaleTables<Key>,\n locale: string,\n overrides?: Partial<TextTable<Key>>,\n): TextTable<Key> {\n return mergeTexts(pickLocaleTable(tables, locale), overrides);\n}\n\n/** Looks up a single text. Unknown keys return the key itself. */\nexport function lookupText<Key extends string>(\n texts: TextTable<Key>,\n key: Key,\n): string {\n return (texts as Record<string, string | undefined>)[key] ?? key;\n}\n","import {\n lookupText,\n resolveTexts,\n type LocaleTables,\n} from \"@/src/lib/texts\";\n\n/**\n * Every string the checkout renders. Pass a partial object through the\n * `texts` prop of `BitsnapCheckout` to override any of them, whatever the\n * locale.\n */\nexport type CheckoutTexts = {\n /** Drawer title. */\n cart: string;\n /** Shown when the cart has no products. */\n emptyCart: string;\n /** Label next to the total price. */\n total: string;\n /** Delivery note next to the total price. */\n delivery: string;\n /** Country selector placeholder. */\n chooseCountry: string;\n /** Checkout button label. */\n nextStep: string;\n /** Error shown when some products are out of stock. */\n unavailableProducts: string;\n /** Error shown when the checkout fails and the server gave no reason. */\n checkoutFailed: string;\n /** Error shown when the shop has no payment gateway connected. */\n noPaymentGateway: string;\n /** Error shown when the payment gateway of the shop is not set up. */\n gatewayNotConfigured: string;\n /** Error shown when delivery of the shop is not set up. */\n shippingNotConfigured: string;\n /** Error shown when the cart mixes subscriptions with one-time products. */\n mixedRecurring: string;\n /** Error shown when the cart currency cannot be paid in. */\n currencyUnsupported: string;\n /** Error shown when a price changed after the product was added. */\n priceChanged: string;\n /** Accessible name of the close button of the drawer. */\n close: string;\n /** Remove button of a cart line (also read together with the product name). */\n remove: string;\n /** Accessible name of the quantity control and its input. */\n quantity: string;\n /** Accessible name of the \"+\" quantity button. */\n increaseQuantity: string;\n /** Accessible name of the \"-\" quantity button. */\n decreaseQuantity: string;\n /** Accessible name of the cart button when it only shows an icon. */\n openCart: string;\n /** Hidden label of the number of products badge; the number is appended after a colon. */\n cartItemsCount: string;\n /** Label before the lowest price of the last 30 days; the price is appended. */\n lowestPrice30Days: string;\n /** Shown instead of the lowest price when the price has no history. */\n noPriceHistory: string;\n /** Error shown when redirecting to the payment failed. */\n redirectFailed: string;\n /** Error shown when a subscription is added to the cart. */\n subscriptionUnsupported: string;\n /** Country search placeholder. */\n searchCountry: string;\n /** Shown when the country search has no match. */\n noCountriesFound: string;\n /** Hint under the checkout button when no country is chosen. */\n countryRequired: string;\n /** Title of the Apple Pay and Google Pay sheet total. */\n paymentForCart: string;\n /** Coupon label in the Google Pay sheet; the code is appended. */\n coupon: string;\n /** Note under the cart total. */\n extrasCalculatedNext: string;\n /** Error shown when the products of the cart could not be loaded. */\n loadFailed: string;\n /** Button that loads the cart again. */\n retry: string;\n /** Heading of the payment method choice (shown only when the shop offers paying by hand). */\n paymentMethodLegend: string;\n /** Option that pays through the shop's online gateway. */\n paymentMethodOnline: string;\n /** Hint under the online option. */\n paymentMethodOnlineDescription: string;\n /** Manual option when the seller takes bank transfers only. */\n paymentMethodManualTransfer: string;\n /** Manual option when the seller takes BLIK transfers to a phone number only. */\n paymentMethodManualBlik: string;\n /** Manual option when the seller takes both. */\n paymentMethodManualBoth: string;\n /** What paying by hand means: the details come after the order is placed. */\n paymentMethodManualDescription: string;\n /** Shown with a selected manual option that includes BLIK to a phone number. */\n paymentMethodManualBlikNote: string;\n /** Cash on delivery option. */\n paymentMethodCod: string;\n /** Hint under the cash on delivery option. */\n paymentMethodCodDescription: string;\n /** Error shown when the shop refused cash on delivery for the order. */\n paymentMethodCodUnavailable: string;\n /** Status while the provider confirms a payment started from an express button. */\n expressPending: string;\n /** Status after the provider confirmed the payment. */\n expressConfirmed: string;\n /** Status when the provider reports a failed payment. */\n expressFailed: string;\n /** Status when the buyer cancelled the provider's payment flow. */\n expressCancelled: string;\n /** Shown while the payment is still unconfirmed after a page return. */\n expressPendingLong: string;\n /** Error shown when the provider's button could not be loaded. */\n expressLoadFailed: string;\n /** Error shown when the cart cannot be paid with this provider right now. */\n expressCartUnavailable: string;\n /** Error shown when another tab/provider changed the same cart line. */\n expressCartConflict: string;\n /** Shown when the server total changed between mounting and paying. */\n expressPriceChanged: string;\n /** Error shown when a product could not be added before the InPost binding. */\n expressProductUnavailable: string;\n};\n\nexport type CheckoutTextKey = keyof CheckoutTexts;\n\nexport const CHECKOUT_TEXT_TABLES: LocaleTables<CheckoutTextKey> = {\n en: {\n cart: \"Cart\",\n emptyCart: \"Your cart is empty.\",\n total: \"Total:\",\n delivery: \"+ delivery\",\n chooseCountry: \"Choose a country\",\n nextStep: \"Next step\",\n unavailableProducts: \"Not all products are available.\",\n checkoutFailed: \"Something went wrong. Please try again later.\",\n noPaymentGateway:\n \"This shop doesn't accept online payments yet. Try again later or contact the seller.\",\n gatewayNotConfigured:\n \"Payments in this shop are not set up correctly. Try again later or contact the seller.\",\n shippingNotConfigured:\n \"Delivery in this shop is not configured yet. Try again later or contact the seller.\",\n mixedRecurring:\n \"Subscriptions and one-time products cannot be paid for together. Pay for them in separate orders.\",\n currencyUnsupported:\n \"The shop doesn't accept payments in this currency. Contact the seller.\",\n priceChanged: \"The product price has changed. Refresh the page to see the current price.\",\n close: \"Close cart\",\n remove: \"Remove\",\n quantity: \"Quantity\",\n increaseQuantity: \"Increase quantity\",\n decreaseQuantity: \"Decrease quantity\",\n openCart: \"Open cart\",\n cartItemsCount: \"Items in cart\",\n lowestPrice30Days: \"Lowest price in the last 30 days:\",\n noPriceHistory: \"No price data for the last 30 days\",\n redirectFailed: \"Could not redirect to the payment. Please try again later.\",\n subscriptionUnsupported: \"Subscriptions cannot be added to the cart yet.\",\n searchCountry: \"Find a country\",\n noCountriesFound: \"No countries found\",\n countryRequired: \"Choose a country to continue.\",\n paymentForCart: \"Cart payment\",\n coupon: \"Coupon\",\n extrasCalculatedNext:\n \"Discounts, shipping and taxes are calculated at the next step\",\n loadFailed: \"Could not load your cart.\",\n retry: \"Try again\",\n paymentMethodLegend: \"How would you like to pay?\",\n paymentMethodOnline: \"Pay online\",\n paymentMethodOnlineDescription:\n \"Card, BLIK code or instant bank payment. You pay right away.\",\n paymentMethodManualTransfer: \"Bank transfer\",\n paymentMethodManualBlik: \"BLIK – transfer to a phone number\",\n paymentMethodManualBoth: \"Bank transfer or BLIK to a phone number\",\n paymentMethodManualDescription:\n \"You pay in your bank's app. We show the payment details after you place the order, and the order waits for your payment.\",\n paymentMethodManualBlikNote:\n \"This is not a BLIK code payment – you do not enter a 6‑digit code.\",\n paymentMethodCod: \"Cash on delivery\",\n paymentMethodCodDescription:\n \"You pay the courier in cash or by card when you receive the parcel.\",\n paymentMethodCodUnavailable:\n \"Cash on delivery is not available for this order. Choose another way to pay.\",\n expressPending: \"Confirming your payment…\",\n expressConfirmed: \"Payment confirmed. Thank you!\",\n expressFailed: \"The payment failed. Your cart is unchanged.\",\n expressCancelled: \"Payment cancelled. Your cart is unchanged.\",\n expressPendingLong:\n \"We are still confirming your payment. We will check again when you come back to this page.\",\n expressLoadFailed:\n \"Could not load this payment button. Try again later or use the regular checkout.\",\n expressCartUnavailable:\n \"This cart cannot be paid with this method right now. Try again later.\",\n expressCartConflict:\n \"Your cart changed in another tab or in the provider's app. Review the quantities and try again.\",\n expressPriceChanged:\n \"Your cart total changed. Check the new total and try again.\",\n expressProductUnavailable:\n \"This product cannot be paid for right now. Try again later.\",\n },\n pl: {\n cart: \"Koszyk\",\n emptyCart: \"Brak produktów w koszyku.\",\n total: \"Suma:\",\n delivery: \"+ dostawa\",\n chooseCountry: \"Wybierz kraj\",\n nextStep: \"Następny krok\",\n unavailableProducts: \"Nie wszystkie produkty są dostępne w magazynie.\",\n checkoutFailed: \"Coś poszło nie tak. Spróbuj ponownie później.\",\n noPaymentGateway:\n \"Ten sklep nie przyjmuje jeszcze płatności online. Spróbuj ponownie później lub skontaktuj się ze sprzedawcą.\",\n gatewayNotConfigured:\n \"Płatności w tym sklepie nie są poprawnie skonfigurowane. Spróbuj ponownie później lub skontaktuj się ze sprzedawcą.\",\n shippingNotConfigured:\n \"Dostawa w tym sklepie nie jest jeszcze skonfigurowana. Spróbuj ponownie później lub skontaktuj się ze sprzedawcą.\",\n mixedRecurring:\n \"Subskrypcji i produktów jednorazowych nie można opłacić razem. Opłać je w osobnych zamówieniach.\",\n currencyUnsupported:\n \"Sklep nie przyjmuje płatności w tej walucie. Skontaktuj się ze sprzedawcą.\",\n priceChanged: \"Cena produktu się zmieniła. Odśwież stronę, aby zobaczyć aktualną cenę.\",\n close: \"Zamknij koszyk\",\n remove: \"Usuń\",\n quantity: \"Ilość\",\n increaseQuantity: \"Zwiększ ilość\",\n decreaseQuantity: \"Zmniejsz ilość\",\n openCart: \"Otwórz koszyk\",\n cartItemsCount: \"Produktów w koszyku\",\n lowestPrice30Days: \"Najniższa cena z 30 dni:\",\n noPriceHistory: \"Brak danych o cenie z ostatnich 30 dni\",\n redirectFailed:\n \"Nie udało się przekierować do płatności. Spróbuj ponownie później.\",\n subscriptionUnsupported: \"Subskrypcji nie można jeszcze dodać do koszyka.\",\n searchCountry: \"Znajdź kraj\",\n noCountriesFound: \"Nie znaleziono krajów\",\n countryRequired: \"Wybierz kraj, aby przejść dalej.\",\n paymentForCart: \"Płatność za koszyk\",\n coupon: \"Kupon\",\n extrasCalculatedNext: \"Rabaty, dostawa i podatki w następnym kroku\",\n loadFailed: \"Nie udało się wczytać koszyka.\",\n retry: \"Spróbuj ponownie\",\n paymentMethodLegend: \"Jak chcesz zapłacić?\",\n paymentMethodOnline: \"Zapłać online\",\n paymentMethodOnlineDescription:\n \"Karta, kod BLIK lub szybki przelew. Płacisz od razu.\",\n paymentMethodManualTransfer: \"Przelew bankowy\",\n paymentMethodManualBlik: \"BLIK – przelew na telefon\",\n paymentMethodManualBoth: \"Przelew lub BLIK na telefon\",\n paymentMethodManualDescription:\n \"Zapłacisz w aplikacji swojego banku. Dane do płatności pokażemy po złożeniu zamówienia, a zamówienie poczeka na Twoją wpłatę.\",\n paymentMethodManualBlikNote:\n \"To nie jest płatność kodem BLIK – nie wpisujesz 6‑cyfrowego kodu.\",\n paymentMethodCod: \"Płatność przy odbiorze\",\n paymentMethodCodDescription:\n \"Zapłacisz kurierowi gotówką lub kartą, gdy odbierzesz przesyłkę.\",\n paymentMethodCodUnavailable:\n \"Płatność przy odbiorze nie jest dostępna dla tego zamówienia. Wybierz inną formę płatności.\",\n expressPending: \"Potwierdzamy płatność…\",\n expressConfirmed: \"Płatność potwierdzona. Dziękujemy!\",\n expressFailed: \"Płatność się nie udała. Koszyk pozostał bez zmian.\",\n expressCancelled: \"Płatność została anulowana. Koszyk pozostał bez zmian.\",\n expressPendingLong:\n \"Nadal potwierdzamy Twoją płatność. Sprawdzimy ponownie, gdy wrócisz na tę stronę.\",\n expressLoadFailed:\n \"Nie udało się wczytać przycisku płatności. Spróbuj ponownie później lub skorzystaj ze zwykłego koszyka.\",\n expressCartUnavailable:\n \"Tego koszyka nie można teraz opłacić tą metodą. Spróbuj ponownie później.\",\n expressCartConflict:\n \"Koszyk zmienił się w innej karcie lub w aplikacji przewoźnika. Sprawdź ilości i spróbuj ponownie.\",\n expressPriceChanged:\n \"Suma koszyka się zmieniła. Sprawdź nową sumę i spróbuj ponownie.\",\n expressProductUnavailable:\n \"Nie można teraz zapłacić za ten produkt. Spróbuj ponownie później.\",\n },\n};\n\n/** Default texts for a locale merged with the caller overrides. */\nexport function resolveCheckoutTexts(\n locale: string,\n overrides?: Partial<CheckoutTexts>,\n): CheckoutTexts {\n return resolveTexts(CHECKOUT_TEXT_TABLES, locale, overrides);\n}\n\nexport function getCheckoutText(\n key: CheckoutTextKey,\n locale: string,\n overrides?: Partial<CheckoutTexts>,\n): string {\n return lookupText(resolveCheckoutTexts(locale, overrides), key);\n}\n","import { pickLocaleTable } from \"@/src/lib/texts\";\nimport { CHECKOUT_TEXT_TABLES } from \"./texts\";\n\nexport const DEFAULT_LOCALE = \"pl-PL\" as const;\nconst localeStorageKey = \"bitsnap-locale\";\n\nlet activeLocale: string | undefined;\n\nexport function setLocale(locale?: string): void {\n const value = locale?.trim();\n activeLocale = value\n ? value.toLowerCase() === \"en\"\n ? \"en-US\"\n : value.toLowerCase() === \"pl\"\n ? DEFAULT_LOCALE\n : value\n : undefined;\n if (typeof localStorage !== \"undefined\") {\n if (activeLocale == null) {\n localStorage.removeItem(localeStorageKey);\n } else {\n localStorage.setItem(localeStorageKey, activeLocale);\n }\n }\n}\n\nexport function getLocale(): string {\n if (activeLocale != null) {\n return activeLocale;\n }\n if (typeof localStorage !== \"undefined\") {\n return localStorage.getItem(localeStorageKey) ?? DEFAULT_LOCALE;\n }\n return DEFAULT_LOCALE;\n}\n\nexport function translate(key: string, locale: string = getLocale()): string {\n return (\n (pickLocaleTable(CHECKOUT_TEXT_TABLES, locale) as Record<string, string>)[\n key\n ] ?? key\n );\n}\n"],"mappings":"AAoBO,SAASA,EACdC,EACAC,EACgB,CAChB,OAAOA,EAAO,YAAY,EAAE,WAAW,IAAI,EAAID,EAAO,GAAKA,EAAO,EACpE,CAMO,SAASE,EACdC,EACAC,EACgB,CAChB,IAAMC,EAAiC,CAAE,GAAGF,CAAM,EAElD,GAAIC,GAAa,KACf,OAAW,CAACE,EAAKC,CAAK,IAAK,OAAO,QAA4BH,CAAS,EACjEG,GAAS,OACXF,EAAOC,CAAG,EAAIC,GAKpB,OAAOF,CACT,CAGO,SAASG,EACdR,EACAC,EACAG,EACgB,CAChB,OAAOF,EAAWH,EAAgBC,EAAQC,CAAM,EAAGG,CAAS,CAC9D,CAGO,SAASK,EACdC,EACAJ,EACQ,CACR,OAAQI,EAA6CJ,CAAG,GAAKA,CAC/D,CC6DO,IAAMK,EAAsD,CACjE,GAAI,CACF,KAAM,OACN,UAAW,sBACX,MAAO,SACP,SAAU,aACV,cAAe,mBACf,SAAU,YACV,oBAAqB,kCACrB,eAAgB,gDAChB,iBACE,uFACF,qBACE,yFACF,sBACE,sFACF,eACE,oGACF,oBACE,yEACF,aAAc,4EACd,MAAO,aACP,OAAQ,SACR,SAAU,WACV,iBAAkB,oBAClB,iBAAkB,oBAClB,SAAU,YACV,eAAgB,gBAChB,kBAAmB,oCACnB,eAAgB,qCAChB,eAAgB,6DAChB,wBAAyB,iDACzB,cAAe,iBACf,iBAAkB,qBAClB,gBAAiB,gCACjB,eAAgB,eAChB,OAAQ,SACR,qBACE,gEACF,WAAY,4BACZ,MAAO,YACP,oBAAqB,6BACrB,oBAAqB,aACrB,+BACE,+DACF,4BAA6B,gBAC7B,wBAAyB,yCACzB,wBAAyB,0CACzB,+BACE,2HACF,4BACE,+EACF,iBAAkB,mBAClB,4BACE,sEACF,4BACE,+EACF,eAAgB,gCAChB,iBAAkB,gCAClB,cAAe,8CACf,iBAAkB,6CAClB,mBACE,6FACF,kBACE,mFACF,uBACE,wEACF,oBACE,kGACF,oBACE,8DACF,0BACE,6DACJ,EACA,GAAI,CACF,KAAM,SACN,UAAW,+BACX,MAAO,QACP,SAAU,YACV,cAAe,eACf,SAAU,qBACV,oBAAqB,4DACrB,eAAgB,qEAChB,iBACE,8IACF,qBACE,0JACF,sBACE,yIACF,eACE,kIACF,oBACE,iGACF,aAAc,kHACd,MAAO,iBACP,OAAQ,YACR,SAAU,kBACV,iBAAkB,+BAClB,iBAAkB,2BAClB,SAAU,mBACV,eAAgB,yBAChB,kBAAmB,gCACnB,eAAgB,yCAChB,eACE,yGACF,wBAAyB,4DACzB,cAAe,mBACf,iBAAkB,2BAClB,gBAAiB,6CACjB,eAAgB,oCAChB,OAAQ,QACR,qBAAsB,mDACtB,WAAY,gDACZ,MAAO,sBACP,oBAAqB,iCACrB,oBAAqB,0BACrB,+BACE,4DACF,4BAA6B,kBAC7B,wBAAyB,iCACzB,wBAAyB,8BACzB,+BACE,mLACF,4BACE,6FACF,iBAAkB,wCAClB,4BACE,+FACF,4BACE,yIACF,eAAgB,6CAChB,iBAAkB,yDAClB,cAAe,mFACf,iBAAkB,kFAClB,mBACE,qHACF,kBACE,mJACF,uBACE,gHACF,oBACE,gIACF,oBACE,+FACF,0BACE,8FACJ,CACF,EAGO,SAASC,EACdC,EACAC,EACe,CACf,OAAOC,EAAaJ,EAAsBE,EAAQC,CAAS,CAC7D,CAEO,SAASE,EACdC,EACAJ,EACAC,EACQ,CACR,OAAOI,EAAWN,EAAqBC,EAAQC,CAAS,EAAGG,CAAG,CAChE,CC5RO,IAAME,EAAiB,QACxBC,EAAmB,iBAErBC,EAEG,SAASC,EAAUC,EAAuB,CAC/C,IAAMC,EAAQD,GAAQ,KAAK,EAC3BF,EAAeG,EACXA,EAAM,YAAY,IAAM,KACtB,QACAA,EAAM,YAAY,IAAM,KACtBL,EACAK,EACJ,OACA,OAAO,aAAiB,MACtBH,GAAgB,KAClB,aAAa,WAAWD,CAAgB,EAExC,aAAa,QAAQA,EAAkBC,CAAY,EAGzD,CAEO,SAASI,GAAoB,CAClC,OAAIJ,IAGA,OAAO,aAAiB,IACnB,aAAa,QAAQD,CAAgB,GAAKD,EAE5CA,EACT","names":["pickLocaleTable","tables","locale","mergeTexts","table","overrides","result","key","value","resolveTexts","lookupText","texts","CHECKOUT_TEXT_TABLES","resolveCheckoutTexts","locale","overrides","resolveTexts","getCheckoutText","key","lookupText","DEFAULT_LOCALE","localeStorageKey","activeLocale","setLocale","locale","value","getLocale"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }function l(t,e){return e.toLowerCase().startsWith("en")?t.en:t.pl}function d(t,e){let n={...t};if(e!=null)for(let[c,i]of Object.entries(e))i!=null&&(n[c]=i);return n}function s(t,e,n){return d(l(t,e),n)}function p(t,e){return _nullishCoalesce(t[e], () => (e))}var u={en:{cart:"Cart",emptyCart:"Your cart is empty.",total:"Total:",delivery:"+ delivery",chooseCountry:"Choose a country",nextStep:"Next step",unavailableProducts:"Not all products are available.",checkoutFailed:"Something went wrong. Please try again later.",noPaymentGateway:"This shop doesn't accept online payments yet. Try again later or contact the seller.",gatewayNotConfigured:"Payments in this shop are not set up correctly. Try again later or contact the seller.",shippingNotConfigured:"Delivery in this shop is not configured yet. Try again later or contact the seller.",mixedRecurring:"Subscriptions and one-time products cannot be paid for together. Pay for them in separate orders.",currencyUnsupported:"The shop doesn't accept payments in this currency. Contact the seller.",priceChanged:"The product price has changed. Refresh the page to see the current price.",close:"Close cart",remove:"Remove",quantity:"Quantity",increaseQuantity:"Increase quantity",decreaseQuantity:"Decrease quantity",openCart:"Open cart",cartItemsCount:"Items in cart",lowestPrice30Days:"Lowest price in the last 30 days:",noPriceHistory:"No price data for the last 30 days",redirectFailed:"Could not redirect to the payment. Please try again later.",subscriptionUnsupported:"Subscriptions cannot be added to the cart yet.",searchCountry:"Find a country",noCountriesFound:"No countries found",countryRequired:"Choose a country to continue.",paymentForCart:"Cart payment",coupon:"Coupon",extrasCalculatedNext:"Discounts, shipping and taxes are calculated at the next step",loadFailed:"Could not load your cart.",retry:"Try again",paymentMethodLegend:"How would you like to pay?",paymentMethodOnline:"Pay online",paymentMethodOnlineDescription:"Card, BLIK code or instant bank payment. You pay right away.",paymentMethodManualTransfer:"Bank transfer",paymentMethodManualBlik:"BLIK \u2013 transfer to a phone number",paymentMethodManualBoth:"Bank transfer or BLIK to a phone number",paymentMethodManualDescription:"You pay in your bank's app. We show the payment details after you place the order, and the order waits for your payment.",paymentMethodManualBlikNote:"This is not a BLIK code payment \u2013 you do not enter a 6\u2011digit code.",paymentMethodCod:"Cash on delivery",paymentMethodCodDescription:"You pay the courier in cash or by card when you receive the parcel.",paymentMethodCodUnavailable:"Cash on delivery is not available for this order. Choose another way to pay.",expressPending:"Confirming your payment\u2026",expressConfirmed:"Payment confirmed. Thank you!",expressFailed:"The payment failed. Your cart is unchanged.",expressCancelled:"Payment cancelled. Your cart is unchanged.",expressPendingLong:"We are still confirming your payment. We will check again when you come back to this page.",expressLoadFailed:"Could not load this payment button. Try again later or use the regular checkout.",expressCartUnavailable:"This cart cannot be paid with this method right now. Try again later.",expressCartConflict:"Your cart changed in another tab or in the provider's app. Review the quantities and try again.",expressPriceChanged:"Your cart total changed. Check the new total and try again.",expressProductUnavailable:"This product cannot be paid for right now. Try again later."},pl:{cart:"Koszyk",emptyCart:"Brak produkt\xF3w w koszyku.",total:"Suma:",delivery:"+ dostawa",chooseCountry:"Wybierz kraj",nextStep:"Nast\u0119pny krok",unavailableProducts:"Nie wszystkie produkty s\u0105 dost\u0119pne w magazynie.",checkoutFailed:"Co\u015B posz\u0142o nie tak. Spr\xF3buj ponownie p\xF3\u017Aniej.",noPaymentGateway:"Ten sklep nie przyjmuje jeszcze p\u0142atno\u015Bci online. Spr\xF3buj ponownie p\xF3\u017Aniej lub skontaktuj si\u0119 ze sprzedawc\u0105.",gatewayNotConfigured:"P\u0142atno\u015Bci w tym sklepie nie s\u0105 poprawnie skonfigurowane. Spr\xF3buj ponownie p\xF3\u017Aniej lub skontaktuj si\u0119 ze sprzedawc\u0105.",shippingNotConfigured:"Dostawa w tym sklepie nie jest jeszcze skonfigurowana. Spr\xF3buj ponownie p\xF3\u017Aniej lub skontaktuj si\u0119 ze sprzedawc\u0105.",mixedRecurring:"Subskrypcji i produkt\xF3w jednorazowych nie mo\u017Cna op\u0142aci\u0107 razem. Op\u0142a\u0107 je w osobnych zam\xF3wieniach.",currencyUnsupported:"Sklep nie przyjmuje p\u0142atno\u015Bci w tej walucie. Skontaktuj si\u0119 ze sprzedawc\u0105.",priceChanged:"Cena produktu si\u0119 zmieni\u0142a. Od\u015Bwie\u017C stron\u0119, aby zobaczy\u0107 aktualn\u0105 cen\u0119.",close:"Zamknij koszyk",remove:"Usu\u0144",quantity:"Ilo\u015B\u0107",increaseQuantity:"Zwi\u0119ksz ilo\u015B\u0107",decreaseQuantity:"Zmniejsz ilo\u015B\u0107",openCart:"Otw\xF3rz koszyk",cartItemsCount:"Produkt\xF3w w koszyku",lowestPrice30Days:"Najni\u017Csza cena z 30 dni:",noPriceHistory:"Brak danych o cenie z ostatnich 30 dni",redirectFailed:"Nie uda\u0142o si\u0119 przekierowa\u0107 do p\u0142atno\u015Bci. Spr\xF3buj ponownie p\xF3\u017Aniej.",subscriptionUnsupported:"Subskrypcji nie mo\u017Cna jeszcze doda\u0107 do koszyka.",searchCountry:"Znajd\u017A kraj",noCountriesFound:"Nie znaleziono kraj\xF3w",countryRequired:"Wybierz kraj, aby przej\u015B\u0107 dalej.",paymentForCart:"P\u0142atno\u015B\u0107 za koszyk",coupon:"Kupon",extrasCalculatedNext:"Rabaty, dostawa i podatki w nast\u0119pnym kroku",loadFailed:"Nie uda\u0142o si\u0119 wczyta\u0107 koszyka.",retry:"Spr\xF3buj ponownie",paymentMethodLegend:"Jak chcesz zap\u0142aci\u0107?",paymentMethodOnline:"Zap\u0142a\u0107 online",paymentMethodOnlineDescription:"Karta, kod BLIK lub szybki przelew. P\u0142acisz od razu.",paymentMethodManualTransfer:"Przelew bankowy",paymentMethodManualBlik:"BLIK \u2013 przelew na telefon",paymentMethodManualBoth:"Przelew lub BLIK na telefon",paymentMethodManualDescription:"Zap\u0142acisz w aplikacji swojego banku. Dane do p\u0142atno\u015Bci poka\u017Cemy po z\u0142o\u017Ceniu zam\xF3wienia, a zam\xF3wienie poczeka na Twoj\u0105 wp\u0142at\u0119.",paymentMethodManualBlikNote:"To nie jest p\u0142atno\u015B\u0107 kodem BLIK \u2013 nie wpisujesz 6\u2011cyfrowego kodu.",paymentMethodCod:"P\u0142atno\u015B\u0107 przy odbiorze",paymentMethodCodDescription:"Zap\u0142acisz kurierowi got\xF3wk\u0105 lub kart\u0105, gdy odbierzesz przesy\u0142k\u0119.",paymentMethodCodUnavailable:"P\u0142atno\u015B\u0107 przy odbiorze nie jest dost\u0119pna dla tego zam\xF3wienia. Wybierz inn\u0105 form\u0119 p\u0142atno\u015Bci.",expressPending:"Potwierdzamy p\u0142atno\u015B\u0107\u2026",expressConfirmed:"P\u0142atno\u015B\u0107 potwierdzona. Dzi\u0119kujemy!",expressFailed:"P\u0142atno\u015B\u0107 si\u0119 nie uda\u0142a. Koszyk pozosta\u0142 bez zmian.",expressCancelled:"P\u0142atno\u015B\u0107 zosta\u0142a anulowana. Koszyk pozosta\u0142 bez zmian.",expressPendingLong:"Nadal potwierdzamy Twoj\u0105 p\u0142atno\u015B\u0107. Sprawdzimy ponownie, gdy wr\xF3cisz na t\u0119 stron\u0119.",expressLoadFailed:"Nie uda\u0142o si\u0119 wczyta\u0107 przycisku p\u0142atno\u015Bci. Spr\xF3buj ponownie p\xF3\u017Aniej lub skorzystaj ze zwyk\u0142ego koszyka.",expressCartUnavailable:"Tego koszyka nie mo\u017Cna teraz op\u0142aci\u0107 t\u0105 metod\u0105. Spr\xF3buj ponownie p\xF3\u017Aniej.",expressCartConflict:"Koszyk zmieni\u0142 si\u0119 w innej karcie lub w aplikacji przewo\u017Anika. Sprawd\u017A ilo\u015Bci i spr\xF3buj ponownie.",expressPriceChanged:"Suma koszyka si\u0119 zmieni\u0142a. Sprawd\u017A now\u0105 sum\u0119 i spr\xF3buj ponownie.",expressProductUnavailable:"Nie mo\u017Cna teraz zap\u0142aci\u0107 za ten produkt. Spr\xF3buj ponownie p\xF3\u017Aniej."}};function y(t,e){return s(u,t,e)}function m(t,e,n){return p(y(e,n),t)}var o="pl-PL",r="bitsnap-locale",a;function w(t){let e=_optionalChain([t, 'optionalAccess', _ => _.trim, 'call', _2 => _2()]);a=e?e.toLowerCase()==="en"?"en-US":e.toLowerCase()==="pl"?o:e:void 0,typeof localStorage<"u"&&(a==null?localStorage.removeItem(r):localStorage.setItem(r,a))}function z(){return _nullishCoalesce(a, () => ((typeof localStorage<"u"?_nullishCoalesce(localStorage.getItem(r), () => (o)):o)))}exports.a = l; exports.b = s; exports.c = m; exports.d = o; exports.e = w; exports.f = z;
|
|
2
|
+
//# sourceMappingURL=chunk-Q337IQNA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/texts.ts","../src/components/checkout/texts.ts","../src/components/checkout/locale.ts"],"names":["pickLocaleTable","tables","locale","mergeTexts","table","overrides","result","key","value","resolveTexts","lookupText","texts","CHECKOUT_TEXT_TABLES","resolveCheckoutTexts","getCheckoutText","DEFAULT_LOCALE","localeStorageKey","activeLocale","setLocale","getLocale"],"mappings":"AAoBO,0rBAASA,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACgB,CAChB,OAAOA,CAAAA,CAAO,WAAA,CAAY,CAAA,CAAE,UAAA,CAAW,IAAI,CAAA,CAAID,CAAAA,CAAO,EAAA,CAAKA,CAAAA,CAAO,EACpE,CAMO,SAASE,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACgB,CAChB,IAAMC,CAAAA,CAAiC,CAAE,GAAGF,CAAM,CAAA,CAElD,EAAA,CAAIC,CAAAA,EAAa,IAAA,CACf,GAAA,CAAA,GAAW,CAACE,CAAAA,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Be,CAAAA,CAAeT,CAAAA,CACXA,CAAAA,CAAM,WAAA,CAAY,CAAA,GAAM,IAAA,CACtB,OAAA,CACAA,CAAAA,CAAM,WAAA,CAAY,CAAA,GAAM,IAAA,CACtBO,CAAAA,CACAP,CAAAA,CACJ,KAAA,CAAA,CACA,OAAO,YAAA,CAAiB,GAAA,EAAA,CACtBS,CAAAA,EAAgB,IAAA,CAClB,YAAA,CAAa,UAAA,CAAWD,CAAgB,CAAA,CAExC,YAAA,CAAa,OAAA,CAAQA,CAAAA,CAAkBC,CAAY,CAAA,CAGzD,CAEO,SAASE,CAAAA,CAAAA,CAAoB,CAClC,wBAAIF,CAAAA,SAAAA,CAGA,OAAO,YAAA,CAAiB,GAAA,kBACnB,YAAA,CAAa,OAAA,CAAQD,CAAgB,CAAA,SAAKD,GAAAA,CAE5CA,CAAAA,GACT,CAAA,yFAAA","file":"/home/user/bitsnap-react-payment-release/dist/chunk-Q337IQNA.js","sourcesContent":["/**\n * Shared text machinery: typed string tables per locale, the locale fallback\n * and a merge with caller overrides. Each module (checkout, later returns)\n * supplies its own key type and default tables.\n */\n\n/** Strings of one locale, keyed by text key. */\nexport type TextTable<Key extends string> = Record<Key, string>;\n\n/** Default tables for the supported locales. */\nexport type LocaleTables<Key extends string> = {\n en: TextTable<Key>;\n pl: TextTable<Key>;\n};\n\n/**\n * Picks the table for a locale. Any locale starting with `en` (case\n * insensitive, so `en`, `en-US`, `EN-gb`) gets English; everything else,\n * including unknown locales, gets the Polish default.\n */\nexport function pickLocaleTable<Key extends string>(\n tables: LocaleTables<Key>,\n locale: string,\n): TextTable<Key> {\n return locale.toLowerCase().startsWith(\"en\") ? tables.en : tables.pl;\n}\n\n/**\n * Merges caller overrides over a table. Overrides apply regardless of the\n * locale; `undefined`/`null` entries are ignored so the default stays.\n */\nexport function mergeTexts<Key extends string>(\n table: TextTable<Key>,\n overrides?: Partial<TextTable<Key>>,\n): TextTable<Key> {\n const result: Record<string, string> = { ...table };\n\n if (overrides != null) {\n for (const [key, value] of Object.entries<string | undefined>(overrides)) {\n if (value != null) {\n result[key] = value;\n }\n }\n }\n\n return result as TextTable<Key>;\n}\n\n/** Locale table merged with the caller overrides. */\nexport function resolveTexts<Key extends string>(\n tables: LocaleTables<Key>,\n locale: string,\n overrides?: Partial<TextTable<Key>>,\n): TextTable<Key> {\n return mergeTexts(pickLocaleTable(tables, locale), overrides);\n}\n\n/** Looks up a single text. Unknown keys return the key itself. */\nexport function lookupText<Key extends string>(\n texts: TextTable<Key>,\n key: Key,\n): string {\n return (texts as Record<string, string | undefined>)[key] ?? key;\n}\n","import {\n lookupText,\n resolveTexts,\n type LocaleTables,\n} from \"@/src/lib/texts\";\n\n/**\n * Every string the checkout renders. Pass a partial object through the\n * `texts` prop of `BitsnapCheckout` to override any of them, whatever the\n * locale.\n */\nexport type CheckoutTexts = {\n /** Drawer title. */\n cart: string;\n /** Shown when the cart has no products. */\n emptyCart: string;\n /** Label next to the total price. */\n total: string;\n /** Delivery note next to the total price. */\n delivery: string;\n /** Country selector placeholder. */\n chooseCountry: string;\n /** Checkout button label. */\n nextStep: string;\n /** Error shown when some products are out of stock. */\n unavailableProducts: string;\n /** Error shown when the checkout fails and the server gave no reason. */\n checkoutFailed: string;\n /** Error shown when the shop has no payment gateway connected. */\n noPaymentGateway: string;\n /** Error shown when the payment gateway of the shop is not set up. */\n gatewayNotConfigured: string;\n /** Error shown when delivery of the shop is not set up. */\n shippingNotConfigured: string;\n /** Error shown when the cart mixes subscriptions with one-time products. */\n mixedRecurring: string;\n /** Error shown when the cart currency cannot be paid in. */\n currencyUnsupported: string;\n /** Error shown when a price changed after the product was added. */\n priceChanged: string;\n /** Accessible name of the close button of the drawer. */\n close: string;\n /** Remove button of a cart line (also read together with the product name). */\n remove: string;\n /** Accessible name of the quantity control and its input. */\n quantity: string;\n /** Accessible name of the \"+\" quantity button. */\n increaseQuantity: string;\n /** Accessible name of the \"-\" quantity button. */\n decreaseQuantity: string;\n /** Accessible name of the cart button when it only shows an icon. */\n openCart: string;\n /** Hidden label of the number of products badge; the number is appended after a colon. */\n cartItemsCount: string;\n /** Label before the lowest price of the last 30 days; the price is appended. */\n lowestPrice30Days: string;\n /** Shown instead of the lowest price when the price has no history. */\n noPriceHistory: string;\n /** Error shown when redirecting to the payment failed. */\n redirectFailed: string;\n /** Error shown when a subscription is added to the cart. */\n subscriptionUnsupported: string;\n /** Country search placeholder. */\n searchCountry: string;\n /** Shown when the country search has no match. */\n noCountriesFound: string;\n /** Hint under the checkout button when no country is chosen. */\n countryRequired: string;\n /** Title of the Apple Pay and Google Pay sheet total. */\n paymentForCart: string;\n /** Coupon label in the Google Pay sheet; the code is appended. */\n coupon: string;\n /** Note under the cart total. */\n extrasCalculatedNext: string;\n /** Error shown when the products of the cart could not be loaded. */\n loadFailed: string;\n /** Button that loads the cart again. */\n retry: string;\n /** Heading of the payment method choice (shown only when the shop offers paying by hand). */\n paymentMethodLegend: string;\n /** Option that pays through the shop's online gateway. */\n paymentMethodOnline: string;\n /** Hint under the online option. */\n paymentMethodOnlineDescription: string;\n /** Manual option when the seller takes bank transfers only. */\n paymentMethodManualTransfer: string;\n /** Manual option when the seller takes BLIK transfers to a phone number only. */\n paymentMethodManualBlik: string;\n /** Manual option when the seller takes both. */\n paymentMethodManualBoth: string;\n /** What paying by hand means: the details come after the order is placed. */\n paymentMethodManualDescription: string;\n /** Shown with a selected manual option that includes BLIK to a phone number. */\n paymentMethodManualBlikNote: string;\n /** Cash on delivery option. */\n paymentMethodCod: string;\n /** Hint under the cash on delivery option. */\n paymentMethodCodDescription: string;\n /** Error shown when the shop refused cash on delivery for the order. */\n paymentMethodCodUnavailable: string;\n /** Status while the provider confirms a payment started from an express button. */\n expressPending: string;\n /** Status after the provider confirmed the payment. */\n expressConfirmed: string;\n /** Status when the provider reports a failed payment. */\n expressFailed: string;\n /** Status when the buyer cancelled the provider's payment flow. */\n expressCancelled: string;\n /** Shown while the payment is still unconfirmed after a page return. */\n expressPendingLong: string;\n /** Error shown when the provider's button could not be loaded. */\n expressLoadFailed: string;\n /** Error shown when the cart cannot be paid with this provider right now. */\n expressCartUnavailable: string;\n /** Error shown when another tab/provider changed the same cart line. */\n expressCartConflict: string;\n /** Shown when the server total changed between mounting and paying. */\n expressPriceChanged: string;\n /** Error shown when a product could not be added before the InPost binding. */\n expressProductUnavailable: string;\n};\n\nexport type CheckoutTextKey = keyof CheckoutTexts;\n\nexport const CHECKOUT_TEXT_TABLES: LocaleTables<CheckoutTextKey> = {\n en: {\n cart: \"Cart\",\n emptyCart: \"Your cart is empty.\",\n total: \"Total:\",\n delivery: \"+ delivery\",\n chooseCountry: \"Choose a country\",\n nextStep: \"Next step\",\n unavailableProducts: \"Not all products are available.\",\n checkoutFailed: \"Something went wrong. Please try again later.\",\n noPaymentGateway:\n \"This shop doesn't accept online payments yet. Try again later or contact the seller.\",\n gatewayNotConfigured:\n \"Payments in this shop are not set up correctly. Try again later or contact the seller.\",\n shippingNotConfigured:\n \"Delivery in this shop is not configured yet. Try again later or contact the seller.\",\n mixedRecurring:\n \"Subscriptions and one-time products cannot be paid for together. Pay for them in separate orders.\",\n currencyUnsupported:\n \"The shop doesn't accept payments in this currency. Contact the seller.\",\n priceChanged: \"The product price has changed. Refresh the page to see the current price.\",\n close: \"Close cart\",\n remove: \"Remove\",\n quantity: \"Quantity\",\n increaseQuantity: \"Increase quantity\",\n decreaseQuantity: \"Decrease quantity\",\n openCart: \"Open cart\",\n cartItemsCount: \"Items in cart\",\n lowestPrice30Days: \"Lowest price in the last 30 days:\",\n noPriceHistory: \"No price data for the last 30 days\",\n redirectFailed: \"Could not redirect to the payment. Please try again later.\",\n subscriptionUnsupported: \"Subscriptions cannot be added to the cart yet.\",\n searchCountry: \"Find a country\",\n noCountriesFound: \"No countries found\",\n countryRequired: \"Choose a country to continue.\",\n paymentForCart: \"Cart payment\",\n coupon: \"Coupon\",\n extrasCalculatedNext:\n \"Discounts, shipping and taxes are calculated at the next step\",\n loadFailed: \"Could not load your cart.\",\n retry: \"Try again\",\n paymentMethodLegend: \"How would you like to pay?\",\n paymentMethodOnline: \"Pay online\",\n paymentMethodOnlineDescription:\n \"Card, BLIK code or instant bank payment. You pay right away.\",\n paymentMethodManualTransfer: \"Bank transfer\",\n paymentMethodManualBlik: \"BLIK – transfer to a phone number\",\n paymentMethodManualBoth: \"Bank transfer or BLIK to a phone number\",\n paymentMethodManualDescription:\n \"You pay in your bank's app. We show the payment details after you place the order, and the order waits for your payment.\",\n paymentMethodManualBlikNote:\n \"This is not a BLIK code payment – you do not enter a 6‑digit code.\",\n paymentMethodCod: \"Cash on delivery\",\n paymentMethodCodDescription:\n \"You pay the courier in cash or by card when you receive the parcel.\",\n paymentMethodCodUnavailable:\n \"Cash on delivery is not available for this order. Choose another way to pay.\",\n expressPending: \"Confirming your payment…\",\n expressConfirmed: \"Payment confirmed. Thank you!\",\n expressFailed: \"The payment failed. Your cart is unchanged.\",\n expressCancelled: \"Payment cancelled. Your cart is unchanged.\",\n expressPendingLong:\n \"We are still confirming your payment. We will check again when you come back to this page.\",\n expressLoadFailed:\n \"Could not load this payment button. Try again later or use the regular checkout.\",\n expressCartUnavailable:\n \"This cart cannot be paid with this method right now. Try again later.\",\n expressCartConflict:\n \"Your cart changed in another tab or in the provider's app. Review the quantities and try again.\",\n expressPriceChanged:\n \"Your cart total changed. Check the new total and try again.\",\n expressProductUnavailable:\n \"This product cannot be paid for right now. Try again later.\",\n },\n pl: {\n cart: \"Koszyk\",\n emptyCart: \"Brak produktów w koszyku.\",\n total: \"Suma:\",\n delivery: \"+ dostawa\",\n chooseCountry: \"Wybierz kraj\",\n nextStep: \"Następny krok\",\n unavailableProducts: \"Nie wszystkie produkty są dostępne w magazynie.\",\n checkoutFailed: \"Coś poszło nie tak. Spróbuj ponownie później.\",\n noPaymentGateway:\n \"Ten sklep nie przyjmuje jeszcze płatności online. Spróbuj ponownie później lub skontaktuj się ze sprzedawcą.\",\n gatewayNotConfigured:\n \"Płatności w tym sklepie nie są poprawnie skonfigurowane. Spróbuj ponownie później lub skontaktuj się ze sprzedawcą.\",\n shippingNotConfigured:\n \"Dostawa w tym sklepie nie jest jeszcze skonfigurowana. Spróbuj ponownie później lub skontaktuj się ze sprzedawcą.\",\n mixedRecurring:\n \"Subskrypcji i produktów jednorazowych nie można opłacić razem. Opłać je w osobnych zamówieniach.\",\n currencyUnsupported:\n \"Sklep nie przyjmuje płatności w tej walucie. Skontaktuj się ze sprzedawcą.\",\n priceChanged: \"Cena produktu się zmieniła. Odśwież stronę, aby zobaczyć aktualną cenę.\",\n close: \"Zamknij koszyk\",\n remove: \"Usuń\",\n quantity: \"Ilość\",\n increaseQuantity: \"Zwiększ ilość\",\n decreaseQuantity: \"Zmniejsz ilość\",\n openCart: \"Otwórz koszyk\",\n cartItemsCount: \"Produktów w koszyku\",\n lowestPrice30Days: \"Najniższa cena z 30 dni:\",\n noPriceHistory: \"Brak danych o cenie z ostatnich 30 dni\",\n redirectFailed:\n \"Nie udało się przekierować do płatności. Spróbuj ponownie później.\",\n subscriptionUnsupported: \"Subskrypcji nie można jeszcze dodać do koszyka.\",\n searchCountry: \"Znajdź kraj\",\n noCountriesFound: \"Nie znaleziono krajów\",\n countryRequired: \"Wybierz kraj, aby przejść dalej.\",\n paymentForCart: \"Płatność za koszyk\",\n coupon: \"Kupon\",\n extrasCalculatedNext: \"Rabaty, dostawa i podatki w następnym kroku\",\n loadFailed: \"Nie udało się wczytać koszyka.\",\n retry: \"Spróbuj ponownie\",\n paymentMethodLegend: \"Jak chcesz zapłacić?\",\n paymentMethodOnline: \"Zapłać online\",\n paymentMethodOnlineDescription:\n \"Karta, kod BLIK lub szybki przelew. Płacisz od razu.\",\n paymentMethodManualTransfer: \"Przelew bankowy\",\n paymentMethodManualBlik: \"BLIK – przelew na telefon\",\n paymentMethodManualBoth: \"Przelew lub BLIK na telefon\",\n paymentMethodManualDescription:\n \"Zapłacisz w aplikacji swojego banku. Dane do płatności pokażemy po złożeniu zamówienia, a zamówienie poczeka na Twoją wpłatę.\",\n paymentMethodManualBlikNote:\n \"To nie jest płatność kodem BLIK – nie wpisujesz 6‑cyfrowego kodu.\",\n paymentMethodCod: \"Płatność przy odbiorze\",\n paymentMethodCodDescription:\n \"Zapłacisz kurierowi gotówką lub kartą, gdy odbierzesz przesyłkę.\",\n paymentMethodCodUnavailable:\n \"Płatność przy odbiorze nie jest dostępna dla tego zamówienia. Wybierz inną formę płatności.\",\n expressPending: \"Potwierdzamy płatność…\",\n expressConfirmed: \"Płatność potwierdzona. Dziękujemy!\",\n expressFailed: \"Płatność się nie udała. Koszyk pozostał bez zmian.\",\n expressCancelled: \"Płatność została anulowana. Koszyk pozostał bez zmian.\",\n expressPendingLong:\n \"Nadal potwierdzamy Twoją płatność. Sprawdzimy ponownie, gdy wrócisz na tę stronę.\",\n expressLoadFailed:\n \"Nie udało się wczytać przycisku płatności. Spróbuj ponownie później lub skorzystaj ze zwykłego koszyka.\",\n expressCartUnavailable:\n \"Tego koszyka nie można teraz opłacić tą metodą. Spróbuj ponownie później.\",\n expressCartConflict:\n \"Koszyk zmienił się w innej karcie lub w aplikacji przewoźnika. Sprawdź ilości i spróbuj ponownie.\",\n expressPriceChanged:\n \"Suma koszyka się zmieniła. Sprawdź nową sumę i spróbuj ponownie.\",\n expressProductUnavailable:\n \"Nie można teraz zapłacić za ten produkt. Spróbuj ponownie później.\",\n },\n};\n\n/** Default texts for a locale merged with the caller overrides. */\nexport function resolveCheckoutTexts(\n locale: string,\n overrides?: Partial<CheckoutTexts>,\n): CheckoutTexts {\n return resolveTexts(CHECKOUT_TEXT_TABLES, locale, overrides);\n}\n\nexport function getCheckoutText(\n key: CheckoutTextKey,\n locale: string,\n overrides?: Partial<CheckoutTexts>,\n): string {\n return lookupText(resolveCheckoutTexts(locale, overrides), key);\n}\n","import { pickLocaleTable } from \"@/src/lib/texts\";\nimport { CHECKOUT_TEXT_TABLES } from \"./texts\";\n\nexport const DEFAULT_LOCALE = \"pl-PL\" as const;\nconst localeStorageKey = \"bitsnap-locale\";\n\nlet activeLocale: string | undefined;\n\nexport function setLocale(locale?: string): void {\n const value = locale?.trim();\n activeLocale = value\n ? value.toLowerCase() === \"en\"\n ? \"en-US\"\n : value.toLowerCase() === \"pl\"\n ? DEFAULT_LOCALE\n : value\n : undefined;\n if (typeof localStorage !== \"undefined\") {\n if (activeLocale == null) {\n localStorage.removeItem(localeStorageKey);\n } else {\n localStorage.setItem(localeStorageKey, activeLocale);\n }\n }\n}\n\nexport function getLocale(): string {\n if (activeLocale != null) {\n return activeLocale;\n }\n if (typeof localStorage !== \"undefined\") {\n return localStorage.getItem(localeStorageKey) ?? DEFAULT_LOCALE;\n }\n return DEFAULT_LOCALE;\n}\n\nexport function translate(key: string, locale: string = getLocale()): string {\n return (\n (pickLocaleTable(CHECKOUT_TEXT_TABLES, locale) as Record<string, string>)[\n key\n ] ?? key\n );\n}\n"]}
|
|
@@ -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-ZKT4N553.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-UTUPPMLK.mjs.map
|