bitsnap-react 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +40 -3
  2. package/dist/CartProvider-F7ER3WSS.js +2 -0
  3. package/dist/CartProvider-F7ER3WSS.js.map +1 -0
  4. package/dist/CartProvider-N73XNL7S.mjs +2 -0
  5. package/dist/analytics.js +1 -1
  6. package/dist/analytics.js.map +1 -1
  7. package/dist/analytics.mjs +1 -1
  8. package/dist/catalog.js +1 -1
  9. package/dist/catalog.js.map +1 -1
  10. package/dist/catalog.mjs +1 -1
  11. package/dist/{chunk-ICFYSZTV.js → chunk-3A4YOO7Z.js} +2 -2
  12. package/dist/chunk-3A4YOO7Z.js.map +1 -0
  13. package/dist/{chunk-UCESDAEC.mjs → chunk-3DGHF373.mjs} +2 -2
  14. package/dist/chunk-5GMWRCHK.mjs +4 -0
  15. package/dist/chunk-5GMWRCHK.mjs.map +1 -0
  16. package/dist/{chunk-MLSKHOA3.js → chunk-6CUCRTIK.js} +2 -2
  17. package/dist/chunk-6CUCRTIK.js.map +1 -0
  18. package/dist/{chunk-DGUIG334.js → chunk-EWLOGFF2.js} +2 -2
  19. package/dist/chunk-EWLOGFF2.js.map +1 -0
  20. package/dist/chunk-GAVLY6RX.mjs +2 -0
  21. package/dist/chunk-GAVLY6RX.mjs.map +1 -0
  22. package/dist/{chunk-XTIY6PXH.js → chunk-IP4OOWZ6.js} +2 -2
  23. package/dist/chunk-IP4OOWZ6.js.map +1 -0
  24. package/dist/chunk-JSDGZ4NY.js.map +1 -1
  25. package/dist/{chunk-3QG7H2AI.mjs → chunk-K2EITRNW.mjs} +2 -2
  26. package/dist/{chunk-5R3WR22A.mjs → chunk-KH7DFTJY.mjs} +2 -2
  27. package/dist/chunk-KOYBZORL.js.map +1 -1
  28. package/dist/{chunk-E5DCEFI2.mjs → chunk-L6J6H73J.mjs} +2 -2
  29. package/dist/chunk-M4KEUK6I.js +2 -0
  30. package/dist/chunk-M4KEUK6I.js.map +1 -0
  31. package/dist/{chunk-QSIKRVZL.mjs → chunk-OC7YS3UY.mjs} +2 -2
  32. package/dist/chunk-TMBC2BHN.js +4 -0
  33. package/dist/chunk-TMBC2BHN.js.map +1 -0
  34. package/dist/{chunk-DF2IK2GN.js → chunk-TSJCVFOX.js} +2 -2
  35. package/dist/chunk-TSJCVFOX.js.map +1 -0
  36. package/dist/{chunk-6IACFTJR.js → chunk-UFQVOGBS.js} +2 -2
  37. package/dist/chunk-UFQVOGBS.js.map +1 -0
  38. package/dist/chunk-XIHGWNTS.js.map +1 -1
  39. package/dist/{chunk-FF2ICGFQ.mjs → chunk-YNGXQJPE.mjs} +2 -2
  40. package/dist/{chunk-FF2ICGFQ.mjs.map → chunk-YNGXQJPE.mjs.map} +1 -1
  41. package/dist/consent.js.map +1 -1
  42. package/dist/course.js +1 -1
  43. package/dist/course.js.map +1 -1
  44. package/dist/course.mjs +1 -1
  45. package/dist/embed/analytics.js +1 -1
  46. package/dist/errors.js.map +1 -1
  47. package/dist/index.css +1 -1
  48. package/dist/index.css.map +1 -1
  49. package/dist/index.d.mts +59 -2
  50. package/dist/index.d.ts +59 -2
  51. package/dist/index.js +1 -1
  52. package/dist/index.js.map +1 -1
  53. package/dist/index.mjs +1 -1
  54. package/dist/index.mjs.map +1 -1
  55. package/dist/internal.js.map +1 -1
  56. package/dist/methods-ADH5XI4I.js +2 -0
  57. package/dist/methods-ADH5XI4I.js.map +1 -0
  58. package/dist/methods-BCR54EWX.mjs +2 -0
  59. package/dist/models.js.map +1 -1
  60. package/dist/returns.js +1 -1
  61. package/dist/returns.js.map +1 -1
  62. package/dist/returns.mjs +1 -1
  63. package/package.json +26 -51
  64. package/dist/CartProvider-XNFSUOCB.js +0 -2
  65. package/dist/CartProvider-XNFSUOCB.js.map +0 -1
  66. package/dist/CartProvider-YMJ7RFO4.mjs +0 -2
  67. package/dist/chunk-4BW6J7FP.js +0 -4
  68. package/dist/chunk-4BW6J7FP.js.map +0 -1
  69. package/dist/chunk-6IACFTJR.js.map +0 -1
  70. package/dist/chunk-DF2IK2GN.js.map +0 -1
  71. package/dist/chunk-DGUIG334.js.map +0 -1
  72. package/dist/chunk-ERL4Z7M7.js +0 -2
  73. package/dist/chunk-ERL4Z7M7.js.map +0 -1
  74. package/dist/chunk-ICFYSZTV.js.map +0 -1
  75. package/dist/chunk-MLSKHOA3.js.map +0 -1
  76. package/dist/chunk-P4Q5KXKS.mjs +0 -2
  77. package/dist/chunk-P4Q5KXKS.mjs.map +0 -1
  78. package/dist/chunk-PNTO3L2C.mjs +0 -4
  79. package/dist/chunk-PNTO3L2C.mjs.map +0 -1
  80. package/dist/chunk-XTIY6PXH.js.map +0 -1
  81. package/dist/methods-DDGOXLP6.mjs +0 -2
  82. package/dist/methods-RQPDIUUN.js +0 -2
  83. package/dist/methods-RQPDIUUN.js.map +0 -1
  84. /package/dist/{CartProvider-YMJ7RFO4.mjs.map → CartProvider-N73XNL7S.mjs.map} +0 -0
  85. /package/dist/{chunk-UCESDAEC.mjs.map → chunk-3DGHF373.mjs.map} +0 -0
  86. /package/dist/{chunk-3QG7H2AI.mjs.map → chunk-K2EITRNW.mjs.map} +0 -0
  87. /package/dist/{chunk-5R3WR22A.mjs.map → chunk-KH7DFTJY.mjs.map} +0 -0
  88. /package/dist/{chunk-E5DCEFI2.mjs.map → chunk-L6J6H73J.mjs.map} +0 -0
  89. /package/dist/{chunk-QSIKRVZL.mjs.map → chunk-OC7YS3UY.mjs.map} +0 -0
  90. /package/dist/{methods-DDGOXLP6.mjs.map → methods-BCR54EWX.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.12.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,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,CACjB,CAKO,SAASwC,GAAYC,EAA+D,CACzF,IAAM1B,EAAQ,OAAO,SAAS0B,CAAO,EAAI,KAAK,IAAI,EAAG,KAAK,IAAI,IAAKA,CAAO,CAAC,EAAI,EAC/E,OAAI1B,GAAS,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.13.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,C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EAAQ,OAAO,SAAS0B,CAAO,EAAI,KAAK,IAAI,EAAG,KAAK,IAAI,IAAKA,CAAO,CAAC,EAAI,EAC/E,OAAI1B,GAAS,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 +1 @@
1
- {"version":3,"sources":["/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/consent.js","../src/consent/react.tsx","../src/consent/core/types.ts","../src/consent/core/activate.ts","../src/consent/core/config.ts","../src/consent/core/styles.ts","../src/consent/core/ui.ts"],"names":["CONSENT_CATEGORIES","SCRIPT_SELECTOR","FRAME_SELECTOR","allowed","c","category","settled","script","resolve","run","doc","placeholder","name","value","external","loaded","activateScripts","activated","gate","loading","inline","frame","src","DEFAULT_API_HOST","DEFAULT_COLLECT_HOST","defaultConfig","THEMES","POSITIONS","HEX_COLOR","safeColor","safeUrl","url","cleanServices","services","item","cookie","mergeConfig","layers","result","layer","accent","privacy","fetchRemoteConfig","apiHost","key","timeoutMs","controller","timer","response"],"mappings":"AAAA,uuBAA+F,+BAA4B,8BCAjE,ICU7CA,CAAAA,CAAiD,CAC5D,WAAA,CACA,WAAA,CACA,aACF,CAAA,CCZA,IAAMC,EAAAA,CAAkB,4EAAA,CAClBC,EAAAA,CAAiB,wCAAA,CAEjBC,EAAAA,CAAU,CAACC,CAAAA,CAAmBC,CAAAA,CAAAA,EACjCL,CAAAA,CAAyC,QAAA,kBAASK,CAAAA,SAAY,IAAE,CAAA,EACjED,CAAAA,CAAEC,CAAgC,CAAA,CAGpC,SAASC,EAAAA,CAAQC,CAAAA,CAA0C,CACzD,OAAO,IAAI,OAAA,CAASC,CAAAA,EAAY,CAC9BD,CAAAA,CAAO,gBAAA,CAAiB,MAAA,CAAQ,CAAA,CAAA,EAAMC,CAAAA,CAAQ,CAAA,CAAG,CAAE,IAAA,CAAM,CAAA,CAAK,CAAC,CAAA,CAC/DD,CAAAA,CAAO,gBAAA,CAAiB,OAAA,CAAS,CAAA,CAAA,EAAMC,CAAAA,CAAQ,CAAA,CAAG,CAAE,IAAA,CAAM,CAAA,CAAK,CAAC,CAClE,CAAC,CACH,CAGA,SAASC,EAAAA,CAAIC,CAAAA,CAAeC,CAAAA,CAA2D,CACrF,IAAMJ,CAAAA,CAASG,CAAAA,CAAI,aAAA,CAAc,QAAQ,CAAA,CACzC,GAAA,CAAA,GAAW,CAAE,IAAA,CAAAE,CAAAA,CAAM,KAAA,CAAAC,CAAM,CAAA,GAAK,KAAA,CAAM,IAAA,CAAKF,CAAAA,CAAY,UAAU,CAAA,CACzDC,CAAAA,GAAS,MAAA,EAAUA,CAAAA,GAAS,qBAAA,EAAA,CAC5BA,CAAAA,GAAS,WAAA,CAEPC,CAAAA,GAAU,QAAA,EAAU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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACqKV","file":"/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/consent.js","sourcesContent":[null,"import { useCallback, useRef, useSyncExternalStore } from \"react\";\nimport { useIsomorphicLayoutEffect } from \"../lib/isomorphic-layout-effect\";\nimport { createConsent } from \"./core/controller\";\nimport type {\n BitsnapConsentApi,\n ConsentChoices,\n ConsentConfig,\n ConsentOptions,\n ConsentState,\n} from \"./core/types\";\n\ndeclare global {\n interface Window {\n BitsnapConsent?: BitsnapConsentApi;\n }\n}\n\nexport type BitsnapConsentProps = {\n /** Public project key: loads the project's banner config and logs choices. */\n projectKey?: string;\n theme?: ConsentOptions[\"theme\"];\n locale?: ConsentOptions[\"locale\"];\n position?: ConsentOptions[\"position\"];\n privacyPolicyUrl?: string;\n /** `project` keeps the consent cookie per project key. */\n scope?: ConsentOptions[\"scope\"];\n apiHost?: string;\n collectHost?: string;\n /** Local config, merged over the project config. */\n config?: Partial<ConsentConfig>;\n reloadOnWithdraw?: boolean;\n /** Google Consent Mode v2: `auto` (default) is on when `gtag` or `dataLayer` already exist. */\n gcm?: ConsentOptions[\"gcm\"];\n /** Categories offered when no remote config is loaded. */\n categories?: ConsentOptions[\"categories\"];\n /** Dashboard preview: shows the banner from the local options only; touches no cookie. */\n preview?: boolean;\n /** Replaces the banner title. */\n title?: string;\n /** Replaces the banner description. */\n description?: string;\n};\n\n/** Mounts Bitsnap Consent on the page. Renders nothing itself (the banner lives in a Shadow DOM). */\nexport function BitsnapConsent(props: BitsnapConsentProps): null {\n const {\n projectKey, theme, locale, position, privacyPolicyUrl, scope, apiHost, collectHost, reloadOnWithdraw,\n gcm, preview, title, description,\n } = props;\n const configKey = JSON.stringify(props.config ?? null);\n const configRef = useRef(props.config);\n configRef.current = props.config;\n const categoriesKey = JSON.stringify(props.categories ?? null);\n const categoriesRef = useRef(props.categories);\n categoriesRef.current = props.categories;\n\n // A layout effect: the page's passive effects (first events, tracker) must find the API already there.\n useIsomorphicLayoutEffect(() => {\n // A banner from the script tag or another instance already runs on this page.\n if (window.BitsnapConsent) return;\n const api = createConsent({\n projectKey,\n theme,\n locale,\n position,\n privacyPolicyUrl,\n scope,\n apiHost,\n collectHost,\n reloadOnWithdraw,\n gcm,\n preview,\n title,\n description,\n categories: categoriesRef.current,\n config: configRef.current,\n });\n window.BitsnapConsent = api;\n return () => {\n api.destroy();\n if (window.BitsnapConsent === api) delete window.BitsnapConsent;\n };\n }, [\n projectKey, theme, locale, position, privacyPolicyUrl, scope, apiHost, collectHost, reloadOnWithdraw,\n gcm, preview, title, description, categoriesKey, configKey,\n ]);\n\n return null;\n}\n\nlet lastKey = \"null\";\nlet lastState: ConsentState | null = null;\n\nfunction getSnapshot(): ConsentState | null {\n const current = typeof window === \"undefined\" ? null : (window.BitsnapConsent?.get() ?? null);\n const key = JSON.stringify(current);\n if (key !== lastKey) {\n lastKey = key;\n lastState = current;\n }\n return lastState;\n}\n\nfunction subscribe(onChange: () => void): () => void {\n window.addEventListener(\"bitsnap:consent\", onChange);\n window.addEventListener(\"bitsnap:consent:ready\", onChange);\n return () => {\n window.removeEventListener(\"bitsnap:consent\", onChange);\n window.removeEventListener(\"bitsnap:consent:ready\", onChange);\n };\n}\n\nexport type UseConsent = {\n /** The stored choice, or `null` while there is none (or on the server). */\n consent: ConsentState | null;\n /** `true` once the visitor has made a choice that is still valid. */\n decided: boolean;\n open: () => void;\n accept: (categories?: Partial<ConsentChoices>) => void;\n acceptAll: () => void;\n rejectAll: () => void;\n reset: () => void;\n};\n\n/** Current consent state of the page, kept up to date as the visitor chooses. */\nexport function useConsent(): UseConsent {\n const consent = useSyncExternalStore(subscribe, getSnapshot, () => null);\n const open = useCallback(() => window.BitsnapConsent?.open(), []);\n const accept = useCallback((categories?: Partial<ConsentChoices>) => window.BitsnapConsent?.accept(categories), []);\n const acceptAll = useCallback(() => window.BitsnapConsent?.acceptAll(), []);\n const rejectAll = useCallback(() => window.BitsnapConsent?.rejectAll(), []);\n const reset = useCallback(() => window.BitsnapConsent?.reset(), []);\n return { consent, decided: consent !== null, open, accept, acceptAll, rejectAll, reset };\n}\n","export type ConsentCategory = \"analytics\" | \"marketing\" | \"preferences\";\n\nexport type ConsentChoices = Record<ConsentCategory, boolean>;\n\nexport type ConsentTheme = \"auto\" | \"light\" | \"dark\";\n\nexport type ConsentPosition = \"bottom\" | \"bottom-left\" | \"bottom-right\";\n\nexport type ConsentLocale = \"pl\" | \"en\";\n\nexport const CONSENT_CATEGORIES: readonly ConsentCategory[] = [\n \"analytics\",\n \"marketing\",\n \"preferences\",\n];\n\nexport const CONSENT_TEXT_KEYS = [\n \"title\",\n \"description\",\n \"acceptAll\",\n \"rejectAll\",\n \"settings\",\n \"save\",\n \"close\",\n \"necessaryTitle\",\n \"necessaryDescription\",\n \"analyticsTitle\",\n \"analyticsDescription\",\n \"marketingTitle\",\n \"marketingDescription\",\n \"preferencesTitle\",\n \"preferencesDescription\",\n \"poweredBy\",\n] as const;\n\nexport type ConsentTexts = Record<(typeof CONSENT_TEXT_KEYS)[number], string>;\n\nexport type ConsentService = {\n name: string;\n category: ConsentCategory;\n /** Cookies to delete (best effort) when the category is withdrawn. A trailing `*` matches a prefix. */\n cookies?: string[];\n};\n\nexport type ConsentConfig = {\n /** Banner version. A stored choice with a lower `bv` makes the banner ask again. */\n version: number;\n theme: ConsentTheme;\n accentColor?: string;\n position: ConsentPosition;\n privacyPolicyUrl?: string;\n categories: ConsentChoices;\n services: ConsentService[];\n texts?: Partial<Record<ConsentLocale, Partial<ConsentTexts>>>;\n poweredBy: true;\n};\n\n/** What the consent cookie holds, and what `get()` returns. */\nexport type ConsentState = {\n id: string;\n /** Unix seconds. */\n ts: number;\n /** Version of the banner the choice was made on. */\n bv: number;\n c: ConsentChoices;\n};\n\nexport type ConsentAction =\n | \"accept_all\"\n | \"reject_all\"\n | \"custom\"\n | \"withdraw\";\n\n/** `detail` of `bitsnap:consent` and the argument of `on('change')`. */\nexport type ConsentChangeDetail = ConsentState & {\n /** `reset` when the visitor's stored choice was cleared (`get()` is `null` then). */\n action: ConsentAction | \"reset\";\n};\n\nexport type ConsentOptions = {\n /** Public project key. Enables the remote config and the consent log. */\n projectKey?: string;\n theme?: ConsentTheme;\n locale?: \"auto\" | ConsentLocale;\n position?: ConsentPosition;\n privacyPolicyUrl?: string;\n /** `project` keeps one cookie per project key (`bitsnap_consent_<key>`). */\n scope?: \"global\" | \"project\";\n apiHost?: string;\n collectHost?: string;\n /** Google Consent Mode v2. `auto` is on when `gtag` or `dataLayer` already exist. */\n gcm?: \"auto\" | \"on\" | \"off\";\n /** Local overrides, merged over the defaults and the remote config. */\n config?: Partial<ConsentConfig>;\n /** Categories used when no remote config is loaded. */\n categories?: Partial<ConsentChoices>;\n reloadOnWithdraw?: boolean;\n /**\n * Dashboard preview: shows the banner at once from the local options, never\n * reads or writes the cookie, loads no remote config, sends no consent log,\n * and the buttons only close the banner.\n */\n preview?: boolean;\n /** Replaces the banner title (current locale, non-empty values only). */\n title?: string;\n /** Replaces the banner description (current locale, non-empty values only). */\n description?: string;\n};\n\nexport type BitsnapConsentApi = {\n /**\n * Whose choice this banner holds: `project` keeps one cookie per project key\n * (`bitsnap_consent_<key>`), `global` the site-wide `bitsnap_consent`.\n */\n readonly scope: \"global\" | \"project\";\n /** The bare public project key the banner was started with, if any (`pk_` stripped). */\n readonly projectKey: string | null;\n get(): ConsentState | null;\n /**\n * `true` when the visitor refused `category`, also in a choice made on an older banner\n * version (which `get()` no longer returns) that they have not answered again yet.\n */\n denied(category: ConsentCategory): boolean;\n on(event: \"change\", fn: (detail: ConsentChangeDetail) => void): () => void;\n open(): void;\n close(): void;\n accept(categories?: Partial<ConsentChoices>): void;\n acceptAll(): void;\n rejectAll(): void;\n reset(): void;\n /** Resolves with the stored choice (or `null`) once config and stored choice are applied. */\n ready: Promise<ConsentState | null>;\n destroy(): void;\n};\n","import { CONSENT_CATEGORIES, type ConsentChoices } from \"./types\";\n\nconst SCRIPT_SELECTOR = 'script[type=\"text/plain\"][data-bitsnap-consent]:not([data-bitsnap-queued])';\nconst FRAME_SELECTOR = \"iframe[data-bitsnap-consent][data-src]\";\n\nconst allowed = (c: ConsentChoices, category: string | null): boolean =>\n (CONSENT_CATEGORIES as readonly string[]).includes(category ?? \"\") &&\n c[category as keyof ConsentChoices];\n\n/** Settles when the script has loaded or failed: a broken script must not block the ones after it. */\nfunction settled(script: HTMLScriptElement): Promise<void> {\n return new Promise((resolve) => {\n script.addEventListener(\"load\", () => resolve(), { once: true });\n script.addEventListener(\"error\", () => resolve(), { once: true });\n });\n}\n\n/** Swaps the placeholder for a live script; resolves once an external one has loaded. */\nfunction run(doc: Document, placeholder: HTMLScriptElement): Promise<void> | undefined {\n const script = doc.createElement(\"script\");\n for (const { name, value } of Array.from(placeholder.attributes)) {\n if (name === \"type\" || name === \"data-bitsnap-queued\") continue;\n if (name === \"data-type\") {\n // The embed writes the original `type=\"module\"` here, as `type` itself is `text/plain`.\n if (value === \"module\") script.setAttribute(\"type\", \"module\");\n } else if (name === \"data-src\") script.setAttribute(\"src\", value);\n else script.setAttribute(name, value);\n }\n if (placeholder.nonce) script.nonce = placeholder.nonce;\n const external = script.hasAttribute(\"src\");\n if (external) {\n // Dynamic scripts are async by default; keep the order of the page.\n if (!placeholder.hasAttribute(\"async\")) script.async = false;\n } else {\n script.text = placeholder.text;\n }\n const loaded = external ? settled(script) : undefined;\n placeholder.parentNode?.replaceChild(script, placeholder);\n return loaded;\n}\n\n/**\n * Turns the consented placeholders into live elements:\n * `<script type=\"text/plain\" data-bitsnap-consent=\"marketing\" [data-src] [data-type=\"module\"]>` becomes\n * a real script (attributes copied, `type` dropped or restored from `data-type`, `data-src` -> `src`),\n * and `<iframe data-src>` gets its `src`.\n * Placeholders run in document order: an inline script waits for the external scripts before it\n * (`<script src=lib.js>` then `<script>Lib.init()</script>`), external ones only follow each other.\n */\nexport function activateScripts(doc: Document, c: ConsentChoices): number {\n let activated = 0;\n try {\n /** Set once a placeholder had to wait: everything after it queues behind it. */\n let gate: Promise<void> | null = null;\n /** External scripts inserted since the last inline one. */\n let loading: Promise<void>[] = [];\n doc.querySelectorAll<HTMLScriptElement>(SCRIPT_SELECTOR).forEach((placeholder) => {\n if (!allowed(c, placeholder.getAttribute(\"data-bitsnap-consent\"))) return;\n activated++;\n const inline = !placeholder.hasAttribute(\"data-src\") && !placeholder.hasAttribute(\"src\");\n if (gate || (inline && loading.length > 0)) {\n // Marked so that another call (a later choice) does not queue it again.\n placeholder.setAttribute(\"data-bitsnap-queued\", \"\");\n gate = (gate ?? Promise.all(loading).then(() => {})).then(() => {\n try {\n return run(doc, placeholder);\n } catch {\n // never throw into the host page\n }\n });\n loading = [];\n return;\n }\n const loaded = run(doc, placeholder);\n if (loaded) loading.push(loaded);\n });\n doc.querySelectorAll<HTMLIFrameElement>(FRAME_SELECTOR).forEach((frame) => {\n if (!allowed(c, frame.getAttribute(\"data-bitsnap-consent\"))) return;\n const src = frame.getAttribute(\"data-src\");\n if (src && frame.getAttribute(\"src\") !== src) {\n frame.setAttribute(\"src\", src);\n frame.removeAttribute(\"data-src\");\n activated++;\n }\n });\n } catch {\n // never throw into the host page\n }\n return activated;\n}\n","import {\n CONSENT_CATEGORIES,\n type ConsentChoices,\n type ConsentConfig,\n type ConsentService,\n} from \"./types\";\n\nexport const DEFAULT_API_HOST = \"https://bitsnap.pl\";\nexport const DEFAULT_COLLECT_HOST = \"https://collect.bitsnap.pl\";\n\nexport function defaultConfig(): ConsentConfig {\n return {\n version: 1,\n theme: \"auto\",\n position: \"bottom\",\n categories: { analytics: true, marketing: true, preferences: false },\n services: [],\n poweredBy: true,\n };\n}\n\nconst THEMES = [\"auto\", \"light\", \"dark\"];\nconst POSITIONS = [\"bottom\", \"bottom-left\", \"bottom-right\"];\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\n\nexport function safeColor(value: unknown): string | undefined {\n return typeof value === \"string\" && HEX_COLOR.test(value.trim())\n ? value.trim()\n : undefined;\n}\n\n/** Only http(s) and relative URLs may end up in the banner. */\nexport function safeUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const url = value.trim();\n return /^(?:https?:\\/\\/|\\/(?!\\/)|#|\\?)/i.test(url) ? url : undefined;\n}\n\nfunction cleanServices(value: unknown): ConsentService[] {\n if (!Array.isArray(value)) return [];\n const services: ConsentService[] = [];\n for (const item of value) {\n if (\n item &&\n typeof item.name === \"string\" &&\n (CONSENT_CATEGORIES as readonly string[]).includes(item.category)\n ) {\n services.push({\n name: item.name,\n category: item.category,\n cookies: Array.isArray(item.cookies)\n ? item.cookies.filter((cookie: unknown) => typeof cookie === \"string\")\n : undefined,\n });\n }\n }\n return services;\n}\n\n/** Layers partial configs (later wins) over the defaults, dropping invalid values. */\nexport function mergeConfig(\n ...layers: (Partial<ConsentConfig> | null | undefined)[]\n): ConsentConfig {\n const result = defaultConfig();\n for (const layer of layers) {\n if (!layer || typeof layer !== \"object\") continue;\n if (typeof layer.version === \"number\" && layer.version >= 0) {\n result.version = Math.floor(layer.version);\n }\n if (THEMES.includes(layer.theme as string)) result.theme = layer.theme!;\n if (POSITIONS.includes(layer.position as string)) result.position = layer.position!;\n const accent = safeColor(layer.accentColor);\n if (accent) result.accentColor = accent;\n const privacy = safeUrl(layer.privacyPolicyUrl);\n if (privacy) result.privacyPolicyUrl = privacy;\n if (layer.categories && typeof layer.categories === \"object\") {\n for (const category of CONSENT_CATEGORIES) {\n if (typeof layer.categories[category] === \"boolean\") {\n result.categories[category] = layer.categories[category];\n }\n }\n }\n if (layer.services !== undefined) result.services = cleanServices(layer.services);\n if (layer.texts && typeof layer.texts === \"object\") result.texts = layer.texts;\n }\n return result;\n}\n\nexport function parseCategoryList(value: string | null | undefined): ConsentChoices {\n const wanted = (value ?? \"\").split(\",\").map((item) => item.trim());\n return {\n analytics: wanted.includes(\"analytics\"),\n marketing: wanted.includes(\"marketing\"),\n preferences: wanted.includes(\"preferences\"),\n };\n}\n\n/** What `GET /api/consent/config` answers: whether the banner is on, and its config. */\nexport type RemoteConsentConfig = {\n /** `false` when the project turned the banner off: nothing is shown, stored choices still apply. */\n enabled: boolean;\n config: Partial<ConsentConfig> | null;\n};\n\n/** Loads the project's banner config. Resolves to `null` on any failure or after the timeout. */\nexport async function fetchRemoteConfig(\n apiHost: string,\n key: string,\n timeoutMs = 3000,\n): Promise<RemoteConsentConfig | null> {\n if (typeof fetch !== \"function\") return null;\n const controller = typeof AbortController === \"function\" ? new AbortController() : undefined;\n const timer = setTimeout(() => controller?.abort(), timeoutMs);\n try {\n const response = await fetch(\n `${apiHost.replace(/\\/+$/, \"\")}/api/consent/config?key=${encodeURIComponent(key)}`,\n { signal: controller?.signal, credentials: \"omit\" },\n );\n if (!response.ok) return null;\n const body = await response.json();\n if (!body || typeof body !== \"object\") return null;\n const config = body.config && typeof body.config === \"object\" ? body.config : null;\n const enabled = body.enabled !== false;\n return config || !enabled ? { enabled, config } : null;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n","/** Colors of both themes. Every text/background pair is checked against WCAG AA in the tests. */\nexport const PALETTE = {\n light: {\n bg: \"#ffffff\",\n fg: \"#14171c\",\n muted: \"#495260\",\n border: \"#c9ced6\",\n off: \"#6b7280\",\n thumb: \"#ffffff\",\n accent: \"#1d4ed8\",\n onAccent: \"#ffffff\",\n link: \"#1d4ed8\",\n },\n dark: {\n bg: \"#171a20\",\n fg: \"#f1f3f6\",\n muted: \"#b7beca\",\n border: \"#3a404b\",\n off: \"#8b93a1\",\n thumb: \"#171a20\",\n accent: \"#8ab4ff\",\n onAccent: \"#0b1220\",\n link: \"#9dc0ff\",\n },\n} as const;\n\nconst vars = (p: (typeof PALETTE)[\"light\"]) =>\n `--bg:${p.bg};--fg:${p.fg};--muted:${p.muted};--border:${p.border};--off:${p.off};--thumb:${p.thumb};--accent:${p.accent};--on-accent:${p.onAccent};--link:${p.link};--focus:${p.accent}`;\n\nexport const STYLES = `\n:host{all:initial}\n*{box-sizing:border-box}\n[hidden]{display:none!important}\n.root{${vars(PALETTE.light)};position:fixed;inset:0;pointer-events:none;z-index:2147483000;font:14px/1.5 system-ui,-apple-system,\"Segoe UI\",Roboto,\"Helvetica Neue\",Arial,sans-serif;color:var(--fg);-webkit-text-size-adjust:100%}\n.root[data-theme=dark]{${vars(PALETTE.dark)};color-scheme:dark}\nbutton,input{font:inherit;color:inherit}\n.banner,.overlay{pointer-events:auto}\n@supports (color:color-mix(in srgb,red 50%,blue)){::selection{background:color-mix(in srgb,var(--accent) 24%,transparent)}}\n.banner{position:absolute;background:var(--bg);color:var(--fg);max-height:92vh;overflow:auto;outline:none;animation:in .22s ease-out}\n.bottom{left:0;right:0;bottom:0;border-top:1px solid var(--border);box-shadow:0 -8px 28px rgba(15,23,42,.08);padding:20px 24px calc(20px + env(safe-area-inset-bottom,0px))}\n.root[data-theme=dark] .bottom{box-shadow:0 -8px 28px rgba(0,0,0,.4)}\n.bottom .inner{display:grid;grid-template-columns:minmax(min(100%,42ch),1fr) auto;grid-template-areas:\"text actions\" \"foot actions\";gap:4px 40px;align-items:center;max-width:1120px;margin:0 auto}\n.bottom .text{max-width:68ch}\n.bottom .btn,.bottom .link-btn{flex:0 0 auto}\n.card{bottom:16px;width:min(400px,calc(100vw - 32px));border:1px solid var(--border);border-radius:14px;padding:20px;box-shadow:0 12px 32px rgba(15,23,42,.14)}\n.root[data-theme=dark] .card{box-shadow:0 12px 32px rgba(0,0,0,.45)}\n.bottom-left{left:16px}\n.bottom-right{right:16px}\n.card .inner{display:flex;flex-direction:column;gap:16px}\n.text{grid-area:text}\n.actions{grid-area:actions;display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:flex-end}\n.card .actions{justify-content:stretch}\n.foot{grid-area:foot}\n.title{overflow-wrap:anywhere;font-size:17px;font-weight:650;line-height:1.35;letter-spacing:-.01em;text-wrap:balance;margin:0 0 6px}\n.desc{overflow-wrap:anywhere;margin:0;color:var(--muted);line-height:1.55;text-wrap:pretty}\n.desc a{color:var(--link);text-decoration:underline;text-underline-offset:3px}\n.btn,.link-btn{min-height:38px;padding:0 16px;border-radius:8px;font-size:13.5px;font-weight:600;cursor:pointer;white-space:nowrap;transition:background-color .12s ease-out,filter .12s ease-out,border-color .12s ease-out}\n.btn{border:2px solid var(--accent);background:var(--accent);color:var(--on-accent);flex:1 1 150px}\n.btn:hover{filter:brightness(.93)}\n.btn:active{filter:brightness(.87)}\n.link-btn{border:1px solid var(--off);background:transparent;color:var(--fg);text-decoration:none}\n.link-btn:hover{border-color:var(--fg)}\n@supports (color:color-mix(in srgb,red 50%,blue)){.link-btn:hover{background:color-mix(in srgb,var(--fg) 9%,transparent)}.link-btn:active{background:color-mix(in srgb,var(--fg) 14%,transparent)}}\n.card .link-btn{flex:1 1 100%}\nbutton:focus-visible,a:focus-visible,.dialog:focus-visible{outline:2px solid var(--focus);outline-offset:2px}\n.foot{font-size:12px;color:var(--muted);padding-top:8px}\n.foot a{color:var(--muted);text-decoration:none;display:inline-flex;align-items:center;gap:5px;vertical-align:middle}\n.foot a:hover{text-decoration:underline}\n.foot b{color:var(--fg);font-weight:700;letter-spacing:-.01em}\n.foot svg{display:block}\n.overlay{position:absolute;inset:0;background:rgba(10,12,16,.58);display:flex;align-items:center;justify-content:center;padding:16px;animation:fade .2s ease-out}\n.dialog{background:var(--bg);color:var(--fg);width:100%;max-width:560px;max-height:min(92vh,760px);display:flex;flex-direction:column;border-radius:16px;box-shadow:0 16px 48px rgba(0,0,0,.35);outline:none;animation:in .22s ease-out}\n.d-head{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:16px 8px 8px 24px}\n.d-head .title{margin:0;font-size:18px}\n.x{width:44px;height:44px;border:0;border-radius:10px;background:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex:none}\n.x:hover{background:var(--border)}\n.d-body{overflow:auto;padding:0 24px 8px;flex:1}\n.cat{border-top:1px solid var(--border);padding:10px 0 14px}\n.row{display:flex;align-items:center;justify-content:space-between;gap:12px}\n.cat-title{font-weight:600;font-size:15px}\n.always{font-size:12px;color:var(--muted);margin-right:4px}\n.cat p{margin:0;color:var(--muted)}\n.cat .svc{margin-top:6px;font-size:13px}\n.cat .svc b{font-weight:600;color:var(--fg)}\n.switch{position:relative;width:52px;height:44px;display:flex;align-items:center;justify-content:flex-end;flex:none}\n.switch input{position:absolute;inset:0;width:100%;height:100%;margin:0;opacity:0;cursor:pointer}\n.switch input:disabled{cursor:default}\n.track{width:44px;height:24px;border-radius:12px;background:var(--off);position:relative;transition:background .15s}\n.track::after{content:\"\";position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:var(--thumb);transition:transform .15s}\ninput:checked+.track{background:var(--accent)}\ninput:checked+.track::after{transform:translateX(20px);background:var(--on-accent)}\ninput:disabled+.track{opacity:.6}\ninput:focus-visible+.track{outline:2px solid var(--focus);outline-offset:2px}\n.d-foot{display:flex;flex-direction:column;gap:8px;padding:12px 24px 16px;border-top:1px solid var(--border)}\n.d-foot .actions{justify-content:stretch}\n@keyframes in{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:none}}\n@keyframes fade{from{opacity:0}to{opacity:1}}\n@media(max-width:960px){\n.bottom .inner{grid-template-columns:minmax(0,1fr);grid-template-areas:\"text\" \"actions\" \"foot\";gap:14px}\n.bottom .actions{justify-content:flex-start}\n}\n@media(max-width:640px){\n.bottom{padding:16px 16px calc(16px + env(safe-area-inset-bottom,0px))}\n.bottom .inner{gap:12px}\n.bottom .actions{justify-content:stretch}\n.bottom .btn{flex:1 1 130px}\n.bottom .link-btn{flex:1 1 100%}\n.card{left:8px;right:8px;bottom:8px;width:auto}\n.overlay{align-items:flex-end;padding:0}\n.dialog{max-width:none;border-radius:16px 16px 0 0;max-height:92vh}\n.d-head{padding-left:16px}\n.d-body{padding:0 16px 8px}\n.d-foot{padding:12px 16px calc(16px + env(safe-area-inset-bottom,0px))}\n.btn{flex-basis:130px}\n.btn,.link-btn{padding:0 12px;min-height:40px}\n}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}\n`.replace(/\\n/g, \"\");\n","import { contrastRatio, onColor } from \"./contrast\";\nimport { UI_LABELS } from \"./texts\";\nimport { PALETTE, STYLES } from \"./styles\";\nimport {\n CONSENT_CATEGORIES,\n type ConsentCategory,\n type ConsentChoices,\n type ConsentConfig,\n type ConsentLocale,\n type ConsentTexts,\n} from \"./types\";\n\nexport type UIOptions = {\n doc: Document;\n config: ConsentConfig;\n texts: ConsentTexts;\n locale: ConsentLocale;\n /** Current choice, used to preset the toggles. */\n getChoices(): ConsentChoices | null;\n /** Whether a valid choice exists, i.e. closing the settings must not bring back the banner. */\n hasChoice(): boolean;\n onAcceptAll(): void;\n onRejectAll(): void;\n onSave(choices: ConsentChoices): void;\n};\n\nexport type ConsentUI = {\n /** `focus` moves keyboard focus into the banner; leave it off when the banner opens on page load. */\n showBanner(focus?: boolean): void;\n showSettings(): void;\n hide(): void;\n destroy(): void;\n};\n\nconst WORDMARK =\n '<svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><rect width=\"16\" height=\"16\" rx=\"4\" fill=\"currentColor\" style=\"color:var(--fg)\"/><circle cx=\"8\" cy=\"8\" r=\"3\" fill=\"var(--bg)\"/></svg>';\n\nconst CLOSE_ICON =\n '<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M3 3l10 10M13 3L3 13\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" fill=\"none\"/></svg>';\n\nconst FOCUSABLE = \"button:not([disabled]),input:not([disabled]),a[href]\";\n\nexport function createUI(options: UIOptions): ConsentUI {\n const { doc, config, texts, locale } = options;\n const labels = UI_LABELS[locale];\n let host: HTMLElement | null = null;\n let shadow: ShadowRoot | null = null;\n let root: HTMLElement;\n let banner: HTMLElement;\n let overlay: HTMLElement;\n let dialog: HTMLElement;\n let settingsButton: HTMLElement;\n let layer: \"none\" | \"banner\" | \"settings\" = \"none\";\n let opener: HTMLElement | null = null;\n let media: MediaQueryList | null = null;\n const toggles = new Map<ConsentCategory, HTMLInputElement>();\n\n function el<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n props: Record<string, string> = {},\n ...children: (Node | string)[]\n ): HTMLElementTagNameMap[K] {\n const node = doc.createElement(tag);\n for (const key of Object.keys(props)) {\n if (key === \"class\") node.className = props[key];\n else node.setAttribute(key, props[key]);\n }\n for (const child of children) node.append(child);\n return node;\n }\n\n function button(cls: string, text: string, onClick: () => void) {\n const node = el(\"button\", { type: \"button\", class: cls }, text);\n node.addEventListener(\"click\", onClick);\n return node;\n }\n\n function powered(): HTMLElement {\n const link = el(\"a\", {\n href: `https://bitsnap.pl/?utm_source=consent_banner&utm_medium=referral&utm_content=${encodeURIComponent(doc.location?.hostname ?? \"\")}`,\n target: \"_blank\",\n rel: \"noopener\",\n });\n link.append(texts.poweredBy + \" \");\n link.insertAdjacentHTML(\"beforeend\", WORDMARK);\n link.append(el(\"b\", {}, \"bitsnap\"));\n return el(\"div\", { class: \"foot\" }, link);\n }\n\n function description(): HTMLElement {\n const node = el(\"p\", { class: \"desc\", id: \"d\" }, texts.description);\n if (config.privacyPolicyUrl) {\n node.append(\n \" \",\n el(\n \"a\",\n { href: config.privacyPolicyUrl, target: \"_blank\", rel: \"noopener\" },\n labels.privacy,\n ),\n );\n }\n return node;\n }\n\n function buildBanner() {\n settingsButton = button(\"link-btn\", texts.settings, () => showSettings());\n banner = el(\n \"div\",\n {\n class: `banner ${config.position === \"bottom\" ? \"bottom\" : `card ${config.position}`}`,\n // Not modal: the page stays usable, so it is a live region, not a dialog.\n role: \"region\",\n \"aria-live\": \"polite\",\n \"aria-labelledby\": \"t\",\n \"aria-describedby\": \"d\",\n tabindex: \"-1\",\n },\n el(\n \"div\",\n { class: \"inner\" },\n el(\"div\", { class: \"text\" }, el(\"div\", { class: \"title\", id: \"t\" }, texts.title), description()),\n el(\n \"div\",\n { class: \"actions\" },\n button(\"btn\", texts.acceptAll, options.onAcceptAll),\n button(\"btn\", texts.rejectAll, options.onRejectAll),\n settingsButton,\n ),\n powered(),\n ),\n );\n }\n\n function category(id: ConsentCategory | \"necessary\"): HTMLElement {\n const services = config.services.filter((service) => service.category === id);\n const input = el(\"input\", { type: \"checkbox\", role: \"switch\", \"aria-labelledby\": `l-${id}`, \"aria-describedby\": `p-${id}` });\n if (id === \"necessary\") {\n input.checked = true;\n input.disabled = true;\n } else {\n toggles.set(id, input);\n }\n const node = el(\n \"div\",\n { class: \"cat\" },\n el(\n \"div\",\n { class: \"row\" },\n el(\"span\", { class: \"cat-title\", id: `l-${id}` }, texts[`${id}Title` as keyof ConsentTexts]),\n el(\n \"span\",\n { style: \"display:flex;align-items:center\" },\n ...(id === \"necessary\" ? [el(\"span\", { class: \"always\" }, labels.always)] : []),\n el(\"label\", { class: \"switch\" }, input, el(\"span\", { class: \"track\" })),\n ),\n ),\n el(\"p\", { id: `p-${id}` }, texts[`${id}Description` as keyof ConsentTexts]),\n );\n if (services.length > 0) {\n node.append(\n el(\"p\", { class: \"svc\" }, el(\"b\", {}, `${labels.services}: `), services.map((s) => s.name).join(\", \")),\n );\n }\n return node;\n }\n\n function buildSettings() {\n const close = el(\"button\", { type: \"button\", class: \"x\", \"aria-label\": texts.close });\n close.insertAdjacentHTML(\"beforeend\", CLOSE_ICON);\n close.addEventListener(\"click\", () => closeSettings());\n const body = el(\"div\", { class: \"d-body\" }, category(\"necessary\"));\n for (const id of CONSENT_CATEGORIES) {\n if (config.categories[id]) body.append(category(id));\n }\n dialog = el(\n \"div\",\n { class: \"dialog\", role: \"dialog\", \"aria-modal\": \"true\", \"aria-labelledby\": \"st\", tabindex: \"-1\" },\n el(\"div\", { class: \"d-head\" }, el(\"div\", { class: \"title\", id: \"st\" }, texts.settings), close),\n body,\n el(\n \"div\",\n { class: \"d-foot\" },\n el(\n \"div\",\n { class: \"actions\" },\n button(\"btn\", texts.save, () => options.onSave(readToggles())),\n button(\"btn\", texts.acceptAll, options.onAcceptAll),\n button(\"btn\", texts.rejectAll, options.onRejectAll),\n ),\n powered(),\n ),\n );\n overlay = el(\"div\", { class: \"overlay\" }, dialog);\n overlay.addEventListener(\"mousedown\", (event) => {\n if (event.target === overlay) closeSettings();\n });\n }\n\n function readToggles(): ConsentChoices {\n const choices = { analytics: false, marketing: false, preferences: false };\n toggles.forEach((input, key) => (choices[key] = input.checked));\n return choices;\n }\n\n function applyTheme() {\n const dark = config.theme === \"dark\" || (config.theme === \"auto\" && !!media?.matches);\n root.setAttribute(\"data-theme\", dark ? \"dark\" : \"light\");\n applyAccent(dark);\n }\n\n /** A custom accent that is too faint on the dark background gives way to the dark theme's own. */\n function applyAccent(dark: boolean) {\n const accent = config.accentColor;\n if (!accent) return;\n if (dark && contrastRatio(accent, PALETTE.dark.bg) < 3) {\n for (const name of [\"--accent\", \"--focus\", \"--on-accent\"]) root.style.removeProperty(name);\n return;\n }\n root.style.setProperty(\"--accent\", accent);\n root.style.setProperty(\"--focus\", accent);\n root.style.setProperty(\"--on-accent\", onColor(accent));\n }\n\n function ensure() {\n if (host) return;\n host = el(\"div\", { id: \"bitsnap-consent\", \"data-bitsnap-consent-host\": \"\" });\n shadow = host.attachShadow({ mode: \"open\" });\n shadow.append(el(\"style\", {}, STYLES));\n root = el(\"div\", { class: \"root\", lang: locale });\n buildBanner();\n buildSettings();\n banner.hidden = true;\n overlay.hidden = true;\n root.append(banner, overlay);\n shadow.append(root);\n if (typeof doc.defaultView?.matchMedia === \"function\") {\n media = doc.defaultView.matchMedia(\"(prefers-color-scheme: dark)\");\n media.addEventListener?.(\"change\", applyTheme);\n }\n applyTheme();\n doc.body.append(host);\n }\n\n function focusables(): HTMLElement[] {\n return Array.from(dialog.querySelectorAll<HTMLElement>(FOCUSABLE));\n }\n\n function onKeydown(event: KeyboardEvent) {\n if (layer !== \"settings\") return;\n if (event.key === \"Escape\") {\n event.preventDefault();\n closeSettings();\n return;\n }\n if (event.key !== \"Tab\") return;\n const items = focusables();\n if (items.length === 0) return;\n const active = shadow?.activeElement as HTMLElement | null;\n const first = items[0];\n const last = items[items.length - 1];\n const outside = !active || !dialog.contains(active);\n if (event.shiftKey && (outside || active === first || active === dialog)) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && (outside || active === last)) {\n event.preventDefault();\n first.focus();\n }\n }\n\n function showBanner(focus = false) {\n try {\n ensure();\n layer = \"banner\";\n doc.removeEventListener(\"keydown\", onKeydown, true);\n overlay.hidden = true;\n banner.hidden = false;\n if (focus) banner.focus({ preventScroll: true });\n } catch {\n // never throw into the host page\n }\n }\n\n function showSettings() {\n try {\n ensure();\n if (layer !== \"settings\") {\n const active = doc.activeElement as HTMLElement | null;\n opener = active && active !== host && active !== doc.body ? active : null;\n }\n const current = options.getChoices();\n toggles.forEach((input, key) => (input.checked = !!current?.[key]));\n layer = \"settings\";\n banner.hidden = true;\n overlay.hidden = false;\n doc.addEventListener(\"keydown\", onKeydown, true);\n dialog.focus({ preventScroll: true });\n } catch {\n // never throw into the host page\n }\n }\n\n function closeSettings() {\n if (layer !== \"settings\") return;\n doc.removeEventListener(\"keydown\", onKeydown, true);\n overlay.hidden = true;\n if (options.hasChoice()) {\n layer = \"none\";\n opener?.focus?.({ preventScroll: true });\n } else {\n layer = \"banner\";\n banner.hidden = false;\n settingsButton.focus({ preventScroll: true });\n }\n }\n\n function hide() {\n if (!host) return;\n doc.removeEventListener(\"keydown\", onKeydown, true);\n const wasSettings = layer === \"settings\";\n layer = \"none\";\n banner.hidden = true;\n overlay.hidden = true;\n if (wasSettings) opener?.focus?.({ preventScroll: true });\n }\n\n function destroy() {\n doc.removeEventListener(\"keydown\", onKeydown, true);\n media?.removeEventListener?.(\"change\", applyTheme);\n host?.remove();\n host = null;\n shadow = null;\n layer = \"none\";\n }\n\n return { showBanner, showSettings, hide, destroy };\n}\n"]}
1
+ {"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/cart-payment-method/dist/consent.js","../src/consent/react.tsx","../src/consent/core/types.ts","../src/consent/core/activate.ts","../src/consent/core/config.ts","../src/consent/core/styles.ts","../src/consent/core/ui.ts"],"names":["CONSENT_CATEGORIES","SCRIPT_SELECTOR","FRAME_SELECTOR","allowed","c","category","settled","script","resolve","run","doc","placeholder","name","value","external","loaded","activateScripts","activated","gate","loading","inline","frame","src","DEFAULT_API_HOST","DEFAULT_COLLECT_HOST","defaultConfig","THEMES","POSITIONS","HEX_COLOR","safeColor","safeUrl","url","cleanServices","services","item","cookie","mergeConfig","layers","result","layer","accent","privacy","fetchRemoteConfig","apiHost","key","timeoutMs","controller","timer","response"],"mappings":"AAAA,uuBAA+F,+BAA4B,8BCAjE,ICU7CA,CAAAA,CAAiD,CAC5D,WAAA,CACA,WAAA,CACA,aACF,CAAA,CCZA,IAAMC,EAAAA,CAAkB,4EAAA,CAClBC,EAAAA,CAAiB,wCAAA,CAEjBC,EAAAA,CAAU,CAACC,CAAAA,CAAmBC,CAAAA,CAAAA,EACjCL,CAAAA,CAAyC,QAAA,kBAASK,CAAAA,SAAY,IAAE,CAAA,EACjED,CAAAA,CAAEC,CAAgC,CAAA,CAGpC,SAASC,EAAAA,CAAQC,CAAAA,CAA0C,CACzD,OAAO,IAAI,OAAA,CAASC,CAAAA,EAAY,CAC9BD,CAAAA,CAAO,gBAAA,CAAiB,MAAA,CAAQ,CAAA,CAAA,EAAMC,CAAAA,CAAQ,CAAA,CAAG,CAAE,IAAA,CAAM,CAAA,CAAK,CAAC,CAAA,CAC/DD,CAAAA,CAAO,gBAAA,CAAiB,OAAA,CAAS,CAAA,CA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AAA,EAAoB,UAAA,CAAa,IAAI,eAAA,CAAoB,KAAA,CAAA,CAC7EC,CAAAA,CAAQ,UAAA,CAAW,CAAA,CAAA,kBAAMD,CAAAA,6BAAY,KAAA,mBAAM,GAAA,CAAGD,CAAS,CAAA,CAC7D,GAAI,CACF,IAAMG,CAAAA,CAAW,MAAM,KAAA,CACrB,CAAA,EAAA;ACvFgB;AAAA;AAAA;AAIK,MAAA;AACgB,uBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACqKV","file":"/home/emems/.t3/worktrees/bitsnap-react/cart-payment-method/dist/consent.js","sourcesContent":[null,"import { useCallback, useRef, useSyncExternalStore } from \"react\";\nimport { useIsomorphicLayoutEffect } from \"../lib/isomorphic-layout-effect\";\nimport { createConsent } from \"./core/controller\";\nimport type {\n BitsnapConsentApi,\n ConsentChoices,\n ConsentConfig,\n ConsentOptions,\n ConsentState,\n} from \"./core/types\";\n\ndeclare global {\n interface Window {\n BitsnapConsent?: BitsnapConsentApi;\n }\n}\n\nexport type BitsnapConsentProps = {\n /** Public project key: loads the project's banner config and logs choices. */\n projectKey?: string;\n theme?: ConsentOptions[\"theme\"];\n locale?: ConsentOptions[\"locale\"];\n position?: ConsentOptions[\"position\"];\n privacyPolicyUrl?: string;\n /** `project` keeps the consent cookie per project key. */\n scope?: ConsentOptions[\"scope\"];\n apiHost?: string;\n collectHost?: string;\n /** Local config, merged over the project config. */\n config?: Partial<ConsentConfig>;\n reloadOnWithdraw?: boolean;\n /** Google Consent Mode v2: `auto` (default) is on when `gtag` or `dataLayer` already exist. */\n gcm?: ConsentOptions[\"gcm\"];\n /** Categories offered when no remote config is loaded. */\n categories?: ConsentOptions[\"categories\"];\n /** Dashboard preview: shows the banner from the local options only; touches no cookie. */\n preview?: boolean;\n /** Replaces the banner title. */\n title?: string;\n /** Replaces the banner description. */\n description?: string;\n};\n\n/** Mounts Bitsnap Consent on the page. Renders nothing itself (the banner lives in a Shadow DOM). */\nexport function BitsnapConsent(props: BitsnapConsentProps): null {\n const {\n projectKey, theme, locale, position, privacyPolicyUrl, scope, apiHost, collectHost, reloadOnWithdraw,\n gcm, preview, title, description,\n } = props;\n const configKey = JSON.stringify(props.config ?? null);\n const configRef = useRef(props.config);\n configRef.current = props.config;\n const categoriesKey = JSON.stringify(props.categories ?? null);\n const categoriesRef = useRef(props.categories);\n categoriesRef.current = props.categories;\n\n // A layout effect: the page's passive effects (first events, tracker) must find the API already there.\n useIsomorphicLayoutEffect(() => {\n // A banner from the script tag or another instance already runs on this page.\n if (window.BitsnapConsent) return;\n const api = createConsent({\n projectKey,\n theme,\n locale,\n position,\n privacyPolicyUrl,\n scope,\n apiHost,\n collectHost,\n reloadOnWithdraw,\n gcm,\n preview,\n title,\n description,\n categories: categoriesRef.current,\n config: configRef.current,\n });\n window.BitsnapConsent = api;\n return () => {\n api.destroy();\n if (window.BitsnapConsent === api) delete window.BitsnapConsent;\n };\n }, [\n projectKey, theme, locale, position, privacyPolicyUrl, scope, apiHost, collectHost, reloadOnWithdraw,\n gcm, preview, title, description, categoriesKey, configKey,\n ]);\n\n return null;\n}\n\nlet lastKey = \"null\";\nlet lastState: ConsentState | null = null;\n\nfunction getSnapshot(): ConsentState | null {\n const current = typeof window === \"undefined\" ? null : (window.BitsnapConsent?.get() ?? null);\n const key = JSON.stringify(current);\n if (key !== lastKey) {\n lastKey = key;\n lastState = current;\n }\n return lastState;\n}\n\nfunction subscribe(onChange: () => void): () => void {\n window.addEventListener(\"bitsnap:consent\", onChange);\n window.addEventListener(\"bitsnap:consent:ready\", onChange);\n return () => {\n window.removeEventListener(\"bitsnap:consent\", onChange);\n window.removeEventListener(\"bitsnap:consent:ready\", onChange);\n };\n}\n\nexport type UseConsent = {\n /** The stored choice, or `null` while there is none (or on the server). */\n consent: ConsentState | null;\n /** `true` once the visitor has made a choice that is still valid. */\n decided: boolean;\n open: () => void;\n accept: (categories?: Partial<ConsentChoices>) => void;\n acceptAll: () => void;\n rejectAll: () => void;\n reset: () => void;\n};\n\n/** Current consent state of the page, kept up to date as the visitor chooses. */\nexport function useConsent(): UseConsent {\n const consent = useSyncExternalStore(subscribe, getSnapshot, () => null);\n const open = useCallback(() => window.BitsnapConsent?.open(), []);\n const accept = useCallback((categories?: Partial<ConsentChoices>) => window.BitsnapConsent?.accept(categories), []);\n const acceptAll = useCallback(() => window.BitsnapConsent?.acceptAll(), []);\n const rejectAll = useCallback(() => window.BitsnapConsent?.rejectAll(), []);\n const reset = useCallback(() => window.BitsnapConsent?.reset(), []);\n return { consent, decided: consent !== null, open, accept, acceptAll, rejectAll, reset };\n}\n","export type ConsentCategory = \"analytics\" | \"marketing\" | \"preferences\";\n\nexport type ConsentChoices = Record<ConsentCategory, boolean>;\n\nexport type ConsentTheme = \"auto\" | \"light\" | \"dark\";\n\nexport type ConsentPosition = \"bottom\" | \"bottom-left\" | \"bottom-right\";\n\nexport type ConsentLocale = \"pl\" | \"en\";\n\nexport const CONSENT_CATEGORIES: readonly ConsentCategory[] = [\n \"analytics\",\n \"marketing\",\n \"preferences\",\n];\n\nexport const CONSENT_TEXT_KEYS = [\n \"title\",\n \"description\",\n \"acceptAll\",\n \"rejectAll\",\n \"settings\",\n \"save\",\n \"close\",\n \"necessaryTitle\",\n \"necessaryDescription\",\n \"analyticsTitle\",\n \"analyticsDescription\",\n \"marketingTitle\",\n \"marketingDescription\",\n \"preferencesTitle\",\n \"preferencesDescription\",\n \"poweredBy\",\n] as const;\n\nexport type ConsentTexts = Record<(typeof CONSENT_TEXT_KEYS)[number], string>;\n\nexport type ConsentService = {\n name: string;\n category: ConsentCategory;\n /** Cookies to delete (best effort) when the category is withdrawn. A trailing `*` matches a prefix. */\n cookies?: string[];\n};\n\nexport type ConsentConfig = {\n /** Banner version. A stored choice with a lower `bv` makes the banner ask again. */\n version: number;\n theme: ConsentTheme;\n accentColor?: string;\n position: ConsentPosition;\n privacyPolicyUrl?: string;\n categories: ConsentChoices;\n services: ConsentService[];\n texts?: Partial<Record<ConsentLocale, Partial<ConsentTexts>>>;\n poweredBy: true;\n};\n\n/** What the consent cookie holds, and what `get()` returns. */\nexport type ConsentState = {\n id: string;\n /** Unix seconds. */\n ts: number;\n /** Version of the banner the choice was made on. */\n bv: number;\n c: ConsentChoices;\n};\n\nexport type ConsentAction =\n | \"accept_all\"\n | \"reject_all\"\n | \"custom\"\n | \"withdraw\";\n\n/** `detail` of `bitsnap:consent` and the argument of `on('change')`. */\nexport type ConsentChangeDetail = ConsentState & {\n /** `reset` when the visitor's stored choice was cleared (`get()` is `null` then). */\n action: ConsentAction | \"reset\";\n};\n\nexport type ConsentOptions = {\n /** Public project key. Enables the remote config and the consent log. */\n projectKey?: string;\n theme?: ConsentTheme;\n locale?: \"auto\" | ConsentLocale;\n position?: ConsentPosition;\n privacyPolicyUrl?: string;\n /** `project` keeps one cookie per project key (`bitsnap_consent_<key>`). */\n scope?: \"global\" | \"project\";\n apiHost?: string;\n collectHost?: string;\n /** Google Consent Mode v2. `auto` is on when `gtag` or `dataLayer` already exist. */\n gcm?: \"auto\" | \"on\" | \"off\";\n /** Local overrides, merged over the defaults and the remote config. */\n config?: Partial<ConsentConfig>;\n /** Categories used when no remote config is loaded. */\n categories?: Partial<ConsentChoices>;\n reloadOnWithdraw?: boolean;\n /**\n * Dashboard preview: shows the banner at once from the local options, never\n * reads or writes the cookie, loads no remote config, sends no consent log,\n * and the buttons only close the banner.\n */\n preview?: boolean;\n /** Replaces the banner title (current locale, non-empty values only). */\n title?: string;\n /** Replaces the banner description (current locale, non-empty values only). */\n description?: string;\n};\n\nexport type BitsnapConsentApi = {\n /**\n * Whose choice this banner holds: `project` keeps one cookie per project key\n * (`bitsnap_consent_<key>`), `global` the site-wide `bitsnap_consent`.\n */\n readonly scope: \"global\" | \"project\";\n /** The bare public project key the banner was started with, if any (`pk_` stripped). */\n readonly projectKey: string | null;\n get(): ConsentState | null;\n /**\n * `true` when the visitor refused `category`, also in a choice made on an older banner\n * version (which `get()` no longer returns) that they have not answered again yet.\n */\n denied(category: ConsentCategory): boolean;\n on(event: \"change\", fn: (detail: ConsentChangeDetail) => void): () => void;\n open(): void;\n close(): void;\n accept(categories?: Partial<ConsentChoices>): void;\n acceptAll(): void;\n rejectAll(): void;\n reset(): void;\n /** Resolves with the stored choice (or `null`) once config and stored choice are applied. */\n ready: Promise<ConsentState | null>;\n destroy(): void;\n};\n","import { CONSENT_CATEGORIES, type ConsentChoices } from \"./types\";\n\nconst SCRIPT_SELECTOR = 'script[type=\"text/plain\"][data-bitsnap-consent]:not([data-bitsnap-queued])';\nconst FRAME_SELECTOR = \"iframe[data-bitsnap-consent][data-src]\";\n\nconst allowed = (c: ConsentChoices, category: string | null): boolean =>\n (CONSENT_CATEGORIES as readonly string[]).includes(category ?? \"\") &&\n c[category as keyof ConsentChoices];\n\n/** Settles when the script has loaded or failed: a broken script must not block the ones after it. */\nfunction settled(script: HTMLScriptElement): Promise<void> {\n return new Promise((resolve) => {\n script.addEventListener(\"load\", () => resolve(), { once: true });\n script.addEventListener(\"error\", () => resolve(), { once: true });\n });\n}\n\n/** Swaps the placeholder for a live script; resolves once an external one has loaded. */\nfunction run(doc: Document, placeholder: HTMLScriptElement): Promise<void> | undefined {\n const script = doc.createElement(\"script\");\n for (const { name, value } of Array.from(placeholder.attributes)) {\n if (name === \"type\" || name === \"data-bitsnap-queued\") continue;\n if (name === \"data-type\") {\n // The embed writes the original `type=\"module\"` here, as `type` itself is `text/plain`.\n if (value === \"module\") script.setAttribute(\"type\", \"module\");\n } else if (name === \"data-src\") script.setAttribute(\"src\", value);\n else script.setAttribute(name, value);\n }\n if (placeholder.nonce) script.nonce = placeholder.nonce;\n const external = script.hasAttribute(\"src\");\n if (external) {\n // Dynamic scripts are async by default; keep the order of the page.\n if (!placeholder.hasAttribute(\"async\")) script.async = false;\n } else {\n script.text = placeholder.text;\n }\n const loaded = external ? settled(script) : undefined;\n placeholder.parentNode?.replaceChild(script, placeholder);\n return loaded;\n}\n\n/**\n * Turns the consented placeholders into live elements:\n * `<script type=\"text/plain\" data-bitsnap-consent=\"marketing\" [data-src] [data-type=\"module\"]>` becomes\n * a real script (attributes copied, `type` dropped or restored from `data-type`, `data-src` -> `src`),\n * and `<iframe data-src>` gets its `src`.\n * Placeholders run in document order: an inline script waits for the external scripts before it\n * (`<script src=lib.js>` then `<script>Lib.init()</script>`), external ones only follow each other.\n */\nexport function activateScripts(doc: Document, c: ConsentChoices): number {\n let activated = 0;\n try {\n /** Set once a placeholder had to wait: everything after it queues behind it. */\n let gate: Promise<void> | null = null;\n /** External scripts inserted since the last inline one. */\n let loading: Promise<void>[] = [];\n doc.querySelectorAll<HTMLScriptElement>(SCRIPT_SELECTOR).forEach((placeholder) => {\n if (!allowed(c, placeholder.getAttribute(\"data-bitsnap-consent\"))) return;\n activated++;\n const inline = !placeholder.hasAttribute(\"data-src\") && !placeholder.hasAttribute(\"src\");\n if (gate || (inline && loading.length > 0)) {\n // Marked so that another call (a later choice) does not queue it again.\n placeholder.setAttribute(\"data-bitsnap-queued\", \"\");\n gate = (gate ?? Promise.all(loading).then(() => {})).then(() => {\n try {\n return run(doc, placeholder);\n } catch {\n // never throw into the host page\n }\n });\n loading = [];\n return;\n }\n const loaded = run(doc, placeholder);\n if (loaded) loading.push(loaded);\n });\n doc.querySelectorAll<HTMLIFrameElement>(FRAME_SELECTOR).forEach((frame) => {\n if (!allowed(c, frame.getAttribute(\"data-bitsnap-consent\"))) return;\n const src = frame.getAttribute(\"data-src\");\n if (src && frame.getAttribute(\"src\") !== src) {\n frame.setAttribute(\"src\", src);\n frame.removeAttribute(\"data-src\");\n activated++;\n }\n });\n } catch {\n // never throw into the host page\n }\n return activated;\n}\n","import {\n CONSENT_CATEGORIES,\n type ConsentChoices,\n type ConsentConfig,\n type ConsentService,\n} from \"./types\";\n\nexport const DEFAULT_API_HOST = \"https://bitsnap.pl\";\nexport const DEFAULT_COLLECT_HOST = \"https://collect.bitsnap.pl\";\n\nexport function defaultConfig(): ConsentConfig {\n return {\n version: 1,\n theme: \"auto\",\n position: \"bottom\",\n categories: { analytics: true, marketing: true, preferences: false },\n services: [],\n poweredBy: true,\n };\n}\n\nconst THEMES = [\"auto\", \"light\", \"dark\"];\nconst POSITIONS = [\"bottom\", \"bottom-left\", \"bottom-right\"];\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\n\nexport function safeColor(value: unknown): string | undefined {\n return typeof value === \"string\" && HEX_COLOR.test(value.trim())\n ? value.trim()\n : undefined;\n}\n\n/** Only http(s) and relative URLs may end up in the banner. */\nexport function safeUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const url = value.trim();\n return /^(?:https?:\\/\\/|\\/(?!\\/)|#|\\?)/i.test(url) ? url : undefined;\n}\n\nfunction cleanServices(value: unknown): ConsentService[] {\n if (!Array.isArray(value)) return [];\n const services: ConsentService[] = [];\n for (const item of value) {\n if (\n item &&\n typeof item.name === \"string\" &&\n (CONSENT_CATEGORIES as readonly string[]).includes(item.category)\n ) {\n services.push({\n name: item.name,\n category: item.category,\n cookies: Array.isArray(item.cookies)\n ? item.cookies.filter((cookie: unknown) => typeof cookie === \"string\")\n : undefined,\n });\n }\n }\n return services;\n}\n\n/** Layers partial configs (later wins) over the defaults, dropping invalid values. */\nexport function mergeConfig(\n ...layers: (Partial<ConsentConfig> | null | undefined)[]\n): ConsentConfig {\n const result = defaultConfig();\n for (const layer of layers) {\n if (!layer || typeof layer !== \"object\") continue;\n if (typeof layer.version === \"number\" && layer.version >= 0) {\n result.version = Math.floor(layer.version);\n }\n if (THEMES.includes(layer.theme as string)) result.theme = layer.theme!;\n if (POSITIONS.includes(layer.position as string)) result.position = layer.position!;\n const accent = safeColor(layer.accentColor);\n if (accent) result.accentColor = accent;\n const privacy = safeUrl(layer.privacyPolicyUrl);\n if (privacy) result.privacyPolicyUrl = privacy;\n if (layer.categories && typeof layer.categories === \"object\") {\n for (const category of CONSENT_CATEGORIES) {\n if (typeof layer.categories[category] === \"boolean\") {\n result.categories[category] = layer.categories[category];\n }\n }\n }\n if (layer.services !== undefined) result.services = cleanServices(layer.services);\n if (layer.texts && typeof layer.texts === \"object\") result.texts = layer.texts;\n }\n return result;\n}\n\nexport function parseCategoryList(value: string | null | undefined): ConsentChoices {\n const wanted = (value ?? \"\").split(\",\").map((item) => item.trim());\n return {\n analytics: wanted.includes(\"analytics\"),\n marketing: wanted.includes(\"marketing\"),\n preferences: wanted.includes(\"preferences\"),\n };\n}\n\n/** What `GET /api/consent/config` answers: whether the banner is on, and its config. */\nexport type RemoteConsentConfig = {\n /** `false` when the project turned the banner off: nothing is shown, stored choices still apply. */\n enabled: boolean;\n config: Partial<ConsentConfig> | null;\n};\n\n/** Loads the project's banner config. Resolves to `null` on any failure or after the timeout. */\nexport async function fetchRemoteConfig(\n apiHost: string,\n key: string,\n timeoutMs = 3000,\n): Promise<RemoteConsentConfig | null> {\n if (typeof fetch !== \"function\") return null;\n const controller = typeof AbortController === \"function\" ? new AbortController() : undefined;\n const timer = setTimeout(() => controller?.abort(), timeoutMs);\n try {\n const response = await fetch(\n `${apiHost.replace(/\\/+$/, \"\")}/api/consent/config?key=${encodeURIComponent(key)}`,\n { signal: controller?.signal, credentials: \"omit\" },\n );\n if (!response.ok) return null;\n const body = await response.json();\n if (!body || typeof body !== \"object\") return null;\n const config = body.config && typeof body.config === \"object\" ? body.config : null;\n const enabled = body.enabled !== false;\n return config || !enabled ? { enabled, config } : null;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n","/** Colors of both themes. Every text/background pair is checked against WCAG AA in the tests. */\nexport const PALETTE = {\n light: {\n bg: \"#ffffff\",\n fg: \"#14171c\",\n muted: \"#495260\",\n border: \"#c9ced6\",\n off: \"#6b7280\",\n thumb: \"#ffffff\",\n accent: \"#1d4ed8\",\n onAccent: \"#ffffff\",\n link: \"#1d4ed8\",\n },\n dark: {\n bg: \"#171a20\",\n fg: \"#f1f3f6\",\n muted: \"#b7beca\",\n border: \"#3a404b\",\n off: \"#8b93a1\",\n thumb: \"#171a20\",\n accent: \"#8ab4ff\",\n onAccent: \"#0b1220\",\n link: \"#9dc0ff\",\n },\n} as const;\n\nconst vars = (p: (typeof PALETTE)[\"light\"]) =>\n `--bg:${p.bg};--fg:${p.fg};--muted:${p.muted};--border:${p.border};--off:${p.off};--thumb:${p.thumb};--accent:${p.accent};--on-accent:${p.onAccent};--link:${p.link};--focus:${p.accent}`;\n\nexport const STYLES = `\n:host{all:initial}\n*{box-sizing:border-box}\n[hidden]{display:none!important}\n.root{${vars(PALETTE.light)};position:fixed;inset:0;pointer-events:none;z-index:2147483000;font:14px/1.5 system-ui,-apple-system,\"Segoe UI\",Roboto,\"Helvetica Neue\",Arial,sans-serif;color:var(--fg);-webkit-text-size-adjust:100%}\n.root[data-theme=dark]{${vars(PALETTE.dark)};color-scheme:dark}\nbutton,input{font:inherit;color:inherit}\n.banner,.overlay{pointer-events:auto}\n@supports (color:color-mix(in srgb,red 50%,blue)){::selection{background:color-mix(in srgb,var(--accent) 24%,transparent)}}\n.banner{position:absolute;background:var(--bg);color:var(--fg);max-height:92vh;overflow:auto;outline:none;animation:in .22s ease-out}\n.bottom{left:0;right:0;bottom:0;border-top:1px solid var(--border);box-shadow:0 -8px 28px rgba(15,23,42,.08);padding:20px 24px calc(20px + env(safe-area-inset-bottom,0px))}\n.root[data-theme=dark] .bottom{box-shadow:0 -8px 28px rgba(0,0,0,.4)}\n.bottom .inner{display:grid;grid-template-columns:minmax(min(100%,42ch),1fr) auto;grid-template-areas:\"text actions\" \"foot actions\";gap:4px 40px;align-items:center;max-width:1120px;margin:0 auto}\n.bottom .text{max-width:68ch}\n.bottom .btn,.bottom .link-btn{flex:0 0 auto}\n.card{bottom:16px;width:min(400px,calc(100vw - 32px));border:1px solid var(--border);border-radius:14px;padding:20px;box-shadow:0 12px 32px rgba(15,23,42,.14)}\n.root[data-theme=dark] .card{box-shadow:0 12px 32px rgba(0,0,0,.45)}\n.bottom-left{left:16px}\n.bottom-right{right:16px}\n.card .inner{display:flex;flex-direction:column;gap:16px}\n.text{grid-area:text}\n.actions{grid-area:actions;display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:flex-end}\n.card .actions{justify-content:stretch}\n.foot{grid-area:foot}\n.title{overflow-wrap:anywhere;font-size:17px;font-weight:650;line-height:1.35;letter-spacing:-.01em;text-wrap:balance;margin:0 0 6px}\n.desc{overflow-wrap:anywhere;margin:0;color:var(--muted);line-height:1.55;text-wrap:pretty}\n.desc a{color:var(--link);text-decoration:underline;text-underline-offset:3px}\n.btn,.link-btn{min-height:38px;padding:0 16px;border-radius:8px;font-size:13.5px;font-weight:600;cursor:pointer;white-space:nowrap;transition:background-color .12s ease-out,filter .12s ease-out,border-color .12s ease-out}\n.btn{border:2px solid var(--accent);background:var(--accent);color:var(--on-accent);flex:1 1 150px}\n.btn:hover{filter:brightness(.93)}\n.btn:active{filter:brightness(.87)}\n.link-btn{border:1px solid var(--off);background:transparent;color:var(--fg);text-decoration:none}\n.link-btn:hover{border-color:var(--fg)}\n@supports (color:color-mix(in srgb,red 50%,blue)){.link-btn:hover{background:color-mix(in srgb,var(--fg) 9%,transparent)}.link-btn:active{background:color-mix(in srgb,var(--fg) 14%,transparent)}}\n.card .link-btn{flex:1 1 100%}\nbutton:focus-visible,a:focus-visible,.dialog:focus-visible{outline:2px solid var(--focus);outline-offset:2px}\n.foot{font-size:12px;color:var(--muted);padding-top:8px}\n.foot a{color:var(--muted);text-decoration:none;display:inline-flex;align-items:center;gap:5px;vertical-align:middle}\n.foot a:hover{text-decoration:underline}\n.foot b{color:var(--fg);font-weight:700;letter-spacing:-.01em}\n.foot svg{display:block}\n.overlay{position:absolute;inset:0;background:rgba(10,12,16,.58);display:flex;align-items:center;justify-content:center;padding:16px;animation:fade .2s ease-out}\n.dialog{background:var(--bg);color:var(--fg);width:100%;max-width:560px;max-height:min(92vh,760px);display:flex;flex-direction:column;border-radius:16px;box-shadow:0 16px 48px rgba(0,0,0,.35);outline:none;animation:in .22s ease-out}\n.d-head{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:16px 8px 8px 24px}\n.d-head .title{margin:0;font-size:18px}\n.x{width:44px;height:44px;border:0;border-radius:10px;background:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex:none}\n.x:hover{background:var(--border)}\n.d-body{overflow:auto;padding:0 24px 8px;flex:1}\n.cat{border-top:1px solid var(--border);padding:10px 0 14px}\n.row{display:flex;align-items:center;justify-content:space-between;gap:12px}\n.cat-title{font-weight:600;font-size:15px}\n.always{font-size:12px;color:var(--muted);margin-right:4px}\n.cat p{margin:0;color:var(--muted)}\n.cat .svc{margin-top:6px;font-size:13px}\n.cat .svc b{font-weight:600;color:var(--fg)}\n.switch{position:relative;width:52px;height:44px;display:flex;align-items:center;justify-content:flex-end;flex:none}\n.switch input{position:absolute;inset:0;width:100%;height:100%;margin:0;opacity:0;cursor:pointer}\n.switch input:disabled{cursor:default}\n.track{width:44px;height:24px;border-radius:12px;background:var(--off);position:relative;transition:background .15s}\n.track::after{content:\"\";position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:var(--thumb);transition:transform .15s}\ninput:checked+.track{background:var(--accent)}\ninput:checked+.track::after{transform:translateX(20px);background:var(--on-accent)}\ninput:disabled+.track{opacity:.6}\ninput:focus-visible+.track{outline:2px solid var(--focus);outline-offset:2px}\n.d-foot{display:flex;flex-direction:column;gap:8px;padding:12px 24px 16px;border-top:1px solid var(--border)}\n.d-foot .actions{justify-content:stretch}\n@keyframes in{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:none}}\n@keyframes fade{from{opacity:0}to{opacity:1}}\n@media(max-width:960px){\n.bottom .inner{grid-template-columns:minmax(0,1fr);grid-template-areas:\"text\" \"actions\" \"foot\";gap:14px}\n.bottom .actions{justify-content:flex-start}\n}\n@media(max-width:640px){\n.bottom{padding:16px 16px calc(16px + env(safe-area-inset-bottom,0px))}\n.bottom .inner{gap:12px}\n.bottom .actions{justify-content:stretch}\n.bottom .btn{flex:1 1 130px}\n.bottom .link-btn{flex:1 1 100%}\n.card{left:8px;right:8px;bottom:8px;width:auto}\n.overlay{align-items:flex-end;padding:0}\n.dialog{max-width:none;border-radius:16px 16px 0 0;max-height:92vh}\n.d-head{padding-left:16px}\n.d-body{padding:0 16px 8px}\n.d-foot{padding:12px 16px calc(16px + env(safe-area-inset-bottom,0px))}\n.btn{flex-basis:130px}\n.btn,.link-btn{padding:0 12px;min-height:40px}\n}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}\n`.replace(/\\n/g, \"\");\n","import { contrastRatio, onColor } from \"./contrast\";\nimport { UI_LABELS } from \"./texts\";\nimport { PALETTE, STYLES } from \"./styles\";\nimport {\n CONSENT_CATEGORIES,\n type ConsentCategory,\n type ConsentChoices,\n type ConsentConfig,\n type ConsentLocale,\n type ConsentTexts,\n} from \"./types\";\n\nexport type UIOptions = {\n doc: Document;\n config: ConsentConfig;\n texts: ConsentTexts;\n locale: ConsentLocale;\n /** Current choice, used to preset the toggles. */\n getChoices(): ConsentChoices | null;\n /** Whether a valid choice exists, i.e. closing the settings must not bring back the banner. */\n hasChoice(): boolean;\n onAcceptAll(): void;\n onRejectAll(): void;\n onSave(choices: ConsentChoices): void;\n};\n\nexport type ConsentUI = {\n /** `focus` moves keyboard focus into the banner; leave it off when the banner opens on page load. */\n showBanner(focus?: boolean): void;\n showSettings(): void;\n hide(): void;\n destroy(): void;\n};\n\nconst WORDMARK =\n '<svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><rect width=\"16\" height=\"16\" rx=\"4\" fill=\"currentColor\" style=\"color:var(--fg)\"/><circle cx=\"8\" cy=\"8\" r=\"3\" fill=\"var(--bg)\"/></svg>';\n\nconst CLOSE_ICON =\n '<svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M3 3l10 10M13 3L3 13\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" fill=\"none\"/></svg>';\n\nconst FOCUSABLE = \"button:not([disabled]),input:not([disabled]),a[href]\";\n\nexport function createUI(options: UIOptions): ConsentUI {\n const { doc, config, texts, locale } = options;\n const labels = UI_LABELS[locale];\n let host: HTMLElement | null = null;\n let shadow: ShadowRoot | null = null;\n let root: HTMLElement;\n let banner: HTMLElement;\n let overlay: HTMLElement;\n let dialog: HTMLElement;\n let settingsButton: HTMLElement;\n let layer: \"none\" | \"banner\" | \"settings\" = \"none\";\n let opener: HTMLElement | null = null;\n let media: MediaQueryList | null = null;\n const toggles = new Map<ConsentCategory, HTMLInputElement>();\n\n function el<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n props: Record<string, string> = {},\n ...children: (Node | string)[]\n ): HTMLElementTagNameMap[K] {\n const node = doc.createElement(tag);\n for (const key of Object.keys(props)) {\n if (key === \"class\") node.className = props[key];\n else node.setAttribute(key, props[key]);\n }\n for (const child of children) node.append(child);\n return node;\n }\n\n function button(cls: string, text: string, onClick: () => void) {\n const node = el(\"button\", { type: \"button\", class: cls }, text);\n node.addEventListener(\"click\", onClick);\n return node;\n }\n\n function powered(): HTMLElement {\n const link = el(\"a\", {\n href: `https://bitsnap.pl/?utm_source=consent_banner&utm_medium=referral&utm_content=${encodeURIComponent(doc.location?.hostname ?? \"\")}`,\n target: \"_blank\",\n rel: \"noopener\",\n });\n link.append(texts.poweredBy + \" \");\n link.insertAdjacentHTML(\"beforeend\", WORDMARK);\n link.append(el(\"b\", {}, \"bitsnap\"));\n return el(\"div\", { class: \"foot\" }, link);\n }\n\n function description(): HTMLElement {\n const node = el(\"p\", { class: \"desc\", id: \"d\" }, texts.description);\n if (config.privacyPolicyUrl) {\n node.append(\n \" \",\n el(\n \"a\",\n { href: config.privacyPolicyUrl, target: \"_blank\", rel: \"noopener\" },\n labels.privacy,\n ),\n );\n }\n return node;\n }\n\n function buildBanner() {\n settingsButton = button(\"link-btn\", texts.settings, () => showSettings());\n banner = el(\n \"div\",\n {\n class: `banner ${config.position === \"bottom\" ? \"bottom\" : `card ${config.position}`}`,\n // Not modal: the page stays usable, so it is a live region, not a dialog.\n role: \"region\",\n \"aria-live\": \"polite\",\n \"aria-labelledby\": \"t\",\n \"aria-describedby\": \"d\",\n tabindex: \"-1\",\n },\n el(\n \"div\",\n { class: \"inner\" },\n el(\"div\", { class: \"text\" }, el(\"div\", { class: \"title\", id: \"t\" }, texts.title), description()),\n el(\n \"div\",\n { class: \"actions\" },\n button(\"btn\", texts.acceptAll, options.onAcceptAll),\n button(\"btn\", texts.rejectAll, options.onRejectAll),\n settingsButton,\n ),\n powered(),\n ),\n );\n }\n\n function category(id: ConsentCategory | \"necessary\"): HTMLElement {\n const services = config.services.filter((service) => service.category === id);\n const input = el(\"input\", { type: \"checkbox\", role: \"switch\", \"aria-labelledby\": `l-${id}`, \"aria-describedby\": `p-${id}` });\n if (id === \"necessary\") {\n input.checked = true;\n input.disabled = true;\n } else {\n toggles.set(id, input);\n }\n const node = el(\n \"div\",\n { class: \"cat\" },\n el(\n \"div\",\n { class: \"row\" },\n el(\"span\", { class: \"cat-title\", id: `l-${id}` }, texts[`${id}Title` as keyof ConsentTexts]),\n el(\n \"span\",\n { style: \"display:flex;align-items:center\" },\n ...(id === \"necessary\" ? [el(\"span\", { class: \"always\" }, labels.always)] : []),\n el(\"label\", { class: \"switch\" }, input, el(\"span\", { class: \"track\" })),\n ),\n ),\n el(\"p\", { id: `p-${id}` }, texts[`${id}Description` as keyof ConsentTexts]),\n );\n if (services.length > 0) {\n node.append(\n el(\"p\", { class: \"svc\" }, el(\"b\", {}, `${labels.services}: `), services.map((s) => s.name).join(\", \")),\n );\n }\n return node;\n }\n\n function buildSettings() {\n const close = el(\"button\", { type: \"button\", class: \"x\", \"aria-label\": texts.close });\n close.insertAdjacentHTML(\"beforeend\", CLOSE_ICON);\n close.addEventListener(\"click\", () => closeSettings());\n const body = el(\"div\", { class: \"d-body\" }, category(\"necessary\"));\n for (const id of CONSENT_CATEGORIES) {\n if (config.categories[id]) body.append(category(id));\n }\n dialog = el(\n \"div\",\n { class: \"dialog\", role: \"dialog\", \"aria-modal\": \"true\", \"aria-labelledby\": \"st\", tabindex: \"-1\" },\n el(\"div\", { class: \"d-head\" }, el(\"div\", { class: \"title\", id: \"st\" }, texts.settings), close),\n body,\n el(\n \"div\",\n { class: \"d-foot\" },\n el(\n \"div\",\n { class: \"actions\" },\n button(\"btn\", texts.save, () => options.onSave(readToggles())),\n button(\"btn\", texts.acceptAll, options.onAcceptAll),\n button(\"btn\", texts.rejectAll, options.onRejectAll),\n ),\n powered(),\n ),\n );\n overlay = el(\"div\", { class: \"overlay\" }, dialog);\n overlay.addEventListener(\"mousedown\", (event) => {\n if (event.target === overlay) closeSettings();\n });\n }\n\n function readToggles(): ConsentChoices {\n const choices = { analytics: false, marketing: false, preferences: false };\n toggles.forEach((input, key) => (choices[key] = input.checked));\n return choices;\n }\n\n function applyTheme() {\n const dark = config.theme === \"dark\" || (config.theme === \"auto\" && !!media?.matches);\n root.setAttribute(\"data-theme\", dark ? \"dark\" : \"light\");\n applyAccent(dark);\n }\n\n /** A custom accent that is too faint on the dark background gives way to the dark theme's own. */\n function applyAccent(dark: boolean) {\n const accent = config.accentColor;\n if (!accent) return;\n if (dark && contrastRatio(accent, PALETTE.dark.bg) < 3) {\n for (const name of [\"--accent\", \"--focus\", \"--on-accent\"]) root.style.removeProperty(name);\n return;\n }\n root.style.setProperty(\"--accent\", accent);\n root.style.setProperty(\"--focus\", accent);\n root.style.setProperty(\"--on-accent\", onColor(accent));\n }\n\n function ensure() {\n if (host) return;\n host = el(\"div\", { id: \"bitsnap-consent\", \"data-bitsnap-consent-host\": \"\" });\n shadow = host.attachShadow({ mode: \"open\" });\n shadow.append(el(\"style\", {}, STYLES));\n root = el(\"div\", { class: \"root\", lang: locale });\n buildBanner();\n buildSettings();\n banner.hidden = true;\n overlay.hidden = true;\n root.append(banner, overlay);\n shadow.append(root);\n if (typeof doc.defaultView?.matchMedia === \"function\") {\n media = doc.defaultView.matchMedia(\"(prefers-color-scheme: dark)\");\n media.addEventListener?.(\"change\", applyTheme);\n }\n applyTheme();\n doc.body.append(host);\n }\n\n function focusables(): HTMLElement[] {\n return Array.from(dialog.querySelectorAll<HTMLElement>(FOCUSABLE));\n }\n\n function onKeydown(event: KeyboardEvent) {\n if (layer !== \"settings\") return;\n if (event.key === \"Escape\") {\n event.preventDefault();\n closeSettings();\n return;\n }\n if (event.key !== \"Tab\") return;\n const items = focusables();\n if (items.length === 0) return;\n const active = shadow?.activeElement as HTMLElement | null;\n const first = items[0];\n const last = items[items.length - 1];\n const outside = !active || !dialog.contains(active);\n if (event.shiftKey && (outside || active === first || active === dialog)) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && (outside || active === last)) {\n event.preventDefault();\n first.focus();\n }\n }\n\n function showBanner(focus = false) {\n try {\n ensure();\n layer = \"banner\";\n doc.removeEventListener(\"keydown\", onKeydown, true);\n overlay.hidden = true;\n banner.hidden = false;\n if (focus) banner.focus({ preventScroll: true });\n } catch {\n // never throw into the host page\n }\n }\n\n function showSettings() {\n try {\n ensure();\n if (layer !== \"settings\") {\n const active = doc.activeElement as HTMLElement | null;\n opener = active && active !== host && active !== doc.body ? active : null;\n }\n const current = options.getChoices();\n toggles.forEach((input, key) => (input.checked = !!current?.[key]));\n layer = \"settings\";\n banner.hidden = true;\n overlay.hidden = false;\n doc.addEventListener(\"keydown\", onKeydown, true);\n dialog.focus({ preventScroll: true });\n } catch {\n // never throw into the host page\n }\n }\n\n function closeSettings() {\n if (layer !== \"settings\") return;\n doc.removeEventListener(\"keydown\", onKeydown, true);\n overlay.hidden = true;\n if (options.hasChoice()) {\n layer = \"none\";\n opener?.focus?.({ preventScroll: true });\n } else {\n layer = \"banner\";\n banner.hidden = false;\n settingsButton.focus({ preventScroll: true });\n }\n }\n\n function hide() {\n if (!host) return;\n doc.removeEventListener(\"keydown\", onKeydown, true);\n const wasSettings = layer === \"settings\";\n layer = \"none\";\n banner.hidden = true;\n overlay.hidden = true;\n if (wasSettings) opener?.focus?.({ preventScroll: true });\n }\n\n function destroy() {\n doc.removeEventListener(\"keydown\", onKeydown, true);\n media?.removeEventListener?.(\"change\", applyTheme);\n host?.remove();\n host = null;\n shadow = null;\n layer = \"none\";\n }\n\n return { showBanner, showSettings, hide, destroy };\n}\n"]}