bitsnap-react 1.13.0 → 1.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +246 -0
- package/README.md +100 -52
- package/dist/CartProvider-2RNAKU3U.js +2 -0
- package/dist/CartProvider-2RNAKU3U.js.map +1 -0
- package/dist/{CartProvider-N73XNL7S.mjs → CartProvider-OSGG573S.mjs} +2 -2
- package/dist/analytics.d.mts +2 -2
- package/dist/analytics.d.ts +2 -2
- package/dist/analytics.js +1 -1
- package/dist/analytics.js.map +1 -1
- package/dist/analytics.mjs +1 -1
- package/dist/catalog.d.mts +1 -1
- package/dist/catalog.d.ts +1 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/catalog.mjs +1 -1
- package/dist/{chunk-TMBC2BHN.js → chunk-2OOQPXCQ.js} +3 -3
- package/dist/chunk-2OOQPXCQ.js.map +1 -0
- package/dist/{chunk-IP4OOWZ6.js → chunk-4MU2YAQT.js} +2 -2
- package/dist/chunk-4MU2YAQT.js.map +1 -0
- package/dist/{chunk-KH7DFTJY.mjs → chunk-4TZAGNEU.mjs} +2 -2
- package/dist/{chunk-EWLOGFF2.js → chunk-5DBLZ3VL.js} +2 -2
- package/dist/chunk-5DBLZ3VL.js.map +1 -0
- package/dist/{chunk-5GMWRCHK.mjs → chunk-7WJSK6SJ.mjs} +2 -2
- package/dist/{chunk-5GMWRCHK.mjs.map → chunk-7WJSK6SJ.mjs.map} +1 -1
- package/dist/{chunk-M4KEUK6I.js → chunk-EJRI366W.js} +2 -2
- package/dist/chunk-EJRI366W.js.map +1 -0
- package/dist/{chunk-K2EITRNW.mjs → chunk-FIWADPQX.mjs} +2 -2
- package/dist/{chunk-6CUCRTIK.js → chunk-GTOZ5BZX.js} +2 -2
- package/dist/chunk-GTOZ5BZX.js.map +1 -0
- package/dist/chunk-JSDGZ4NY.js.map +1 -1
- package/dist/{chunk-YNGXQJPE.mjs → chunk-JZBU5SZJ.mjs} +2 -2
- package/dist/{chunk-YNGXQJPE.mjs.map → chunk-JZBU5SZJ.mjs.map} +1 -1
- package/dist/{chunk-3A4YOO7Z.js → chunk-KKOIDDOW.js} +2 -2
- package/dist/chunk-KKOIDDOW.js.map +1 -0
- package/dist/chunk-KOYBZORL.js.map +1 -1
- package/dist/{chunk-3DGHF373.mjs → chunk-L7LZG6MR.mjs} +2 -2
- package/dist/chunk-MDCP5JNP.mjs +2 -0
- package/dist/chunk-MDCP5JNP.mjs.map +1 -0
- package/dist/{chunk-L6J6H73J.mjs → chunk-ONTCJSSD.mjs} +2 -2
- package/dist/{chunk-TSJCVFOX.js → chunk-PVJ2I46C.js} +2 -2
- package/dist/chunk-PVJ2I46C.js.map +1 -0
- package/dist/{chunk-UFQVOGBS.js → chunk-QQDZIVWY.js} +2 -2
- package/dist/chunk-QQDZIVWY.js.map +1 -0
- package/dist/{chunk-GAVLY6RX.mjs → chunk-TBYY3RL2.mjs} +2 -2
- package/dist/chunk-W3RGQYPD.js +2 -0
- package/dist/chunk-W3RGQYPD.js.map +1 -0
- package/dist/{chunk-OC7YS3UY.mjs → chunk-WJGC6EHC.mjs} +2 -2
- package/dist/consent.js +4 -4
- package/dist/consent.js.map +1 -1
- package/dist/consent.mjs +4 -4
- package/dist/consent.mjs.map +1 -1
- package/dist/course.d.mts +2 -2
- package/dist/course.d.ts +2 -2
- package/dist/course.js +1 -1
- package/dist/course.js.map +1 -1
- package/dist/course.mjs +1 -1
- package/dist/embed/analytics.js +1 -1
- package/dist/embed/consent.js +4 -4
- package/dist/errors.js.map +1 -1
- package/dist/index.d.mts +18 -3
- package/dist/index.d.ts +18 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{instrument-CmxK7S4T.d.ts → instrument-BE8ktMUv.d.mts} +14 -0
- package/dist/{instrument-CmxK7S4T.d.mts → instrument-BE8ktMUv.d.ts} +14 -0
- package/dist/internal.js.map +1 -1
- package/dist/methods-4WVTFI3Q.mjs +2 -0
- package/dist/methods-W5JTLIIX.js +2 -0
- package/dist/methods-W5JTLIIX.js.map +1 -0
- package/dist/models.js.map +1 -1
- package/dist/returns.d.mts +1 -1
- package/dist/returns.d.ts +1 -1
- package/dist/returns.js +1 -1
- package/dist/returns.js.map +1 -1
- package/dist/returns.mjs +1 -1
- package/dist/{types-BnVWLcoB.d.mts → types-DP1vxo5E.d.mts} +1 -1
- package/dist/{types-i-IuN4Im.d.ts → types-u8VwmC3j.d.ts} +1 -1
- package/package.json +39 -13
- package/dist/CartProvider-F7ER3WSS.js +0 -2
- package/dist/CartProvider-F7ER3WSS.js.map +0 -1
- package/dist/chunk-3A4YOO7Z.js.map +0 -1
- package/dist/chunk-6CUCRTIK.js.map +0 -1
- package/dist/chunk-ADYVTMGH.mjs +0 -2
- package/dist/chunk-ADYVTMGH.mjs.map +0 -1
- package/dist/chunk-EWLOGFF2.js.map +0 -1
- package/dist/chunk-IP4OOWZ6.js.map +0 -1
- package/dist/chunk-M4KEUK6I.js.map +0 -1
- package/dist/chunk-TMBC2BHN.js.map +0 -1
- package/dist/chunk-TSJCVFOX.js.map +0 -1
- package/dist/chunk-UFQVOGBS.js.map +0 -1
- package/dist/chunk-XIHGWNTS.js +0 -2
- package/dist/chunk-XIHGWNTS.js.map +0 -1
- package/dist/methods-ADH5XI4I.js +0 -2
- package/dist/methods-ADH5XI4I.js.map +0 -1
- package/dist/methods-BCR54EWX.mjs +0 -2
- /package/dist/{CartProvider-N73XNL7S.mjs.map → CartProvider-OSGG573S.mjs.map} +0 -0
- /package/dist/{chunk-KH7DFTJY.mjs.map → chunk-4TZAGNEU.mjs.map} +0 -0
- /package/dist/{chunk-K2EITRNW.mjs.map → chunk-FIWADPQX.mjs.map} +0 -0
- /package/dist/{chunk-3DGHF373.mjs.map → chunk-L7LZG6MR.mjs.map} +0 -0
- /package/dist/{chunk-L6J6H73J.mjs.map → chunk-ONTCJSSD.mjs.map} +0 -0
- /package/dist/{chunk-GAVLY6RX.mjs.map → chunk-TBYY3RL2.mjs.map} +0 -0
- /package/dist/{chunk-OC7YS3UY.mjs.map → chunk-WJGC6EHC.mjs.map} +0 -0
- /package/dist/{methods-BCR54EWX.mjs.map → methods-4WVTFI3Q.mjs.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/analytics/contract.ts","../src/consent/core/cookie.ts","../src/lib/isomorphic-layout-effect.ts"],"sourcesContent":["/**\n * Bitsnap merchant analytics: the wire contract.\n *\n * SOURCE OF TRUTH: instapay `apps/collector/src/contract.ts` (prose version:\n * `docs/merchant-analytics-contract.md`). This file is a verbatim copy of it\n * (everything below the next comment block). Do not edit it here: change\n * instapay's file and copy it over. `computeVisitorId` and\n * `computeConsentedVisitorId` are pure but need the server secret; they are\n * server-only: the browser never calls them, so bundlers drop them.\n */\n\nexport const SCHEMA_VERSION = 1;\n\n// ---------------------------------------------------------------------------\n// Limits\n// ---------------------------------------------------------------------------\n\nexport const LIMITS = {\n /** Events in one POST /e. */\n maxBatchEvents: 50,\n /** Body of one POST /e or /consent, in bytes. */\n maxBodyBytes: 64 * 1024,\n /** `JSON.stringify(props)` of one event, in UTF-16 code units. */\n maxPropsChars: 4096,\n maxPropString: 200,\n maxPropArray: 50,\n host: 253,\n path: 512,\n referrerHost: 253,\n utm: 100,\n refCode: 64,\n id: 64,\n sdk: 64,\n pageId: 32,\n region: 64,\n osBrowser: 32,\n /** Collector replaces a client `ts` farther than this from `received_at`. */\n tsSkewMs: 24 * 60 * 60 * 1000,\n} as const;\n\n// ---------------------------------------------------------------------------\n// Enumerations\n// ---------------------------------------------------------------------------\n\nexport const STREAMS = [\n \"storefront_events\",\n \"app_events\",\n \"business_events\",\n] as const;\nexport type Stream = (typeof STREAMS)[number];\n\nexport const ENVS = [\"live\", \"test\"] as const;\nexport type Env = (typeof ENVS)[number];\n\nexport const SOURCES = [\n \"storefront\",\n \"sdk_react\",\n \"script\",\n \"server\",\n \"dashboard\",\n] as const;\nexport type Source = (typeof SOURCES)[number];\n\nexport const CHANNELS = [\n \"hosted\",\n \"custom_domain\",\n \"embed\",\n \"api\",\n \"panel\",\n] as const;\nexport type Channel = (typeof CHANNELS)[number];\n\nexport const PAGE_TYPES = [\n \"shop\",\n \"catalog\",\n \"product\",\n \"cart\",\n \"checkout\",\n \"payment\",\n \"panel\",\n \"course\",\n \"custom_page\",\n \"order\",\n \"returns\",\n \"app\",\n \"other\",\n] as const;\nexport type PageType = (typeof PAGE_TYPES)[number];\n\nexport const DEVICE_TYPES = [\"desktop\", \"mobile\", \"tablet\", \"other\"] as const;\nexport type DeviceType = (typeof DEVICE_TYPES)[number];\n\n/** Sources a browser may claim, per stream. `business_events` is server-only. */\nexport const SOURCES_FOR_STREAM: Record<Stream, readonly Source[]> = {\n storefront_events: [\"storefront\", \"sdk_react\", \"script\"],\n app_events: [\"dashboard\"],\n business_events: [\"server\"],\n};\n\n// ---------------------------------------------------------------------------\n// Event catalogue\n//\n// Each prop is `<type>[?]`: type is `string`, `number`, `boolean`, `string[]`,\n// `number[]` or `enum:a|b|c`; a trailing `?` makes the prop optional.\n// Money is always integer minor units (`*_minor`, grosze/cents) + `currency`\n// (ISO 4217, upper case). `product_id`, `variant_id` and `order_ref` live in\n// the envelope, never in props. Strings never hold PII (see the prose doc).\n// ---------------------------------------------------------------------------\n\nconst MONEY = { value_minor: \"number\", currency: \"string\" } as const;\n\n/** Browser events from hosted pages (H), bitsnap-react (R) and the script (S). */\nexport const STOREFRONT_EVENT_SPEC = {\n page_view: { landing: \"boolean\" },\n product_list_viewed: { list_id: \"string?\", item_count: \"number\" },\n product_impression: {\n list_id: \"string?\",\n product_ids: \"string[]\",\n positions: \"number[]\",\n },\n product_clicked: { list_id: \"string?\", position: \"number?\" },\n product_view: {\n price_minor: \"number\",\n currency: \"string\",\n availability: \"enum:in_stock|out_of_stock|preorder\",\n },\n variant_selected: {},\n add_to_cart: { qty: \"number\", ...MONEY },\n remove_from_cart: { qty: \"number\", ...MONEY },\n cart_opened: { item_count: \"number\", ...MONEY },\n checkout_started: {\n item_count: \"number\",\n checkout_type: \"enum:single|cart|link\",\n ...MONEY,\n },\n checkout_step_completed: {\n step: \"enum:contact|delivery|invoice|consents\",\n },\n checkout_validation_error: { field: \"string\", rule: \"string\" },\n coupon_applied: { coupon_id: \"string\" },\n coupon_rejected: { coupon_id: \"string?\", reason: \"string\" },\n delivery_method_selected: { method: \"string\" },\n payment_method_selected: { gateway: \"string\", method: \"string\" },\n payment_submitted: { gateway: \"string\", method: \"string\" },\n apple_pay_clicked: {},\n apple_pay_result: { outcome: \"enum:success|fail|cancel\" },\n payment_returned: {\n gateway: \"string\",\n method: \"string?\",\n outcome: \"enum:success|fail|cancel|pending\",\n error_code: \"string?\",\n },\n availability_signup: {},\n panel_login: {},\n panel_order_viewed: {},\n panel_download: {},\n return_started: {},\n return_submitted: { reason_code: \"string\", item_count: \"number\" },\n course_opened: { course_id: \"string\" },\n lesson_started: {\n course_id: \"string\",\n lesson_id: \"string\",\n position: \"number\",\n },\n lesson_completed: {\n course_id: \"string\",\n lesson_id: \"string\",\n position: \"number\",\n },\n video_progress: {\n course_id: \"string\",\n lesson_id: \"string\",\n /** 25, 50, 75 or 100. */\n milestone: \"number\",\n },\n test_submitted: {\n course_id: \"string\",\n lesson_id: \"string\",\n score_bucket: \"enum:0-24|25-49|50-74|75-99|100\",\n },\n lesson_rated: {\n course_id: \"string\",\n lesson_id: \"string\",\n /** 1..5. */\n rating: \"number\",\n },\n /** Written by the collector's POST /consent, never sent to POST /e. */\n consent_updated: {\n consent_id: \"string\",\n action: \"enum:accept_all|reject_all|custom|withdraw\",\n analytics: \"boolean\",\n marketing: \"boolean\",\n preferences: \"boolean\",\n banner_version: \"number\",\n },\n /**\n * Written by the collector's POST /consent (action `shown`), never sent to\n * POST /e. A banner impression: no consent id, no choice, no visitor.\n */\n consent_shown: {\n banner_version: \"number\",\n },\n} as const;\n\n/** Merchant behaviour in /app, sent through the same tracker core. */\nexport const APP_EVENT_SPEC = {\n app_page_view: { route: \"string\", previous_route: \"string?\" },\n insight_shown: { insight_type: \"string\", rank: \"number\", category: \"string\" },\n insight_clicked: {\n insight_type: \"string\",\n rank: \"number\",\n category: \"string\",\n },\n insight_dismissed: {\n insight_type: \"string\",\n rank: \"number\",\n category: \"string\",\n },\n checklist_step_viewed: { step: \"string\" },\n checklist_step_completed: { step: \"string\" },\n gateway_connect_started: { gateway: \"string\", step: \"string?\" },\n gateway_connect_completed: { gateway: \"string\", step: \"string?\" },\n gateway_connect_failed: {\n gateway: \"string\",\n step: \"string?\",\n error_code: \"string?\",\n },\n domain_connect_started: {},\n domain_connect_verified: {},\n domain_connect_failed: { error_code: \"string?\" },\n product_created: { product_type: \"string?\" },\n product_published: { product_type: \"string?\" },\n product_editor_section_opened: { section: \"string\" },\n feature_enabled: { feature: \"string\" },\n stats_viewed: { tab: \"string\" },\n stats_filter_changed: { tab: \"string\", filter: \"string\" },\n report_exported: { report: \"string\", format: \"string?\" },\n search_performed: { result_count: \"number\" },\n error_shown: { code: \"string\", route: \"string\" },\n help_opened: { topic: \"string?\" },\n ai_assistant_used: { topic: \"string?\" },\n member_invited: { role: \"string\" },\n} as const;\n\nconst TX = {\n gateway: \"string?\",\n method: \"string?\",\n value_minor: \"number?\",\n currency: \"string?\",\n} as const;\nconst SUB = {\n subscription_id: \"string?\",\n value_minor: \"number?\",\n currency: \"string?\",\n} as const;\n\n/**\n * Emitted by instapay only. The lower-cased `EventType` of\n * server/event-system/event.list.ts maps 1:1 to the first group.\n */\nexport const BUSINESS_EVENT_SPEC = {\n // Mirror of the event bus (EventType.X -> x.toLowerCase()).\n transaction_created: TX,\n transaction_success: TX,\n transaction_failure: { ...TX, error_code: \"string?\" },\n transaction_expired: TX,\n transaction_charge: TX,\n subscription_created: SUB,\n subscription_paused: SUB,\n subscription_resumed: SUB,\n subscription_updated: SUB,\n subscription_deleted: SUB,\n subscription_charge_paid: SUB,\n subscription_charge_failed: { ...SUB, error_code: \"string?\" },\n subscription_past_due: SUB,\n subscription_canceled: SUB,\n access_expires_in_3_days: {},\n access_expired: {},\n cart_recovery: { value_minor: \"number?\", currency: \"string?\" },\n testimonial_email_send: {},\n testimonial_fulfilled: {},\n partner_commission_earned: {\n partner_id: \"string\",\n commission_minor: \"number\",\n currency: \"string\",\n },\n // Added by the analytics work.\n checkout_session_created: {\n item_count: \"number\",\n checkout_type: \"enum:single|cart|link\",\n gateway: \"string?\",\n ...MONEY,\n },\n order_paid: {\n gateway: \"string\",\n method: \"string?\",\n item_count: \"number?\",\n /** UTC date (`YYYY-MM-DD`) the envelope `visitor_id` was computed for. */\n visitor_day: \"string?\",\n /** Every line of the order (public hashed product ids), at most 50. */\n items: \"line_items?\",\n ...MONEY,\n },\n refund_issued: {\n gateway: \"string?\",\n reason: \"string?\",\n ...MONEY,\n },\n return_requested: { item_count: \"number\", reason_code: \"string?\" },\n automation_run_completed: {\n automation_id: \"string\",\n status: \"string\",\n trigger: \"string?\",\n },\n notification_sent: { medium: \"string\", template: \"string?\" },\n notification_failed: {\n medium: \"string\",\n template: \"string?\",\n error_code: \"string?\",\n },\n recovery_email_sent: { step: \"number?\" },\n recovery_link_clicked: {},\n api_request: {\n /** Route template without ids or query, e.g. `/api/rpc/public.v1.PublicApiService/ListProducts`. */\n endpoint: \"string\",\n /** `X-Bitsnap-Client` value, absent when the caller sent none. */\n client: \"string?\",\n status: \"number\",\n latency_bucket: \"enum:lt_50|lt_200|lt_1000|gte_1000\",\n /** 1 for errors, <1 for sampled successes; rollups divide counts by it. */\n sample_rate: \"number\",\n },\n} as const;\n\nexport const EVENT_SPEC_BY_STREAM = {\n storefront_events: STOREFRONT_EVENT_SPEC,\n app_events: APP_EVENT_SPEC,\n business_events: BUSINESS_EVENT_SPEC,\n} as const;\n\nexport const EVENT_SPEC = {\n ...STOREFRONT_EVENT_SPEC,\n ...APP_EVENT_SPEC,\n ...BUSINESS_EVENT_SPEC,\n} as const;\n\nexport type StorefrontEventName = keyof typeof STOREFRONT_EVENT_SPEC;\nexport type AppEventName = keyof typeof APP_EVENT_SPEC;\nexport type BusinessEventName = keyof typeof BUSINESS_EVENT_SPEC;\nexport type EventName = StorefrontEventName | AppEventName | BusinessEventName;\n\nexport const EVENT_NAMES = {\n storefront_events: Object.keys(STOREFRONT_EVENT_SPEC) as StorefrontEventName[],\n app_events: Object.keys(APP_EVENT_SPEC) as AppEventName[],\n business_events: Object.keys(BUSINESS_EVENT_SPEC) as BusinessEventName[],\n} as const;\n\nexport const STREAM_FOR_EVENT: Record<EventName, Stream> = Object.fromEntries(\n STREAMS.flatMap((stream) =>\n (EVENT_NAMES[stream] as string[]).map((name) => [name, stream] as const),\n ),\n) as Record<EventName, Stream>;\n\n/** True for a catalogue event name; own keys only (`constructor`, `toString` are not events). */\nexport function isEventName(name: unknown): name is EventName {\n return typeof name === \"string\" && Object.hasOwn(STREAM_FOR_EVENT, name);\n}\n\n// -- props types, derived from the spec ------------------------------------\n\ntype PropPrimitives = {\n string: string;\n number: number;\n boolean: boolean;\n \"string[]\": string[];\n \"number[]\": number[];\n line_items: Array<{ product_id: string; qty: number; value_minor: number }>;\n};\ntype SplitEnum<S extends string> = S extends `${infer H}|${infer R}`\n ? H | SplitEnum<R>\n : S;\ntype StripOpt<S extends string> = S extends `${infer B}?` ? B : S;\ntype ResolveProp<S extends string> =\n StripOpt<S> extends `enum:${infer E}`\n ? SplitEnum<E>\n : StripOpt<S> extends keyof PropPrimitives\n ? PropPrimitives[StripOpt<S>]\n : never;\ntype PropsFromSpec<S extends Record<string, string>> = {\n [K in keyof S as S[K] extends `${string}?` ? never : K]: ResolveProp<S[K]>;\n} & {\n [K in keyof S as S[K] extends `${string}?` ? K : never]?: ResolveProp<S[K]>;\n};\n\nexport type EventProps<E extends EventName> = PropsFromSpec<\n (typeof EVENT_SPEC)[E]\n>;\n\n// ---------------------------------------------------------------------------\n// Envelope\n// ---------------------------------------------------------------------------\n\n/** Fields the emitter fills in. Everything else is derived by the collector. */\nexport interface ClientEvent<E extends EventName = EventName> {\n /** UUIDv7, generated by the emitter. Dedupe key. */\n event_id: string;\n event: E;\n /** Client clock, unix ms. */\n ts: number;\n schema_version: typeof SCHEMA_VERSION;\n env: Env;\n source: Source;\n channel: Channel;\n /** `<package>@<version>`, e.g. `bitsnap-react@1.9.0`. */\n sdk?: string | null;\n /** Random per page load, in memory only. */\n page_id?: string | null;\n page_type?: PageType | null;\n host?: string | null;\n /** Path without query string and fragment, already run through `sanitizePath`. */\n path?: string | null;\n referrer_host?: string | null;\n utm_source?: string | null;\n utm_medium?: string | null;\n utm_campaign?: string | null;\n utm_content?: string | null;\n utm_term?: string | null;\n ref_code?: string | null;\n product_id?: string | null;\n variant_id?: string | null;\n order_ref?: string | null;\n /** Object on the wire; the collector stores `JSON.stringify(props)`. */\n props: EventProps<E>;\n /**\n * Only honoured for `source: \"dashboard\"`: the hashed Clerk user id computed\n * by instapay and handed to the dashboard tracker. Ignored for every other\n * source (the collector computes `visitor_id` itself).\n */\n visitor_id?: string | null;\n /**\n * The value of the first-party `bs_vid_<projectKey>` cookie (`CLIENT_ID_RE`), sent only\n * while analytics consent is granted. The collector turns it into a stable\n * `consentedVisitorId` and never stores it.\n */\n client_id?: string | null;\n}\n\n/** One row as stored in Basin (all three streams share this shape). */\nexport interface StoredEvent {\n event_id: string;\n event: EventName;\n /** Unix ms, client clock after `clampTs`. */\n ts: number;\n /** Unix ms, collector clock. */\n received_at: number;\n schema_version: number;\n /** Numeric database id. Resolved by the collector, never taken from the client. */\n project_id: number;\n env: Env;\n source: Source;\n channel: Channel;\n sdk: string | null;\n visitor_id: string | null;\n page_id: string | null;\n page_type: PageType | null;\n host: string | null;\n path: string | null;\n referrer_host: string | null;\n utm_source: string | null;\n utm_medium: string | null;\n utm_campaign: string | null;\n utm_content: string | null;\n utm_term: string | null;\n ref_code: string | null;\n country: string | null;\n region: string | null;\n device_type: DeviceType | null;\n os: string | null;\n browser: string | null;\n product_id: string | null;\n variant_id: string | null;\n order_ref: string | null;\n /** `JSON.stringify` of the props object. */\n props: string;\n}\n\n/** POST /e body. */\nexport interface IngestBody {\n /** Project key, see `normalizeProjectKey`. */\n k: string;\n events: ClientEvent[];\n}\n\n// ---------------------------------------------------------------------------\n// Consent shapes\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;\nexport type ConsentTextKey = (typeof CONSENT_TEXT_KEYS)[number];\nexport type ConsentTexts = Record<ConsentTextKey, string>;\n\nexport type ConsentCategory = \"analytics\" | \"marketing\" | \"preferences\";\nexport type ConsentChoice = Record<ConsentCategory, boolean>;\n\nexport type ConsentConfig = {\n version: number;\n theme: \"auto\" | \"light\" | \"dark\";\n accentColor?: string;\n position: \"bottom\" | \"bottom-left\" | \"bottom-right\";\n privacyPolicyUrl?: string;\n categories: { analytics: boolean; marketing: boolean; preferences: boolean };\n services: Array<{\n name: string;\n category: \"analytics\" | \"marketing\" | \"preferences\";\n cookies?: string[];\n }>;\n texts?: Partial<Record<\"pl\" | \"en\", Partial<ConsentTexts>>>;\n poweredBy: true;\n};\n\n/** Value of the consent cookie, JSON then base64url. */\nexport interface ConsentCookie {\n v: 1;\n /** Random consent id (also sent to POST /consent). */\n id: string;\n /** Unix seconds. */\n ts: number;\n /** Banner version (`ConsentConfig.version`) the visitor answered. */\n bv: number;\n c: ConsentChoice;\n}\n\nexport const CONSENT_COOKIE_NAME = \"bitsnap_consent\";\nexport const CONSENT_COOKIE_MAX_AGE_SECONDS = 365 * 24 * 60 * 60;\nexport const CONSENT_ACTIONS = [\n \"accept_all\",\n \"reject_all\",\n \"custom\",\n \"withdraw\",\n] as const;\nexport type ConsentAction = (typeof CONSENT_ACTIONS)[number];\n/** POST /consent `action` of a banner impression (not a choice, not in `CONSENT_ACTIONS`). */\nexport const CONSENT_SHOWN_ACTION = \"shown\";\n\n/** POST /consent body of a choice (`CONSENT_ACTIONS`). */\nexport interface ConsentLogBody {\n k: string;\n /** Same random id as `ConsentCookie.id`. 16 to 64 chars of `[A-Za-z0-9_-]`. */\n consent_id: string;\n action: ConsentAction;\n c: ConsentChoice;\n /** Banner version. */\n bv: number;\n /** Hostname the banner ran on. Collector overwrites it with the Origin host. */\n host: string;\n /** Unix SECONDS (like the cookie), not ms. */\n ts: number;\n}\n\n/**\n * POST /consent body of a banner impression: the banner opened by itself\n * because the visitor has no valid choice. Once per page load; no consent id\n * and no choice.\n */\nexport interface ConsentShownBody {\n k: string;\n action: typeof CONSENT_SHOWN_ACTION;\n /** Banner version. */\n bv: number;\n /** Hostname the banner ran on. Collector overwrites it with the Origin host. */\n host: string;\n /** Unix SECONDS (like the cookie), not ms. */\n ts: number;\n}\n\n/** Any POST /consent body; discriminate on `action`. */\nexport type ConsentBody = ConsentLogBody | ConsentShownBody;\n\n/** `bitsnap_consent`, or `bitsnap_consent_<projectKey>` for `data-scope=\"project\"`. */\nexport function consentCookieName(scope: \"site\" | \"project\", projectKey?: string): string {\n if (scope === \"project\") {\n if (!projectKey) throw new Error(\"projectKey required for project scope\");\n return `${CONSENT_COOKIE_NAME}_${normalizeProjectKey(projectKey)}`;\n }\n return CONSENT_COOKIE_NAME;\n}\n\n/**\n * Decodes the value of a consent cookie (§11.3). Null when it is not base64url\n * JSON of the documented shape (`v` 1 and a boolean per category).\n */\nexport function parseConsentCookie(value: string | null | undefined): ConsentCookie | null {\n if (!value || !/^[A-Za-z0-9_-]+$/.test(value)) return null;\n try {\n const padded = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const bin = atob(padded + \"=\".repeat((4 - (padded.length % 4)) % 4));\n const json: unknown = JSON.parse(\n new TextDecoder().decode(Uint8Array.from(bin, (ch) => ch.charCodeAt(0))),\n );\n if (!isRecord(json) || json.v !== 1) return null;\n const c = json.c;\n if (!isRecord(c)) return null;\n if (\n typeof c.analytics !== \"boolean\" ||\n typeof c.marketing !== \"boolean\" ||\n typeof c.preferences !== \"boolean\"\n ) {\n return null;\n }\n return json as unknown as ConsentCookie;\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Project key\n// ---------------------------------------------------------------------------\n\n/**\n * The project key is the existing public hashed project id\n * (`hashId(projectId)` in apps/bitsnap/queries/hashids.ts, the `projectID`\n * of bitsnap-react). A leading `pk_` is accepted and dropped so the\n * documented `pk_…` snippets work too. Returns null when it is not a plausible\n * key (hashids default alphabet).\n */\nexport function normalizeProjectKey(key: string): string | null {\n const bare = key.startsWith(\"pk_\") ? key.slice(3) : key;\n return /^[A-Za-z0-9]{1,32}$/.test(bare) ? bare : null;\n}\n\n// ---------------------------------------------------------------------------\n// X-Bitsnap-Client\n// ---------------------------------------------------------------------------\n\nconst CLIENT_RE = /^([a-z][a-z0-9-]{0,39})@(\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.+-]{1,20})?)$/;\n\n/** `<package>@<version>`, e.g. `bitsnap-react@1.9.0`. Also the shape of `sdk`. */\nexport function parseClientHeader(\n value: string | null | undefined,\n): { package: string; version: string } | null {\n if (!value || value.length > LIMITS.sdk) return null;\n const m = CLIENT_RE.exec(value);\n return m ? { package: m[1], version: m[2] } : null;\n}\n\n// ---------------------------------------------------------------------------\n// URL stripping\n// ---------------------------------------------------------------------------\n\nconst MAX_QUERY_VALUE = LIMITS.utm;\n\n/**\n * Campaign/ref value: trimmed, capped, null when empty or when it holds an \"@\"\n * (someone put an email in a tag). The collector runs every client-supplied\n * `utm_*` and `ref_code` through it again.\n */\nexport function cleanValue(v: string | null | undefined, max: number): string | null {\n if (v == null) return null;\n const t = v.trim();\n // An \"@\" means someone put an email in a campaign tag: drop the value.\n if (t.length === 0 || t.includes(\"@\")) return null;\n return t.slice(0, max);\n}\n\n/**\n * Path sanitiser: no query, no fragment, capped. Opaque segments (24+ chars of\n * `[A-Za-z0-9_-]`, i.e. tokens in order/panel links) become `:token` and\n * segments containing `@` become `:email`.\n */\nexport function sanitizePath(pathname: string): string {\n const segments = pathname.split(\"/\").map((seg) => {\n if (seg.includes(\"@\") || seg.includes(\"%40\")) return \":email\";\n if (/^[A-Za-z0-9_-]{24,}$/.test(seg)) return \":token\";\n return seg;\n });\n const joined = segments.join(\"/\") || \"/\";\n return (joined.startsWith(\"/\") ? joined : `/${joined}`).slice(0, LIMITS.path);\n}\n\nexport interface UrlParts {\n host: string;\n /** Sanitised path, no query. */\n path: string;\n utm_source: string | null;\n utm_medium: string | null;\n utm_campaign: string | null;\n utm_content: string | null;\n utm_term: string | null;\n /** The `ref` query parameter. */\n ref_code: string | null;\n}\n\n/**\n * Parses a URL and keeps only what may leave the browser: host, sanitised path\n * and the `utm_*` and `ref` query parameters. Returns null for non-http(s) or\n * unparseable input. `base` resolves relative URLs.\n */\nexport function parseUrl(url: string, base?: string): UrlParts | null {\n let u: URL;\n try {\n u = new URL(url, base);\n } catch {\n return null;\n }\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n const q = u.searchParams;\n return {\n host: u.hostname.toLowerCase().slice(0, LIMITS.host),\n path: sanitizePath(u.pathname),\n utm_source: cleanValue(q.get(\"utm_source\"), MAX_QUERY_VALUE),\n utm_medium: cleanValue(q.get(\"utm_medium\"), MAX_QUERY_VALUE),\n utm_campaign: cleanValue(q.get(\"utm_campaign\"), MAX_QUERY_VALUE),\n utm_content: cleanValue(q.get(\"utm_content\"), MAX_QUERY_VALUE),\n utm_term: cleanValue(q.get(\"utm_term\"), MAX_QUERY_VALUE),\n ref_code: cleanValue(q.get(\"ref\"), LIMITS.refCode),\n };\n}\n\n/**\n * Returns the URL with userinfo, fragment and every query parameter removed\n * except `utm_*` and `ref`. Null when `url` is not a usable http(s) URL.\n */\nexport function stripUrl(url: string, base?: string): string | null {\n let u: URL;\n try {\n u = new URL(url, base);\n } catch {\n return null;\n }\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n const keep = new URLSearchParams();\n for (const [key, value] of u.searchParams) {\n if (key !== \"ref\" && !key.startsWith(\"utm_\")) continue;\n const cleaned = cleanValue(value, MAX_QUERY_VALUE);\n if (cleaned != null) keep.append(key, cleaned);\n }\n const qs = keep.toString();\n return `${u.protocol}//${u.host}${sanitizePath(u.pathname)}${qs ? `?${qs}` : \"\"}`;\n}\n\nconst HOSTNAME_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;\n\n/** A plain DNS hostname (lower-cased), or null: no scheme, port, path, userinfo or \"@\". */\nexport function cleanHostname(\n v: string | null | undefined,\n max: number = LIMITS.referrerHost,\n): string | null {\n if (typeof v !== \"string\") return null;\n const h = v.trim().toLowerCase();\n return h.length > 0 && h.length <= max && HOSTNAME_RE.test(h) ? h : null;\n}\n\n/** Public hashed ids (`product_id`, `variant_id`, `order_ref`): URL-safe, at most `LIMITS.id`. */\nexport const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;\n\nexport function cleanId(v: string | null | undefined): string | null {\n return typeof v === \"string\" && ID_RE.test(v) ? v : null;\n}\n\n/** Host of a referrer URL, or null (also null for non-http(s) referrers). */\nexport function referrerHost(referrer: string | null | undefined): string | null {\n if (!referrer) return null;\n try {\n const u = new URL(referrer);\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n return u.hostname.toLowerCase().slice(0, LIMITS.referrerHost);\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Bot rule\n// ---------------------------------------------------------------------------\n\nconst BOT_UA =\n /bot\\b|crawl|spider|slurp|facebookexternalhit|bingpreview|headless|phantomjs|lighthouse|pagespeed|gtmetrix|pingdom|uptime|statuscake|monitor|preview|scrapy|curl\\/|wget|python-|go-http-client|java\\/|okhttp|axios|node-fetch|undici|libwww|httpclient|aiohttp|postman|insomnia/i;\n\n/** True when the User-Agent is empty or looks automated. Such events are dropped. */\nexport function isBotUserAgent(ua: string | null | undefined): boolean {\n if (!ua || ua.trim().length === 0) return true;\n return BOT_UA.test(ua);\n}\n\n// ---------------------------------------------------------------------------\n// visitor_id\n// ---------------------------------------------------------------------------\n\nconst encoder = new TextEncoder();\n\nasync function hmacSha256(\n key: Uint8Array,\n message: string,\n): Promise<Uint8Array> {\n const cryptoKey = await crypto.subtle.importKey(\n \"raw\",\n key,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n return new Uint8Array(\n await crypto.subtle.sign(\"HMAC\", cryptoKey, encoder.encode(message)),\n );\n}\n\nfunction base64url(bytes: Uint8Array): string {\n let bin = \"\";\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** `YYYY-MM-DD` of a unix-ms timestamp in UTC. */\nexport function utcDate(ms: number): string {\n return new Date(ms).toISOString().slice(0, 10);\n}\n\n/**\n * IP as hashed: lower-case; IPv4 unchanged; IPv4-mapped IPv6 (`::ffff:1.2.3.4`\n * or `::ffff:102:304`) becomes plain IPv4; any other IPv6, including one with\n * an embedded dotted quad (`64:ff9b::1.2.3.4`), is cut to its /64 (first four\n * hextets, canonical form `a:b:c:d::`). Both the Worker and the instapay\n * server MUST call this on the client IP before `computeVisitorId`.\n */\nexport function normalizeIp(ip: string): string {\n let s = ip.trim().toLowerCase();\n const zone = s.indexOf(\"%\");\n if (zone >= 0) s = s.slice(0, zone);\n if (!s.includes(\":\")) return s; // plain IPv4 (or not an IP at all)\n\n // Embedded dotted quad in the last 32 bits: turn it into two hextets.\n const quad = /^(.*:)(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(s);\n if (quad) {\n const o = [quad[2], quad[3], quad[4], quad[5]].map(Number);\n if (o.some((n) => n > 255)) return s;\n const hex = (hi: number, lo: number) => (hi * 256 + lo).toString(16);\n s = `${quad[1]}${hex(o[0], o[1])}:${hex(o[2], o[3])}`;\n }\n\n const [head, tail] = s.split(\"::\");\n const headParts = head ? head.split(\":\") : [];\n const tailParts = tail !== undefined && tail !== \"\" ? tail.split(\":\") : [];\n const fill =\n tail === undefined ? 0 : Math.max(0, 8 - headParts.length - tailParts.length);\n const groups = [...headParts, ...Array<string>(fill).fill(\"0\"), ...tailParts];\n if (groups.length !== 8) return s;\n const h = groups.map((g) => Number.parseInt(g, 16) || 0);\n\n // ::ffff:a.b.c.d in hex form.\n if (h.slice(0, 5).every((x) => x === 0) && h[5] === 0xffff) {\n return `${h[6] >> 8}.${h[6] & 255}.${h[7] >> 8}.${h[7] & 255}`;\n }\n return `${h\n .slice(0, 4)\n .map((g) => g.toString(16))\n .join(\":\")}::`;\n}\n\n/**\n * Cookieless visitor id, identical in the Worker and the instapay server.\n *\n * day_secret = HMAC-SHA256(key = utf8(masterSecret), msg = utf8(\"YYYY-MM-DD\")) // 32 raw bytes\n * visitor_id = base64url(HMAC-SHA256(key = day_secret, msg = utf8(ip + \"\\n\" + ua + \"\\n\" + projectId))).slice(0, 22)\n *\n * `dateUtc` is the UTC date of the request; `ip` is `normalizeIp(<client IP>)`;\n * `ua` is the raw `User-Agent` request header; `projectId` is the decimal\n * numeric project id.\n */\nexport async function computeVisitorId(\n masterSecret: string,\n dateUtc: string,\n ip: string,\n ua: string,\n projectId: number | string,\n): Promise<string> {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(dateUtc)) {\n throw new Error(`dateUtc must be YYYY-MM-DD, got ${dateUtc}`);\n }\n const daySecret = await hmacSha256(encoder.encode(masterSecret), dateUtc);\n const mac = await hmacSha256(daySecret, `${ip}\\n${ua}\\n${projectId}`);\n return base64url(mac).slice(0, 22);\n}\n\n/**\n * The `bs_vid_<projectKey>` cookie name. `projectKey` is the bare public key\n * (like `consentCookieName`): consent is per project, so is the client id.\n */\nexport function clientIdCookieName(projectKey: string): string {\n return `bs_vid_${projectKey}`;\n}\n\n/** Value of the `bs_vid_<projectKey>` cookie: 16 random bytes, base64url without padding. */\nexport const CLIENT_ID_RE = /^[A-Za-z0-9_-]{22}$/;\n\n/**\n * Stable visitor id of a browser that granted analytics consent (contract §6).\n *\n * consented_visitor_id = \"p_\" + base64url(HMAC-SHA256(key = utf8(masterSecret),\n * msg = utf8(\"client\\n\" + clientId + \"\\n\" + projectId))).slice(0, 22)\n *\n * 24 characters; daily ids are 22, so `isConsentedVisitorId` tells them apart.\n * `clientId` is the `bs_vid_<projectKey>` cookie value and is never stored.\n */\nexport async function computeConsentedVisitorId(\n masterSecret: string,\n clientId: string,\n projectId: number | string,\n): Promise<string> {\n if (!CLIENT_ID_RE.test(clientId)) {\n throw new Error(\"clientId must be 22 base64url characters\");\n }\n const mac = await hmacSha256(\n encoder.encode(masterSecret),\n `client\\n${clientId}\\n${projectId}`,\n );\n return `p_${base64url(mac).slice(0, 22)}`;\n}\n\n/** Whether `visitorId` came from `computeConsentedVisitorId` (not a daily id). */\nexport function isConsentedVisitorId(visitorId: string): boolean {\n return visitorId.length === 24 && visitorId.startsWith(\"p_\");\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nexport type ValidationResult = { ok: true } | { ok: false; reason: string };\n\nconst UUID_V7 =\n /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nconst PAGE_ID_RE = /^[A-Za-z0-9_-]{8,32}$/;\n/** A letter TLD is required: `bitsnap-react@1.9.0` and `v@1.2` are not addresses. */\nconst EMAIL_LIKE = /[^\\s@]+@[^\\s@]+\\.[A-Za-z]{2,}\\b/;\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nfunction nullableString(\n e: Record<string, unknown>,\n key: string,\n max: number,\n): string | null {\n const v = e[key];\n if (v === undefined || v === null) return null;\n if (typeof v !== \"string\") return `bad_${key}`;\n return v.length > max ? `too_long_${key}` : null;\n}\n\nfunction checkPropValue(spec: string, value: unknown): boolean {\n const optional = spec.endsWith(\"?\");\n const type = optional ? spec.slice(0, -1) : spec;\n if (type.startsWith(\"enum:\")) {\n return typeof value === \"string\" && type.slice(5).split(\"|\").includes(value);\n }\n switch (type) {\n case \"string\":\n return typeof value === \"string\" && value.length <= LIMITS.maxPropString;\n case \"number\":\n return typeof value === \"number\" && Number.isFinite(value);\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"string[]\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every((x) => typeof x === \"string\" && x.length <= LIMITS.maxPropString)\n );\n case \"number[]\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every((x) => typeof x === \"number\" && Number.isFinite(x))\n );\n case \"line_items\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every(\n (x) =>\n isRecord(x) &&\n typeof x.product_id === \"string\" &&\n ID_RE.test(x.product_id) &&\n isNonNegativeSafeInteger(x.qty) &&\n isNonNegativeSafeInteger(x.value_minor),\n )\n );\n default:\n return false;\n }\n}\n\nfunction isNonNegativeSafeInteger(value: unknown): boolean {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\n/** True when `value` looks like an email address (also exported for the collector's re-checks). */\nexport function looksLikeEmail(value: string): boolean {\n // A well-formed `<package>@<version>` client id is never an address.\n if (parseClientHeader(value) !== null) return false;\n return EMAIL_LIKE.test(value);\n}\n\nfunction hasEmailLike(value: unknown): boolean {\n if (typeof value === \"string\") return looksLikeEmail(value);\n if (Array.isArray(value)) return value.some(hasEmailLike);\n if (isRecord(value)) return Object.values(value).some(hasEmailLike);\n return false;\n}\n\n/**\n * Validates `props` against the catalogue and returns a copy without keys the\n * catalogue does not know (forward compatibility: a newer SDK adding an\n * optional prop must not get its events dropped by an older collector).\n * Fails on missing required props, wrong types, bad enum values, oversize\n * props and string values that look like an email address.\n */\nexport function sanitizeProps(\n event: string,\n props: unknown,\n): { ok: true; props: Record<string, unknown> } | { ok: false; reason: string } {\n if (!isEventName(event)) return { ok: false, reason: \"unknown_event\" };\n const spec = (EVENT_SPEC as Record<string, Record<string, string>>)[event];\n if (!spec) return { ok: false, reason: \"unknown_event\" };\n if (!isRecord(props)) return { ok: false, reason: \"bad_props\" };\n const out: Record<string, unknown> = {};\n for (const [key, type] of Object.entries(spec)) {\n const value = props[key];\n if (value === undefined || value === null) {\n if (!type.endsWith(\"?\")) return { ok: false, reason: `props_missing_${key}` };\n continue;\n }\n if (!checkPropValue(type, value)) return { ok: false, reason: `props_bad_${key}` };\n if (hasEmailLike(value)) return { ok: false, reason: `props_pii_${key}` };\n out[key] =\n type.startsWith(\"line_items\") && Array.isArray(value)\n ? value.map((x) => ({ product_id: x.product_id, qty: x.qty, value_minor: x.value_minor }))\n : value;\n }\n if (JSON.stringify(out).length > LIMITS.maxPropsChars) {\n return { ok: false, reason: \"props_too_large\" };\n }\n return { ok: true, props: out };\n}\n\nexport interface ValidateOptions {\n /**\n * Who sent it. `browser` (default) is POST /e: the event must belong to\n * `storefront_events` or `app_events`, `consent_updated` and `consent_shown`\n * are refused (only POST /consent writes them) and `source` must fit the\n * stream. `server` is the instapay emitter: any stream, `source` must fit the\n * stream.\n */\n from?: \"browser\" | \"server\";\n}\n\n/**\n * Validates the emitter-controlled part of an event: names, types, enums,\n * lengths, the event/source/stream pairing and `props`. It does not check\n * that `ts` is plausible (use `clampTs`), origins or project keys.\n */\nexport function validateEnvelope(\n e: unknown,\n options: ValidateOptions = {},\n): ValidationResult {\n const from = options.from ?? \"browser\";\n const fail = (reason: string): ValidationResult => ({ ok: false, reason });\n if (!isRecord(e)) return fail(\"not_object\");\n\n if (typeof e.event_id !== \"string\" || !UUID_V7.test(e.event_id)) {\n return fail(\"bad_event_id\");\n }\n if (!isEventName(e.event)) return fail(\"unknown_event\");\n const stream = STREAM_FOR_EVENT[e.event as EventName];\n if (from === \"browser\") {\n if (stream === \"business_events\") return fail(\"server_only_event\");\n if (e.event === \"consent_updated\" || e.event === \"consent_shown\") {\n return fail(\"consent_via_consent_endpoint\");\n }\n }\n if (\n typeof e.ts !== \"number\" ||\n !Number.isInteger(e.ts) ||\n e.ts <= 0 ||\n e.ts > 4e12\n ) {\n return fail(\"bad_ts\");\n }\n if (e.schema_version !== SCHEMA_VERSION) return fail(\"bad_schema_version\");\n if (!ENVS.includes(e.env as Env)) return fail(\"bad_env\");\n if (!SOURCES.includes(e.source as Source)) return fail(\"bad_source\");\n if (!SOURCES_FOR_STREAM[stream].includes(e.source as Source)) {\n return fail(\"source_not_allowed_for_event\");\n }\n if (!CHANNELS.includes(e.channel as Channel)) return fail(\"bad_channel\");\n\n if (e.sdk != null) {\n if (typeof e.sdk !== \"string\" || parseClientHeader(e.sdk) === null) {\n return fail(\"bad_sdk\");\n }\n }\n if (e.page_id != null) {\n if (typeof e.page_id !== \"string\" || !PAGE_ID_RE.test(e.page_id)) {\n return fail(\"bad_page_id\");\n }\n }\n if (e.page_type != null && !PAGE_TYPES.includes(e.page_type as PageType)) {\n return fail(\"bad_page_type\");\n }\n if (from === \"browser\") {\n if (typeof e.host !== \"string\" || e.host.length === 0) return fail(\"bad_host\");\n if (typeof e.path !== \"string\" || !e.path.startsWith(\"/\")) return fail(\"bad_path\");\n }\n if (typeof e.path === \"string\" && e.path.includes(\"?\")) return fail(\"path_has_query\");\n if (typeof e.path === \"string\" && e.path.includes(\"#\")) return fail(\"path_has_fragment\");\n\n const lengths: Array<[string, number]> = [\n [\"host\", LIMITS.host],\n [\"path\", LIMITS.path],\n [\"referrer_host\", LIMITS.referrerHost],\n [\"utm_source\", LIMITS.utm],\n [\"utm_medium\", LIMITS.utm],\n [\"utm_campaign\", LIMITS.utm],\n [\"utm_content\", LIMITS.utm],\n [\"utm_term\", LIMITS.utm],\n [\"ref_code\", LIMITS.refCode],\n [\"product_id\", LIMITS.id],\n [\"variant_id\", LIMITS.id],\n [\"order_ref\", LIMITS.id],\n ];\n for (const [key, max] of lengths) {\n const problem = nullableString(e, key, max);\n if (problem) return fail(problem);\n }\n if (e.visitor_id != null) {\n if (typeof e.visitor_id !== \"string\" || !/^[A-Za-z0-9_-]{22}$/.test(e.visitor_id)) {\n return fail(\"bad_visitor_id\");\n }\n }\n if (e.client_id != null) {\n if (typeof e.client_id !== \"string\" || !CLIENT_ID_RE.test(e.client_id)) {\n return fail(\"bad_client_id\");\n }\n }\n\n const props = sanitizeProps(e.event, e.props);\n if (!props.ok) return fail(props.reason);\n return { ok: true };\n}\n\n/** Client `ts` as stored: replaced by `receivedAt` when more than 24 h away from it. */\nexport function clampTs(ts: number, receivedAt: number): number {\n return Math.abs(ts - receivedAt) > LIMITS.tsSkewMs ? receivedAt : ts;\n}\n","import type { ConsentChoices, ConsentService, ConsentState } from \"./types\";\n\nexport const COOKIE_NAME = \"bitsnap_consent\";\nexport const COOKIE_MAX_AGE = 31536000;\n\n/** `bitsnap_consent`, or `bitsnap_consent_<projectKey>` when the cookie is scoped to a project. */\nexport function cookieName(projectKey?: string, scope?: \"global\" | \"project\"): string {\n if (scope === \"project\" && projectKey) {\n return `${COOKIE_NAME}_${projectKey.replace(/[^A-Za-z0-9_-]/g, \"_\")}`;\n }\n return COOKIE_NAME;\n}\n\nfunction toBase64Url(text: string): string {\n return btoa(text).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction fromBase64Url(text: string): string {\n const padded = text.replace(/-/g, \"+\").replace(/_/g, \"/\");\n return atob(padded + \"=\".repeat((4 - (padded.length % 4)) % 4));\n}\n\nexport function encodeState(state: ConsentState): string {\n return toBase64Url(\n JSON.stringify({ v: 1, id: state.id, ts: state.ts, bv: state.bv, c: state.c }),\n );\n}\n\nexport function decodeState(value: string): ConsentState | null {\n try {\n const raw = JSON.parse(fromBase64Url(value));\n if (\n !raw ||\n raw.v !== 1 ||\n typeof raw.id !== \"string\" ||\n raw.id === \"\" ||\n typeof raw.ts !== \"number\" ||\n typeof raw.bv !== \"number\" ||\n !raw.c ||\n typeof raw.c.analytics !== \"boolean\" ||\n typeof raw.c.marketing !== \"boolean\" ||\n typeof raw.c.preferences !== \"boolean\"\n ) {\n return null;\n }\n return {\n id: raw.id,\n ts: raw.ts,\n bv: raw.bv,\n c: {\n analytics: raw.c.analytics,\n marketing: raw.c.marketing,\n preferences: raw.c.preferences,\n },\n };\n } catch {\n return null;\n }\n}\n\n/** The `Set-Cookie`-style string for `document.cookie`. */\nexport function serializeCookie(name: string, state: ConsentState, secure: boolean): string {\n return (\n `${name}=${encodeState(state)}; Max-Age=${COOKIE_MAX_AGE}; Path=/; SameSite=Lax` +\n (secure ? \"; Secure\" : \"\")\n );\n}\n\nexport function cookieNames(header: string): string[] {\n return header\n .split(\";\")\n .map((part) => part.split(\"=\")[0].trim())\n .filter(Boolean);\n}\n\n/** Reads the consent from a `document.cookie` header. */\nexport function parseCookie(header: string, name: string): ConsentState | null {\n for (const part of header.split(\";\")) {\n const index = part.indexOf(\"=\");\n if (index === -1) continue;\n if (part.slice(0, index).trim() === name) {\n return decodeState(part.slice(index + 1).trim());\n }\n }\n return null;\n}\n\nexport function newConsentId(): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n } catch {\n // fall through to the random fallback\n }\n let id = \"\";\n for (let i = 0; i < 32; i++) id += Math.floor(Math.random() * 16).toString(16);\n return id;\n}\n\nexport function readConsent(doc: Document, name: string): ConsentState | null {\n try {\n return parseCookie(doc.cookie, name);\n } catch {\n return null;\n }\n}\n\nexport function writeConsent(doc: Document, name: string, state: ConsentState): void {\n try {\n doc.cookie = serializeCookie(name, state, doc.location?.protocol === \"https:\");\n } catch {\n // cookies blocked (sandboxed frame)\n }\n}\n\nexport function clearConsent(doc: Document, name: string): void {\n try {\n doc.cookie = `${name}=; Max-Age=0; Path=/; SameSite=Lax`;\n } catch {\n // ignore\n }\n}\n\n/** `a.b.example.com` -> the host and every parent with at least two labels. */\nexport function domainCandidates(hostname: string): string[] {\n if (!hostname || /^[\\d.]+$/.test(hostname) || hostname.includes(\":\")) return [];\n const labels = hostname.split(\".\");\n const result: string[] = [];\n for (let i = 0; i <= labels.length - 2; i++) result.push(labels.slice(i).join(\".\"));\n return result;\n}\n\n/**\n * Best-effort deletion of cookies the withdrawn categories declared, on the\n * current host and its parent domains. A trailing `*` matches a name prefix.\n */\nexport function deleteServiceCookies(\n doc: Document,\n services: ConsentService[],\n categories: (keyof ConsentChoices)[],\n): void {\n try {\n const wanted = services\n .filter((service) => categories.includes(service.category))\n .flatMap((service) => service.cookies ?? []);\n if (wanted.length === 0) return;\n const present = cookieNames(doc.cookie);\n const names = new Set<string>();\n for (const pattern of wanted) {\n if (pattern.endsWith(\"*\")) {\n const prefix = pattern.slice(0, -1);\n for (const name of present) if (name.startsWith(prefix)) names.add(name);\n } else {\n names.add(pattern);\n }\n }\n const domains = domainCandidates(doc.location?.hostname ?? \"\");\n for (const name of names) {\n const base = `${encodeURIComponent(name)}=; Max-Age=0; Path=/`;\n doc.cookie = base;\n for (const domain of domains) {\n doc.cookie = `${base}; Domain=${domain}`;\n doc.cookie = `${base}; Domain=.${domain}`;\n }\n }\n } catch {\n // best effort\n }\n}\n","import { useEffect, useLayoutEffect, type DependencyList, type EffectCallback } from \"react\";\n\n/**\n * `useLayoutEffect` in the browser (it runs before any passive effect), `useEffect` on the server,\n * where React warns about layout effects. Chosen per call: a page's `window` can appear after import.\n */\nexport function useIsomorphicLayoutEffect(effect: EffectCallback, deps?: DependencyList): void {\n // eslint-disable-next-line react-hooks/rules-of-hooks -- the environment never changes between renders\n (typeof window !== \"undefined\" ? useLayoutEffect : useEffect)(effect, deps);\n}\n"],"mappings":"AAiBO,IAAMA,EAAS,CAEpB,eAAgB,GAEhB,aAAc,MAEd,cAAe,KACf,cAAe,IACf,aAAc,GACd,KAAM,IACN,KAAM,IACN,aAA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EAAG,CACzB,IAAMC,EAASD,EAAQ,MAAM,EAAG,EAAE,EAClC,QAAWzB,KAAQuB,EAAavB,EAAK,WAAW0B,CAAM,GAAGF,EAAM,IAAIxB,CAAI,CACzE,MACEwB,EAAM,IAAIC,CAAO,EAGrB,IAAME,EAAUb,EAAiBH,EAAI,UAAU,UAAY,EAAE,EAC7D,QAAWX,KAAQwB,EAAO,CACxB,IAAMI,EAAO,GAAG,mBAAmB5B,CAAI,CAAC,uBACxCW,EAAI,OAASiB,EACb,QAAWC,KAAUF,EACnBhB,EAAI,OAAS,GAAGiB,CAAI,YAAYC,CAAM,GACtClB,EAAI,OAAS,GAAGiB,CAAI,aAAaC,CAAM,EAE3C,CACF,MAAQ,CAER,CACF,CCzKA,OAAS,aAAAC,EAAW,mBAAAC,OAAiE,QAM9E,SAASC,GAA0BC,EAAwBC,EAA6B,EAE5F,OAAO,OAAW,IAAcH,GAAkBD,GAAWG,EAAQC,CAAI,CAC5E","names":["LIMITS","STREAMS","ENVS","SOURCES","CHANNELS","PAGE_TYPES","SOURCES_FOR_STREAM","MONEY","STOREFRONT_EVENT_SPEC","APP_EVENT_SPEC","TX","SUB","BUSINESS_EVENT_SPEC","EVENT_SPEC","STOREFRONT_EVENT_SPEC","APP_EVENT_SPEC","BUSINESS_EVENT_SPEC","EVENT_NAMES","STREAM_FOR_EVENT","STREAMS","stream","name","isEventName","CONSENT_COOKIE_MAX_AGE_SECONDS","CONSENT_SHOWN_ACTION","normalizeProjectKey","key","bare","CLIENT_RE","parseClientHeader","value","LIMITS","m","MAX_QUERY_VALUE","cleanValue","v","max","t","sanitizePath","pathname","joined","seg","parseUrl","url","base","u","q","ID_RE","referrerHost","referrer","u","LIMITS","encoder","clientIdCookieName","projectKey","CLIENT_ID_RE","UUID_V7","PAGE_ID_RE","EMAIL_LIKE","isRecord","v","nullableString","e","key","max","checkPropValue","spec","value","type","LIMITS","x","ID_RE","isNonNegativeSafeInteger","looksLikeEmail","parseClientHeader","hasEmailLike","sanitizeProps","event","props","isEventName","EVENT_SPEC","out","validateEnvelope","options","from","fail","reason","stream","STREAM_FOR_EVENT","ENVS","SOURCES","SOURCES_FOR_STREAM","CHANNELS","PAGE_TYPES","lengths","problem","CLIENT_ID_RE","COOKIE_NAME","cookieName","projectKey","scope","COOKIE_NAME","toBase64Url","text","fromBase64Url","padded","encodeState","state","decodeState","value","raw","serializeCookie","name","secure","cookieNames","header","part","parseCookie","index","newConsentId","id","i","readConsent","doc","writeConsent","clearConsent","domainCandidates","hostname","labels","result","deleteServiceCookies","services","categories","wanted","service","present","names","pattern","prefix","domains","base","domain","useEffect","useLayoutEffect","useIsomorphicLayoutEffect","effect","deps"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as N,f as m,i,j as d,k as R,s as c,t as E,u as p,v as S,w as l,x as y,y as I,z as T}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{A as N,f as m,i,j as d,k as R,s as c,t as E,u as p,v as S,w as l,x as y,y as I,z as T}from"./chunk-4TZAGNEU.mjs";import{d as a}from"./chunk-TBYY3RL2.mjs";var B=["orders","order","confirmation","result","myReturns","myReturn"];function P(e){return B.includes(e)}function f(e){return e?{name:"orders"}:{name:"email"}}function C(e,n){switch(n.type){case"SESSION_EXPIRED":return P(e.name)?{name:"email"}:e;case"CODE_SENT":return e.name==="email"?{name:"code"}:e;case"AUTHENTICATED":return e.name==="email"||e.name==="code"?{name:"orders"}:e;case"SELECT_ORDER":return e.name==="orders"?{name:"order",orderId:n.orderId}:e;case"REVIEW":return e.name==="order"?{name:"confirmation",orderId:e.orderId,items:n.items,note:n.note}:e;case"SUBMITTED":return e.name==="confirmation"?{name:"result",returnId:n.returnId}:e;case"OPEN_MY_RETURNS":return e.name==="orders"||e.name==="result"?{name:"myReturns"}:e;case"SELECT_RETURN":return e.name==="myReturns"?{name:"myReturn",returnId:n.returnId}:e;case"CONTINUE":return e.name==="result"?{name:"orders"}:e;case"BACK":switch(e.name){case"code":return{name:"email"};case"order":case"myReturns":return{name:"orders"};case"confirmation":return{name:"order",orderId:e.orderId,items:e.items,note:e.note};case"myReturn":return{name:"myReturns"};default:return e}}}var x={email:1,code:2,orders:3,order:4,confirmation:5,result:6},_=6;function O(e){return x[e]}import{useEffect as D,useReducer as A}from"react";import{jsx as o,jsxs as L}from"react/jsx-runtime";function g({current:e}){let n=i(),r=m("stepIndicator");return o("p",{"data-bitsnap-returns-slot":"stepIndicator",className:a("text-xs",r.className),style:r.style,children:n("stepIndicator",{current:e,total:_})})}function b({panelToken:e}){let{status:n}=d("BitsnapReturns"),[r,t]=A(C,f(!1));if(D(()=>{n==="authenticated"?t({type:"AUTHENTICATED"}):n==="anonymous"&&t({type:"SESSION_EXPIRED"})},[n]),n==="exchanging"||n==="hydrating"&&e)return o(c,{});let s=O(r.name);return L("div",{className:"flex flex-col gap-4",children:[s!=null&&o(g,{current:s}),r.name==="email"&&o(E,{onSubmitted:()=>t({type:"CODE_SENT"})}),r.name==="code"&&o(p,{onVerified:()=>t({type:"AUTHENTICATED"}),onBack:()=>t({type:"BACK"})}),r.name==="orders"&&o(S,{showLogout:!e,onSelectOrder:u=>t({type:"SELECT_ORDER",orderId:u}),onOpenMyReturns:()=>t({type:"OPEN_MY_RETURNS"})}),r.name==="order"&&o(l,{orderId:r.orderId,initialItems:r.items,initialNote:r.note,onBack:()=>t({type:"BACK"}),onContinue:({items:u,note:U})=>t({type:"REVIEW",items:u,note:U})}),r.name==="confirmation"&&o(y,{orderId:r.orderId,items:r.items,note:r.note,onBack:()=>t({type:"BACK"}),onSubmitted:u=>t({type:"SUBMITTED",returnId:u})}),r.name==="result"&&o(I,{returnId:r.returnId,onContinue:()=>t({type:"CONTINUE"}),onOpenMyReturns:()=>t({type:"OPEN_MY_RETURNS"})}),r.name==="myReturns"&&o(T,{onSelectReturn:u=>t({type:"SELECT_RETURN",returnId:u}),onBack:()=>t({type:"BACK"})}),r.name==="myReturn"&&o(N,{returnId:r.returnId,onBack:()=>t({type:"BACK"})})]})}function q(e){return o(R,{...e,children:o(b,{panelToken:e.panelAccessToken!=null&&e.panelAccessToken!==""})})}export{q as a};
|
|
2
|
+
//# sourceMappingURL=chunk-ONTCJSSD.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkXIHGWNTSjs = require('./chunk-XIHGWNTS.js');var Oe=Symbol.for("bitsnap.pageViews");function ye(e){let t=e;return t[Oe]??={path:null,starters:new Set,watching:!1}}function De(e,t){let n=()=>{try{t()}catch (e2){}};for(let o of["pushState","replaceState"]){let a=e.history[o];e.history[o]=function(...i){let c=a.apply(this,i);return n(),c}}e.addEventListener("popstate",n)}function A(e,t=window){try{let n=ye(t),o=()=>e();n.watching||(n.watching=!0,De(t,()=>{let i=t.location.pathname;i===n.path||n.starters.size===0||(n.path=i,_optionalChain([n, 'access', _2 => _2.starters, 'access', _3 => _3.values, 'call', _4 => _4(), 'access', _5 => _5.next, 'call', _6 => _6(), 'access', _7 => _7.value, 'optionalCall', _8 => _8()]))})),n.starters.add(o);let a=t.location.pathname;return a!==n.path&&(n.path=a,o()),()=>void n.starters.delete(o)}catch (e3){return()=>{}}}function ge(e=window){let t=ye(e);t.path=null,t.starters.clear()}var ve="1.13.0";function I(e){let t=new Uint8Array(e),n=typeof crypto<"u"?crypto:void 0;if(n&&typeof n.getRandomValues=="function")n.getRandomValues(t);else for(let o=0;o<e;o++)t[o]=Math.floor(Math.random()*256);return t}var me="X-Bitsnap-Visitor",$e=390*24*60*60,Me=/^[A-Za-z0-9_-]{22}$/;function R(e){return e.BitsnapConsent}function je(e,t){for(let n of e.cookie.split(";")){let o=n.indexOf("=");if(o!==-1&&n.slice(0,o).trim()===t)return n.slice(o+1).trim()}return null}function He(e){let t=e.toLowerCase();return t==="bitsnap.pl"||t.endsWith(".bitsnap.pl")}function F(e,t){try{let n=R(e);if(!n)return!1;if(n.scope==="project")return n.projectKey===t;let o=He(e.location.hostname);return n.scope==="global"?!o:!1}catch (e4){return!1}}function J(e,t){try{return _optionalChain([R, 'call', _9 => _9(e), 'optionalAccess', _10 => _10.get, 'call', _11 => _11(), 'optionalAccess', _12 => _12.c, 'access', _13 => _13.analytics])===!0&&F(e,t)}catch (e5){return!1}}function he(){let e="";return I(16).forEach(t=>e+=String.fromCharCode(t)),btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ee(e,t){try{return je(e,_chunkXIHGWNTSjs.f.call(void 0, t))}catch (e6){return null}}function B(e,t){let n=Ee(e,t);return n!==null&&Me.test(n)?n:null}function ke(e,t,n){try{let o=e.document,a=`${_chunkXIHGWNTSjs.f.call(void 0, t)}=${n}; Max-Age=${$e}; Path=/; SameSite=Lax`+(e.location.protocol==="https:"?"; Secure":"");for(let i of _chunkXIHGWNTSjs.n.call(void 0, e.location.hostname).reverse())if(o.cookie=`${a}; Domain=${i}`,B(o,t)===n)return;o.cookie=a}catch (e7){}}function be(e,t){try{let n=e.document;if(Ee(n,t)===null)return;let o=`${_chunkXIHGWNTSjs.f.call(void 0, t)}=; Max-Age=0; Path=/; SameSite=Lax`+(e.location.protocol==="https:"?"; Secure":"");n.cookie=o;for(let a of _chunkXIHGWNTSjs.n.call(void 0, e.location.hostname))n.cookie=`${o}; Domain=${a}`}catch (e8){}}function N(e,t){try{let n=e.navigator;return _optionalChain([n, 'optionalAccess', _14 => _14.globalPrivacyControl])===!0||_optionalChain([n, 'optionalAccess', _15 => _15.webdriver])===!0?null:J(e,t)?B(e.document,t):null}catch (e9){return null}}var Ue="https://collect.bitsnap.pl",Ke=5e3,Ge=20,Te=32*1024,ze=60*1024,xe=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function _e(e){return typeof TextEncoder=="function"?new TextEncoder().encode(e).length:unescape(encodeURIComponent(e)).length}var y={track(){},page(){},clientId:()=>null,flush(){},setEnabled(){},onEvent:()=>()=>{},configure(){},destroy(){}};function Ye(e=Date.now()){let t=I(16),n=e;for(let a=5;a>=0;a--)t[a]=n%256,n=Math.floor(n/256);t[6]=t[6]&15|112,t[8]=t[8]&63|128;let o=Array.from(t,a=>a.toString(16).padStart(2,"0")).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}var Ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Fe(){return Array.from(I(16),e=>Ce[e%Ce.length]).join("")}function Je(e,t,n=!1){let o=_e(JSON.stringify({k:e,events:[]})),a=[],i=[],c=o,s=()=>{i.length>0&&a.push({body:JSON.stringify({k:e,events:i}),bytes:c,count:i.length}),i=[],c=o};for(let u of t){let l=_e(JSON.stringify(u));o+l>Te||((i.length>=_chunkXIHGWNTSjs.a.maxBatchEvents||c+l+(i.length>0?1:0)>Te)&&s(),c+=l+(i.length>0?1:0),i.push(u))}if(s(),n){let u=0,l=a.length;for(;l>0&&u+a[l-1].bytes<=ze;)u+=a[l-1].bytes,l--;a=a.slice(l)}return a}function Xe(e){try{return typeof window>"u"||typeof document>"u"?y:qe(e,window)}catch (e10){return y}}function qe(e,t){let n=_chunkXIHGWNTSjs.b.call(void 0, _nullishCoalesce(e.projectKey, () => (""))),o=!!e.debug,a=(...r)=>{o&&console.warn("[bitsnap analytics]",...r)};if(!n)return a("invalid projectKey, tracking is off"),y;let i=n,c=r=>`${(r||Ue).replace(/\/+$/,"")}/e`,s=c(e.endpoint),u=_nullishCoalesce(e.source, () => ("sdk_react")),l=_nullishCoalesce(e.channel, () => ("embed")),b=`bitsnap-react@${ve}`,M=Fe(),T=_chunkXIHGWNTSjs.d.call(void 0, t.location.href),j=_nullishCoalesce(e.env, () => ("live"));if(!e.env)try{new URLSearchParams(t.location.search).has("test")&&(j="test")}catch (e11){}let Le=_chunkXIHGWNTSjs.e.call(void 0, document.referrer),H=e.enabled!==!1,ee=null,Re=0,p=[],h=null,C=new Set;e.onEvent&&C.add(e.onEvent);let E=[],g,m=!0;function W(){let r=R(t);!r||r===g||(g=r,m=!r.ready,_optionalChain([r, 'access', _16 => _16.ready, 'optionalAccess', _17 => _17.then, 'call', _18 => _18(()=>{g===r&&(m=!0,re())},()=>{g===r&&(m=!0)})]))}function te(){W();try{if(!g)return!1;let r=g.get();return!!g.denied&&g.denied("analytics")||!!r&&r.c.analytics===!1}catch (e12){return!1}}function ne(r){C.forEach(f=>{try{f(r)}catch (e13){}})}function U(r){try{if(W(),!g||!F(t,i))return;J(t,i)?P()&&B(t.document,i)===null&&ke(t,i,he()):r&&be(t,i)}catch (e14){}}function re(){if(U(!0),te())p=[],E=[],w();else{if(m&&E.length>0){let r=E;E=[],r.forEach(ne)}p.length>0&&x()}}function P(){if(!H)return!1;let r=t.navigator;return r&&(r.globalPrivacyControl===!0||r.webdriver===!0)?!1:!te()}function w(){h!==null&&clearTimeout(h),h=null}function Be(){h===null&&(h=setTimeout(()=>{h=null,x()},Ke),_optionalChain([h, 'access', _19 => _19.unref, 'optionalCall', _20 => _20()]))}function Ne(r){try{if(typeof fetch=="function"){fetch(s,{method:"POST",body:r,keepalive:!0,credentials:"omit",headers:{"Content-Type":"text/plain"}}).catch(()=>{});return}}catch (e15){}try{let f=t.navigator;f&&typeof f.sendBeacon=="function"&&f.sendBeacon(s,new Blob([r],{type:"text/plain"}))}catch (e16){}}function x(r=!1){try{if(w(),p.length===0)return;if(!P()){p=[];return}if(!m)return;U(m);let f=N(t,i),d=f?p.map(k=>({...k,client_id:f})):p;p=[],Je(i,d,r).forEach(k=>Ne(k.body))}catch (e17){}}function oe(r,f,d){if(!P())return;let k=_chunkXIHGWNTSjs.g.call(void 0, r,f);if(!k.ok){a("dropped",r,k.reason);return}let se=_chunkXIHGWNTSjs.d.call(void 0, t.location.href),K={event_id:_optionalChain([d, 'optionalAccess', _21 => _21.event_id])&&xe.test(d.event_id)?d.event_id:Ye(),event:r,ts:Date.now(),schema_version:1,env:j,source:u,channel:l,sdk:b,page_id:M,page_type:_optionalChain([d, 'optionalAccess', _22 => _22.page_type])!==void 0?d.page_type:ee,host:_nullishCoalesce(_optionalChain([se, 'optionalAccess', _23 => _23.host]), () => (null)),path:_optionalChain([d, 'optionalAccess', _24 => _24.path])?_chunkXIHGWNTSjs.c.call(void 0, d.path.split(/[?#]/)[0]):_nullishCoalesce(_optionalChain([se, 'optionalAccess', _25 => _25.path]), () => (null)),referrer_host:Le,utm_source:_nullishCoalesce(_optionalChain([T, 'optionalAccess', _26 => _26.utm_source]), () => (null)),utm_medium:_nullishCoalesce(_optionalChain([T, 'optionalAccess', _27 => _27.utm_medium]), () => (null)),utm_campaign:_nullishCoalesce(_optionalChain([T, 'optionalAccess', _28 => _28.utm_campaign]), () => (null)),utm_content:_nullishCoalesce(_optionalChain([T, 'optionalAccess', _29 => _29.utm_content]), () => (null)),utm_term:_nullishCoalesce(_optionalChain([T, 'optionalAccess', _30 => _30.utm_term]), () => (null)),ref_code:_nullishCoalesce(_optionalChain([T, 'optionalAccess', _31 => _31.ref_code]), () => (null)),product_id:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _32 => _32.product_id]), () => (null)),variant_id:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _33 => _33.variant_id]), () => (null)),order_ref:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _34 => _34.order_ref]), () => (null)),props:k.props};_optionalChain([d, 'optionalAccess', _35 => _35.event_id])&&!xe.test(d.event_id)&&a("ignored invalid event_id",r),u==="dashboard"&&e.visitorId&&(K.visitor_id=e.visitorId);let ce=_chunkXIHGWNTSjs.h.call(void 0, K);if(!ce.ok){a("dropped",r,ce.reason);return}let G=K;m?ne(G):E.push(G),p.push(G),p.length>=Ge?x():Be()}let ie=()=>x(!0),ae=()=>{document.visibilityState==="hidden"&&x(!0)},S=()=>re();return t.addEventListener("pagehide",ie),document.addEventListener("visibilitychange",ae),t.addEventListener("bitsnap:consent",S),t.addEventListener("bitsnap:consent:ready",S),W(),U(m),{track(r,f,d){try{oe(r,f,d)}catch (e18){}},page(r,f){try{r!==void 0&&(ee=r),oe("page_view",{landing:Re++===0},f)}catch (e19){}},clientId(r){try{return r!==void 0&&_chunkXIHGWNTSjs.b.call(void 0, r)!==i?null:P()?N(t,i):null}catch (e20){return null}},flush:()=>x(),setEnabled(r){H=!!r,H||(p=[],E=[],w())},configure(r){try{(r.env==="live"||r.env==="test")&&(j=r.env),typeof r.endpoint=="string"&&r.endpoint&&(s=c(r.endpoint))}catch (e21){}},onEvent(r){return C.add(r),()=>void C.delete(r)},destroy(){p=[],E=[],w(),C.clear(),t.removeEventListener("pagehide",ie),document.removeEventListener("visibilitychange",ae),t.removeEventListener("bitsnap:consent",S),t.removeEventListener("bitsnap:consent:ready",S)}}}var v,O=null;function D(e){if(!v){let t=Xe(e);return t===y||(v=t,O=_chunkXIHGWNTSjs.b.call(void 0, _nullishCoalesce(e.projectKey, () => ("")))),t}try{let t=_chunkXIHGWNTSjs.b.call(void 0, _nullishCoalesce(e.projectKey, () => ("")));t!==O&&e.debug&&console.warn("[bitsnap analytics]","tracker already started for another projectKey, ignoring",e.projectKey),t===O&&((e.env||e.endpoint)&&v.configure({env:e.env,endpoint:e.endpoint}),e.enabled!=null&&v.setEnabled(e.enabled))}catch (e22){}return v}function Ae(){return v}function xt(){typeof window<"u"&&ge(window),_optionalChain([v, 'optionalAccess', _36 => _36.destroy, 'call', _37 => _37()]),v=void 0,O=null}function _t(e){try{if(typeof window>"u")return{};let t=v,n=null;if(t)n=t.clientId(e);else{let o=e?_chunkXIHGWNTSjs.b.call(void 0, e):null;n=o?N(window,o):null}return n?{[me]:n}:{}}catch (e23){return{}}}var _react = require('react');var nt={track:y.track,page:y.page},Pe=_react.createContext.call(void 0, nt);function St({projectKey:e,env:t,enabled:n,endpoint:o,onEvent:a,autoPageViews:i,children:c}){let s=_react.useMemo.call(void 0, ()=>D({projectKey:e,env:t,endpoint:o,enabled:n}),[e,t,o]),u=_react.useRef.call(void 0, a);u.current=a,_chunkXIHGWNTSjs.p.call(void 0, ()=>{s.setEnabled(n!==!1)},[s,n]),_chunkXIHGWNTSjs.p.call(void 0, ()=>{if(!(i===!1||n===!1||s===y))return A(()=>s.page(null))},[s,i,n]),_chunkXIHGWNTSjs.p.call(void 0, ()=>s.onEvent(b=>_optionalChain([u, 'access', _38 => _38.current, 'optionalCall', _39 => _39(b)])),[s]);let l=_react.useMemo.call(void 0, ()=>({track:s.track.bind(s),page:s.page.bind(s)}),[s]);return _react.createElement.call(void 0, Pe.Provider,{value:l},c)}function we(){return _react.useContext.call(void 0, Pe)}var $={track(){}},X=null;function lt(e){let t=Symbol("bitsnap-instrument");function n(){if(typeof window>"u")return null;let{projectKey:i,analytics:c,provided:s}=e();return c===!1?null:s||(i?D({projectKey:i,source:"sdk_react",channel:"embed",env:typeof c=="object"?c.env:void 0}):null)}let o={track(i,c,s){try{let u=n();if(!u)return;let{analytics:l,pageType:b}=e(),M=b&&_optionalChain([s, 'optionalAccess', _40 => _40.page_type])===void 0?{...s,page_type:b}:s;X=typeof l=="object"&&l.onEvent?t:null,u.track(i,c,M)}catch (e24){}finally{X=null}}};function a(){try{if(!n())return()=>{};let i=Ae();if(!i)return()=>{};let c=e().provided?()=>{}:A(()=>i.page(_nullishCoalesce(e().pageType, () => (null)))),s=i.onEvent(u=>{if(X===t)try{let{analytics:l}=e();typeof l=="object"&&_optionalChain([l, 'access', _41 => _41.onEvent, 'optionalCall', _42 => _42(u)])}catch (e25){}});return()=>{c(),s()}}catch (e26){return()=>{}}}return{instrument:o,attach:a}}var Z=_react.createContext.call(void 0, null);function Nt({value:e,children:t}){return _react.createElement.call(void 0, Z.Provider,{value:e},t)}function Ot(){return _nullishCoalesce(_react.useContext.call(void 0, Z), () => ($))}function Dt(e,t,n){let o=_react.useContext.call(void 0, Z),a=we(),i=a.track===y.track?null:a,c=_react.useRef.call(void 0, {projectKey:e,analytics:t,pageType:n,provided:i});c.current={projectKey:e,analytics:t,pageType:n,provided:i};let s=_react.useMemo.call(void 0, ()=>lt(()=>c.current),[]),u=t===void 0&&o!==null,l=typeof t=="object"&&!!t.onEvent;return _react.useLayoutEffect.call(void 0, ()=>{if(!u)return s.attach()},[s,u,l,e]),u?o:s.instrument}var Q=$;function Se(e){Q=_nullishCoalesce(e, () => ($))}var q=0;function $t(){return q>0?$:Q}async function Mt(e){q++;try{return await e()}finally{q--}}function jt(e){_react.useEffect.call(void 0, ()=>(Se(e),()=>{Q===e&&Se(null)}),[e])}function Ht(e){let t=Number.isFinite(e)?Math.max(0,Math.min(100,e)):0;return t>=100?"100":t>=75?"75-99":t>=50?"50-74":t>=25?"25-49":"0-24"}function Wt(e,t){let n=[];for(let o of[25,50,75,100])e>=o&&!t.has(o)&&(t.add(o),n.push(o));return n}exports.a = ve; exports.b = A; exports.c = Ue; exports.d = Xe; exports.e = D; exports.f = Ae; exports.g = xt; exports.h = _t; exports.i = St; exports.j = we; exports.k = $; exports.l = Nt; exports.m = Ot; exports.n = Dt; exports.o = $t; exports.p = Mt; exports.q = jt; exports.r = Ht; exports.s = Wt;
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkW3RGQYPDjs = require('./chunk-W3RGQYPD.js');var Oe=Symbol.for("bitsnap.pageViews");function ye(e){let t=e;return t[Oe]??={path:null,starters:new Set,watching:!1}}function De(e,t){let n=()=>{try{t()}catch (e2){}};for(let o of["pushState","replaceState"]){let a=e.history[o];e.history[o]=function(...i){let c=a.apply(this,i);return n(),c}}e.addEventListener("popstate",n)}function A(e,t=window){try{let n=ye(t),o=()=>e();n.watching||(n.watching=!0,De(t,()=>{let i=t.location.pathname;i===n.path||n.starters.size===0||(n.path=i,_optionalChain([n, 'access', _2 => _2.starters, 'access', _3 => _3.values, 'call', _4 => _4(), 'access', _5 => _5.next, 'call', _6 => _6(), 'access', _7 => _7.value, 'optionalCall', _8 => _8()]))})),n.starters.add(o);let a=t.location.pathname;return a!==n.path&&(n.path=a,o()),()=>void n.starters.delete(o)}catch (e3){return()=>{}}}function ge(e=window){let t=ye(e);t.path=null,t.starters.clear()}var ve="1.14.1";function I(e){let t=new Uint8Array(e),n=typeof crypto<"u"?crypto:void 0;if(n&&typeof n.getRandomValues=="function")n.getRandomValues(t);else for(let o=0;o<e;o++)t[o]=Math.floor(Math.random()*256);return t}var me="X-Bitsnap-Visitor",$e=390*24*60*60,Me=/^[A-Za-z0-9_-]{22}$/;function R(e){return e.BitsnapConsent}function je(e,t){for(let n of e.cookie.split(";")){let o=n.indexOf("=");if(o!==-1&&n.slice(0,o).trim()===t)return n.slice(o+1).trim()}return null}function He(e){let t=e.toLowerCase();return t==="bitsnap.pl"||t.endsWith(".bitsnap.pl")}function F(e,t){try{let n=R(e);if(!n)return!1;if(n.scope==="project")return n.projectKey===t;let o=He(e.location.hostname);return n.scope==="global"?!o:!1}catch (e4){return!1}}function J(e,t){try{return _optionalChain([R, 'call', _9 => _9(e), 'optionalAccess', _10 => _10.get, 'call', _11 => _11(), 'optionalAccess', _12 => _12.c, 'access', _13 => _13.analytics])===!0&&F(e,t)}catch (e5){return!1}}function he(){let e="";return I(16).forEach(t=>e+=String.fromCharCode(t)),btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ee(e,t){try{return je(e,_chunkW3RGQYPDjs.g.call(void 0, t))}catch (e6){return null}}function B(e,t){let n=Ee(e,t);return n!==null&&Me.test(n)?n:null}function ke(e,t,n){try{let o=e.document,a=`${_chunkW3RGQYPDjs.g.call(void 0, t)}=${n}; Max-Age=${$e}; Path=/; SameSite=Lax`+(e.location.protocol==="https:"?"; Secure":"");for(let i of _chunkW3RGQYPDjs.o.call(void 0, e.location.hostname).reverse())if(o.cookie=`${a}; Domain=${i}`,B(o,t)===n)return;o.cookie=a}catch (e7){}}function be(e,t){try{let n=e.document;if(Ee(n,t)===null)return;let o=`${_chunkW3RGQYPDjs.g.call(void 0, t)}=; Max-Age=0; Path=/; SameSite=Lax`+(e.location.protocol==="https:"?"; Secure":"");n.cookie=o;for(let a of _chunkW3RGQYPDjs.o.call(void 0, e.location.hostname))n.cookie=`${o}; Domain=${a}`}catch (e8){}}function N(e,t){try{let n=e.navigator;return _optionalChain([n, 'optionalAccess', _14 => _14.globalPrivacyControl])===!0||_optionalChain([n, 'optionalAccess', _15 => _15.webdriver])===!0?null:J(e,t)?B(e.document,t):null}catch (e9){return null}}var Ue="https://collect.bitsnap.pl",Ke=5e3,Ge=20,Te=32*1024,ze=60*1024,xe=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function _e(e){return typeof TextEncoder=="function"?new TextEncoder().encode(e).length:unescape(encodeURIComponent(e)).length}var y={track(){},page(){},clientId:()=>null,flush(){},setEnabled(){},onEvent:()=>()=>{},configure(){},destroy(){}};function Ye(e=Date.now()){let t=I(16),n=e;for(let a=5;a>=0;a--)t[a]=n%256,n=Math.floor(n/256);t[6]=t[6]&15|112,t[8]=t[8]&63|128;let o=Array.from(t,a=>a.toString(16).padStart(2,"0")).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}var Ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Fe(){return Array.from(I(16),e=>Ce[e%Ce.length]).join("")}function Je(e,t,n=!1){let o=_e(JSON.stringify({k:e,events:[]})),a=[],i=[],c=o,s=()=>{i.length>0&&a.push({body:JSON.stringify({k:e,events:i}),bytes:c,count:i.length}),i=[],c=o};for(let u of t){let l=_e(JSON.stringify(u));o+l>Te||((i.length>=_chunkW3RGQYPDjs.a.maxBatchEvents||c+l+(i.length>0?1:0)>Te)&&s(),c+=l+(i.length>0?1:0),i.push(u))}if(s(),n){let u=0,l=a.length;for(;l>0&&u+a[l-1].bytes<=ze;)u+=a[l-1].bytes,l--;a=a.slice(l)}return a}function Xe(e){try{return typeof window>"u"||typeof document>"u"?y:qe(e,window)}catch (e10){return y}}function qe(e,t){let n=_chunkW3RGQYPDjs.c.call(void 0, _nullishCoalesce(e.projectKey, () => (""))),o=!!e.debug,a=(...r)=>{o&&console.warn("[bitsnap analytics]",...r)};if(!n)return a("invalid projectKey, tracking is off"),y;let i=n,c=r=>`${(r||Ue).replace(/\/+$/,"")}/e`,s=c(e.endpoint),u=_nullishCoalesce(e.source, () => ("sdk_react")),l=_nullishCoalesce(e.channel, () => ("embed")),b=`bitsnap-react@${ve}`,M=Fe(),T=_chunkW3RGQYPDjs.e.call(void 0, t.location.href),j=_nullishCoalesce(e.env, () => ("live"));if(!e.env)try{new URLSearchParams(t.location.search).has("test")&&(j="test")}catch (e11){}let Le=_chunkW3RGQYPDjs.f.call(void 0, document.referrer),H=e.enabled!==!1,ee=null,Re=0,p=[],h=null,C=new Set;e.onEvent&&C.add(e.onEvent);let E=[],g,m=!0;function W(){let r=R(t);!r||r===g||(g=r,m=!r.ready,_optionalChain([r, 'access', _16 => _16.ready, 'optionalAccess', _17 => _17.then, 'call', _18 => _18(()=>{g===r&&(m=!0,re())},()=>{g===r&&(m=!0)})]))}function te(){W();try{if(!g)return!1;let r=g.get();return!!g.denied&&g.denied("analytics")||!!r&&r.c.analytics===!1}catch (e12){return!1}}function ne(r){C.forEach(f=>{try{f(r)}catch (e13){}})}function U(r){try{if(W(),!g||!F(t,i))return;J(t,i)?P()&&B(t.document,i)===null&&ke(t,i,he()):r&&be(t,i)}catch (e14){}}function re(){if(U(!0),te())p=[],E=[],w();else{if(m&&E.length>0){let r=E;E=[],r.forEach(ne)}p.length>0&&x()}}function P(){if(!H)return!1;let r=t.navigator;return r&&(r.globalPrivacyControl===!0||r.webdriver===!0)?!1:!te()}function w(){h!==null&&clearTimeout(h),h=null}function Be(){h===null&&(h=setTimeout(()=>{h=null,x()},Ke),_optionalChain([h, 'access', _19 => _19.unref, 'optionalCall', _20 => _20()]))}function Ne(r){try{if(typeof fetch=="function"){fetch(s,{method:"POST",body:r,keepalive:!0,credentials:"omit",headers:{"Content-Type":"text/plain"}}).catch(()=>{});return}}catch (e15){}try{let f=t.navigator;f&&typeof f.sendBeacon=="function"&&f.sendBeacon(s,new Blob([r],{type:"text/plain"}))}catch (e16){}}function x(r=!1){try{if(w(),p.length===0)return;if(!P()){p=[];return}if(!m)return;U(m);let f=N(t,i),d=f?p.map(k=>({...k,client_id:f})):p;p=[],Je(i,d,r).forEach(k=>Ne(k.body))}catch (e17){}}function oe(r,f,d){if(!P())return;let k=_chunkW3RGQYPDjs.h.call(void 0, r,f);if(!k.ok){a("dropped",r,k.reason);return}let se=_chunkW3RGQYPDjs.e.call(void 0, t.location.href),K={event_id:_optionalChain([d, 'optionalAccess', _21 => _21.event_id])&&xe.test(d.event_id)?d.event_id:Ye(),event:r,ts:Date.now(),schema_version:1,env:j,source:u,channel:l,sdk:b,page_id:M,page_type:_optionalChain([d, 'optionalAccess', _22 => _22.page_type])!==void 0?d.page_type:ee,host:_nullishCoalesce(_optionalChain([se, 'optionalAccess', _23 => _23.host]), () => (null)),path:_optionalChain([d, 'optionalAccess', _24 => _24.path])?_chunkW3RGQYPDjs.d.call(void 0, d.path.split(/[?#]/)[0]):_nullishCoalesce(_optionalChain([se, 'optionalAccess', _25 => _25.path]), () => (null)),referrer_host:Le,utm_source:_nullishCoalesce(_optionalChain([T, 'optionalAccess', _26 => _26.utm_source]), () => (null)),utm_medium:_nullishCoalesce(_optionalChain([T, 'optionalAccess', _27 => _27.utm_medium]), () => (null)),utm_campaign:_nullishCoalesce(_optionalChain([T, 'optionalAccess', _28 => _28.utm_campaign]), () => (null)),utm_content:_nullishCoalesce(_optionalChain([T, 'optionalAccess', _29 => _29.utm_content]), () => (null)),utm_term:_nullishCoalesce(_optionalChain([T, 'optionalAccess', _30 => _30.utm_term]), () => (null)),ref_code:_nullishCoalesce(_optionalChain([T, 'optionalAccess', _31 => _31.ref_code]), () => (null)),product_id:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _32 => _32.product_id]), () => (null)),variant_id:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _33 => _33.variant_id]), () => (null)),order_ref:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _34 => _34.order_ref]), () => (null)),props:k.props};_optionalChain([d, 'optionalAccess', _35 => _35.event_id])&&!xe.test(d.event_id)&&a("ignored invalid event_id",r),u==="dashboard"&&e.visitorId&&(K.visitor_id=e.visitorId);let ce=_chunkW3RGQYPDjs.i.call(void 0, K);if(!ce.ok){a("dropped",r,ce.reason);return}let G=K;m?ne(G):E.push(G),p.push(G),p.length>=Ge?x():Be()}let ie=()=>x(!0),ae=()=>{document.visibilityState==="hidden"&&x(!0)},S=()=>re();return t.addEventListener("pagehide",ie),document.addEventListener("visibilitychange",ae),t.addEventListener("bitsnap:consent",S),t.addEventListener("bitsnap:consent:ready",S),W(),U(m),{track(r,f,d){try{oe(r,f,d)}catch (e18){}},page(r,f){try{r!==void 0&&(ee=r),oe("page_view",{landing:Re++===0},f)}catch (e19){}},clientId(r){try{return r!==void 0&&_chunkW3RGQYPDjs.c.call(void 0, r)!==i?null:P()?N(t,i):null}catch (e20){return null}},flush:()=>x(),setEnabled(r){H=!!r,H||(p=[],E=[],w())},configure(r){try{(r.env==="live"||r.env==="test")&&(j=r.env),typeof r.endpoint=="string"&&r.endpoint&&(s=c(r.endpoint))}catch (e21){}},onEvent(r){return C.add(r),()=>void C.delete(r)},destroy(){p=[],E=[],w(),C.clear(),t.removeEventListener("pagehide",ie),document.removeEventListener("visibilitychange",ae),t.removeEventListener("bitsnap:consent",S),t.removeEventListener("bitsnap:consent:ready",S)}}}var v,O=null;function D(e){if(!v){let t=Xe(e);return t===y||(v=t,O=_chunkW3RGQYPDjs.c.call(void 0, _nullishCoalesce(e.projectKey, () => ("")))),t}try{let t=_chunkW3RGQYPDjs.c.call(void 0, _nullishCoalesce(e.projectKey, () => ("")));t!==O&&e.debug&&console.warn("[bitsnap analytics]","tracker already started for another projectKey, ignoring",e.projectKey),t===O&&((e.env||e.endpoint)&&v.configure({env:e.env,endpoint:e.endpoint}),e.enabled!=null&&v.setEnabled(e.enabled))}catch (e22){}return v}function Ae(){return v}function xt(){typeof window<"u"&&ge(window),_optionalChain([v, 'optionalAccess', _36 => _36.destroy, 'call', _37 => _37()]),v=void 0,O=null}function _t(e){try{if(typeof window>"u")return{};let t=v,n=null;if(t)n=t.clientId(e);else{let o=e?_chunkW3RGQYPDjs.c.call(void 0, e):null;n=o?N(window,o):null}return n?{[me]:n}:{}}catch (e23){return{}}}var _react = require('react');var nt={track:y.track,page:y.page},Pe=_react.createContext.call(void 0, nt);function St({projectKey:e,env:t,enabled:n,endpoint:o,onEvent:a,autoPageViews:i,children:c}){let s=_react.useMemo.call(void 0, ()=>D({projectKey:e,env:t,endpoint:o,enabled:n}),[e,t,o]),u=_react.useRef.call(void 0, a);u.current=a,_chunkW3RGQYPDjs.q.call(void 0, ()=>{s.setEnabled(n!==!1)},[s,n]),_chunkW3RGQYPDjs.q.call(void 0, ()=>{if(!(i===!1||n===!1||s===y))return A(()=>s.page(null))},[s,i,n]),_chunkW3RGQYPDjs.q.call(void 0, ()=>s.onEvent(b=>_optionalChain([u, 'access', _38 => _38.current, 'optionalCall', _39 => _39(b)])),[s]);let l=_react.useMemo.call(void 0, ()=>({track:s.track.bind(s),page:s.page.bind(s)}),[s]);return _react.createElement.call(void 0, Pe.Provider,{value:l},c)}function we(){return _react.useContext.call(void 0, Pe)}var $={track(){}},X=null;function lt(e){let t=Symbol("bitsnap-instrument");function n(){if(typeof window>"u")return null;let{projectKey:i,analytics:c,provided:s}=e();return c===!1?null:s||(i?D({projectKey:i,source:"sdk_react",channel:"embed",env:typeof c=="object"?c.env:void 0}):null)}let o={track(i,c,s){try{let u=n();if(!u)return;let{analytics:l,pageType:b}=e(),M=b&&_optionalChain([s, 'optionalAccess', _40 => _40.page_type])===void 0?{...s,page_type:b}:s;X=typeof l=="object"&&l.onEvent?t:null,u.track(i,c,M)}catch (e24){}finally{X=null}}};function a(){try{if(!n())return()=>{};let i=Ae();if(!i)return()=>{};let c=e().provided?()=>{}:A(()=>i.page(_nullishCoalesce(e().pageType, () => (null)))),s=i.onEvent(u=>{if(X===t)try{let{analytics:l}=e();typeof l=="object"&&_optionalChain([l, 'access', _41 => _41.onEvent, 'optionalCall', _42 => _42(u)])}catch (e25){}});return()=>{c(),s()}}catch (e26){return()=>{}}}return{instrument:o,attach:a}}var Z=_react.createContext.call(void 0, null);function Nt({value:e,children:t}){return _react.createElement.call(void 0, Z.Provider,{value:e},t)}function Ot(){return _nullishCoalesce(_react.useContext.call(void 0, Z), () => ($))}function Dt(e,t,n){let o=_react.useContext.call(void 0, Z),a=we(),i=a.track===y.track?null:a,c=_react.useRef.call(void 0, {projectKey:e,analytics:t,pageType:n,provided:i});c.current={projectKey:e,analytics:t,pageType:n,provided:i};let s=_react.useMemo.call(void 0, ()=>lt(()=>c.current),[]),u=t===void 0&&o!==null,l=typeof t=="object"&&!!t.onEvent;return _react.useLayoutEffect.call(void 0, ()=>{if(!u)return s.attach()},[s,u,l,e]),u?o:s.instrument}var Q=$;function Se(e){Q=_nullishCoalesce(e, () => ($))}var q=0;function $t(){return q>0?$:Q}async function Mt(e){q++;try{return await e()}finally{q--}}function jt(e){_react.useEffect.call(void 0, ()=>(Se(e),()=>{Q===e&&Se(null)}),[e])}function Ht(e){let t=Number.isFinite(e)?Math.max(0,Math.min(100,e)):0;return t>=100?"100":t>=75?"75-99":t>=50?"50-74":t>=25?"25-49":"0-24"}function Wt(e,t){let n=[];for(let o of[25,50,75,100])e>=o&&!t.has(o)&&(t.add(o),n.push(o));return n}exports.a = ve; exports.b = A; exports.c = Ue; exports.d = Xe; exports.e = D; exports.f = Ae; exports.g = xt; exports.h = _t; exports.i = St; exports.j = we; exports.k = $; exports.l = Nt; exports.m = Ot; exports.n = Dt; exports.o = $t; exports.p = Mt; exports.q = jt; exports.r = Ht; exports.s = Wt;
|
|
2
|
+
//# sourceMappingURL=chunk-PVJ2I46C.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/dx/dist/chunk-PVJ2I46C.js","../src/analytics/pageviews.ts","../src/version.ts","../src/analytics/random.ts","../src/analytics/visitor.ts"],"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","readCookie","doc","part","index","isBitsnapHost","hostname","host","consentBelongsTo","projectKey","api","onBitsnap","analyticsGranted","newVisitorId","binary","byte","rawVisitorCookie","clientIdCookieName","readVisitorCookie","value","writeVisitorCookie","id","base"],"mappings":"AAAA,uuBAA2G,ICYrGA,EAAAA,CAAW,MAAA,CAAO,GAAA,CAAI,mBAAmB,CAAA,CA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B,CAAK,CAAA,CAAIA,CAAAA,CAAQ,IAC/D,CAOO,SAASC,EAAAA,CAAmB5C,CAAAA,CAAaiC,CAAAA,CAAoBY,CAAAA,CAAkB,CACpF,GAAI,CACF,IAAMnB,CAAAA,CAAM1B,CAAAA,CAAI,QAAA,CACV8C,CAAAA,CACJ,CAAA,EAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/dx/dist/chunk-PVJ2I46C.js","sourcesContent":[null,"/**\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.14.1\";\n","export function randomBytes(n: number): Uint8Array {\n const bytes = new Uint8Array(n);\n const c = typeof crypto !== \"undefined\" ? crypto : undefined;\n if (c && typeof c.getRandomValues === \"function\") c.getRandomValues(bytes);\n else for (let i = 0; i < n; i++) bytes[i] = Math.floor(Math.random() * 256);\n return bytes;\n}\n","import { domainCandidates } from \"../consent/core/cookie\";\nimport { clientIdCookieName } from \"./contract\";\nimport { randomBytes } from \"./random\";\n\n/** The part of `window.BitsnapConsent` (`bitsnap-react/consent`) the tracker reads. */\nexport type ConsentLike = {\n /** Absent on a consent script older than 1.9.0, which never counts as the project's banner. */\n scope?: \"global\" | \"project\";\n projectKey?: string | null;\n get(): { c: { analytics?: boolean } } | null;\n /** Also true for a refusal made on an older banner version, which `get()` no longer returns. */\n denied?(category: \"analytics\"): boolean;\n ready?: Promise<unknown>;\n};\n\n/** Sent to the Bitsnap server on the requests that create a checkout or payment link. */\nexport const VISITOR_HEADER = \"X-Bitsnap-Visitor\";\n// 390 days, under the 13 months CNIL allows. Set once, never extended.\nconst MAX_AGE_SECONDS = 390 * 24 * 60 * 60;\nconst VISITOR_ID_RE = /^[A-Za-z0-9_-]{22}$/;\n\nexport function consentApi(win: Window): ConsentLike | undefined {\n return (win as unknown as { BitsnapConsent?: ConsentLike }).BitsnapConsent;\n}\n\nfunction readCookie(doc: Document, name: string): string | null {\n for (const part of doc.cookie.split(\";\")) {\n const index = part.indexOf(\"=\");\n if (index !== -1 && part.slice(0, index).trim() === name) return part.slice(index + 1).trim();\n }\n return null;\n}\n\n/** bitsnap.pl and its subdomains: many merchants share them, and the site-wide choice is bitsnap's own. */\nfunction isBitsnapHost(hostname: string): boolean {\n const host = hostname.toLowerCase();\n return host === \"bitsnap.pl\" || host.endsWith(\".bitsnap.pl\");\n}\n\n/**\n * Whether the page's consent banner speaks for `projectKey`: a project-scope banner of that\n * key, or a site-scope banner on a merchant's own site. On bitsnap.pl a site-scope choice is\n * bitsnap's own, so only a project-scope one counts.\n */\nexport function consentBelongsTo(win: Window, projectKey: string): boolean {\n try {\n const api = consentApi(win);\n if (!api) return false;\n if (api.scope === \"project\") return api.projectKey === projectKey;\n const onBitsnap = isBitsnapHost(win.location.hostname);\n if (api.scope === \"global\") return !onBitsnap;\n // A consent script from before the scope info: it cannot be told apart from another project's banner.\n return false;\n } catch {\n return false;\n }\n}\n\n/** `true` only while a banner that speaks for `projectKey` holds a valid choice that grants `analytics`. */\nexport function analyticsGranted(win: Window, projectKey: string): boolean {\n try {\n return consentApi(win)?.get()?.c.analytics === true && consentBelongsTo(win, projectKey);\n } catch {\n return false;\n }\n}\n\n/** 16 random bytes as 22 base64url characters. */\nexport function newVisitorId(): string {\n let binary = \"\";\n randomBytes(16).forEach((byte) => (binary += String.fromCharCode(byte)));\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** Value of the `bs_vid_<projectKey>` cookie, whatever it holds; `null` when it is absent. */\nfunction rawVisitorCookie(doc: Document, projectKey: string): string | null {\n try {\n return readCookie(doc, clientIdCookieName(projectKey));\n } catch {\n return null;\n }\n}\n\n/** The project's client id from its first-party cookie (`bs_vid_<projectKey>`), or `null` if absent or malformed. */\nexport function readVisitorCookie(doc: Document, projectKey: string): string | null {\n const value = rawVisitorCookie(doc, projectKey);\n return value !== null && VISITOR_ID_RE.test(value) ? value : null;\n}\n\n/**\n * Sets the cookie on the widest registrable domain the browser accepts\n * (shortest suffix with two labels first, so `shop.example.co.uk` skips the\n * refused `co.uk`), host-only where no domain sticks (localhost, IP hosts).\n */\nexport function writeVisitorCookie(win: Window, projectKey: string, id: string): void {\n try {\n const doc = win.document;\n const base =\n `${clientIdCookieName(projectKey)}=${id}; Max-Age=${MAX_AGE_SECONDS}; Path=/; SameSite=Lax` +\n (win.location.protocol === \"https:\" ? \"; Secure\" : \"\");\n for (const domain of domainCandidates(win.location.hostname).reverse()) {\n doc.cookie = `${base}; Domain=${domain}`;\n if (readVisitorCookie(doc, projectKey) === id) return;\n }\n doc.cookie = base;\n } catch {\n // cookies blocked (sandboxed frame)\n }\n}\n\n/** Expires the cookie on the host and on every parent domain it may have been set on. */\nexport function deleteVisitorCookie(win: Window, projectKey: string): void {\n try {\n const doc = win.document;\n // Present under any value: a malformed one must go too.\n if (rawVisitorCookie(doc, projectKey) === null) return;\n const base =\n `${clientIdCookieName(projectKey)}=; Max-Age=0; Path=/; SameSite=Lax` +\n (win.location.protocol === \"https:\" ? \"; Secure\" : \"\");\n doc.cookie = base;\n for (const domain of domainCandidates(win.location.hostname)) doc.cookie = `${base}; Domain=${domain}`;\n } catch {\n // best effort\n }\n}\n\n/**\n * The project's client id to send, or `null`: analytics consent is granted,\n * Global Privacy Control is off, the browser is not automated and the cookie exists.\n */\nexport function readVisitorId(win: Window, projectKey: string): string | null {\n try {\n const nav = win.navigator as { globalPrivacyControl?: boolean; webdriver?: boolean } | undefined;\n if (nav?.globalPrivacyControl === true || nav?.webdriver === true) return null;\n return analyticsGranted(win, projectKey) ? readVisitorCookie(win.document, projectKey) : null;\n } catch {\n return null;\n }\n}\n"]}
|