bitsnap-react 1.21.1 → 1.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/AGENTS.md +20 -0
  2. package/dist/BitsnapCart-GK3MQGP7.js +2 -0
  3. package/dist/BitsnapCart-GK3MQGP7.js.map +1 -0
  4. package/dist/BitsnapCart-ZC6LMXLO.mjs +2 -0
  5. package/dist/CartProvider-FJDBDV4N.js +2 -0
  6. package/dist/CartProvider-FJDBDV4N.js.map +1 -0
  7. package/dist/CartProvider-P7BZVK2M.mjs +2 -0
  8. package/dist/PanelModelFiles-EKQRLF46.js.map +1 -1
  9. package/dist/analytics.js +1 -1
  10. package/dist/analytics.js.map +1 -1
  11. package/dist/analytics.mjs +1 -1
  12. package/dist/catalog.js +1 -1
  13. package/dist/catalog.js.map +1 -1
  14. package/dist/catalog.mjs +1 -1
  15. package/dist/chat.d.mts +2 -2
  16. package/dist/chat.d.ts +2 -2
  17. package/dist/chat.js +1 -1
  18. package/dist/chat.js.map +1 -1
  19. package/dist/chat.mjs +1 -1
  20. package/dist/chat.mjs.map +1 -1
  21. package/dist/{chunk-EK3D44XW.js → chunk-2CL4B4KM.js} +2 -2
  22. package/dist/chunk-2CL4B4KM.js.map +1 -0
  23. package/dist/chunk-2D2TQK3R.js +2 -0
  24. package/dist/chunk-2D2TQK3R.js.map +1 -0
  25. package/dist/{chunk-EXC5Z5VM.mjs → chunk-4AU5SEHU.mjs} +2 -2
  26. package/dist/chunk-6Q3VGPSF.js.map +1 -1
  27. package/dist/{chunk-FPCMLZFM.js → chunk-7GSQV4NW.js} +2 -2
  28. package/dist/chunk-7GSQV4NW.js.map +1 -0
  29. package/dist/chunk-7IP3JWZ3.mjs +2 -0
  30. package/dist/chunk-7IP3JWZ3.mjs.map +1 -0
  31. package/dist/{chunk-J6YI6FJN.js → chunk-CA5EJJW7.js} +2 -2
  32. package/dist/chunk-CA5EJJW7.js.map +1 -0
  33. package/dist/chunk-DCICRN6G.js +2 -0
  34. package/dist/chunk-DCICRN6G.js.map +1 -0
  35. package/dist/{chunk-J6WKSO33.mjs → chunk-EVV25IKM.mjs} +2 -2
  36. package/dist/{chunk-J6WKSO33.mjs.map → chunk-EVV25IKM.mjs.map} +1 -1
  37. package/dist/{chunk-J4GUVJP4.js → chunk-EVX5SQL2.js} +2 -2
  38. package/dist/chunk-EVX5SQL2.js.map +1 -0
  39. package/dist/chunk-FVZ4W7QG.js +5 -0
  40. package/dist/chunk-FVZ4W7QG.js.map +1 -0
  41. package/dist/chunk-GMQYQTUM.mjs +2 -0
  42. package/dist/{chunk-MMQTRSI5.js.map → chunk-GMQYQTUM.mjs.map} +1 -1
  43. package/dist/{chunk-OCJ7YWFX.js → chunk-I6QN3T6K.js} +2 -2
  44. package/dist/chunk-I6QN3T6K.js.map +1 -0
  45. package/dist/chunk-ILYJCT5S.js +2 -0
  46. package/dist/chunk-ILYJCT5S.js.map +1 -0
  47. package/dist/{chunk-FG7NLLJV.mjs → chunk-JRSQ2IGQ.mjs} +2 -2
  48. package/dist/chunk-JSDGZ4NY.js.map +1 -1
  49. package/dist/chunk-KOYBZORL.js.map +1 -1
  50. package/dist/{chunk-QWQPAN4F.mjs → chunk-M6QFQ3DR.mjs} +2 -2
  51. package/dist/chunk-MDAFPGPA.js.map +1 -1
  52. package/dist/{chunk-MMQTRSI5.js → chunk-MY6BPCRV.js} +2 -2
  53. package/dist/{chunk-YV3UGLQ3.mjs.map → chunk-MY6BPCRV.js.map} +1 -1
  54. package/dist/{chunk-QXCL5CE6.mjs → chunk-NMXTTD5M.mjs} +2 -2
  55. package/dist/chunk-PFKZ7KUU.js +2 -0
  56. package/dist/chunk-PFKZ7KUU.js.map +1 -0
  57. package/dist/chunk-Q337IQNA.js.map +1 -1
  58. package/dist/{chunk-7WTQGXPQ.mjs → chunk-RA6M3TJ3.mjs} +2 -2
  59. package/dist/{chunk-2HINORSP.mjs → chunk-SKQJESEB.mjs} +2 -2
  60. package/dist/chunk-STDV54FL.mjs +2 -0
  61. package/dist/chunk-STDV54FL.mjs.map +1 -0
  62. package/dist/{chunk-6DEKVABT.js → chunk-SZLSKIYU.js} +2 -2
  63. package/dist/chunk-SZLSKIYU.js.map +1 -0
  64. package/dist/chunk-W3RGQYPD.js.map +1 -1
  65. package/dist/chunk-W4EUYPJ3.mjs +2 -0
  66. package/dist/chunk-W4EUYPJ3.mjs.map +1 -0
  67. package/dist/chunk-Z3YOJ6NZ.js.map +1 -1
  68. package/dist/chunk-ZMEWUEZJ.mjs +5 -0
  69. package/dist/chunk-ZMEWUEZJ.mjs.map +1 -0
  70. package/dist/consent.js.map +1 -1
  71. package/dist/course.js +1 -1
  72. package/dist/course.js.map +1 -1
  73. package/dist/course.mjs +1 -1
  74. package/dist/embed/analytics.js +1 -1
  75. package/dist/errors.js.map +1 -1
  76. package/dist/index.css +1 -1
  77. package/dist/index.css.map +1 -1
  78. package/dist/index.d.mts +2 -2
  79. package/dist/index.d.ts +2 -2
  80. package/dist/index.js +1 -1
  81. package/dist/index.js.map +1 -1
  82. package/dist/index.mjs +1 -1
  83. package/dist/index.mjs.map +1 -1
  84. package/dist/internal.js.map +1 -1
  85. package/dist/methods-IEHZTZEY.mjs +2 -0
  86. package/dist/methods-S4KBRY2I.js +2 -0
  87. package/dist/methods-S4KBRY2I.js.map +1 -0
  88. package/dist/model-files-client-P4PORZJ6.js.map +1 -1
  89. package/dist/models.js.map +1 -1
  90. package/dist/returns.js +1 -1
  91. package/dist/returns.js.map +1 -1
  92. package/dist/returns.mjs +1 -1
  93. package/dist/viewer3d.js.map +1 -1
  94. package/dist/viewer3d.mjs +1 -1
  95. package/dist/{widgets-DmHlIbp8.d.mts → widgets-CAQRHzT7.d.mts} +41 -1
  96. package/dist/{widgets-BL6pCMdc.d.ts → widgets-DS_Pk7Br.d.ts} +41 -1
  97. package/package.json +2 -2
  98. package/dist/BitsnapCart-3RSI3PIM.mjs +0 -2
  99. package/dist/BitsnapCart-4DKJ7OXL.js +0 -2
  100. package/dist/BitsnapCart-4DKJ7OXL.js.map +0 -1
  101. package/dist/CartProvider-TXRCAXOT.mjs +0 -2
  102. package/dist/CartProvider-ZAGTSCHJ.js +0 -2
  103. package/dist/CartProvider-ZAGTSCHJ.js.map +0 -1
  104. package/dist/chunk-3TUL63IC.js +0 -2
  105. package/dist/chunk-3TUL63IC.js.map +0 -1
  106. package/dist/chunk-56X4DBMQ.mjs +0 -5
  107. package/dist/chunk-56X4DBMQ.mjs.map +0 -1
  108. package/dist/chunk-6DEKVABT.js.map +0 -1
  109. package/dist/chunk-EK3D44XW.js.map +0 -1
  110. package/dist/chunk-FPCMLZFM.js.map +0 -1
  111. package/dist/chunk-GLKBCVNH.mjs +0 -2
  112. package/dist/chunk-GLKBCVNH.mjs.map +0 -1
  113. package/dist/chunk-J4GUVJP4.js.map +0 -1
  114. package/dist/chunk-J6YI6FJN.js.map +0 -1
  115. package/dist/chunk-K2HIALKR.js +0 -2
  116. package/dist/chunk-K2HIALKR.js.map +0 -1
  117. package/dist/chunk-NW5PFIZB.js +0 -2
  118. package/dist/chunk-NW5PFIZB.js.map +0 -1
  119. package/dist/chunk-OCJ7YWFX.js.map +0 -1
  120. package/dist/chunk-TWZQ4CBY.js +0 -5
  121. package/dist/chunk-TWZQ4CBY.js.map +0 -1
  122. package/dist/chunk-VU2MX5HY.mjs +0 -2
  123. package/dist/chunk-VU2MX5HY.mjs.map +0 -1
  124. package/dist/chunk-YV3UGLQ3.mjs +0 -2
  125. package/dist/methods-27HZQY5L.js +0 -2
  126. package/dist/methods-27HZQY5L.js.map +0 -1
  127. package/dist/methods-27JU6IH7.mjs +0 -2
  128. /package/dist/{BitsnapCart-3RSI3PIM.mjs.map → BitsnapCart-ZC6LMXLO.mjs.map} +0 -0
  129. /package/dist/{CartProvider-TXRCAXOT.mjs.map → CartProvider-P7BZVK2M.mjs.map} +0 -0
  130. /package/dist/{chunk-EXC5Z5VM.mjs.map → chunk-4AU5SEHU.mjs.map} +0 -0
  131. /package/dist/{chunk-FG7NLLJV.mjs.map → chunk-JRSQ2IGQ.mjs.map} +0 -0
  132. /package/dist/{chunk-QWQPAN4F.mjs.map → chunk-M6QFQ3DR.mjs.map} +0 -0
  133. /package/dist/{chunk-QXCL5CE6.mjs.map → chunk-NMXTTD5M.mjs.map} +0 -0
  134. /package/dist/{chunk-7WTQGXPQ.mjs.map → chunk-RA6M3TJ3.mjs.map} +0 -0
  135. /package/dist/{chunk-2HINORSP.mjs.map → chunk-SKQJESEB.mjs.map} +0 -0
  136. /package/dist/{methods-27JU6IH7.mjs.map → methods-IEHZTZEY.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/analytics/contract.ts"],"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","EVENT_NAMES","STREAM_FOR_EVENT","stream","name","isEventName","CONSENT_COOKIE_MAX_AGE_SECONDS","CONSENT_SHOWN_ACTION","normalizeProjectKey","key","bare","CLIENT_RE","parseClientHeader","value","m","MAX_QUERY_VALUE","cleanValue","v","max","t","sanitizePath","pathname","joined","seg"],"mappings":"AAiBO,qrBAAMA,CAAAA,CAAS,CAEpB,cAAA,CAAgB,EAAA,CAEhB,YAAA,CAAc,KAAA,CAEd,aAAA,CAAe,IAAA,CACf,aAAA,CAAe,GAAA,CACf,YAAA,CAAc,EAAA,CACd,IAAA,CAAM,GAAA,CACN,IAAA,CAAM,GAAA,CACN,YAAA,CAAc,GAAA,CACd,GAAA,CAAK,GAAA,CACL,OAAA,CAAS,EAAA,CACT,EAAA,CAAI,EAAA,CACJ,GAAA,CAAK,EAAA,CACL,MAAA,CAAQ,EAAA,CACR,MAAA,CAAQ,EAAA,CACR,SAAA,CAAW,EAAA,CAEX,QAAA,CAAU,KACZ,CAAA,CAMaC,CAAAA,CAAU,CAC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C,MAAA,CAAQD,CAAAA,CAAO,UAAA,CAAW,GAAG,CAAA,CAAIA,CAAAA,CAAS,CAAA,CAAA,EAAIA,CAAM,CAAA,CAAA","file":"/home/emems/.t3/worktrees/bitsnap-react-panel-key/dist/chunk-W3RGQYPD.js","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"]}
1
+ {"version":3,"sources":["../src/analytics/contract.ts"],"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","EVENT_NAMES","STREAM_FOR_EVENT","stream","name","isEventName","CONSENT_COOKIE_MAX_AGE_SECONDS","CONSENT_SHOWN_ACTION","normalizeProjectKey","key","bare","CLIENT_RE","parseClientHeader","value","m","MAX_QUERY_VALUE","cleanValue","v","max","t","sanitizePath","pathname","joined","seg"],"mappings":"AAiBO,qrBAAMA,CAAAA,CAAS,CAEpB,cAAA,CAAgB,EAAA,CAEhB,YAAA,CAAc,KAAA,CAEd,aAAA,CAAe,IAAA,CACf,aAAA,CAAe,GAAA,CACf,YAAA,CAAc,EAAA,CACd,IAAA,CAAM,GAAA,CACN,IAAA,CAAM,GAAA,CACN,YAAA,CAAc,GAAA,CACd,GAAA,CAAK,GAAA,CACL,OAAA,CAAS,EAAA,CACT,EAAA,CAAI,EAAA,CACJ,GAAA,CAAK,EAAA,CACL,MAAA,CAAQ,EAAA,CACR,MAAA,CAAQ,EAAA,CACR,SAAA,CAAW,EAAA,CAEX,QAAA,CAAU,KACZ,CAAA,CAMaC,CAAAA,CAAU,CACrB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MAAA,CAAQD,CAAAA,CAAO,UAAA,CAAW,GAAG,CAAA,CAAIA,CAAAA,CAAS,CAAA,CAAA,EAAIA,CAAM,CAAA,CAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/emems-order-history-panel/dist/chunk-W3RGQYPD.js","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"]}
@@ -0,0 +1,2 @@
1
+ import{a as It,b as Lt}from"./chunk-KOVKUJAW.mjs";import{b as St,d as Ze,e as ie,f as ht,i as kt,j as Nt,l as P,m as Tt,o as wt,p as Et,q as Ct}from"./chunk-GMQYQTUM.mjs";import{a as me}from"./chunk-7IP3JWZ3.mjs";import{a as i}from"./chunk-5R6AGO3Z.mjs";import{l as Rt,m as Ee,n as xt}from"./chunk-EVV25IKM.mjs";import{a as Ce,b as vt,f as Ie}from"./chunk-OFPRIENJ.mjs";var Lr=["root","header","title","description","backButton","stepIndicator","error","emptyState","skeleton","emailForm","emailInput","codeForm","codeInput","resendButton","logoutButton","orderList","orderCard","orderReference","orderDate","orderTotal","pagination","lineList","line","lineName","linePrice","lineQuantityControl","quantityButton","quantityInput","lineIneligibleReason","noteInput","summary","submitButton","secondaryButton","successState","returnReference","returnInstructions","returnList","returnCard","statusBadge","history","historyEntry"],Nn={fontFamily:"--bitsnap-returns-font-family",fontSize:"--bitsnap-returns-font-size",background:"--bitsnap-returns-background",surface:"--bitsnap-returns-surface",foreground:"--bitsnap-returns-foreground",mutedForeground:"--bitsnap-returns-muted-foreground",border:"--bitsnap-returns-border",buttonBackground:"--bitsnap-returns-button-background",buttonForeground:"--bitsnap-returns-button-foreground",buttonHoverBackground:"--bitsnap-returns-button-hover-background",hoverSurface:"--bitsnap-returns-hover-surface",focusRing:"--bitsnap-returns-focus-ring",error:"--bitsnap-returns-error",success:"--bitsnap-returns-success",warning:"--bitsnap-returns-warning",badgeBackground:"--bitsnap-returns-badge-background",badgeForeground:"--bitsnap-returns-badge-foreground",inputBackground:"--bitsnap-returns-input-background",radius:"--bitsnap-returns-radius"},Tn={light:{background:"#ffffff",surface:"#f9fafb",foreground:"#18181b",mutedForeground:"#71717a",border:"#e4e4e7",buttonBackground:"#18181b",buttonForeground:"#fafafa",buttonHoverBackground:"#000000",hoverSurface:"#f4f4f5",focusRing:"#71717a",error:"#dc2626",success:"#16a34a",warning:"#d97706",badgeBackground:"#f4f4f5",badgeForeground:"#3f3f46",inputBackground:"#ffffff",radius:"8px"},dark:{background:"#18181b",surface:"#27272a",foreground:"#fafafa",mutedForeground:"#a1a1aa",border:"#3f3f46",buttonBackground:"#fafafa",buttonForeground:"#18181b",buttonHoverBackground:"#e4e4e7",hoverSurface:"#3f3f46",focusRing:"#a1a1aa",error:"#f87171",success:"#4ade80",warning:"#fbbf24",badgeBackground:"#3f3f46",badgeForeground:"#e4e4e7",inputBackground:"#27272a",radius:"8px"}},wn=[{token:"background",variable:"--background"},{token:"foreground",variable:"--foreground"},{token:"surface",variable:"--card"},{token:"foreground",variable:"--card-foreground"},{token:"surface",variable:"--popover"},{token:"foreground",variable:"--popover-foreground"},{token:"buttonBackground",variable:"--primary"},{token:"buttonForeground",variable:"--primary-foreground"},{token:"surface",variable:"--secondary"},{token:"foreground",variable:"--secondary-foreground"},{token:"hoverSurface",variable:"--accent"},{token:"foreground",variable:"--accent-foreground"},{token:"mutedForeground",variable:"--muted-foreground"},{token:"border",variable:"--border"},{token:"border",variable:"--input"},{token:"focusRing",variable:"--ring"},{token:"error",variable:"--destructive"},{token:"radius",variable:"--radius"}];function Ge(e){let t=It(e,{defaultTheme:"light",presets:Tn,variables:Nn,shadcnVariables:wn});return{theme:t.theme,tokens:t.tokens,elements:t.elements,boundaryClassName:t.theme,boundaryStyle:t.boundaryStyle}}function Pt(e,t){return Lt(e.elements,t)}import{createContext as En,useContext as Cn,useMemo as In}from"react";import{jsx as Ln}from"react/jsx-runtime";var At=En(Ge());function Ot({appearance:e,children:t}){let n=In(()=>Ge(e),[e]);return Ln(At.Provider,{value:n,children:t})}function $e(){return Cn(At)}function d(e){let t=$e();return Pt(t,e)??{}}function Bt(e){return e==="test"||e===1?1:0}var zt={title:["emailStepTitle"],email:["emailLabel"],sendCode:["emailSubmit"],code:["codeLabel"],verify:["codeSubmit"],orders:["ordersTitle"],submit:["confirmationSubmit"],note:["noteLabel"],history:["myReturnsTitle","myReturnsLink"]};function Mt(e){if(e==null)return;let t={};for(let[n,s]of Object.entries(zt)){let a=e[n];if(typeof a=="string")for(let u of s)t[u]=a}for(let n of Object.keys(e)){if(n in zt)continue;let s=e[n];typeof s=="string"&&(t[n]=s)}return t}function Dt(e,t){let n=t?.brandColor?.trim();return n==null||n===""?e:{...e,tokens:{...wt(n),...e?.tokens}}}function Xe(e,t){return typeof e=="object"&&e!=null?{pageSize:e.pageSize??20,explicitPageToken:void 0}:typeof e=="number"||t!==void 0?{pageSize:e??20,explicitPageToken:t??""}:{pageSize:20,explicitPageToken:void 0}}var Pn={en:{back:"Back",stepIndicator:"Step {current} of {total}",loading:"Loading",myReturnsLink:"My returns",emailStepTitle:"Return a product",emailStepDescription:"Enter the email address you used for the order. We will send you a verification code.",emailLabel:"Email address",emailPlaceholder:"name@example.com",emailSubmit:"Send code",codeStepTitle:"Enter the code",codeStepDescription:"We sent a verification code to {email}.",codeLabel:"Verification code",codeSubmit:"Verify",resend:"Send the code again",resendIn:"Send again in {seconds} s",resendSent:"We sent a new code.",codeSpamHint:"Can't see the email? Check your spam folder.",codeValidity:"The code is valid for 10 minutes.",codeIncomplete:"Enter all 6 digits of the code.",logout:"Sign out",ordersTitle:"Your orders",ordersDescription:"Choose the order that contains the product to return.",ordersEmpty:"There are no orders eligible for return.",orderTitle:"Order {reference}",orderReturnableLines:"Products available to return: {count}",orderSelect:"Choose",paginationPrevious:"Previous",paginationNext:"Next",paginationInfo:"Page {page}, {total} orders",orderDetailTitle:"Order {reference}",orderDetailDescription:"Select the products and quantities to return.",quantityLabel:"Quantity to return: {name}",quantityDecrease:"Decrease quantity: {name}",quantityIncrease:"Increase quantity: {name}",quantityOfAvailable:"of {available}",lineIneligibleFallback:"This product cannot be returned.",noteLabel:"Note (optional)",notePlaceholder:"Tell us why you are returning the product",selectionContinue:"Continue",selectionEmpty:"Select at least one item to return.",previousReturnsTitle:"Earlier returns for this order",confirmationTitle:"Confirm the return",confirmationDescription:"Check the products before you submit the request.",confirmationSummary:"Products to return",confirmationQuantity:"Quantity: {quantity}",confirmationNote:"Your note",confirmationSubmit:"Submit return request",successTitle:"Return request submitted",successDescription:"We received your request and will keep you posted.",successReference:"Request number",successInstructions:"What to do next",successDone:"Back to orders",myReturnsTitle:"My returns",myReturnsDescription:"Track the status of your return requests.",myReturnsEmpty:"You have not submitted any return requests yet.",myReturnOpen:"Details",myReturnDetailTitle:"Return details",myReturnTitle:"Return {reference}",myReturnCreatedAt:"Submitted",myReturnRefund:"Refund",myReturnLines:"Products",myReturnLineQuantities:"Requested: {requested}, approved: {approved}, received: {received}",myReturnNote:"Your note",myReturnHistory:"History",statusSubmitted:"Submitted",statusApproved:"Approved",statusRejected:"Rejected",statusAwaitingReceipt:"Awaiting the package",statusReceived:"Package received",statusCompleted:"Completed",statusCancelled:"Cancelled",statusRefunded:"Refunded",statusFallback:"In progress",refundStatusNotStarted:"Not started",refundStatusPending:"Refund in progress",refundStatusSucceeded:"Refunded",refundStatusFailed:"Refund failed",refundStatusFallback:"Unknown",errorGeneric:"Something went wrong. Please try again.",errorNetwork:"Cannot reach the server. Check your connection and try again.",errorInvalidEmail:"Enter a valid email address.",errorInvalidCode:"The code is invalid or has expired.",errorSessionExpired:"Your session has expired. Verify your email again.",errorOrderNotFound:"We could not find this order.",errorReturnNotFound:"We could not find this return request.",errorQuantityUnavailable:"The selected quantity is no longer available for return.",errorItemNotReturnable:"One of the selected products cannot be returned.",errorReturnsDisabled:"Returns are not available in this shop.",errorRateLimited:"Too many attempts. Please try again later.",errorIdempotencyConflict:"This request was already submitted with different contents. Reload and try again.",errorDeliveryFailed:"We could not send the code. Please try again.",errorRetry:"Try again"},pl:{back:"Wstecz",stepIndicator:"Krok {current} z {total}",loading:"\u0141adowanie",myReturnsLink:"Moje zwroty",emailStepTitle:"Zwr\xF3\u0107 produkt",emailStepDescription:"Podaj adres e-mail u\u017Cyty w zam\xF3wieniu. Wy\u015Blemy na niego kod weryfikacyjny.",emailLabel:"Adres e-mail",emailPlaceholder:"jan@example.com",emailSubmit:"Wy\u015Blij kod",codeStepTitle:"Wpisz kod",codeStepDescription:"Wys\u0142ali\u015Bmy kod weryfikacyjny na adres {email}.",codeLabel:"Kod weryfikacyjny",codeSubmit:"Zweryfikuj",resend:"Wy\u015Blij kod ponownie",resendIn:"Wy\u015Blij ponownie za {seconds} s",resendSent:"Wys\u0142ali\u015Bmy nowy kod.",codeSpamHint:"Nie widzisz e-maila? Sprawd\u017A folder spam.",codeValidity:"Kod jest wa\u017Cny 10 minut.",codeIncomplete:"Wpisz wszystkie 6 cyfr kodu.",logout:"Wyloguj si\u0119",ordersTitle:"Twoje zam\xF3wienia",ordersDescription:"Wybierz zam\xF3wienie z produktem do zwrotu.",ordersEmpty:"Brak zam\xF3wie\u0144, kt\xF3re mo\u017Cna zwr\xF3ci\u0107.",orderTitle:"Zam\xF3wienie {reference}",orderReturnableLines:"Produkty do zwrotu: {count}",orderSelect:"Wybierz",paginationPrevious:"Poprzednia",paginationNext:"Nast\u0119pna",paginationInfo:"Strona {page}, zam\xF3wie\u0144: {total}",orderDetailTitle:"Zam\xF3wienie {reference}",orderDetailDescription:"Wybierz produkty i ilo\u015Bci do zwrotu.",quantityLabel:"Ilo\u015B\u0107 do zwrotu: {name}",quantityDecrease:"Zmniejsz ilo\u015B\u0107: {name}",quantityIncrease:"Zwi\u0119ksz ilo\u015B\u0107: {name}",quantityOfAvailable:"z {available}",lineIneligibleFallback:"Ten produkt nie podlega zwrotowi.",noteLabel:"Uwagi (opcjonalnie)",notePlaceholder:"Napisz, dlaczego zwracasz produkt",selectionContinue:"Dalej",selectionEmpty:"Wybierz co najmniej jedn\u0105 sztuk\u0119 do zwrotu.",previousReturnsTitle:"Wcze\u015Bniejsze zwroty tego zam\xF3wienia",confirmationTitle:"Potwierd\u017A zwrot",confirmationDescription:"Sprawd\u017A produkty przed wys\u0142aniem zg\u0142oszenia.",confirmationSummary:"Produkty do zwrotu",confirmationQuantity:"Ilo\u015B\u0107: {quantity}",confirmationNote:"Twoje uwagi",confirmationSubmit:"Wy\u015Blij zg\u0142oszenie zwrotu",successTitle:"Zg\u0142oszenie zwrotu zosta\u0142o wys\u0142ane",successDescription:"Otrzymali\u015Bmy zg\u0142oszenie i b\u0119dziemy informowa\u0107 o jego statusie.",successReference:"Numer zg\u0142oszenia",successInstructions:"Co dalej",successDone:"Wr\xF3\u0107 do zam\xF3wie\u0144",myReturnsTitle:"Moje zwroty",myReturnsDescription:"Sprawd\u017A status swoich zg\u0142osze\u0144 zwrotu.",myReturnsEmpty:"Nie masz jeszcze \u017Cadnych zg\u0142osze\u0144 zwrotu.",myReturnOpen:"Szczeg\xF3\u0142y",myReturnDetailTitle:"Szczeg\xF3\u0142y zwrotu",myReturnTitle:"Zwrot {reference}",myReturnCreatedAt:"Zg\u0142oszono",myReturnRefund:"Zwrot \u015Brodk\xF3w",myReturnLines:"Produkty",myReturnLineQuantities:"Zg\u0142oszono: {requested}, zaakceptowano: {approved}, odebrano: {received}",myReturnNote:"Twoje uwagi",myReturnHistory:"Historia",statusSubmitted:"Zg\u0142oszony",statusApproved:"Zaakceptowany",statusRejected:"Odrzucony",statusAwaitingReceipt:"Oczekiwanie na paczk\u0119",statusReceived:"Paczka odebrana",statusCompleted:"Zako\u0144czony",statusCancelled:"Anulowany",statusRefunded:"\u015Arodki zwr\xF3cone",statusFallback:"W trakcie",refundStatusNotStarted:"Nie rozpocz\u0119to",refundStatusPending:"Zwrot \u015Brodk\xF3w w toku",refundStatusSucceeded:"\u015Arodki zwr\xF3cone",refundStatusFailed:"Zwrot \u015Brodk\xF3w nie powi\xF3d\u0142 si\u0119",refundStatusFallback:"Nieznany",errorGeneric:"Co\u015B posz\u0142o nie tak. Spr\xF3buj ponownie.",errorNetwork:"Brak po\u0142\u0105czenia z serwerem. Sprawd\u017A internet i spr\xF3buj ponownie.",errorInvalidEmail:"Podaj poprawny adres e-mail.",errorInvalidCode:"Kod jest nieprawid\u0142owy lub wygas\u0142.",errorSessionExpired:"Sesja wygas\u0142a. Zweryfikuj adres e-mail ponownie.",errorOrderNotFound:"Nie znaleziono tego zam\xF3wienia.",errorReturnNotFound:"Nie znaleziono tego zg\u0142oszenia zwrotu.",errorQuantityUnavailable:"Wybrana ilo\u015B\u0107 nie jest ju\u017C dost\u0119pna do zwrotu.",errorItemNotReturnable:"Jeden z wybranych produkt\xF3w nie podlega zwrotowi.",errorReturnsDisabled:"Zwroty nie s\u0105 dost\u0119pne w tym sklepie.",errorRateLimited:"Zbyt wiele pr\xF3b. Spr\xF3buj ponownie p\xF3\u017Aniej.",errorIdempotencyConflict:"To zg\u0142oszenie zosta\u0142o ju\u017C wys\u0142ane z inn\u0105 zawarto\u015Bci\u0105. Od\u015Bwie\u017C stron\u0119 i spr\xF3buj ponownie.",errorDeliveryFailed:"Nie uda\u0142o si\u0119 wys\u0142a\u0107 kodu. Spr\xF3buj ponownie.",errorRetry:"Spr\xF3buj ponownie"}};function Je(e,t){return vt(Pn,e,t)}function Ft(e,t){return e.replace(/\{(\w+)\}/g,(n,s)=>Object.prototype.hasOwnProperty.call(t,s)?String(t[s]):n)}var An={submitted:"statusSubmitted",approved:"statusApproved",rejected:"statusRejected",awaiting_receipt:"statusAwaitingReceipt",received:"statusReceived",completed:"statusCompleted",cancelled:"statusCancelled",refunded:"statusRefunded"},On={not_started:"refundStatusNotStarted",pending:"refundStatusPending",succeeded:"refundStatusSucceeded",failed:"refundStatusFailed"};function Kt(e){return An[e]??"statusFallback"}function jt(e){return On[e]??"refundStatusFallback"}import{createContext as zn,useCallback as Bn,useContext as _t,useMemo as Mn}from"react";import{jsx as Dn}from"react/jsx-runtime";var et=zn({locale:"pl-PL",texts:Je("pl-PL")});function qt({texts:e,locale:t,children:n}){let s=t??Ie(),a=Mn(()=>({locale:s,texts:Je(s,e)}),[s,e]);return Dn(et.Provider,{value:a,children:n})}function z(){let{texts:e}=_t(et);return Bn((t,n)=>n==null?e[t]:Ft(e[t],n),[e])}function Z(){return _t(et).locale}import{createClient as jn}from"@connectrpc/connect";import{createConnectQueryKey as _n,TransportProvider as qn}from"@connectrpc/connect-query";import{QueryClient as Un,QueryClientContext as Vn,QueryClientProvider as Qn,useQueryClient as Wn}from"@tanstack/react-query";import{createContext as Hn,useCallback as ze,useContext as Ht,useEffect as Wt,useMemo as Be,useRef as Yn,useState as ke}from"react";function tt(){try{return typeof window<"u"?window.sessionStorage:void 0}catch{return}}function Ut(e,t,n){return`bitsnap-login-pending:${e}:${encodeURIComponent(n??"")}:${encodeURIComponent(t??"")}`}function Le(e,t){try{tt()?.setItem(e,JSON.stringify(t))}catch{}}function fe(e){try{tt()?.removeItem(e)}catch{}}function Pe(e,t=Date.now()){let n=tt();if(n!=null)try{let s=n.getItem(e);if(s==null)return;let a=JSON.parse(s);if(a!=null&&typeof a.email=="string"&&a.email!==""&&typeof a.sentAt=="number"&&typeof a.resendAt=="number"&&(a.challengeId==null||typeof a.challengeId=="string")&&t-a.sentAt<6e5)return{email:a.email,challengeId:a.challengeId,resendAt:a.resendAt,sentAt:a.sentAt};n.removeItem(e)}catch{try{n.removeItem(e)}catch{}}}import{timestampMs as Fn}from"@bufbuild/protobuf/wkt";var Kn="bitsnap-returns-session:";function nt(e){return`${Kn}${e}`}function Ae(){try{return typeof window<"u"?window.sessionStorage:void 0}catch{return}}function Vt(e,t,n=Date.now()){if(e==null)return;let s=nt(t);try{let a=e.getItem(s);if(a==null)return;let u=JSON.parse(a);if(u!=null&&typeof u=="object"&&typeof u.token=="string"&&u.token.length>0&&typeof u.expiresAt=="number"&&u.expiresAt>n){let{token:o,expiresAt:r}=u;return{token:o,expiresAt:r}}e.removeItem(s)}catch{try{e.removeItem(s)}catch{}}}function Qt(e,t,n){try{e?.setItem(nt(t),JSON.stringify(n))}catch{}}function rt(e,t){try{e?.removeItem(nt(t))}catch{}}function Oe(e){return e==null?void 0:Fn(e)}import{jsx as ue}from"react/jsx-runtime";var Yt=Hn(void 0);function D(e){let t=Ht(Yt);if(t==null)throw new Error(`${e} must be rendered inside <ReturnsProvider>`);return t}function st(){return _n({schema:Ze,cardinality:void 0})}var Zn=2**31-1;function Gn({projectID:e,environment:t,transport:n,panelAccessToken:s,className:a,children:u}){let o=Wn(),{boundaryClassName:r,boundaryStyle:g}=$e(),m=d("root"),[l,y]=ke({status:"hydrating"}),[c,f]=ke(),[b,x]=ke(),[v,k]=ke(),S=Ut("returns",e),w=Yn(void 0),h=ze(N=>{if(x(N),N==null){fe(S);return}k(N.email),Le(S,{email:N.email,challengeId:N.challengeId,resendAt:N.resendAvailableAt,sentAt:Date.now()})},[S]),C=ze(()=>{o.removeQueries({queryKey:st()})},[o]),U=ze(()=>{rt(Ae(),e),h(void 0),y({status:"anonymous"}),C()},[e,C,h]),j=ze(N=>{Qt(Ae(),e,N),f(void 0),h(void 0),y({status:"authenticated",token:N.token,expiresAt:N.expiresAt})},[e,h]);Wt(()=>{let N=!1,Y=Ae();if(s==null||s===""){let A=w.current!=null;if(w.current=void 0,A){U();return}let _=Vt(Y,e),V=_==null?Pe(S):void 0;V?.challengeId!=null&&(x({challengeId:V.challengeId,email:V.email,resendAvailableAt:V.resendAt}),k(V.email)),y(_!=null?{status:"authenticated",token:_.token,expiresAt:_.expiresAt}:{status:"anonymous"});return}return w.current=s,rt(Y,e),C(),f(void 0),y({status:"exchanging"}),jn(Ze,n).exchangePanelSession({projectId:e,accessToken:s,environment:t}).then(A=>{if(N)return;let _=Oe(A.expiresAt);if(A.sessionToken===""||_==null)throw new Error("EMPTY_SESSION");j({token:A.sessionToken,expiresAt:_})}).catch(A=>{N||(f(A),y({status:"anonymous"}))}),()=>{N=!0}},[s,e,t,n]),Wt(()=>{if(l.status!=="authenticated"||l.expiresAt==null)return;let N=l.expiresAt-Date.now();if(N<=0){U();return}let Y=setTimeout(U,Math.min(N,Zn));return()=>clearTimeout(Y)},[l.status,l.expiresAt,U]);let J=Be(()=>({projectID:e,environment:t,status:l.status,token:l.token,exchangeError:c,challenge:b,setChallenge:h,lastEmail:v,authenticate:j,clearSession:U}),[e,t,l.status,l.token,c,b,h,v,j,U]);return ue(Yt.Provider,{value:J,children:ue("div",{"data-bitsnap-returns":"root","data-bitsnap-returns-slot":"root",className:i("bitsnap-react",r,a,m.className),style:{...g,...m.style},children:u})})}function $n({projectID:e,host:t,environment:n,appearance:s,texts:a,theme:u,locale:o,panelAccessToken:r,className:g,analytics:m,children:l}){let y=xt(e,m,"returns"),c=Ht(Vn),[f]=ke(()=>c==null?new Un({defaultOptions:{queries:{staleTime:5e3}}}):void 0),b=t??kt(),x=Be(()=>Nt(b),[b]),v=u?.brandColor,k=Be(()=>Dt(s,{brandColor:v}),[s,v]),S=Be(()=>Mt(a),[a]),w=ue(Rt,{value:y,children:ue(qn,{transport:x,children:ue(Ot,{appearance:k,children:ue(qt,{texts:S,locale:o,children:ue(Gn,{projectID:e,environment:Bt(n),transport:x,panelAccessToken:r,className:g,children:l})})})})});return c==null&&f!=null?ue(Qn,{client:f,children:w}):w}var us=$n;import{useMutation as it,useQuery as Me}from"@connectrpc/connect-query";import{useQueryClient as nr}from"@tanstack/react-query";import{useCallback as oe,useEffect as Jt,useRef as rr,useState as sr}from"react";import{Code as Jn,ConnectError as er}from"@connectrpc/connect";import{Code as Ne,ConnectError as Xn}from"@connectrpc/connect";function Zt(e){let t=Xn.from(e);switch(t.code){case Ne.ResourceExhausted:return"rateLimited";case Ne.Unavailable:case Ne.DeadlineExceeded:case Ne.Canceled:return"network";case Ne.Unknown:return e instanceof TypeError||t.cause instanceof TypeError?"network":"unknown";default:return"unknown"}}var tr="SESSION_EXPIRED",Gt={INVALID_EMAIL:"errorInvalidEmail",INVALID_OR_EXPIRED_CODE:"errorInvalidCode",SESSION_EXPIRED:"errorSessionExpired",ORDER_NOT_FOUND:"errorOrderNotFound",RETURN_NOT_FOUND:"errorReturnNotFound",QUANTITY_UNAVAILABLE:"errorQuantityUnavailable",ITEM_NOT_RETURNABLE:"errorItemNotReturnable",INVALID_RETURN_ITEMS:"errorItemNotReturnable",RETURNS_DISABLED:"errorReturnsDisabled",SUBMISSION_RATE_LIMITED:"errorRateLimited",IDEMPOTENCY_CONFLICT:"errorIdempotencyConflict",VERIFICATION_DELIVERY_FAILED:"errorDeliveryFailed"};function $t(e){if(e==null||typeof e!="object")return;let{rawMessage:t,message:n}=e;if(typeof t=="string"&&t.length>0)return t;if(typeof n=="string")return Object.keys(Gt).find(s=>n.includes(s))}function ot(e){return $t(e)===tr}function Xt(e){let t=$t(e),n=t!=null?Gt[t]:void 0;if(n!=null)return n;if(e!=null&&typeof e=="object"){if(er.from(e).code===Jn.ResourceExhausted)return"errorRateLimited";if(Zt(e)==="network")return"errorNetwork"}return"errorGeneric"}function at(){let e=typeof globalThis<"u"?globalThis.crypto:void 0;if(typeof e?.randomUUID=="function")return e.randomUUID();let t=new Uint8Array(16);if(typeof e?.getRandomValues=="function")e.getRandomValues(t);else for(let n=0;n<t.length;n++)t[n]=Math.floor(Math.random()*256);return Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}function ge(e){return e==null?null:e instanceof Error?e:new Error(String(e))}function ye(e){return e==null?void 0:Xt(e)}function De(e,t){Jt(()=>{ot(e)&&t()},[e,t])}function en(e){let[t,n]=sr([""]);return Jt(()=>{n([""])},[e]),{pageToken:t[t.length-1]??"",page:t.length,push:s=>n(a=>[...a,s]),pop:()=>n(s=>s.length>1?s.slice(0,-1):s)}}function Fe(){let e=D("useReturnSession"),t=it(ie.returns.startReturnSession),n=it(ie.returns.verifyReturnSession),{setChallenge:s,authenticate:a,clearSession:u}=e,o=Z().toLowerCase().startsWith("en")?"en":"pl",r=oe(async f=>{n.reset();let b=f.trim(),x=await t.mutateAsync({projectId:e.projectID,email:b,environment:e.environment,locale:o});return s({challengeId:x.challengeId,email:b,resendAvailableAt:Date.now()+Math.max(0,x.resendAfterSeconds)*1e3}),x},[e.projectID,e.environment,o,s,t,n]),g=oe(async f=>{let b=await n.mutateAsync({projectId:e.projectID,challengeId:f.challengeId,code:f.code,environment:e.environment}),x=Oe(b.expiresAt);if(b.sessionToken===""||x==null)throw new Error("EMPTY_SESSION");return a({token:b.sessionToken,expiresAt:x}),b},[e.projectID,e.environment,a,n]),m=oe(async f=>{try{return await r(f),!0}catch{return!1}},[r]),l=oe(async f=>{if(e.challenge==null)return!1;try{return await g({challengeId:e.challenge.challengeId,code:f.trim()}),!0}catch{return!1}},[e.challenge,g]),y=oe(()=>e.challenge!=null?m(e.challenge.email):Promise.resolve(!1),[e.challenge,m]),c=ge(t.error??n.error??e.exchangeError);return{status:e.status,isAuthenticated:e.status==="authenticated",challenge:e.challenge,isStarting:t.isPending,isVerifying:n.isPending,starting:t.isPending,verifying:n.isPending,error:c,errorKey:ye(c),start:m,startSession:r,verifySession:g,verify:l,resend:y,logout:u}}function Ke(e){return e.status==="hydrating"||e.status==="exchanging"}function tn(e,t){let n=D("useReturnOrders"),{pageSize:s,explicitPageToken:a}=Xe(e,t),u=en(n.token),o=Me(ie.returns.listReturnOrders,{projectId:n.projectID,sessionToken:n.token??"",pageSize:s,pageToken:a??u.pageToken},{enabled:n.token!=null});De(o.error,n.clearSession);let r=o.data?.nextPageToken??"";return{orders:o.data?.orders??[],total:o.data?.total??0,data:o.data,isLoading:Ke(n)||o.isLoading,isFetching:o.isFetching,error:ge(o.error),errorKey:ye(o.error),status:o.status,isError:o.isError,isSuccess:o.isSuccess,page:u.page,hasNext:r!=="",hasPrevious:u.page>1,next:()=>{r!==""&&u.push(r)},previous:u.pop,refetch:()=>o.refetch()}}function ut(e){let t=D("useReturnableOrder"),n=Me(ie.returns.getReturnableOrder,{projectId:t.projectID,sessionToken:t.token??"",canonicalOrderId:e??""},{enabled:t.token!=null&&e!=null&&e!==""});return De(n.error,t.clearSession),{order:n.data?.order,returnHistory:n.data?.returnHistory??[],data:n.data,isLoading:e!=null&&e!==""&&(Ke(t)||n.isLoading),error:ge(n.error),errorKey:ye(n.error),status:n.status,isError:n.isError,isSuccess:n.isSuccess,refetch:()=>n.refetch()}}function nn(){let e=D("useCreateReturn"),t=nr(),n=it(ie.returns.createReturnRequest),s=Ee(),a=rr(void 0),{clearSession:u}=e,o=oe(async(l,y)=>{try{let c=await n.mutateAsync({projectId:e.projectID,sessionToken:e.token??"",canonicalOrderId:l.orderId,items:l.items,note:l.note??"",idempotencyKey:y});return t.invalidateQueries({queryKey:st()}),s.track("return_submitted",{reason_code:"unspecified",item_count:l.items.length},{order_ref:null}),c}catch(c){throw ot(c)&&u(),c}},[e.projectID,e.token,n,t,u,s]),r=oe(async l=>{a.current??=at();try{let y=await o(l,a.current);return a.current=void 0,y.request}catch{return}},[o]),g=oe(async l=>{if(e.token==null)throw new Error("Verify your email to continue.");return o({orderId:l.canonicalOrderID,items:l.items,note:l.note},l.idempotencyKey??at())},[e.token,o]),m=oe((l,y)=>{g(l).then(c=>y?.onSuccess?.(c),c=>y?.onError?.(ge(c)))},[g]);return{submit:r,isPending:n.isPending,error:ge(n.error),errorKey:ye(n.error),mutateAsync:g,mutate:m,data:n.data,reset:n.reset,status:n.status,isError:n.isError,isSuccess:n.isSuccess}}function rn(e,t){let n=D("useMyReturns"),{pageSize:s,explicitPageToken:a}=Xe(e,t),u=en(n.token),o=Me(ie.returns.listMyReturns,{projectId:n.projectID,sessionToken:n.token??"",pageSize:s,pageToken:a??u.pageToken},{enabled:n.token!=null});De(o.error,n.clearSession);let r=o.data?.nextPageToken??"";return{returns:o.data?.returns??[],total:o.data?.total??0,data:o.data,isLoading:Ke(n)||o.isLoading,isFetching:o.isFetching,error:ge(o.error),errorKey:ye(o.error),status:o.status,isError:o.isError,isSuccess:o.isSuccess,page:u.page,hasNext:r!=="",hasPrevious:u.page>1,next:()=>{r!==""&&u.push(r)},previous:u.pop,refetch:()=>o.refetch()}}function je(e){let t=D("useMyReturn"),n=Me(ie.returns.getMyReturn,{projectId:t.projectID,sessionToken:t.token??"",returnId:e},{enabled:t.token!=null});return De(n.error,t.clearSession),{request:n.data?.request,isLoading:Ke(t)||n.isLoading,error:n.error,errorKey:ye(n.error),refetch:()=>n.refetch()}}import{useEffect as Tr,useRef as yn,useState as we}from"react";import*as sn from"@radix-ui/react-label";import{jsx as or}from"react/jsx-runtime";function Te({className:e,...t}){return or(sn.Root,{"data-slot":"label",className:i("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}import{Loader2Icon as ar}from"lucide-react";import{jsx as ir}from"react/jsx-runtime";function be({className:e,...t}){return ir(ar,{role:"status","aria-label":"Loading",className:i("size-4 animate-spin",e),...t})}import{useState as ur}from"react";import{Fragment as pr,jsx as ee,jsxs as on}from"react/jsx-runtime";var lr={pl:{alt:"Logo sklepu"},en:{alt:"Shop logo"}},lt="flex h-10 items-center",dt="block max-h-10 max-w-48 w-auto object-contain";function dr(){return on("span",{role:"img","aria-label":"Bitsnap",className:"inline-flex items-center gap-1.5",children:[ee("svg",{"aria-hidden":"true",width:"29",height:"27",viewBox:"0 0 33 30",fill:"none",stroke:"currentColor",strokeWidth:"3.04",strokeLinecap:"round",children:ee("path",{d:"M20.2 1.8h0M22.8 6.2h0M22.8 10.6h0M22.8 15h0M22.8 19.4h0M22.8 23.8h0M20.2 28.2h0M27.1 10.6h0M27.1 15h0M27.1 19.4h0M31.5 15h0M1.5 1.8h0M5.4 1.8h0M9.3 1.8h0M13.2 1.8h0M5.4 15h0M9.3 15h0M13.2 15h0M5.4 28.2h0M9.3 28.2h0M13.2 28.2h0M1.5 6.2h0M1.5 10.6h0M1.5 15h0M1.5 19.4h0M1.5 23.8h0M1.5 28.2h0M16.7 19.4h0M16.7 23.8h0M16.7 6.2h0M16.7 10.6h0"})}),ee("span",{"aria-hidden":"true",className:"text-xl tracking-wider",children:"bitsnap."})]})}function cr(e,t){return ht(St,{projectId:e},{enabled:t,staleTime:1/0,retry:!1,refetchOnWindowFocus:!1})}function ct({projectId:e,name:t,locale:n,showLogo:s=!0,logoUrl:a,logoDarkUrl:u,className:o}){let[r,g]=ur([]),m=a||u,l=e?.trim()??"",{data:y,isPending:c}=cr(l,s&&!m&&l!=="");if(!s)return null;if(!m&&l!==""&&c)return ee("div",{className:i(lt,o),"aria-hidden":"true"});let f=(m?a||u:y?.logoUrl||y?.logoDarkUrl)||"",b=(m?u||a:y?.logoDarkUrl||y?.logoUrl)||"",x=h=>h!==""&&!r.includes(h),v=x(f)?f:x(b)?b:"",k=x(b)?b:x(f)?f:"";if(v===""&&k==="")return ee("div",{className:i(lt,o),children:ee(dr,{})});let S=t||y?.name||Ce(lr,n??Ie()).alt,w=h=>()=>g(C=>C.includes(h)?C:[...C,h]);return ee("div",{className:i(lt,o),children:v===k?ee("img",{src:v,alt:S,className:dt,draggable:!1,onError:w(v)}):on(pr,{children:[ee("img",{src:v,alt:S,className:i(dt,"dark:hidden"),draggable:!1,onError:w(v)}),ee("img",{src:k,alt:S,className:i(dt,"hidden dark:block"),draggable:!1,onError:w(k)})]})})}import{REGEXP_ONLY_DIGITS as Sr}from"input-otp";import{useCallback as hr}from"react";import*as an from"react";import{OTPInput as mr,OTPInputContext as fr}from"input-otp";import{MinusIcon as Ws}from"lucide-react";import{jsx as _e,jsxs as gr}from"react/jsx-runtime";function un({className:e,containerClassName:t,...n}){return _e(mr,{"data-slot":"input-otp",containerClassName:i("flex items-center gap-2 has-disabled:opacity-50",t),className:i("disabled:cursor-not-allowed",e),...n})}function ln({className:e,...t}){return _e("div",{"data-slot":"input-otp-group",className:i("flex items-center",e),...t})}function dn({index:e,className:t,...n}){let s=an.useContext(fr),{char:a,hasFakeCaret:u,isActive:o}=s?.slots[e]??{};return gr("div",{"data-slot":"input-otp-slot","data-active":o,className:i("data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",t),...n,children:[a,u&&_e("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:_e("div",{className:"animate-caret-blink bg-foreground h-4 w-px duration-1000"})})]})}import{useCallback as ae,useEffect as Ue,useRef as Re,useState as G}from"react";import{useEffect as yr,useState as br}from"react";function qe(e){let[,t]=br(0);return yr(()=>{if(e==null||Date.now()>=e)return;let n=setInterval(()=>{t(s=>s+1),Date.now()>=e&&clearInterval(n)},1e3);return()=>clearInterval(n)},[e]),e!=null?Math.max(0,Math.ceil((e-Date.now())/1e3)):0}var Rr={pl:{emailLabel:"E-mail",emailPlaceholder:"m@example.com",sendCode:"Wy\u015Blij kod",sending:"Wysy\u0142anie\u2026",invalidEmail:"Podaj poprawny adres e-mail.",codeSentTo:"Wys\u0142ali\u015Bmy kod na {email}.",changeEmail:"Zmie\u0144",codeLabel:"Kod z e-maila",verify:"Zaloguj si\u0119",verifying:"Sprawdzanie\u2026",codeIncomplete:"Wpisz wszystkie 6 cyfr kodu.",spamHint:"Nie widzisz e-maila? Sprawd\u017A folder spam.",validity:"Kod jest wa\u017Cny 10 minut.",resend:"Wy\u015Blij ponownie",resendIn:"Wy\u015Blij ponownie za {seconds}\xA0s",resendNew:"Wy\u015Blij nowy kod",resent:"Wys\u0142ali\u015Bmy nowy kod.",haveCodePrompt:"Masz ju\u017C kod?",haveCode:"Mam ju\u017C kod",noCode:"Nie masz kodu? Wy\u015Blij go",stepEmail:"Krok 1 z 2: podaj adres e-mail.",stepCode:"Krok 2 z 2: wpisz kod z e-maila.",wrongCode:"Nieprawid\u0142owy kod. Spr\xF3buj jeszcze raz.",expired:"Kod wygas\u0142. Wy\u015Blij nowy kod.",tooManyAttempts:"Zbyt wiele b\u0142\u0119dnych pr\xF3b. Wy\u015Blij nowy kod albo zmie\u0144 adres e-mail.",rateLimited:"Zbyt wiele pr\xF3b. Spr\xF3buj ponownie za {time}.",alreadySent:"Kod zosta\u0142 ju\u017C wys\u0142any. Nowy mo\u017Cesz poprosi\u0107 za {time}.",emailNotFound:"Nie znale\u017Ali\u015Bmy konta z tym adresem e-mail.",deliveryFailed:"Nie uda\u0142o si\u0119 wys\u0142a\u0107 kodu. Spr\xF3buj ponownie.",deliveryUnavailable:"Nie mo\u017Cemy teraz wys\u0142a\u0107 kodu na ten adres. Spr\xF3buj p\xF3\u017Aniej.",captchaRequired:"Potwierd\u017A, \u017Ce jeste\u015B cz\u0142owiekiem, aby wys\u0142a\u0107 kod.",captchaInvalid:"Nie uda\u0142o si\u0119 zweryfikowa\u0107. Spr\xF3buj ponownie.",network:"Brak po\u0142\u0105czenia z serwerem. Sprawd\u017A internet i spr\xF3buj ponownie.",generic:"Co\u015B posz\u0142o nie tak. Spr\xF3buj ponownie."},en:{emailLabel:"Email",emailPlaceholder:"m@example.com",sendCode:"Send code",sending:"Sending\u2026",invalidEmail:"Enter a valid email address.",codeSentTo:"We sent a code to {email}.",changeEmail:"Change",codeLabel:"Code from the email",verify:"Sign in",verifying:"Checking\u2026",codeIncomplete:"Enter all 6 digits of the code.",spamHint:"Can't see the email? Check your spam folder.",validity:"The code is valid for 10 minutes.",resend:"Resend",resendIn:"Resend in {seconds}s",resendNew:"Send a new code",resent:"We sent a new code.",haveCodePrompt:"Already have a code?",haveCode:"I have a code",noCode:"No code yet? Send one",stepEmail:"Step 1 of 2: enter your email address.",stepCode:"Step 2 of 2: enter the code from the email.",wrongCode:"Incorrect code. Please try again.",expired:"The code has expired. Send a new one.",tooManyAttempts:"Too many wrong attempts. Send a new code or change the email address.",rateLimited:"Too many attempts. Try again in {time}.",alreadySent:"A code was already sent. You can ask for a new one in {time}.",emailNotFound:"We could not find an account with this email address.",deliveryFailed:"We could not send the code. Please try again.",deliveryUnavailable:"We cannot send a code to this address right now. Try again later.",captchaRequired:"Complete the security check before requesting a code.",captchaInvalid:"Verification failed. Please try again.",network:"Cannot reach the server. Check your connection and try again.",generic:"Something went wrong. Please try again."}};function Js(e,...t){let n={...Ce(Rr,e)};for(let s of t)if(s!=null)for(let[a,u]of Object.entries(s))u!=null&&(n[a]=u);return n}function cn(e){let t=Math.max(1,Math.ceil(e));return t<=60?`${t}\xA0s`:`${Math.ceil(t/60)}\xA0min`}function pt(e,t){return e.replace(/\{(\w+)\}/g,(n,s)=>Object.prototype.hasOwnProperty.call(t,s)?String(t[s]):n)}var de=6,mn=60,xr=/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;function pn(e){return xr.test(e.trim())}function Ve(e,t,n){return{...vr(e,t,n),failure:t}}function vr(e,t,n){let s=cn(n??mn);switch(t){case"invalidEmail":return{kind:"error",text:e.invalidEmail};case"emailNotFound":return{kind:"error",text:e.emailNotFound};case"wrongCode":return{kind:"error",text:e.wrongCode};case"expired":return{kind:"error",text:e.expired};case"tooManyAttempts":return{kind:"error",text:e.tooManyAttempts};case"rateLimited":return{kind:"error",text:pt(e.rateLimited,{time:s})};case"alreadySent":return{kind:"info",text:pt(e.alreadySent,{time:s})};case"deliveryFailed":return{kind:"error",text:e.deliveryFailed};case"deliveryUnavailable":return{kind:"error",text:e.deliveryUnavailable};case"captchaRequired":return{kind:"error",text:e.captchaRequired};case"captchaInvalid":return{kind:"error",text:e.captchaInvalid};case"network":return{kind:"error",text:e.network};default:return{kind:"error",text:e.generic}}}function oo(e){let{storageKey:t}=e,n=Re(e);n.current=e;let[s,a]=G("email"),[u,o]=G(e.initialEmail??""),[r,g]=G(""),[m,l]=G(),[y,c]=G(),[f,b]=G(!1),[x,v]=G(),[k,S]=G(),[w,h]=G(),[C,U]=G(!1),[j,J]=G(""),[N,Y]=G(0),A=Re(!1),_=Re("email"),V=Re(null),F=Re(null),re=Re("email"),Se=qe(y),B=ae(T=>{_.current=T,Y(O=>O+1)},[]);Ue(()=>{N!==0&&(_.current==="email"?V:F).current?.focus()},[N]),Ue(()=>{if(a("email"),g(""),l(void 0),c(void 0),b(!1),v(void 0),S(void 0),t==null)return;let T=Pe(t);T!=null&&(o(T.email),l(T.challengeId),c(T.resendAt>Date.now()?T.resendAt:void 0),a("code"))},[t]),Ue(()=>{re.current!==s&&(re.current=s,J(s==="code"?n.current.texts.stepCode:n.current.texts.stepEmail))},[s]),Ue(()=>{s==="code"&&N===0&&B(f?"email":"code")},[s]);let R=ae((T,O,L,M)=>{T!=="wrongCode"&&T!=="invalidEmail"&&T!=="alreadySent"&&n.current.onFailure?.(T,L);let se=Ve(n.current.texts,T,O);return M!=null?{...se,text:M}:se},[]),X=ae((T,O,L,M)=>{let se=Date.now(),bt=se+(L??mn)*1e3;o(T),a("code"),b(!1),l(O),c(bt),g(""),v(void 0),S(M),t!=null&&Le(t,{email:T,challengeId:O,resendAt:bt,sentAt:se}),B("code")},[t,B]),Q=ae(async T=>{if(A.current)return;let O=u.trim();if(!pn(O)){S(Ve(n.current.texts,"invalidEmail")),B("email");return}if(A.current=!0,h(T),S(void 0),n.current.beforeSend&&!await n.current.beforeSend()){A.current=!1,h(void 0),S(Ve(n.current.texts,"captchaInvalid"));return}let L;try{L=await n.current.adapter.send(O,{resend:T==="resend"})}catch(se){L={ok:!1,kind:"network",cause:se}}if(A.current=!1,h(void 0),L.ok){X(O,L.challengeId,L.retryIn,T==="resend"?{kind:"success",text:n.current.texts.resent}:void 0);return}let M=R(L.kind,L.retryIn,L.cause,L.message);if(L.kind==="alreadySent"&&T==="send"){X(O,void 0,L.retryIn,M);return}L.retryIn!=null&&T==="resend"&&c(Date.now()+L.retryIn*1e3),S(M),T==="send"&&B("email")},[u,X,R,B]),he=ae(async T=>{let O=T??r;if(A.current||C||x!=null)return;let L=u.trim();if(f&&!pn(L)){S(Ve(n.current.texts,"invalidEmail")),B("email");return}if(O.length!==de){S({kind:"error",text:n.current.texts.codeIncomplete}),B("code");return}A.current=!0,h("verify"),S(void 0);let M;try{M=await n.current.adapter.verify({email:L,code:O,challengeId:m})}catch(se){M={ok:!1,kind:"network",cause:se}}if(A.current=!1,h(void 0),M.ok){t!=null&&fe(t),U(!0),n.current.onVerified?.(M.value,L);return}switch(S(R(M.kind,M.retryIn,M.cause,M.message)),M.kind){case"expired":case"tooManyAttempts":v(M.kind),g(""),t!=null&&fe(t);break;case"invalidEmail":case"emailNotFound":B(f?"email":"code");break;case"network":case"unknown":case"deliveryFailed":case"deliveryUnavailable":B("code");break;default:g(""),B("code")}},[r,m,x,C,u,R,f,B,t]),Ye=ae(T=>{o(T),S(O=>O?.kind==="error"?void 0:O)},[]),Sn=ae(T=>{g(T.replace(/\D/g,"").slice(0,de)),S(O=>O?.kind==="error"?void 0:O)},[]),hn=ae(()=>{a("email"),b(!1),g(""),l(void 0),c(void 0),v(void 0),S(void 0),t!=null&&fe(t),B("email")},[t,B]),kn=ae(()=>{a("code"),b(!0),g(""),l(void 0),c(void 0),v(void 0),S(void 0),B("email")},[B]);return{step:s,email:u,setEmail:Ye,code:r,setCode:Sn,needsEmail:f,busy:w,isBusy:w!=null||C,done:C,notice:k,dead:x,secondsLeft:Se,announcement:j,emailRef:V,codeRef:F,sendCode:()=>Q("send"),resend:()=>Q("resend"),submitCode:he,changeEmail:hn,haveCode:kn}}import{jsx as mt}from"react/jsx-runtime";function kr(e){return e.replace(/[\s-]/g,"")}function Nr(e){e!=null&&(e.style.boxSizing="border-box",e.style.padding="0")}function fn({id:e,name:t,value:n,onChange:s,onComplete:a,disabled:u,invalid:o,inputRef:r,autoFocus:g,slotClassName:m,slotStyle:l,className:y,...c}){let f=hr(x=>{Nr(x),typeof r=="function"?r(x):r!=null&&(r.current=x)},[r]),b={className:i("h-11 w-auto min-w-0 flex-1 rounded-md border first:rounded-md last:rounded-md text-base","dark:border-foreground/30 dark:data-[active=true]:border-foreground/70 dark:data-[active=true]:ring-foreground/25","dark:aria-invalid:border-destructive-foreground dark:data-[active=true]:aria-invalid:border-destructive-foreground dark:aria-invalid:ring-destructive-foreground/30 dark:data-[active=true]:aria-invalid:ring-destructive-foreground/30",m),style:l,"aria-invalid":o?!0:void 0};return mt(un,{ref:f,id:e,name:t,maxLength:de,value:n,onChange:s,onComplete:a,disabled:u,autoFocus:g,inputMode:"numeric",autoComplete:"one-time-code",pattern:Sr,pasteTransformer:kr,"aria-invalid":o?!0:void 0,"aria-label":c["aria-label"],"aria-describedby":c["aria-describedby"],containerClassName:i("w-full",y),children:mt(ln,{className:"w-full gap-1.5 sm:gap-2",children:Array.from({length:de},(x,v)=>mt(dn,{index:v,...b},v))})})}import{jsx as $,jsxs as Qe}from"react/jsx-runtime";var ce="bg-[var(--bitsnap-returns-button-background,#18181b)] text-[color:var(--bitsnap-returns-button-foreground,#fafafa)] hover:bg-[var(--bitsnap-returns-button-hover-background,#000000)] focus-visible:ring-[color:var(--bitsnap-returns-focus-ring,#71717a)]/50",W="border border-[color:var(--bitsnap-returns-border,#e4e4e7)] bg-transparent text-[color:var(--bitsnap-returns-foreground,#18181b)] hover:bg-[var(--bitsnap-returns-hover-surface,#f4f4f5)] focus-visible:ring-[color:var(--bitsnap-returns-focus-ring,#71717a)]/50",xe="bg-[var(--bitsnap-returns-input-background,#ffffff)] dark:bg-[var(--bitsnap-returns-input-background,#ffffff)] border-[color:var(--bitsnap-returns-border,#e4e4e7)] text-[color:var(--bitsnap-returns-foreground,#18181b)] placeholder:text-[color:var(--bitsnap-returns-muted-foreground,#71717a)] focus-visible:border-[color:var(--bitsnap-returns-focus-ring,#71717a)] focus-visible:ring-[color:var(--bitsnap-returns-focus-ring,#71717a)]/50",gn=i(xe,"data-[active=true]:border-[color:var(--bitsnap-returns-focus-ring,#71717a)] data-[active=true]:ring-[color:var(--bitsnap-returns-focus-ring,#71717a)]/50");function te({title:e,description:t,onBack:n,lead:s,className:a,children:u}){let o=z(),r=d("header"),g=d("title"),m=d("description"),l=d("backButton");return Qe("section",{className:i("flex flex-col gap-5",a),children:[s,Qe("div",{"data-bitsnap-returns-slot":"header",className:i("flex flex-col gap-2",r.className),style:r.style,children:[n!=null&&$(P,{type:"button",variant:"ghost",size:"sm","data-bitsnap-returns-slot":"backButton",className:i("self-start -ml-3 text-[color:var(--bitsnap-returns-muted-foreground,#71717a)] hover:bg-[var(--bitsnap-returns-hover-surface,#f4f4f5)]",l.className),style:l.style,onClick:n,children:o("back")}),$("h2",{"data-bitsnap-returns-slot":"title",className:i("text-2xl font-semibold",g.className),style:g.style,children:e}),t!=null&&$("p",{"data-bitsnap-returns-slot":"description",className:i("text-sm",m.className),style:m.style,children:t})]}),u]})}function H({errorKey:e,onRetry:t}){let n=z(),s=d("error"),a=d("secondaryButton");return Qe("div",{role:"alert","data-bitsnap-returns-slot":"error",className:i("flex flex-col items-start gap-2 text-sm",s.className),style:s.style,children:[$("p",{children:n(e)}),t!=null&&$(P,{type:"button",variant:"secondary",size:"sm","data-bitsnap-returns-slot":"secondaryButton",className:i(W,a.className),style:a.style,onClick:t,children:n("errorRetry")})]})}function We({children:e}){let t=d("emptyState");return $("p",{"data-bitsnap-returns-slot":"emptyState",className:i("py-6 text-center text-sm",t.className),style:t.style,children:e})}function le({rows:e=3}){let t=z(),n=d("skeleton");return $("div",{role:"status","aria-busy":"true","aria-label":t("loading"),className:"flex flex-col gap-3",children:Array.from({length:e},(s,a)=>$(Et,{"data-bitsnap-returns-slot":"skeleton",className:i("h-16 w-full bg-[var(--bitsnap-returns-hover-surface,#f4f4f5)]",n.className),style:n.style},a))})}function ve({status:e}){let t=z(),n=d("statusBadge");return $("span",{"data-bitsnap-returns-slot":"statusBadge","data-status":e,className:i("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium",n.className),style:n.style,children:t(Kt(e))})}function ft(){let e=z();return t=>e(jt(t))}function He({page:e,total:t,hasNext:n,hasPrevious:s,isFetching:a,onNext:u,onPrevious:o}){let r=z(),g=d("pagination"),m=d("secondaryButton");return!n&&!s?null:Qe("nav",{"data-bitsnap-returns-slot":"pagination",className:i("flex items-center justify-between gap-3 text-sm",g.className),style:g.style,children:[$(P,{type:"button",variant:"secondary",size:"sm","data-bitsnap-returns-slot":"secondaryButton",className:i(W,m.className),style:m.style,disabled:!s||a,onClick:o,children:r("paginationPrevious")}),$("span",{"aria-live":"polite",children:r("paginationInfo",{page:e,total:t})}),$(P,{type:"button",variant:"secondary",size:"sm","data-bitsnap-returns-slot":"secondaryButton",className:i(W,m.className),style:m.style,disabled:!n||a,onClick:u,children:r("paginationNext")})]})}import{jsx as K,jsxs as ne}from"react/jsx-runtime";function Fo({onSubmitted:e,className:t,...n}){let s=D("ReturnsEmailStep"),a=z(),u=Z(),o=Fe(),[r,g]=we(s.lastEmail??""),m=d("emailForm"),l=d("emailInput"),y=d("submitButton");async function c(f){f.preventDefault(),!o.isStarting&&await o.start(r)&&e?.(r.trim())}return K(te,{className:t,lead:K(ct,{projectId:s.projectID,locale:u,...n}),title:a("emailStepTitle"),description:a("emailStepDescription"),children:ne("form",{"data-bitsnap-returns-slot":"emailForm",className:i("flex flex-col gap-4",m.className),style:m.style,onSubmit:c,children:[ne("div",{className:"flex flex-col gap-2",children:[K(Te,{htmlFor:"bitsnap-returns-email",children:a("emailLabel")}),K(Tt,{id:"bitsnap-returns-email",type:"email",name:"email",autoComplete:"email",inputMode:"email",autoCapitalize:"none",spellCheck:!1,autoFocus:!0,required:!0,value:r,placeholder:a("emailPlaceholder"),disabled:o.isStarting,"data-bitsnap-returns-slot":"emailInput",className:i(xe,l.className),style:l.style,onChange:f=>g(f.target.value)})]}),o.errorKey!=null&&K(H,{errorKey:o.errorKey}),ne(P,{type:"submit",disabled:o.isStarting,"data-bitsnap-returns-slot":"submitButton",className:i(ce,y.className),style:y.style,children:[o.isStarting&&K(be,{}),a("emailSubmit")]})]})})}function Ko({onVerified:e,onBack:t,className:n,...s}){let a=D("ReturnsCodeStep"),u=z(),o=Z(),r=Fe(),[g,m]=we(""),[l,y]=we(!1),[c,f]=we(!1),[b,x]=we(1),v=yn(null),k=yn(!1),S=qe(r.challenge?.resendAvailableAt),w=d("codeForm"),h=d("codeInput"),C=d("submitButton"),U=d("resendButton"),j=r.isVerifying||r.isStarting,J="bitsnap-returns-code",N=`${J}-hint`;Tr(()=>{j||v.current?.focus()},[b,j]);async function Y(F){if(!(j||k.current)){if(F.length!==de){y(!0),x(re=>re+1);return}k.current=!0,y(!1),f(!1);try{await r.verify(F)?e?.():(m(""),x(re=>re+1))}finally{k.current=!1}}}async function A(F){F.preventDefault(),await Y(g)}async function _(){y(!1),f(!1),await r.resend()&&(m(""),f(!0)),x(F=>F+1)}function V(){a.setChallenge(void 0),t?.()}return K(te,{className:n,onBack:t!=null?V:void 0,lead:K(ct,{projectId:a.projectID,locale:o,...s}),title:u("codeStepTitle"),description:u("codeStepDescription",{email:r.challenge?.email??""}),children:ne("form",{"data-bitsnap-returns-slot":"codeForm",className:i("flex flex-col gap-4",w.className),style:w.style,noValidate:!0,onSubmit:A,children:[ne("div",{className:"flex flex-col gap-2",children:[K(Te,{htmlFor:J,children:u("codeLabel")}),K(fn,{id:J,name:"code",inputRef:v,value:g,disabled:j,invalid:r.errorKey!=null||l,"aria-describedby":N,slotClassName:i(gn,h.className),slotStyle:h.style,onChange:F=>{m(F.replace(/\D/g,"")),y(!1)},onComplete:F=>void Y(F)}),ne("p",{id:N,className:"text-xs",children:[u("codeValidity")," ",u("codeSpamHint")]})]}),ne("div",{className:"min-h-10",children:[l&&K("p",{role:"alert",className:"text-sm",children:u("codeIncomplete")}),!l&&r.errorKey!=null&&K(H,{errorKey:r.errorKey}),!l&&r.errorKey==null&&c&&K("p",{role:"status",className:"text-sm",children:u("resendSent")})]}),ne("div",{className:"flex flex-wrap items-center gap-3",children:[ne(P,{type:"submit",disabled:j||r.challenge==null,"data-bitsnap-returns-slot":"submitButton",className:i("h-11",ce,C.className),style:C.style,children:[r.isVerifying&&K(be,{"aria-hidden":!0}),u("codeSubmit")]}),ne(P,{type:"button",variant:"secondary",disabled:j||S>0||r.challenge==null,"data-bitsnap-returns-slot":"resendButton",className:i("h-11",W,U.className),style:U.style,onClick:()=>void _(),children:[r.isStarting&&K(be,{"aria-hidden":!0}),S>0?u("resendIn",{seconds:S}):u("resend")]})]})]})})}function bn(){let e=z(),t=Fe(),n=d("logoutButton");return K(P,{type:"button",variant:"ghost",size:"sm","data-bitsnap-returns-slot":"logoutButton",className:i("text-[color:var(--bitsnap-returns-muted-foreground,#71717a)] hover:bg-[var(--bitsnap-returns-hover-surface,#f4f4f5)]",n.className),style:n.style,onClick:t.logout,children:e("logout")})}import{useEffect as Er,useState as yt}from"react";import{timestampDate as wr}from"@bufbuild/protobuf/wkt";function pe(e,t){if(e==null)return"";let n=wr(e);try{return new Intl.DateTimeFormat(t,{dateStyle:"medium"}).format(n)}catch{return n.toISOString().slice(0,10)}}function Rn(e,t){return Number.isFinite(e)?Math.min(Math.max(0,Math.trunc(e)),Math.max(0,t)):0}function gt(e){return e.eligible&&e.availableQuantity>0}function xn(e,t){return e.map(n=>({lineId:n,quantity:t[n]??0})).filter(n=>n.quantity>0)}import{Fragment as vn,jsx as p,jsxs as E}from"react/jsx-runtime";function ia({onSelectOrder:e,onOpenMyReturns:t,showLogout:n=!0,pageSize:s,className:a}){D("ReturnsOrderList");let u=z(),o=Z(),r=tn({pageSize:s}),g=d("orderList"),m=d("orderCard"),l=d("orderReference"),y=d("orderDate"),c=d("orderTotal"),f=d("secondaryButton");return E(te,{className:a,title:u("ordersTitle"),description:u("ordersDescription"),children:[(n||t!=null)&&E("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[t!=null?p(P,{type:"button",variant:"secondary",size:"sm","data-bitsnap-returns-slot":"secondaryButton",className:i(W,f.className),style:f.style,onClick:t,children:u("myReturnsLink")}):p("span",{}),n&&p(bn,{})]}),r.isLoading?p(le,{}):r.errorKey!=null?p(H,{errorKey:r.errorKey,onRetry:r.refetch}):r.orders.length===0?p(We,{children:u("ordersEmpty")}):E(vn,{children:[p("ul",{"data-bitsnap-returns-slot":"orderList",className:i("flex flex-col gap-3",g.className),style:g.style,children:r.orders.map(b=>E("li",{"data-bitsnap-returns-slot":"orderCard",className:i("flex flex-wrap items-center justify-between gap-3 border p-4",m.className),style:m.style,children:[E("div",{className:"flex flex-col gap-1",children:[p("span",{"data-bitsnap-returns-slot":"orderReference",className:i("font-medium",l.className),style:l.style,children:u("orderTitle",{reference:b.displayReference})}),p("span",{"data-bitsnap-returns-slot":"orderDate",className:i("text-sm",y.className),style:y.style,children:pe(b.purchasedAt,o)}),p("span",{className:"text-sm",children:u("orderReturnableLines",{count:b.returnableLineCount})})]}),E("div",{className:"flex items-center gap-4",children:[p("span",{"data-bitsnap-returns-slot":"orderTotal",className:i("font-medium",c.className),style:c.style,children:me(b.totalMinor,b.currency,o)}),p(P,{type:"button",variant:"secondary",size:"sm","aria-label":`${u("orderSelect")}: ${u("orderTitle",{reference:b.displayReference})}`,"data-bitsnap-returns-slot":"secondaryButton",className:i(W,f.className),style:f.style,onClick:()=>e?.(b.canonicalOrderId),children:u("orderSelect")})]})]},b.canonicalOrderId))}),p(He,{page:r.page,total:r.total,hasNext:r.hasNext,hasPrevious:r.hasPrevious,isFetching:r.isFetching,onNext:r.next,onPrevious:r.previous})]})]})}function ua({orderId:e,onContinue:t,onBack:n,initialItems:s,initialNote:a,className:u}){D("ReturnsOrderDetail");let o=Ee();Er(()=>{o.track("return_started",{},{order_ref:null})},[o]);let r=z(),g=Z(),{order:m,returnHistory:l,isLoading:y,errorKey:c,refetch:f}=ut(e),[b,x]=yt(()=>Object.fromEntries((s??[]).map(R=>[R.lineId,R.quantity]))),[v,k]=yt(a??""),[S,w]=yt(!1),h=d("lineList"),C=d("line"),U=d("lineName"),j=d("linePrice"),J=d("lineQuantityControl"),N=d("quantityButton"),Y=d("quantityInput"),A=d("lineIneligibleReason"),_=d("noteInput"),V=d("submitButton"),F=d("history"),re=d("historyEntry");function Se(R,X){w(!1),x(Q=>({...Q,[R.lineId]:Rn(X,R.availableQuantity)}))}function B(R){if(R.preventDefault(),m==null)return;let X=xn(m.lines.filter(gt).map(Q=>Q.lineId),b);if(X.length===0){w(!0);return}t?.({items:X,note:v.trim()})}return p(te,{className:u,onBack:n,title:r("orderDetailTitle",{reference:m?.displayReference??""}),description:r("orderDetailDescription"),children:y?p(le,{}):c!=null?p(H,{errorKey:c,onRetry:f}):m==null?null:E("form",{className:"flex flex-col gap-5",onSubmit:B,children:[p("ul",{"data-bitsnap-returns-slot":"lineList",className:i("flex flex-col gap-3",h.className),style:h.style,children:m.lines.map(R=>{let X=gt(R),Q=b[R.lineId]??0,he=`bitsnap-returns-quantity-${R.lineId}`;return E("li",{"data-bitsnap-returns-slot":"line","data-selected":Q>0?"":void 0,"data-ineligible":X?void 0:"",className:i("flex flex-col gap-3 border p-4",C.className),style:C.style,children:[E("div",{className:"flex flex-wrap items-baseline justify-between gap-2",children:[p("span",{"data-bitsnap-returns-slot":"lineName",className:i("font-medium",U.className),style:U.style,children:R.name}),p("span",{"data-bitsnap-returns-slot":"linePrice",className:i("text-sm",j.className),style:j.style,children:me(R.paidUnitMinor,R.currency,g)})]}),X?E("div",{role:"group","aria-label":r("quantityLabel",{name:R.name}),"data-bitsnap-returns-slot":"lineQuantityControl",className:i("flex items-center gap-2",J.className),style:J.style,children:[p(P,{type:"button",variant:"secondary",size:"icon-sm","aria-label":r("quantityDecrease",{name:R.name}),"aria-controls":he,disabled:Q<=0,"data-bitsnap-returns-slot":"quantityButton",className:i(W,N.className),style:N.style,onClick:()=>Se(R,Q-1),children:p("span",{"aria-hidden":"true",children:"-"})}),p("input",{id:he,type:"number",inputMode:"numeric",min:0,max:R.availableQuantity,step:1,value:Q,"aria-label":r("quantityLabel",{name:R.name}),"data-bitsnap-returns-slot":"quantityInput",className:i("h-8 w-16 rounded-md border px-2 text-center text-sm outline-none focus-visible:ring-[3px]",xe,Y.className),style:Y.style,onChange:Ye=>Se(R,Ye.target.valueAsNumber)}),p(P,{type:"button",variant:"secondary",size:"icon-sm","aria-label":r("quantityIncrease",{name:R.name}),"aria-controls":he,disabled:Q>=R.availableQuantity,"data-bitsnap-returns-slot":"quantityButton",className:i(W,N.className),style:N.style,onClick:()=>Se(R,Q+1),children:p("span",{"aria-hidden":"true",children:"+"})}),p("span",{className:"text-sm",children:r("quantityOfAvailable",{available:R.availableQuantity})})]}):p("p",{"data-bitsnap-returns-slot":"lineIneligibleReason",className:i("text-sm",A.className),style:A.style,children:R.exclusionReason!==""?R.exclusionReason:r("lineIneligibleFallback")})]},R.lineId)})}),E("div",{className:"flex flex-col gap-2",children:[p(Te,{htmlFor:"bitsnap-returns-note",children:r("noteLabel")}),p(Ct,{id:"bitsnap-returns-note",name:"note",rows:3,maxLength:1e3,value:v,placeholder:r("notePlaceholder"),"data-bitsnap-returns-slot":"noteInput",className:i(xe,"dark:border-[color:var(--bitsnap-returns-border,#e4e4e7)] dark:placeholder:text-[color:var(--bitsnap-returns-muted-foreground,#71717a)] dark:focus-visible:ring-[color:var(--bitsnap-returns-focus-ring,#71717a)]",_.className),style:_.style,onChange:R=>k(R.target.value)})]}),S&&p(H,{errorKey:"selectionEmpty"}),p(P,{type:"submit","data-bitsnap-returns-slot":"submitButton",className:i(ce,V.className),style:V.style,children:r("selectionContinue")}),l.length>0&&E("div",{className:"flex flex-col gap-2",children:[p("h3",{className:"text-sm font-medium",children:r("previousReturnsTitle")}),p("ul",{"data-bitsnap-returns-slot":"history",className:i("flex flex-col gap-2",F.className),style:F.style,children:l.map(R=>E("li",{"data-bitsnap-returns-slot":"historyEntry",className:i("flex flex-wrap items-center justify-between gap-2 text-sm",re.className),style:re.style,children:[p("span",{children:R.reference}),p("span",{children:pe(R.createdAt,g)}),p(ve,{status:R.status})]},R.id))})]})]})})}function la({orderId:e,items:t,note:n,onSubmitted:s,onBack:a,className:u}){D("ReturnsConfirmation");let o=z(),r=Z(),{order:g,isLoading:m,errorKey:l,refetch:y}=ut(e),c=nn(),f=d("summary"),b=d("line"),x=d("lineName"),v=d("linePrice"),k=d("submitButton");async function S(w){if(w.preventDefault(),c.isPending)return;let h=await c.submit({orderId:e,items:t.map(C=>({lineId:C.lineId,quantity:C.quantity})),note:n});h!=null&&s?.(h.id,h)}return p(te,{className:u,onBack:a,title:o("confirmationTitle"),description:o("confirmationDescription"),children:m?p(le,{rows:2}):l!=null?p(H,{errorKey:l,onRetry:y}):E("form",{className:"flex flex-col gap-5",onSubmit:S,children:[E("div",{"data-bitsnap-returns-slot":"summary",className:i("flex flex-col gap-3 border p-4",f.className),style:f.style,children:[p("h3",{className:"text-sm font-medium",children:o("confirmationSummary")}),p("ul",{className:"flex flex-col gap-3",children:t.map(w=>{let h=g?.lines.find(C=>C.lineId===w.lineId);return E("li",{"data-bitsnap-returns-slot":"line",className:i("flex flex-wrap items-baseline justify-between gap-2",b.className),style:b.style,children:[p("span",{"data-bitsnap-returns-slot":"lineName",className:i("font-medium",x.className),style:x.style,children:h?.name??w.lineId}),E("span",{"data-bitsnap-returns-slot":"linePrice",className:i("text-sm",v.className),style:v.style,children:[o("confirmationQuantity",{quantity:w.quantity}),h!=null&&` \xB7 ${me(h.paidUnitMinor*BigInt(w.quantity),h.currency,r)}`]})]},w.lineId)})}),n!=null&&n!==""&&E("div",{className:"flex flex-col gap-1 text-sm",children:[p("span",{className:"font-medium",children:o("confirmationNote")}),p("span",{className:"whitespace-pre-wrap",children:n})]})]}),c.errorKey!=null&&p(H,{errorKey:c.errorKey}),E(P,{type:"submit",disabled:c.isPending||t.length===0,"data-bitsnap-returns-slot":"submitButton",className:i(ce,k.className),style:k.style,children:[c.isPending&&p(be,{}),o("confirmationSubmit")]})]})})}function da({returnId:e,onContinue:t,onOpenMyReturns:n,className:s}){D("ReturnsResult");let a=z(),{request:u,isLoading:o,errorKey:r,refetch:g}=je(e),m=d("successState"),l=d("returnReference"),y=d("returnInstructions"),c=d("submitButton"),f=d("secondaryButton");return E("section",{className:i("flex flex-col gap-5",s),children:[E("div",{role:"status","data-bitsnap-returns-slot":"successState",className:i("flex flex-col gap-4 border p-5",m.className),style:m.style,children:[p("h2",{className:"text-2xl font-semibold",children:a("successTitle")}),p("p",{className:"text-sm",children:a("successDescription")}),o?p(le,{rows:2}):r!=null?p(H,{errorKey:r,onRetry:g}):u!=null&&E(vn,{children:[E("div",{className:"flex flex-col gap-1",children:[p("span",{className:"text-sm",children:a("successReference")}),p("span",{"data-bitsnap-returns-slot":"returnReference",className:i("text-lg font-semibold",l.className),style:l.style,children:u.reference})]}),u.returnInstructions!==""&&E("div",{className:"flex flex-col gap-1",children:[p("span",{className:"text-sm font-medium",children:a("successInstructions")}),p("p",{"data-bitsnap-returns-slot":"returnInstructions",className:i("whitespace-pre-wrap border p-3 text-sm",y.className),style:y.style,children:u.returnInstructions})]})]})]}),E("div",{className:"flex flex-wrap gap-3",children:[p(P,{type:"button","data-bitsnap-returns-slot":"submitButton",className:i(ce,c.className),style:c.style,onClick:t,children:a("successDone")}),n!=null&&p(P,{type:"button",variant:"secondary","data-bitsnap-returns-slot":"secondaryButton",className:i(W,f.className),style:f.style,onClick:n,children:a("myReturnsLink")})]})]})}import{Fragment as Cr,jsx as I,jsxs as q}from"react/jsx-runtime";function ha({onSelectReturn:e,onBack:t,pageSize:n,className:s}){D("ReturnsMyReturnsList");let a=z(),u=Z(),o=ft(),r=rn({pageSize:n}),g=d("returnList"),m=d("returnCard"),l=d("returnReference"),y=d("secondaryButton");return I(te,{className:s,onBack:t,title:a("myReturnsTitle"),description:a("myReturnsDescription"),children:r.isLoading?I(le,{}):r.errorKey!=null?I(H,{errorKey:r.errorKey,onRetry:r.refetch}):r.returns.length===0?I(We,{children:a("myReturnsEmpty")}):q(Cr,{children:[I("ul",{"data-bitsnap-returns-slot":"returnList",className:i("flex flex-col gap-3",g.className),style:g.style,children:r.returns.map(c=>q("li",{"data-bitsnap-returns-slot":"returnCard",className:i("flex flex-wrap items-center justify-between gap-3 border p-4",m.className),style:m.style,children:[q("div",{className:"flex flex-col gap-1",children:[I("span",{"data-bitsnap-returns-slot":"returnReference",className:i("font-medium",l.className),style:l.style,children:c.reference}),I("span",{className:"text-sm",children:pe(c.createdAt,u)}),q("span",{className:"text-sm",children:[a("myReturnRefund"),": ",o(c.refundStatus)]})]}),q("div",{className:"flex items-center gap-3",children:[I(ve,{status:c.status}),I(P,{type:"button",variant:"secondary",size:"sm","aria-label":`${a("myReturnOpen")}: ${c.reference}`,"data-bitsnap-returns-slot":"secondaryButton",className:i(W,y.className),style:y.style,onClick:()=>e?.(c.id),children:a("myReturnOpen")})]})]},c.id))}),I(He,{page:r.page,total:r.total,hasNext:r.hasNext,hasPrevious:r.hasPrevious,isFetching:r.isFetching,onNext:r.next,onPrevious:r.previous})]})})}function ka({returnId:e,onBack:t,className:n}){D("ReturnsMyReturnDetail");let s=z(),a=Z(),u=ft(),{request:o,isLoading:r,errorKey:g,refetch:m}=je(e),l=d("summary"),y=d("lineList"),c=d("line"),f=d("lineName"),b=d("returnInstructions"),x=d("history"),v=d("historyEntry");return I(te,{className:n,onBack:t,title:o!=null?s("myReturnTitle",{reference:o.reference}):s("myReturnDetailTitle"),children:r?I(le,{}):g!=null?I(H,{errorKey:g,onRetry:m}):o!=null&&q("div",{className:"flex flex-col gap-5",children:[q("div",{"data-bitsnap-returns-slot":"summary",className:i("flex flex-col gap-2 border p-4 text-sm",l.className),style:l.style,children:[q("div",{className:"flex items-center justify-between gap-2",children:[I(ve,{status:o.status}),q("span",{children:[s("myReturnCreatedAt"),":"," ",pe(o.createdAt,a)]})]}),q("span",{children:[s("myReturnRefund"),": ",u(o.refundStatus),o.refundAmountMinor>BigInt(0)&&` \xB7 ${me(o.refundAmountMinor,o.currency,a)}`]}),o.customerNote!==""&&q("span",{className:"whitespace-pre-wrap",children:[s("myReturnNote"),": ",o.customerNote]})]}),o.returnInstructions!==""&&I("p",{"data-bitsnap-returns-slot":"returnInstructions",className:i("whitespace-pre-wrap border p-3 text-sm",b.className),style:b.style,children:o.returnInstructions}),q("div",{className:"flex flex-col gap-2",children:[I("h3",{className:"text-sm font-medium",children:s("myReturnLines")}),I("ul",{"data-bitsnap-returns-slot":"lineList",className:i("flex flex-col gap-3",y.className),style:y.style,children:o.lines.map(k=>q("li",{"data-bitsnap-returns-slot":"line",className:i("flex flex-wrap items-baseline justify-between gap-2 border p-4",c.className),style:c.style,children:[I("span",{"data-bitsnap-returns-slot":"lineName",className:i("font-medium",f.className),style:f.style,children:k.name}),I("span",{className:"text-sm",children:s("myReturnLineQuantities",{requested:k.requestedQuantity,approved:k.approvedQuantity,received:k.receivedQuantity})})]},k.lineId))})]}),o.history.length>0&&q("div",{className:"flex flex-col gap-2",children:[I("h3",{className:"text-sm font-medium",children:s("myReturnHistory")}),I("ul",{"data-bitsnap-returns-slot":"history",className:i("flex flex-col gap-2",x.className),style:x.style,children:o.history.map(k=>q("li",{"data-bitsnap-returns-slot":"historyEntry",className:i("flex flex-wrap items-center justify-between gap-2 text-sm",v.className),style:v.style,children:[I(ve,{status:k.status}),I("span",{children:pe(k.createdAt,a)})]},k.id))})]})]})})}export{Zt as a,cr as b,ct as c,Te as d,be as e,Ut as f,Rr as g,Js as h,pt as i,oo as j,fn as k,Lr as l,Ot as m,$e as n,d as o,ot as p,Xt as q,Je as r,Kt as s,z as t,Z as u,D as v,$n as w,us as x,Fe as y,tn as z,ut as A,nn as B,rn as C,je as D,le as E,Fo as F,Ko as G,ia as H,ua as I,la as J,da as K,ha as L,ka as M};
2
+ //# sourceMappingURL=chunk-W4EUYPJ3.mjs.map