bitsnap-react 1.8.0 → 1.9.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 (124) hide show
  1. package/README.md +130 -0
  2. package/dist/CartProvider-XWTLBIZ5.js +2 -0
  3. package/dist/CartProvider-XWTLBIZ5.js.map +1 -0
  4. package/dist/CartProvider-ZURLJNBW.mjs +2 -0
  5. package/dist/analytics.d.mts +28 -0
  6. package/dist/analytics.d.ts +28 -0
  7. package/dist/analytics.js +2 -0
  8. package/dist/analytics.js.map +1 -0
  9. package/dist/analytics.mjs +2 -0
  10. package/dist/catalog.d.mts +14 -1
  11. package/dist/catalog.d.ts +14 -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/chunk-3IMJALBX.js +2 -0
  16. package/dist/chunk-3IMJALBX.js.map +1 -0
  17. package/dist/chunk-3UHPJ6NK.js +2 -0
  18. package/dist/chunk-3UHPJ6NK.js.map +1 -0
  19. package/dist/chunk-CO2P4FR5.js +2 -0
  20. package/dist/chunk-CO2P4FR5.js.map +1 -0
  21. package/dist/chunk-E6QVQEGZ.mjs +2 -0
  22. package/dist/chunk-E6QVQEGZ.mjs.map +1 -0
  23. package/dist/{chunk-WRCXZMKK.js → chunk-FHDFLSPW.js} +2 -2
  24. package/dist/chunk-FHDFLSPW.js.map +1 -0
  25. package/dist/chunk-GN63ITLA.mjs +2 -0
  26. package/dist/{chunk-OJT3YO2R.mjs.map → chunk-GN63ITLA.mjs.map} +1 -1
  27. package/dist/chunk-HKVMSMDF.mjs +2 -0
  28. package/dist/chunk-HKVMSMDF.mjs.map +1 -0
  29. package/dist/chunk-JSDGZ4NY.js.map +1 -1
  30. package/dist/chunk-KG6RU37U.js +4 -0
  31. package/dist/chunk-KG6RU37U.js.map +1 -0
  32. package/dist/chunk-KOYBZORL.js.map +1 -1
  33. package/dist/chunk-LJWS6ZRJ.mjs +2 -0
  34. package/dist/chunk-LJWS6ZRJ.mjs.map +1 -0
  35. package/dist/chunk-LZE2E4TE.mjs +4 -0
  36. package/dist/chunk-LZE2E4TE.mjs.map +1 -0
  37. package/dist/chunk-QZJGNLCZ.js +2 -0
  38. package/dist/chunk-QZJGNLCZ.js.map +1 -0
  39. package/dist/chunk-RA452LXZ.mjs +2 -0
  40. package/dist/chunk-RA452LXZ.mjs.map +1 -0
  41. package/dist/chunk-SLLBTQTW.mjs +2 -0
  42. package/dist/chunk-SLLBTQTW.mjs.map +1 -0
  43. package/dist/chunk-SZ256RCC.mjs +2 -0
  44. package/dist/chunk-SZ256RCC.mjs.map +1 -0
  45. package/dist/chunk-V4U2PTKN.js +2 -0
  46. package/dist/chunk-V4U2PTKN.js.map +1 -0
  47. package/dist/chunk-VM6JEJFZ.js +2 -0
  48. package/dist/chunk-VM6JEJFZ.js.map +1 -0
  49. package/dist/{chunk-T2POA6RW.js → chunk-VXB7LA4E.js} +2 -2
  50. package/dist/chunk-VXB7LA4E.js.map +1 -0
  51. package/dist/chunk-XVQKEGPO.mjs +2 -0
  52. package/dist/chunk-XVQKEGPO.mjs.map +1 -0
  53. package/dist/consent.d.mts +158 -0
  54. package/dist/consent.d.ts +158 -0
  55. package/dist/consent.js +75 -0
  56. package/dist/consent.js.map +1 -0
  57. package/dist/consent.mjs +75 -0
  58. package/dist/consent.mjs.map +1 -0
  59. package/dist/course.d.mts +13 -3
  60. package/dist/course.d.ts +13 -3
  61. package/dist/course.js +1 -1
  62. package/dist/course.js.map +1 -1
  63. package/dist/course.mjs +1 -1
  64. package/dist/course.mjs.map +1 -1
  65. package/dist/embed/analytics.js +1 -0
  66. package/dist/embed/consent.js +74 -0
  67. package/dist/errors.js.map +1 -1
  68. package/dist/index.css +1 -1
  69. package/dist/index.css.map +1 -1
  70. package/dist/index.d.mts +54 -7
  71. package/dist/index.d.ts +54 -7
  72. package/dist/index.js +1 -1
  73. package/dist/index.js.map +1 -1
  74. package/dist/index.mjs +1 -1
  75. package/dist/index.mjs.map +1 -1
  76. package/dist/instrument-C_abZLHk.d.mts +912 -0
  77. package/dist/instrument-C_abZLHk.d.ts +912 -0
  78. package/dist/internal.js.map +1 -1
  79. package/dist/methods-CYARZTYL.mjs +2 -0
  80. package/dist/methods-CYARZTYL.mjs.map +1 -0
  81. package/dist/methods-DAPEWVI6.js +2 -0
  82. package/dist/methods-DAPEWVI6.js.map +1 -0
  83. package/dist/models.js.map +1 -1
  84. package/dist/returns.d.mts +9 -1
  85. package/dist/returns.d.ts +9 -1
  86. package/dist/returns.js +1 -1
  87. package/dist/returns.js.map +1 -1
  88. package/dist/returns.mjs +1 -1
  89. package/dist/{types-BTm_ZolC.d.ts → types-BaqLJYuq.d.ts} +13 -0
  90. package/dist/{types-PSBBDdQm.d.mts → types-D_WnqwR_.d.mts} +13 -0
  91. package/package.json +46 -45
  92. package/dist/CartProvider-5KAG5QGA.mjs +0 -2
  93. package/dist/CartProvider-7GJXW2IP.js +0 -2
  94. package/dist/CartProvider-7GJXW2IP.js.map +0 -1
  95. package/dist/chunk-45AP7UZE.mjs +0 -2
  96. package/dist/chunk-45AP7UZE.mjs.map +0 -1
  97. package/dist/chunk-7XTDFTQU.js +0 -4
  98. package/dist/chunk-7XTDFTQU.js.map +0 -1
  99. package/dist/chunk-C6Z7LOHB.mjs +0 -2
  100. package/dist/chunk-C6Z7LOHB.mjs.map +0 -1
  101. package/dist/chunk-HB6KQT26.mjs +0 -4
  102. package/dist/chunk-HB6KQT26.mjs.map +0 -1
  103. package/dist/chunk-LWK4E5G5.js +0 -2
  104. package/dist/chunk-LWK4E5G5.js.map +0 -1
  105. package/dist/chunk-OJT3YO2R.mjs +0 -2
  106. package/dist/chunk-OUYRKNZJ.mjs +0 -2
  107. package/dist/chunk-OUYRKNZJ.mjs.map +0 -1
  108. package/dist/chunk-P2YB25KZ.js +0 -2
  109. package/dist/chunk-P2YB25KZ.js.map +0 -1
  110. package/dist/chunk-T2POA6RW.js.map +0 -1
  111. package/dist/chunk-VPKE2ZOR.mjs +0 -2
  112. package/dist/chunk-VPKE2ZOR.mjs.map +0 -1
  113. package/dist/chunk-WRCXZMKK.js.map +0 -1
  114. package/dist/chunk-WSM4OM72.mjs +0 -2
  115. package/dist/chunk-WSM4OM72.mjs.map +0 -1
  116. package/dist/chunk-XRNTUSBH.js +0 -2
  117. package/dist/chunk-XRNTUSBH.js.map +0 -1
  118. package/dist/chunk-Z2BKIX6F.js +0 -2
  119. package/dist/chunk-Z2BKIX6F.js.map +0 -1
  120. package/dist/methods-ITD6WFIY.mjs +0 -2
  121. package/dist/methods-JENIGNF7.js +0 -2
  122. package/dist/methods-JENIGNF7.js.map +0 -1
  123. /package/dist/{CartProvider-5KAG5QGA.mjs.map → CartProvider-ZURLJNBW.mjs.map} +0 -0
  124. /package/dist/{methods-ITD6WFIY.mjs.map → analytics.mjs.map} +0 -0
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk3UHPJ6NKjs = require('./chunk-3UHPJ6NK.js');var oe="1.9.0";var be="https://collect.bitsnap.pl",Te=5e3,_e=20,ie=32*1024,xe=60*1024,ae=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function ce(e){return typeof TextEncoder=="function"?new TextEncoder().encode(e).length:unescape(encodeURIComponent(e)).length}var y={track(){},page(){},flush(){},setEnabled(){},onEvent:()=>()=>{},configure(){},destroy(){}};function ue(e){let t=new Uint8Array(e),a=typeof crypto<"u"?crypto:void 0;if(a&&typeof a.getRandomValues=="function")a.getRandomValues(t);else for(let r=0;r<e;r++)t[r]=Math.floor(Math.random()*256);return t}function Pe(e=Date.now()){let t=ue(16),a=e;for(let i=5;i>=0;i--)t[i]=a%256,a=Math.floor(a/256);t[6]=t[6]&15|112,t[8]=t[8]&63|128;let r=Array.from(t,i=>i.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}var se="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Ae(){return Array.from(ue(16),e=>se[e%se.length]).join("")}function Ce(e,t,a=!1){let r=ce(JSON.stringify({k:e,events:[]})),i=[],c=[],o=r,s=()=>{c.length>0&&i.push({body:JSON.stringify({k:e,events:c}),bytes:o,count:c.length}),c=[],o=r};for(let l of t){let u=ce(JSON.stringify(l));r+u>ie||((c.length>=_chunk3UHPJ6NKjs.a.maxBatchEvents||o+u+(c.length>0?1:0)>ie)&&s(),o+=u+(c.length>0?1:0),c.push(l))}if(s(),a){let l=0,u=i.length;for(;u>0&&l+i[u-1].bytes<=xe;)l+=i[u-1].bytes,u--;i=i.slice(u)}return i}function Ie(e){try{return typeof window>"u"||typeof document>"u"?y:we(e,window)}catch (e2){return y}}function we(e,t){let a=_chunk3UHPJ6NKjs.b.call(void 0, _nullishCoalesce(e.projectKey, () => (""))),r=!!e.debug,i=(...n)=>{r&&console.warn("[bitsnap analytics]",...n)};if(!a)return i("invalid projectKey, tracking is off"),y;let c=a,o=n=>`${(n||be).replace(/\/+$/,"")}/e`,s=o(e.endpoint),l=_nullishCoalesce(e.source, () => ("sdk_react")),u=_nullishCoalesce(e.channel, () => ("embed")),_=`bitsnap-react@${oe}`,S=Ae(),h=_chunk3UHPJ6NKjs.d.call(void 0, t.location.href),L=_nullishCoalesce(e.env, () => ("live"));if(!e.env)try{new URLSearchParams(t.location.search).has("test")&&(L="test")}catch (e3){}let me=_chunk3UHPJ6NKjs.e.call(void 0, document.referrer),B=e.enabled!==!1,$=null,ge=0,p=[],g=null,T=new Set;e.onEvent&&T.add(e.onEvent);let E=[],v,k=!0;function H(){let n=t.BitsnapConsent;!n||n===v||(v=n,k=!n.ready,_optionalChain([n, 'access', _2 => _2.ready, 'optionalAccess', _3 => _3.then, 'call', _4 => _4(()=>{v===n&&(k=!0,Y())},()=>{v===n&&(k=!0)})]))}function z(){H();try{if(!v)return!1;let n=v.get();return!!v.denied&&v.denied("analytics")||!!n&&n.c.analytics===!1}catch (e4){return!1}}function F(n){T.forEach(f=>{try{f(n)}catch (e5){}})}function Y(){if(z())p=[],E=[],x();else{if(k&&E.length>0){let n=E;E=[],n.forEach(F)}p.length>0&&b()}}function G(){if(!B)return!1;let n=t.navigator;return n&&(n.globalPrivacyControl===!0||n.webdriver===!0)?!1:!z()}function x(){g!==null&&clearTimeout(g),g=null}function Ee(){g===null&&(g=setTimeout(()=>{g=null,b()},Te),_optionalChain([g, 'access', _5 => _5.unref, 'optionalCall', _6 => _6()]))}function he(n){try{if(typeof fetch=="function"){fetch(s,{method:"POST",body:n,keepalive:!0,credentials:"omit",headers:{"Content-Type":"text/plain"}}).catch(()=>{});return}}catch (e6){}try{let f=t.navigator;f&&typeof f.sendBeacon=="function"&&f.sendBeacon(s,new Blob([n],{type:"text/plain"}))}catch (e7){}}function b(n=!1){try{if(x(),p.length===0)return;if(!G()){p=[];return}if(!k)return;let f=p;p=[],Ce(c,f,n).forEach(d=>he(d.body))}catch (e8){}}function J(n,f,d){if(!G())return;let N=_chunk3UHPJ6NKjs.f.call(void 0, n,f);if(!N.ok){i("dropped",n,N.reason);return}let X=_chunk3UHPJ6NKjs.d.call(void 0, t.location.href),R={event_id:_optionalChain([d, 'optionalAccess', _7 => _7.event_id])&&ae.test(d.event_id)?d.event_id:Pe(),event:n,ts:Date.now(),schema_version:1,env:L,source:l,channel:u,sdk:_,page_id:S,page_type:_optionalChain([d, 'optionalAccess', _8 => _8.page_type])!==void 0?d.page_type:$,host:_nullishCoalesce(_optionalChain([X, 'optionalAccess', _9 => _9.host]), () => (null)),path:_optionalChain([d, 'optionalAccess', _10 => _10.path])?_chunk3UHPJ6NKjs.c.call(void 0, d.path.split(/[?#]/)[0]):_nullishCoalesce(_optionalChain([X, 'optionalAccess', _11 => _11.path]), () => (null)),referrer_host:me,utm_source:_nullishCoalesce(_optionalChain([h, 'optionalAccess', _12 => _12.utm_source]), () => (null)),utm_medium:_nullishCoalesce(_optionalChain([h, 'optionalAccess', _13 => _13.utm_medium]), () => (null)),utm_campaign:_nullishCoalesce(_optionalChain([h, 'optionalAccess', _14 => _14.utm_campaign]), () => (null)),utm_content:_nullishCoalesce(_optionalChain([h, 'optionalAccess', _15 => _15.utm_content]), () => (null)),utm_term:_nullishCoalesce(_optionalChain([h, 'optionalAccess', _16 => _16.utm_term]), () => (null)),ref_code:_nullishCoalesce(_optionalChain([h, 'optionalAccess', _17 => _17.ref_code]), () => (null)),product_id:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _18 => _18.product_id]), () => (null)),variant_id:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _19 => _19.variant_id]), () => (null)),order_ref:_nullishCoalesce(_optionalChain([d, 'optionalAccess', _20 => _20.order_ref]), () => (null)),props:N.props};_optionalChain([d, 'optionalAccess', _21 => _21.event_id])&&!ae.test(d.event_id)&&i("ignored invalid event_id",n),l==="dashboard"&&e.visitorId&&(R.visitor_id=e.visitorId);let Q=_chunk3UHPJ6NKjs.g.call(void 0, R);if(!Q.ok){i("dropped",n,Q.reason);return}let O=R;k?F(O):E.push(O),p.push(O),p.length>=_e?b():Ee()}let q=()=>b(!0),W=()=>{document.visibilityState==="hidden"&&b(!0)},P=()=>Y();return t.addEventListener("pagehide",q),document.addEventListener("visibilitychange",W),t.addEventListener("bitsnap:consent",P),t.addEventListener("bitsnap:consent:ready",P),H(),{track(n,f,d){try{J(n,f,d)}catch (e9){}},page(n,f){try{n!==void 0&&($=n),J("page_view",{landing:ge++===0},f)}catch (e10){}},flush:()=>b(),setEnabled(n){B=!!n,B||(p=[],E=[],x())},configure(n){try{(n.env==="live"||n.env==="test")&&(L=n.env),typeof n.endpoint=="string"&&n.endpoint&&(s=o(n.endpoint))}catch (e11){}},onEvent(n){return T.add(n),()=>void T.delete(n)},destroy(){p=[],E=[],x(),T.clear(),t.removeEventListener("pagehide",q),document.removeEventListener("visibilitychange",W),t.removeEventListener("bitsnap:consent",P),t.removeEventListener("bitsnap:consent:ready",P)}}}var m,C=null;function I(e){if(!m){let t=Ie(e);return t===y||(m=t,C=_chunk3UHPJ6NKjs.b.call(void 0, _nullishCoalesce(e.projectKey, () => ("")))),t}try{let t=_chunk3UHPJ6NKjs.b.call(void 0, _nullishCoalesce(e.projectKey, () => ("")));t!==C&&e.debug&&console.warn("[bitsnap analytics]","tracker already started for another projectKey, ignoring",e.projectKey),t===C&&((e.env||e.endpoint)&&m.configure({env:e.env,endpoint:e.endpoint}),e.enabled!=null&&m.setEnabled(e.enabled))}catch (e12){}return m}function le(){return m}function Ye(){_optionalChain([m, 'optionalAccess', _22 => _22.destroy, 'call', _23 => _23()]),m=void 0,C=null}var _react = require('react');var Re={track:y.track,page:y.page},fe=_react.createContext.call(void 0, Re);function Xe({projectKey:e,env:t,enabled:a,endpoint:r,onEvent:i,children:c}){let o=_react.useMemo.call(void 0, ()=>I({projectKey:e,env:t,endpoint:r,enabled:a}),[e,t,r]),s=_react.useRef.call(void 0, i);s.current=i,_chunk3UHPJ6NKjs.h.call(void 0, ()=>{o.setEnabled(a!==!1)},[o,a]),_chunk3UHPJ6NKjs.h.call(void 0, ()=>o.onEvent(u=>_optionalChain([s, 'access', _24 => _24.current, 'optionalCall', _25 => _25(u)])),[o]);let l=_react.useMemo.call(void 0, ()=>({track:o.track.bind(o),page:o.page.bind(o)}),[o]);return _react.createElement.call(void 0, fe.Provider,{value:l},c)}function pe(){return _react.useContext.call(void 0, fe)}var w={track(){}},K=null;function Ve(e){let t=Symbol("bitsnap-instrument");function a(){if(typeof window>"u")return null;let{projectKey:c,analytics:o,provided:s}=e();return o===!1?null:s||(c?I({projectKey:c,source:"sdk_react",channel:"embed",env:typeof o=="object"?o.env:void 0}):null)}let r={track(c,o,s){try{let l=a();if(!l)return;let{analytics:u,pageType:_}=e(),S=_&&_optionalChain([s, 'optionalAccess', _26 => _26.page_type])===void 0?{...s,page_type:_}:s;K=typeof u=="object"&&u.onEvent?t:null,l.track(c,o,S)}catch (e13){}finally{K=null}}};function i(){try{if(!a())return()=>{};let c=le();return c?c.onEvent(o=>{if(K===t)try{let{analytics:s}=e();typeof s=="object"&&_optionalChain([s, 'access', _27 => _27.onEvent, 'optionalCall', _28 => _28(o)])}catch (e14){}}):()=>{}}catch (e15){return()=>{}}}return{instrument:r,attach:i}}var U=_react.createContext.call(void 0, null);function nt({value:e,children:t}){return _react.createElement.call(void 0, U.Provider,{value:e},t)}function rt(){return _nullishCoalesce(_react.useContext.call(void 0, U), () => (w))}function ot(e,t,a){let r=_react.useContext.call(void 0, U),i=pe(),c=i.track===y.track?null:i,o=_react.useRef.call(void 0, {projectKey:e,analytics:t,pageType:a,provided:c});o.current={projectKey:e,analytics:t,pageType:a,provided:c};let s=_react.useMemo.call(void 0, ()=>Ve(()=>o.current),[]),l=t===void 0&&r!==null,u=typeof t=="object"&&!!t.onEvent;return _react.useLayoutEffect.call(void 0, ()=>{if(!l)return s.attach()},[s,l,u,e]),l?r:s.instrument}var V=w;function ye(e){V=_nullishCoalesce(e, () => (w))}var D=0;function it(){return D>0?w:V}async function at(e){D++;try{return await e()}finally{D--}}function ct(e){_react.useEffect.call(void 0, ()=>(ye(e),()=>{V===e&&ye(null)}),[e])}function st(e){let t=Number.isFinite(e)?Math.max(0,Math.min(100,e)):0;return t>=100?"100":t>=75?"75-99":t>=50?"50-74":t>=25?"25-49":"0-24"}function ut(e,t){let a=[];for(let r of[25,50,75,100])e>=r&&!t.has(r)&&(t.add(r),a.push(r));return a}exports.a = oe; exports.b = be; exports.c = Ie; exports.d = I; exports.e = le; exports.f = Ye; exports.g = Xe; exports.h = pe; exports.i = w; exports.j = nt; exports.k = rt; exports.l = ot; exports.m = it; exports.n = at; exports.o = ct; exports.p = st; exports.q = ut;
2
+ //# sourceMappingURL=chunk-QZJGNLCZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/chunk-QZJGNLCZ.js","../src/version.ts","../src/analytics/core.ts"],"names":["SDK_VERSION","DEFAULT_ENDPOINT","FLUSH_INTERVAL_MS","FLUSH_AT","MAX_BODY_BYTES","KEEPALIVE_BUDGET_BYTES","EVENT_ID_RE","byteLength","text","noopTracker","randomBytes","n","bytes","c","i","uuidv7","now","b","t","hex","x"],"mappings":"AAAA,uuBAA4F,ICC/EA,EAAAA,CAAc,OAAA,CCmFpB,IAAMC,EAAAA,CAAmB,4BAAA,CAE1BC,EAAAA,CAAoB,GAAA,CACpBC,EAAAA,CAAW,EAAA,CAEXC,EAAAA,CAAiB,EAAA,CAAK,IAAA,CAEtBC,EAAAA,CAAyB,EAAA,CAAK,IAAA,CAC9BC,EAAAA,CAAc,wEAAA,CAEpB,SAASC,EAAAA,CAAWC,CAAAA,CAAsB,CACxC,OAAI,OAAO,WAAA,EAAgB,UAAA,CAAmB,IAAI,WAAA,CAAY,CAAA,CAAE,MAAA,CAAOA,CAAI,CAAA,CAAE,MAAA,CACtE,QAAA,CAAS,kBAAA,CAAmBA,CAAI,CAAC,CAAA,CAAE,MAC5C,CAEO,IAAMC,CAAAA,CAAuB,CAClC,KAAA,CAAA,CAAQ,CAAC,CAAA,CACT,IAAA,CAAA,CAAO,CAAC,CAAA,CACR,KAAA,CAAA,CAAQ,CAAC,CAAA,CACT,UAAA,CAAA,CAAa,CAAC,CAAA,CACd,OAAA,CAAS,CAAA,CAAA,EAAM,CAAA,CAAA,EAAM,C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AA,EAAMA,CAAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,QAAA,CAAS,CAAA,CAAG,GAAG,CAAC,CAAA,CAAE,IAAA,CAAK,EAAE,CAAA,CACzE,MAAO,CAAA,EAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/chunk-QZJGNLCZ.js","sourcesContent":[null,"// Generated by scripts/write-version.mjs from package.json. Do not edit.\nexport const SDK_VERSION = \"1.9.0\";\n","import {\n LIMITS,\n PAGE_TYPES,\n SCHEMA_VERSION,\n normalizeProjectKey,\n parseUrl,\n referrerHost,\n sanitizeProps,\n sanitizePath,\n validateEnvelope,\n type AppEventName,\n type Channel,\n type ClientEvent,\n type Env,\n type EventProps,\n type PageType,\n type Source,\n type StorefrontEventName,\n} from \"./contract\";\nimport { SDK_VERSION } from \"../version\";\n\n/** Events a browser may send. `consent_updated` is written by the consent log only. */\nexport type BrowserEventName = Exclude<StorefrontEventName, \"consent_updated\"> | AppEventName;\n\nexport type TrackerOptions = {\n /** Public project key (the hashed project id). `pk_` prefix is accepted. */\n projectKey: string;\n /** Defaults to `live`, or `test` when the page URL has the `?test=` test-mode parameter. */\n env?: Env;\n /** Collector origin. Default `https://collect.bitsnap.pl`. */\n endpoint?: string;\n /** `false` turns tracking off. Default `true`. */\n enabled?: boolean;\n /** Default `embed`. */\n channel?: Channel;\n /** Default `sdk_react`. */\n source?: Source;\n /** Only honoured by the collector for `source: \"dashboard\"` (hashed user id). */\n visitorId?: string;\n /** Receives every valid envelope before it is queued, e.g. to forward it to the merchant's own tools. */\n onEvent?: (event: ClientEvent) => void;\n /** `console.warn` dropped events. */\n debug?: boolean;\n};\n\n/** Envelope fields a call site may set per event. */\nexport type TrackExtra = {\n page_type?: PageType | null;\n product_id?: string | null;\n variant_id?: string | null;\n order_ref?: string | null;\n /** Route template for pages whose URL path is not the path to report (the dashboard). */\n path?: string;\n /**\n * Deterministic UUIDv7 for events another system reports too (e.g. hosted\n * `payment_returned`), so the collector dedupes them. An invalid value is\n * ignored and a fresh id is used.\n */\n event_id?: string;\n};\n\nexport interface Tracker {\n track<E extends BrowserEventName>(event: E, props: EventProps<E>, extra?: TrackExtra): void;\n /** Sends `page_view` and makes `pageType` the page type of the following events. */\n page(pageType?: PageType | null, extra?: TrackExtra): void;\n /** Sends the queue now. */\n flush(): void;\n setEnabled(enabled: boolean): void;\n /** Returns an unsubscribe function. */\n onEvent(fn: (event: ClientEvent) => void): () => void;\n /** Updates `env` and `endpoint` of a running tracker. Other options are fixed at creation. */\n configure(patch: { env?: Env; endpoint?: string }): void;\n /** Removes the page listeners and drops the queue. */\n destroy(): void;\n}\n\n/** The part of `window.BitsnapConsent` (`bitsnap-react/consent`) the tracker reads. */\ntype ConsentLike = {\n get(): { c: { analytics?: boolean } } | null;\n /** Also true for a refusal made on an older banner version, which `get()` no longer returns. */\n denied?(category: \"analytics\"): boolean;\n ready?: Promise<unknown>;\n};\n\nexport const DEFAULT_ENDPOINT = \"https://collect.bitsnap.pl\";\n\nconst FLUSH_INTERVAL_MS = 5000;\nconst FLUSH_AT = 20;\n// Half the collector's 64 KB body limit, measured in UTF-8 bytes of the whole body.\nconst MAX_BODY_BYTES = 32 * 1024;\n// Browsers share ~64 KB of in-flight keepalive requests; stay under it on pagehide.\nconst KEEPALIVE_BUDGET_BYTES = 60 * 1024;\nconst EVENT_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nfunction byteLength(text: string): number {\n if (typeof TextEncoder === \"function\") return new TextEncoder().encode(text).length;\n return unescape(encodeURIComponent(text)).length;\n}\n\nexport const noopTracker: Tracker = {\n track() {},\n page() {},\n flush() {},\n setEnabled() {},\n onEvent: () => () => {},\n configure() {},\n destroy() {},\n};\n\nfunction randomBytes(n: number): Uint8Array {\n const bytes = new Uint8Array(n);\n const c = typeof crypto !== \"undefined\" ? crypto : undefined;\n if (c && typeof c.getRandomValues === \"function\") c.getRandomValues(bytes);\n else for (let i = 0; i < n; i++) bytes[i] = Math.floor(Math.random() * 256);\n return bytes;\n}\n\n/** UUIDv7: 48-bit unix ms, version 7, variant 10, 74 random bits. */\nexport function uuidv7(now = Date.now()): string {\n const b = randomBytes(16);\n let t = now;\n for (let i = 5; i >= 0; i--) {\n b[i] = t % 256;\n t = Math.floor(t / 256);\n }\n b[6] = (b[6] & 0x0f) | 0x70;\n b[8] = (b[8] & 0x3f) | 0x80;\n const hex = Array.from(b, (x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nconst PAGE_ID_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\nfunction newPageId(): string {\n return Array.from(randomBytes(16), (x) => PAGE_ID_ALPHABET[x % PAGE_ID_ALPHABET.length]).join(\"\");\n}\n\nexport function isPageType(value: unknown): value is PageType {\n return typeof value === \"string\" && (PAGE_TYPES as readonly string[]).includes(value);\n}\n\nexport type PackedBody = { body: string; bytes: number; count: number };\n\n/**\n * Splits events into `POST /e` bodies of at most `MAX_BODY_BYTES` UTF-8 bytes\n * (wrapper included) and `maxBatchEvents` events. With `leaving` (pagehide)\n * only the newest bodies that fit the shared keepalive quota are kept.\n */\nexport function packEvents(projectKey: string, events: ClientEvent[], leaving = false): PackedBody[] {\n const wrapper = byteLength(JSON.stringify({ k: projectKey, events: [] }));\n let bodies: PackedBody[] = [];\n let batch: ClientEvent[] = [];\n let size = wrapper;\n const close = () => {\n if (batch.length > 0) bodies.push({ body: JSON.stringify({ k: projectKey, events: batch }), bytes: size, count: batch.length });\n batch = [];\n size = wrapper;\n };\n for (const event of events) {\n const own = byteLength(JSON.stringify(event));\n if (wrapper + own > MAX_BODY_BYTES) continue; // a single event that can never fit\n // +1 for the comma that joins it to the previous event.\n if (batch.length >= LIMITS.maxBatchEvents || size + own + (batch.length > 0 ? 1 : 0) > MAX_BODY_BYTES) close();\n size += own + (batch.length > 0 ? 1 : 0);\n batch.push(event);\n }\n close();\n if (leaving) {\n let total = 0;\n let keep = bodies.length;\n while (keep > 0 && total + bodies[keep - 1].bytes <= KEEPALIVE_BUDGET_BYTES) {\n total += bodies[keep - 1].bytes;\n keep--;\n }\n bodies = bodies.slice(keep);\n }\n return bodies;\n}\n\n/**\n * Cookieless, in-memory event tracker. It never throws into the host page and\n * never touches cookies or Web Storage. On the server it returns a no-op.\n */\nexport function createTracker(options: TrackerOptions): Tracker {\n try {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return noopTracker;\n return build(options, window);\n } catch {\n return noopTracker;\n }\n}\n\nfunction build(options: TrackerOptions, win: Window & typeof globalThis): Tracker {\n const projectKey = normalizeProjectKey(options.projectKey ?? \"\");\n const debug = !!options.debug;\n const warn = (...args: unknown[]) => {\n if (debug) console.warn(\"[bitsnap analytics]\", ...args);\n };\n if (!projectKey) {\n warn(\"invalid projectKey, tracking is off\");\n return noopTracker;\n }\n const key: string = projectKey;\n\n const endpointUrl = (endpoint: string | undefined) => `${(endpoint || DEFAULT_ENDPOINT).replace(/\\/+$/, \"\")}/e`;\n let url = endpointUrl(options.endpoint);\n const source = options.source ?? \"sdk_react\";\n const channel = options.channel ?? \"embed\";\n const sdk = `bitsnap-react@${SDK_VERSION}`;\n const pageId = newPageId();\n const landing = parseUrl(win.location.href);\n let env: Env = options.env ?? \"live\";\n if (!options.env) {\n try {\n if (new URLSearchParams(win.location.search).has(\"test\")) env = \"test\";\n } catch {}\n }\n const refHost = referrerHost(document.referrer);\n\n let enabled = options.enabled !== false;\n let pageType: PageType | null = null;\n let pageViews = 0;\n let queue: ClientEvent[] = [];\n let timer: ReturnType<typeof setTimeout> | null = null;\n const listeners = new Set<(event: ClientEvent) => void>();\n if (options.onEvent) listeners.add(options.onEvent);\n /** Events the listeners have not seen yet because consent was still loading. */\n let held: ClientEvent[] = [];\n\n // -- consent: respect a rejection, wait for the stored choice to load -----\n\n let attached: ConsentLike | undefined;\n let consentReady = true;\n\n function attachConsent() {\n const api = (win as unknown as { BitsnapConsent?: ConsentLike }).BitsnapConsent;\n if (!api || api === attached) return;\n attached = api;\n consentReady = !api.ready;\n api.ready?.then(\n () => {\n if (attached !== api) return;\n consentReady = true;\n afterConsentChange();\n },\n () => {\n if (attached === api) consentReady = true;\n },\n );\n }\n\n function consentDenied(): boolean {\n attachConsent();\n try {\n if (!attached) return false;\n const state = attached.get();\n return (!!attached.denied && attached.denied(\"analytics\")) || (!!state && state.c.analytics === false);\n } catch {\n return false;\n }\n }\n\n function notify(event: ClientEvent) {\n listeners.forEach((fn) => {\n try {\n fn(event);\n } catch {}\n });\n }\n\n function afterConsentChange() {\n if (consentDenied()) {\n queue = [];\n held = [];\n clearTimer();\n } else {\n if (consentReady && held.length > 0) {\n const release = held;\n held = [];\n release.forEach(notify);\n }\n if (queue.length > 0) flush();\n }\n }\n\n // -- state ----------------------------------------------------------------\n\n function active(): boolean {\n if (!enabled) return false;\n const nav = win.navigator;\n if (nav && ((nav as { globalPrivacyControl?: boolean }).globalPrivacyControl === true || nav.webdriver === true)) {\n return false;\n }\n return !consentDenied();\n }\n\n function clearTimer() {\n if (timer !== null) clearTimeout(timer);\n timer = null;\n }\n\n function schedule() {\n if (timer !== null) return;\n timer = setTimeout(() => {\n timer = null;\n flush();\n }, FLUSH_INTERVAL_MS);\n (timer as { unref?: () => void }).unref?.();\n }\n\n // -- sending --------------------------------------------------------------\n\n function send(body: string) {\n // fetch keepalive first (no size cap below the shared quota); sendBeacon only as a fallback.\n try {\n if (typeof fetch === \"function\") {\n fetch(url, {\n method: \"POST\",\n body,\n keepalive: true,\n credentials: \"omit\",\n headers: { \"Content-Type\": \"text/plain\" },\n }).catch(() => {});\n return;\n }\n } catch {}\n try {\n const nav = win.navigator;\n if (nav && typeof nav.sendBeacon === \"function\") {\n nav.sendBeacon(url, new Blob([body], { type: \"text/plain\" }));\n }\n } catch {}\n }\n\n function flush(leaving = false) {\n try {\n clearTimer();\n if (queue.length === 0) return;\n if (!active()) {\n queue = [];\n return;\n }\n // Hold events until Bitsnap Consent has loaded the stored choice.\n if (!consentReady) return;\n const pending = queue;\n queue = [];\n packEvents(key, pending, leaving).forEach((entry) => send(entry.body));\n } catch {}\n }\n\n // -- building -------------------------------------------------------------\n\n function emit(name: string, props: unknown, extra: TrackExtra | undefined) {\n if (!active()) return;\n const cleaned = sanitizeProps(name, props);\n if (!cleaned.ok) {\n warn(\"dropped\", name, cleaned.reason);\n return;\n }\n const here = parseUrl(win.location.href);\n const event: Record<string, unknown> = {\n event_id: extra?.event_id && EVENT_ID_RE.test(extra.event_id) ? extra.event_id : uuidv7(),\n event: name,\n ts: Date.now(),\n schema_version: SCHEMA_VERSION,\n env,\n source,\n channel,\n sdk,\n page_id: pageId,\n page_type: extra?.page_type !== undefined ? extra.page_type : pageType,\n host: here?.host ?? null,\n path: extra?.path ? sanitizePath(extra.path.split(/[?#]/)[0]) : (here?.path ?? null),\n referrer_host: refHost,\n utm_source: landing?.utm_source ?? null,\n utm_medium: landing?.utm_medium ?? null,\n utm_campaign: landing?.utm_campaign ?? null,\n utm_content: landing?.utm_content ?? null,\n utm_term: landing?.utm_term ?? null,\n ref_code: landing?.ref_code ?? null,\n product_id: extra?.product_id ?? null,\n variant_id: extra?.variant_id ?? null,\n order_ref: extra?.order_ref ?? null,\n props: cleaned.props,\n };\n if (extra?.event_id && !EVENT_ID_RE.test(extra.event_id)) warn(\"ignored invalid event_id\", name);\n if (source === \"dashboard\" && options.visitorId) event.visitor_id = options.visitorId;\n\n const verdict = validateEnvelope(event);\n if (!verdict.ok) {\n warn(\"dropped\", name, verdict.reason);\n return;\n }\n const valid = event as unknown as ClientEvent;\n // Listeners (the merchant's own tools) only see events once consent is known and not denied.\n if (consentReady) notify(valid);\n else held.push(valid);\n queue.push(valid);\n if (queue.length >= FLUSH_AT) flush();\n else schedule();\n }\n\n // -- page lifecycle -------------------------------------------------------\n\n const onHide = () => flush(true);\n const onVisibility = () => {\n if (document.visibilityState === \"hidden\") flush(true);\n };\n const onConsent = () => afterConsentChange();\n win.addEventListener(\"pagehide\", onHide);\n document.addEventListener(\"visibilitychange\", onVisibility);\n win.addEventListener(\"bitsnap:consent\", onConsent);\n win.addEventListener(\"bitsnap:consent:ready\", onConsent);\n attachConsent();\n\n return {\n track(event, props, extra) {\n try {\n emit(event, props, extra);\n } catch {}\n },\n page(type, extra) {\n try {\n if (type !== undefined) pageType = type;\n emit(\"page_view\", { landing: pageViews++ === 0 }, extra);\n } catch {}\n },\n flush: () => flush(),\n setEnabled(value) {\n enabled = !!value;\n if (!enabled) {\n queue = [];\n held = [];\n clearTimer();\n }\n },\n configure(patch) {\n try {\n if (patch.env === \"live\" || patch.env === \"test\") env = patch.env;\n if (typeof patch.endpoint === \"string\" && patch.endpoint) url = endpointUrl(patch.endpoint);\n } catch {}\n },\n onEvent(fn) {\n listeners.add(fn);\n return () => void listeners.delete(fn);\n },\n destroy() {\n queue = [];\n held = [];\n clearTimer();\n listeners.clear();\n win.removeEventListener(\"pagehide\", onHide);\n document.removeEventListener(\"visibilitychange\", onVisibility);\n win.removeEventListener(\"bitsnap:consent\", onConsent);\n win.removeEventListener(\"bitsnap:consent:ready\", onConsent);\n },\n };\n}\n\n// -- singleton ----------------------------------------------------------------\n\nlet instance: Tracker | undefined;\nlet instanceKey: string | null = null;\n\n/**\n * Creates the page's tracker on the first call and returns that same tracker\n * afterwards. A later call with another `projectKey` is ignored (warns in\n * debug mode); a later call with `env`, `endpoint` or `enabled` updates the\n * running tracker. A malformed key is not remembered, so a later valid call still works.\n */\nexport function initTracker(options: TrackerOptions): Tracker {\n if (!instance) {\n const created = createTracker(options);\n if (created === noopTracker) return created;\n instance = created;\n instanceKey = normalizeProjectKey(options.projectKey ?? \"\");\n return created;\n }\n try {\n const key = normalizeProjectKey(options.projectKey ?? \"\");\n if (key !== instanceKey && options.debug) {\n console.warn(\"[bitsnap analytics]\", \"tracker already started for another projectKey, ignoring\", options.projectKey);\n }\n if (key === instanceKey) {\n if (options.env || options.endpoint) instance.configure({ env: options.env, endpoint: options.endpoint });\n if (options.enabled != null) instance.setEnabled(options.enabled);\n }\n } catch {}\n return instance;\n}\n\n/** The tracker made by `initTracker`, if any. */\nexport function getTracker(): Tracker | undefined {\n return instance;\n}\n\n/** Destroys the singleton so that `initTracker` can build a fresh one (tests, hot reload). */\nexport function resetTracker() {\n instance?.destroy();\n instance = undefined;\n instanceKey = null;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import{a as c}from"./chunk-XVQKEGPO.mjs";var p="X-Bitsnap-Client",a=`bitsnap-react@${c}`,T="bs_client",L={[p]:a},E=e=>t=>(t.header.set(p,a),e(t));function h(e){let t=e.indexOf("#"),o=t===-1?e:e.slice(0,t),s=t===-1?"":e.slice(t),n=o.includes("?")?/[?&]$/.test(o)?"":"&":"?";return`${o}${n}${T}=${encodeURIComponent(a)}${s}`}var y="https://bitsnap.pl",g=y;function v(e){console.log("setCustomHost",e),g=e}function d(e,t){return t.toLowerCase().startsWith("en")?e.en:e.pl}function f(e,t){let o={...e};if(t!=null)for(let[s,n]of Object.entries(t))n!=null&&(o[s]=n);return o}function u(e,t,o){return f(d(e,t),o)}function x(e,t){return e[t]??t}var C={en:{cart:"Cart",emptyCart:"Your cart is empty.",total:"Total:",delivery:"+ delivery",chooseCountry:"Choose a country",nextStep:"Next step",unavailableProducts:"Not all products are available."},pl:{cart:"Koszyk",emptyCart:"Brak produkt\xF3w w koszyku.",total:"Suma:",delivery:"+ dostawa",chooseCountry:"Wybierz kraj",nextStep:"Nast\u0119pny krok",unavailableProducts:"Nie wszystkie produkty s\u0105 dost\u0119pne w magazynie."}};function m(e,t){return u(C,e,t)}function A(e,t,o){return x(m(t,o),e)}var i="pl-PL",l="bitsnap-locale",r;function w(e){let t=e?.trim();r=t?t.toLowerCase()==="en"?"en-US":t.toLowerCase()==="pl"?i:t:void 0,typeof localStorage<"u"&&(r==null?localStorage.removeItem(l):localStorage.setItem(l,r))}function H(){return r??(typeof localStorage<"u"?localStorage.getItem(l)??i:i)}import{clsx as b}from"clsx";import{twMerge as K}from"tailwind-merge";function $(...e){return K(b(e))}export{L as a,E as b,h as c,$ as d,y as e,g as f,v as g,d as h,u as i,A as j,i as k,w as l,H as m};
2
+ //# sourceMappingURL=chunk-RA452LXZ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/client-header.ts","../src/components/checkout/constants.ts","../src/lib/texts.ts","../src/components/checkout/texts.ts","../src/components/checkout/locale.ts","../src/lib/utils.ts"],"sourcesContent":["import type { Interceptor } from \"@connectrpc/connect\";\nimport { SDK_VERSION } from \"../version\";\n\nexport const CLIENT_HEADER_NAME = \"X-Bitsnap-Client\";\nexport const CLIENT_HEADER_VALUE = `bitsnap-react@${SDK_VERSION}`;\n\nexport const CLIENT_QUERY_PARAM = \"bs_client\";\n\n/**\n * Spread into the `headers` of a fetch that already triggers a CORS preflight\n * (JSON POST, Connect RPC). Never use it on a simple cross-origin GET: the\n * custom header would force a preflight that older servers and merchant\n * proxies do not allow. Use `withClientParam` there.\n */\nexport const clientHeaders: Record<string, string> = {\n [CLIENT_HEADER_NAME]: CLIENT_HEADER_VALUE,\n};\n\n/** Connect interceptor adding the client header to every RPC. */\nexport const clientHeaderInterceptor: Interceptor = (next) => (req) => {\n req.header.set(CLIENT_HEADER_NAME, CLIENT_HEADER_VALUE);\n return next(req);\n};\n\n/** Adds `bs_client=<pkg>@<ver>` to a URL, for simple GETs that must stay preflight-free. */\nexport function withClientParam(url: string): string {\n const hash = url.indexOf(\"#\");\n const base = hash === -1 ? url : url.slice(0, hash);\n const fragment = hash === -1 ? \"\" : url.slice(hash);\n const separator = base.includes(\"?\") ? (/[?&]$/.test(base) ? \"\" : \"&\") : \"?\";\n return `${base}${separator}${CLIENT_QUERY_PARAM}=${encodeURIComponent(CLIENT_HEADER_VALUE)}${fragment}`;\n}\n","export const DEFAULT_HOST = \"https://bitsnap.pl\";\nexport let HOST = DEFAULT_HOST;\n\nexport function setCustomHost(host: string) {\n console.log(\"setCustomHost\", host);\n HOST = host;\n}\n","/**\n * Shared text machinery: typed string tables per locale, the locale fallback\n * and a merge with caller overrides. Each module (checkout, later returns)\n * supplies its own key type and default tables.\n */\n\n/** Strings of one locale, keyed by text key. */\nexport type TextTable<Key extends string> = Record<Key, string>;\n\n/** Default tables for the supported locales. */\nexport type LocaleTables<Key extends string> = {\n en: TextTable<Key>;\n pl: TextTable<Key>;\n};\n\n/**\n * Picks the table for a locale. Any locale starting with `en` (case\n * insensitive, so `en`, `en-US`, `EN-gb`) gets English; everything else,\n * including unknown locales, gets the Polish default.\n */\nexport function pickLocaleTable<Key extends string>(\n tables: LocaleTables<Key>,\n locale: string,\n): TextTable<Key> {\n return locale.toLowerCase().startsWith(\"en\") ? tables.en : tables.pl;\n}\n\n/**\n * Merges caller overrides over a table. Overrides apply regardless of the\n * locale; `undefined`/`null` entries are ignored so the default stays.\n */\nexport function mergeTexts<Key extends string>(\n table: TextTable<Key>,\n overrides?: Partial<TextTable<Key>>,\n): TextTable<Key> {\n const result: Record<string, string> = { ...table };\n\n if (overrides != null) {\n for (const [key, value] of Object.entries<string | undefined>(overrides)) {\n if (value != null) {\n result[key] = value;\n }\n }\n }\n\n return result as TextTable<Key>;\n}\n\n/** Locale table merged with the caller overrides. */\nexport function resolveTexts<Key extends string>(\n tables: LocaleTables<Key>,\n locale: string,\n overrides?: Partial<TextTable<Key>>,\n): TextTable<Key> {\n return mergeTexts(pickLocaleTable(tables, locale), overrides);\n}\n\n/** Looks up a single text. Unknown keys return the key itself. */\nexport function lookupText<Key extends string>(\n texts: TextTable<Key>,\n key: Key,\n): string {\n return (texts as Record<string, string | undefined>)[key] ?? key;\n}\n","import {\n lookupText,\n resolveTexts,\n type LocaleTables,\n} from \"@/src/lib/texts\";\n\n/**\n * Every string the checkout renders. Pass a partial object through the\n * `texts` prop of `BitsnapCheckout` to override any of them, whatever the\n * locale.\n */\nexport type CheckoutTexts = {\n /** Drawer title. */\n cart: string;\n /** Shown when the cart has no products. */\n emptyCart: string;\n /** Label next to the total price. */\n total: string;\n /** Delivery note next to the total price. */\n delivery: string;\n /** Country selector placeholder. */\n chooseCountry: string;\n /** Checkout button label. */\n nextStep: string;\n /** Error shown when some products are out of stock. */\n unavailableProducts: string;\n};\n\nexport type CheckoutTextKey = keyof CheckoutTexts;\n\nexport const CHECKOUT_TEXT_TABLES: LocaleTables<CheckoutTextKey> = {\n en: {\n cart: \"Cart\",\n emptyCart: \"Your cart is empty.\",\n total: \"Total:\",\n delivery: \"+ delivery\",\n chooseCountry: \"Choose a country\",\n nextStep: \"Next step\",\n unavailableProducts: \"Not all products are available.\",\n },\n pl: {\n cart: \"Koszyk\",\n emptyCart: \"Brak produktów w koszyku.\",\n total: \"Suma:\",\n delivery: \"+ dostawa\",\n chooseCountry: \"Wybierz kraj\",\n nextStep: \"Następny krok\",\n unavailableProducts: \"Nie wszystkie produkty są dostępne w magazynie.\",\n },\n};\n\n/** Default texts for a locale merged with the caller overrides. */\nexport function resolveCheckoutTexts(\n locale: string,\n overrides?: Partial<CheckoutTexts>,\n): CheckoutTexts {\n return resolveTexts(CHECKOUT_TEXT_TABLES, locale, overrides);\n}\n\nexport function getCheckoutText(\n key: CheckoutTextKey,\n locale: string,\n overrides?: Partial<CheckoutTexts>,\n): string {\n return lookupText(resolveCheckoutTexts(locale, overrides), key);\n}\n","import { pickLocaleTable } from \"@/src/lib/texts\";\nimport { CHECKOUT_TEXT_TABLES } from \"./texts\";\n\nexport const DEFAULT_LOCALE = \"pl-PL\" as const;\nconst localeStorageKey = \"bitsnap-locale\";\n\nlet activeLocale: string | undefined;\n\nexport function setLocale(locale?: string): void {\n const value = locale?.trim();\n activeLocale = value\n ? value.toLowerCase() === \"en\"\n ? \"en-US\"\n : value.toLowerCase() === \"pl\"\n ? DEFAULT_LOCALE\n : value\n : undefined;\n if (typeof localStorage !== \"undefined\") {\n if (activeLocale == null) {\n localStorage.removeItem(localeStorageKey);\n } else {\n localStorage.setItem(localeStorageKey, activeLocale);\n }\n }\n}\n\nexport function getLocale(): string {\n if (activeLocale != null) {\n return activeLocale;\n }\n if (typeof localStorage !== \"undefined\") {\n return localStorage.getItem(localeStorageKey) ?? DEFAULT_LOCALE;\n }\n return DEFAULT_LOCALE;\n}\n\nexport function translate(key: string, locale: string = getLocale()): string {\n return (\n (pickLocaleTable(CHECKOUT_TEXT_TABLES, locale) as Record<string, string>)[\n key\n ] ?? key\n );\n}\n","import { type ClassValue, clsx } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n\nexport type Modify<T, R> = Omit<T, keyof R> & R;\n\nexport type Partial<T> = {\n [P in keyof T]?: T[P];\n};\n"],"mappings":"yCAGO,IAAMA,EAAqB,mBACrBC,EAAsB,iBAAiBC,CAAW,GAElDC,EAAqB,YAQrBC,EAAwC,CACnD,CAACJ,CAAkB,EAAGC,CACxB,EAGaI,EAAwCC,GAAUC,IAC7DA,EAAI,OAAO,IAAIP,EAAoBC,CAAmB,EAC/CK,EAAKC,CAAG,GAIV,SAASC,EAAgBC,EAAqB,CACnD,IAAMC,EAAOD,EAAI,QAAQ,GAAG,EACtBE,EAAOD,IAAS,GAAKD,EAAMA,EAAI,MAAM,EAAGC,CAAI,EAC5CE,EAAWF,IAAS,GAAK,GAAKD,EAAI,MAAMC,CAAI,EAC5CG,EAAYF,EAAK,SAAS,GAAG,EAAK,QAAQ,KAAKA,CAAI,EAAI,GAAK,IAAO,IACzE,MAAO,GAAGA,CAAI,GAAGE,CAAS,GAAGV,CAAkB,IAAI,mBAAmBF,CAAmB,CAAC,GAAGW,CAAQ,EACvG,CC/BO,IAAME,EAAe,qBACjBC,EAAOD,EAEX,SAASE,EAAcC,EAAc,CAC1C,QAAQ,IAAI,gBAAiBA,CAAI,EACjCF,EAAOE,CACT,CCcO,SAASC,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QD,CAAgB,GAAKD,EAE5CA,EACT,CClCA,OAA0B,QAAAO,MAAY,OACtC,OAAS,WAAAC,MAAe,iBAEjB,SAASC,KAAMC,EAAsB,CAC1C,OAAOF,EAAQD,EAAKG,CAAM,CAAC,CAC7B","names":["CLIENT_HEADER_NAME","CLIENT_HEADER_VALUE","SDK_VERSION","CLIENT_QUERY_PARAM","clientHeaders","clientHeaderInterceptor","next","req","withClientParam","url","hash","base","fragment","separator","DEFAULT_HOST","HOST","setCustomHost","host","pickLocaleTable","tables","locale","mergeTexts","table","overrides","result","key","value","resolveTexts","lookupText","texts","CHECKOUT_TEXT_TABLES","resolveCheckoutTexts","locale","overrides","resolveTexts","getCheckoutText","key","lookupText","DEFAULT_LOCALE","localeStorageKey","activeLocale","setLocale","locale","value","getLocale","clsx","twMerge","cn","inputs"]}
@@ -0,0 +1,2 @@
1
+ import{a as ct,b as dt}from"./chunk-KOVKUJAW.mjs";import{c as Y,d as F,e as st,f as U,g as it,i as ut,k as D}from"./chunk-RA452LXZ.mjs";import{e as tt,i as et,j as rt,k as ot,l as nt,n as at}from"./chunk-XVQKEGPO.mjs";var It=["root","grid","card","cardLink","image","imagePlaceholder","body","name","description","price","comparePrice","badge","actions","addToCartButton","selectButton","message","pagination","paginationButton","pageIndicator","emptyState","error","retryButton","skeleton"],wt={fontFamily:"--bitsnap-products-font-family",fontSize:"--bitsnap-products-font-size",background:"--bitsnap-products-background",surface:"--bitsnap-products-surface",foreground:"--bitsnap-products-foreground",mutedForeground:"--bitsnap-products-muted-foreground",border:"--bitsnap-products-border",buttonBackground:"--bitsnap-products-button-background",buttonForeground:"--bitsnap-products-button-foreground",buttonHoverBackground:"--bitsnap-products-button-hover-background",hoverSurface:"--bitsnap-products-hover-surface",focusRing:"--bitsnap-products-focus-ring",error:"--bitsnap-products-error",badgeBackground:"--bitsnap-products-badge-background",badgeForeground:"--bitsnap-products-badge-foreground",radius:"--bitsnap-products-radius"},Et={light:{background:"#ffffff",surface:"#f9fafb",foreground:"#18181b",mutedForeground:"#71717a",border:"#e4e4e7",buttonBackground:"#18181b",buttonForeground:"#fafafa",buttonHoverBackground:"#000000",hoverSurface:"#f4f4f5",focusRing:"#71717a",error:"#dc2626",badgeBackground:"#f4f4f5",badgeForeground:"#3f3f46",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",badgeBackground:"#3f3f46",badgeForeground:"#e4e4e7",radius:"8px"}},_t=[];function lt(t){let e=ct(t,{defaultTheme:"light",presets:Et,variables:wt,shadcnVariables:_t});return{theme:e.theme,tokens:e.tokens,elements:e.elements,boundaryClassName:e.theme,boundaryStyle:e.boundaryStyle}}function q(t,e){return dt(t.elements,e)}function pt(t,e){try{return new Intl.NumberFormat(t,{style:"currency",currency:e,currencyDisplay:"symbol"})}catch{return}}function H(t,e,r=D){let o=t/100,n=pt(r,e)??pt(D,e);return n!=null?n.format(o):`${o.toFixed(2)} ${e}`}import{useCallback as gt,useEffect as Bt,useMemo as jt,useState as z}from"react";var Dt=24,Ot=48,M=class extends Error{status;constructor(e,r){super(e),this.name="ProductListError",this.status=r}};function O(t){return t==null||!Number.isFinite(t)?Dt:Math.min(Ot,Math.max(1,Math.floor(t)))}function mt(t,e){return Math.max(1,Math.ceil(t/e))}function N(t){return t.replace(/\/+$/,"")}function Nt(t){let e=new URLSearchParams;e.set("limit",String(t.limit)),e.set("offset",String(t.offset)),t.locale&&e.set("locale",t.locale);let r=t.search?.trim();return r&&e.set("search",r),`${N(t.host)}/api/integrations/${encodeURIComponent(t.projectID)}/public-commerce/product-list?${e.toString()}`}function Rt(t){return typeof t=="object"&&t!=null&&Array.isArray(t.items)&&typeof t.totalCount=="number"}async function ft(t,e){let r=await fetch(Y(Nt(t)),{method:"GET",credentials:"omit",headers:{Accept:"application/json"},signal:e});if(!r.ok)throw new M(`Could not load products (${r.status})`,r.status);let o=await r.json();if(!Rt(o))throw new M("Unexpected product list response");return o}function G(t){let{projectID:e,locale:r,search:o,initialData:n}=t,[a]=z(()=>U),i=t.host??a,d=O(t.pageSize),c=JSON.stringify([e,i,r??null,o?.trim()??null,d]),[m,u]=z({queryKey:c,page:1});m.queryKey!==c&&u({queryKey:c,page:1});let[b,v]=z(0),[f,l]=z(()=>({requestKey:n!=null?`${c}|1|0`:"",data:n,error:void 0})),g=f.data?.totalCount??0,P=mt(g,d),h=m.queryKey===c?m.page:1,k=g>0?Math.min(h,P):h,C=`${c}|${k}|${b}`,T=f.requestKey===C;Bt(()=>{if(T)return;let y=new AbortController;return ft({projectID:e,host:i,locale:r,search:o,limit:d,offset:(k-1)*d},y.signal).then(x=>{y.signal.aborted||l({requestKey:C,data:x,error:void 0})},x=>{y.signal.aborted||l(w=>({requestKey:C,data:w.data,error:x instanceof Error?x:new Error(String(x))}))}),()=>y.abort()},[C,T]);let I=gt(y=>{let x=Math.max(1,Math.floor(y));u({queryKey:c,page:g>0?Math.min(x,P):x})},[c,g,P]),A=gt(()=>v(y=>y+1),[]);return jt(()=>({products:f.data?.items??[],totalCount:g,page:k,pageCount:P,setPage:I,isLoading:!T,error:T?f.error:void 0,refetch:A}),[f,g,k,P,I,T,A])}import{createContext as ht,useCallback as V,useContext as xt,useEffect as R,useMemo as B,useRef as K,useState as Mt}from"react";function Pt(t,e){if(t.projectID!=null&&t.projectID!==e.projectID)return{ok:!1,reason:`the page cart already belongs to project "${t.projectID}"`};let r=null,o=e.host?N(e.host):"",n=N(t.host);if(o&&o!==n){if(n!==N(t.defaultHost))return{ok:!1,reason:`the page cart already uses the host "${t.host}"`};r=o}return{ok:!0,setProjectID:t.projectID==null?e.projectID:null,setHost:r}}function Q(t,e){let r=e.cartItemId!=null&&e.cartItemId!==e.id?e.cartItemId:null;t.track("add_to_cart",{qty:1,value_minor:e.price,currency:e.currency},{product_id:e.id,variant_id:r})}async function bt(t,e){let[{Bitsnap:r},{getProjectID:o,setProjectID:n}]=await Promise.all([import("./methods-CYARZTYL.mjs"),import("./CartProvider-ZURLJNBW.mjs")]),a=Pt({projectID:o(),host:U,defaultHost:st},e);if(!a.ok)return Ft(a.reason);if(a.setProjectID!=null&&n(a.setProjectID),a.setHost!=null&&it(a.setHost),await r.addProductToCart(t.cartItemId??t.id,1,void 0,{name:t.name,price:t.price,currency:t.currency,analytics:et})!=null)throw new Error("Could not add the product to the cart");e.analytics!=null&&Q(e.analytics,t),e.showCart&&r.showCart()}function Ft(t){throw console.warn(`bitsnap-react: ProductList did not add to the cart because ${t}. Pass onAddToCart to use another cart.`),new Error("The page cart belongs to another project or host")}var $=50,Ut=1e3;function yt(t,e=Ut){let r=new Set,o=new Map,n=[],a=[],i,d,c=!1;function m(){for(d!==void 0&&clearTimeout(d),d=void 0;n.length>0;){let l=n.slice(0,$),g=a.slice(0,$);n=n.slice($),a=a.slice($);try{t({productIds:l,positions:g})}catch{}}}function u(){m();try{tt()?.flush()}catch{}}let b=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&u()};function v(){c||typeof window>"u"||(c=!0,window.addEventListener("pagehide",u,!0),document.addEventListener("visibilitychange",b,!0))}function f(){if(i)return i;if(!(typeof IntersectionObserver>"u"))return i=new IntersectionObserver(l=>{for(let g of l){let P=o.get(g.target);!P||!g.isIntersecting||g.intersectionRatio<.5||(o.delete(g.target),i?.unobserve(g.target),!r.has(P.id)&&(r.add(P.id),n.push(P.id),a.push(P.position)))}n.length>0&&d===void 0&&(d=setTimeout(m,e),d.unref?.())},{threshold:[.5]}),v(),i}return{observe(l,g,P){try{if(r.has(g))return()=>{};let h=f();return h?(o.set(l,{id:g,position:P}),h.observe(l),()=>{o.delete(l),h.unobserve(l)}):()=>{}}catch{return()=>{}}},flush:m,destroy(){try{m(),i?.disconnect(),c&&(window.removeEventListener("pagehide",u,!0),document.removeEventListener("visibilitychange",b,!0),c=!1)}catch{}i=void 0,o.clear()}}}var Ht={en:{addToCart:"Add to cart",addingToCart:"Adding\u2026",addedToCart:"Added to cart",addToCartError:"Could not add to the cart. Try again.",chooseOptions:"Choose",viewProduct:"View",unavailable:"Unavailable",subscription:"Subscription",priceFrom:"from {price}",originalPrice:"Original price",loading:"Loading products",empty:"There are no products to show.",error:"Could not load the products.",retry:"Try again",pagination:"Pagination",previousPage:"Previous",nextPage:"Next",pageOf:"Page {page} of {pageCount}"},pl:{addToCart:"Dodaj do koszyka",addingToCart:"Dodawanie\u2026",addedToCart:"Dodano do koszyka",addToCartError:"Nie uda\u0142o si\u0119 doda\u0107 do koszyka. Spr\xF3buj ponownie.",chooseOptions:"Wybierz",viewProduct:"Zobacz",unavailable:"Niedost\u0119pny",subscription:"Subskrypcja",priceFrom:"od {price}",originalPrice:"Cena przed obni\u017Ck\u0105",loading:"\u0141adowanie produkt\xF3w",empty:"Brak produkt\xF3w do wy\u015Bwietlenia.",error:"Nie uda\u0142o si\u0119 za\u0142adowa\u0107 produkt\xF3w.",retry:"Spr\xF3buj ponownie",pagination:"Paginacja",previousPage:"Poprzednia",nextPage:"Nast\u0119pna",pageOf:"Strona {page} z {pageCount}"}};function Lt(t,e){return ut(Ht,t,e)}function X(t,e){return t.replace(/\{(\w+)\}/g,(r,o)=>o in e?String(e[o]):r)}import{Fragment as At,jsx as s,jsxs as S}from"react/jsx-runtime";var Tt=ht(void 0),zt={observe:()=>()=>{},clicked:()=>{}},vt=ht(zt);function j(){let t=xt(Tt);if(t==null)throw new Error("ProductList parts must be rendered inside ProductList");return t}function p(t,e){let{appearance:r}=j(),o=q(r,t);return{"data-bitsnap-products-slot":t,className:F(e,o?.className),style:o?.style}}var Z="inline-flex cursor-pointer items-center justify-center px-4 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 aria-disabled:cursor-not-allowed aria-disabled:opacity-50",Ct=`${Z} w-full`,$t=`${Ct} no-underline`;function Kt({product:t,onAdd:e}){let{texts:r}=j(),[o,n]=Mt("idle"),a=p("addToCartButton",Ct),i=p("message","mt-2 text-xs");R(()=>{if(o!=="added")return;let m=setTimeout(()=>n("idle"),2e3);return()=>clearTimeout(m)},[o]);let d=V(async()=>{n("adding");try{await e(),n("added")}catch(m){console.error("bitsnap-react: could not add to the cart",m),n("error")}},[e]),c=o==="adding"?r.addingToCart:o==="added"?r.addedToCart:r.addToCart;return S(At,{children:[s("button",{type:"button",...a,disabled:o==="adding","aria-label":`${c}: ${t.name}`,onClick:d,children:c}),o==="error"?s("p",{...i,role:"alert",children:r.addToCartError}):null]})}function Vt({product:t,position:e,href:r,onAdd:o,renderItem:n}){let{texts:a,locale:i}=j(),d=xt(vt),c=K(null);R(()=>{if(c.current!=null)return d.observe(c.current,t.id,e)},[d,t.id,e]);let m=V(()=>d.clicked(t,e),[d,t,e]),u=p("card","relative flex flex-col overflow-hidden border transition-colors"),b=p("cardLink","flex flex-1 flex-col no-underline"),v=p("image","aspect-square w-full overflow-hidden"),f=p("imagePlaceholder","aspect-square w-full"),l=p("body","flex flex-1 flex-col gap-1 p-4"),g=p("name","text-base font-medium leading-snug"),P=p("description","line-clamp-2 text-sm"),h=p("price","mt-auto pt-2 text-base font-semibold"),k=p("comparePrice","ml-2 text-sm font-normal"),C=p("badge","absolute left-3 top-3 px-2 py-0.5 text-xs font-medium"),T=p("actions","p-4 pt-0"),I=p("selectButton",$t),A=H(t.price,t.currency,i),y=t.compareAtPrice!=null&&t.compareAtPrice>t.price?H(t.compareAtPrice,t.currency,i):null;if(n!=null)return s("li",{ref:c,...u,"data-unavailable":t.available?void 0:"",children:n(t,{href:r,price:A,compareAtPrice:y,texts:a,locale:i,addToCart:o,trackClick:m})});let x=t.image?.thumbnailUrl??t.image?.url,w=t.available?t.isRecurring?a.subscription:null:a.unavailable;return S("li",{ref:c,...u,"data-unavailable":t.available?void 0:"",children:[S("a",{...b,href:r,onClick:m,children:[x!=null?s("div",{...v,children:s("img",{src:x,alt:"",loading:"lazy",decoding:"async",className:"h-full w-full object-cover"})}):s("div",{...f,"aria-hidden":"true"}),S("div",{...l,children:[s("h3",{...g,children:t.name}),t.shortDescription?s("p",{...P,children:t.shortDescription}):null,S("p",{...h,children:[t.priceFrom?X(a.priceFrom,{price:A}):A,y!=null?S(At,{children:[S("span",{className:"sr-only",children:[a.originalPrice,": "]}),s("del",{...k,children:y})]}):null]})]})]}),w!=null?s("span",{...C,"data-kind":t.available?"subscription":"unavailable",children:w}):null,s("div",{...T,children:t.available?t.addToCart?s(Kt,{product:t,onAdd:o}):s("a",{...I,href:r,onClick:m,children:t.variantCount>1?a.chooseOptions:a.viewProduct}):s("button",{type:"button",...I,disabled:!0,children:a.unavailable})})]})}var St="m-0 grid list-none grid-cols-[repeat(auto-fill,minmax(min(100%,15rem),1fr))] gap-5 p-0";function qt({count:t,label:e}){let r=p("grid",St),o=p("skeleton","aspect-[3/4] animate-pulse");return s("div",{...r,role:"status","aria-busy":"true","aria-label":e,children:Array.from({length:t},(n,a)=>s("div",{...o,"aria-hidden":"true"},a))})}function Gt({page:t,pageCount:e,isLoading:r,onPage:o}){let{texts:n}=j(),a=p("pagination","mt-8 flex items-center justify-center gap-4"),i=p("paginationButton",Z),d=p("pageIndicator","text-sm");return S("nav",{...a,"aria-label":n.pagination,children:[s("button",{type:"button",...i,"aria-disabled":r||t<=1,onClick:()=>{!r&&t>1&&o(t-1)},children:n.previousPage}),s("span",{...d,"aria-live":"polite",children:X(n.pageOf,{page:t,pageCount:e})}),s("button",{type:"button",...i,"aria-disabled":r||t>=e,onClick:()=>{!r&&t<e&&o(t+1)},children:n.nextPage})]})}function Qt({options:t,productHref:e,renderItem:r,onAddToCart:o,showCartOnAdd:n}){let{texts:a}=j(),{products:i,page:d,pageCount:c,setPage:m,isLoading:u,error:b,refetch:v}=G(t),f=ot(),l=t.search?.trim()?"search":"catalog",g=O(t.pageSize),P=K(!1);R(()=>{P.current||u||b!=null||(P.current=!0,f.track("product_list_viewed",{list_id:l,item_count:i.length}))},[f,u,b,l,i.length]);let h=B(()=>yt(({productIds:L,positions:_})=>f.track("product_impression",{list_id:l,product_ids:L,positions:_})),[f,l]);R(()=>()=>h.destroy(),[h]);let k=B(()=>({observe:h.observe,clicked:(L,_)=>f.track("product_clicked",{list_id:l,position:_},{product_id:L.id})}),[h,f,l]),C=K(null),T=K(!1),I=V(L=>{T.current=!0,m(L)},[m]);R(()=>{u||!T.current||(T.current=!1,C.current?.focus({preventScroll:!0}),C.current?.scrollIntoView({block:"start"}))},[u]);let A=p("grid",St),y=p("emptyState","py-12 text-center text-sm"),x=p("error","flex flex-col items-center gap-3 py-12 text-center text-sm"),w=p("retryButton",Z),{projectID:J,host:W}=t,kt=V(L=>async()=>{if(o!=null){await at(()=>o(L)),Q(f,L);return}await bt(L,{projectID:J,host:W,showCart:n,analytics:f})},[o,J,W,n,f]),E;return u&&i.length===0?E=s(qt,{count:Math.min(O(t.pageSize),8),label:a.loading}):b!=null?E=S("div",{...x,role:"alert",children:[s("p",{children:a.error}),s("button",{type:"button",...w,onClick:v,children:a.retry})]}):i.length===0?E=s("p",{...y,children:a.empty}):E=s("ul",{...A,"aria-busy":u||void 0,className:F(A.className,u&&"opacity-60"),children:i.map((L,_)=>s(Vt,{product:L,position:(d-1)*g+_,href:e(L),onAdd:kt(L),renderItem:r},L.id))}),s(vt.Provider,{value:k,children:S("div",{ref:C,tabIndex:-1,className:"p-1 outline-none scroll-mt-4",children:[E,c>1&&b==null?s(Gt,{page:d,pageCount:c,isLoading:u,onPage:I}):null]})})}var Xt=t=>`/p/${encodeURIComponent(t.uniqueSlug)}`;function Zt({productHref:t=Xt,appearance:e,texts:r,renderItem:o,onAddToCart:n,showCartOnAdd:a=!0,className:i,analytics:d,...c}){let m=nt(c.projectID,d,"catalog"),u=c.locale??D,b=B(()=>lt(e),[e]),v=B(()=>Lt(u,r),[u,r]),f=B(()=>({appearance:b,texts:v,locale:u}),[b,v,u]),l=q(b,"root");return s(rt,{value:m,children:s(Tt.Provider,{value:f,children:s("div",{"data-bitsnap-products":"root","data-bitsnap-products-slot":"root",className:F("bitsnap-react",b.boundaryClassName,i,l?.className),style:{...b.boundaryStyle,...l?.style},children:s(Qt,{options:c,productHref:t,renderItem:o,onAddToCart:n,showCartOnAdd:a})})})})}export{It as a,H as b,G as c,Zt as d};
2
+ //# sourceMappingURL=chunk-SLLBTQTW.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/products/appearance.ts","../src/components/products/format.ts","../src/components/products/useProducts.ts","../src/components/products/fetch.ts","../src/components/products/ProductList.tsx","../src/components/products/cart-target.ts","../src/components/products/add-to-cart.ts","../src/components/products/impressions.ts","../src/components/products/texts.ts"],"sourcesContent":["import type { CSSProperties } from \"react\";\nimport {\n getSlotAppearance,\n resolveAppearanceCore,\n type AppearanceElements,\n type ShadcnVariableMapping,\n type SlotAppearance,\n} from \"@/src/lib/appearance-core\";\n\n/**\n * Product list appearance API.\n *\n * It mirrors `CheckoutAppearance` and `ReturnsAppearance` (theme, tokens,\n * elements) so a shop can reuse one brand object for all of them. The resolver\n * is pure: it turns the caller input into a theme name, the tokens in effect,\n * the slot overrides and the inline style for the theme boundary.\n */\n\nexport type ProductListTheme = \"light\" | \"dark\";\n\nexport type ProductListAppearanceTokens = {\n /** Font family of the list. The library never loads fonts. */\n fontFamily?: string;\n /** Base font size. */\n fontSize?: string;\n /** List background. */\n background?: string;\n /** Raised surfaces: cards, image placeholders, skeletons. */\n surface?: string;\n /** Main text color. */\n foreground?: string;\n /** Secondary text: descriptions, the struck-through price. */\n mutedForeground?: string;\n /** Borders of cards and buttons. */\n border?: string;\n /** \"Add to cart\" button background. */\n buttonBackground?: string;\n /** \"Add to cart\" button text. */\n buttonForeground?: string;\n /** \"Add to cart\" button background on hover. */\n buttonHoverBackground?: string;\n /** Hover surface of cards and secondary buttons. */\n hoverSurface?: string;\n /** Focus ring color. */\n focusRing?: string;\n /** Error and unavailable state color. */\n error?: string;\n /** Badge background (subscription, unavailable). */\n badgeBackground?: string;\n /** Badge text. */\n badgeForeground?: string;\n /** Corner radius of cards, images and buttons. */\n radius?: string;\n};\n\n/**\n * Stable slot names. They are exposed as `data-bitsnap-products-slot`\n * attributes so they can also be targeted from plain CSS.\n */\nexport const PRODUCT_LIST_SLOT_NAMES = [\n \"root\",\n \"grid\",\n \"card\",\n \"cardLink\",\n \"image\",\n \"imagePlaceholder\",\n \"body\",\n \"name\",\n \"description\",\n \"price\",\n \"comparePrice\",\n \"badge\",\n \"actions\",\n \"addToCartButton\",\n \"selectButton\",\n \"message\",\n \"pagination\",\n \"paginationButton\",\n \"pageIndicator\",\n \"emptyState\",\n \"error\",\n \"retryButton\",\n \"skeleton\",\n] as const;\n\nexport type ProductListSlotName = (typeof PRODUCT_LIST_SLOT_NAMES)[number];\n\nexport type ProductListSlotAppearance = SlotAppearance;\n\nexport type ProductListAppearanceElements =\n AppearanceElements<ProductListSlotName>;\n\nexport type ProductListAppearance = {\n /** `\"light\"` or `\"dark\"`. Omitted means `\"light\"`. */\n theme?: ProductListTheme;\n /** Partial overrides applied over the theme preset. */\n tokens?: ProductListAppearanceTokens;\n /** Per element `className`/`style` overrides. */\n elements?: ProductListAppearanceElements;\n};\n\nexport type ResolvedProductListAppearance = {\n theme: ProductListTheme;\n /** Tokens that are in effect (the theme preset plus caller overrides). */\n tokens: ProductListAppearanceTokens;\n elements: ProductListAppearanceElements;\n /** Theme marker class for the theme boundary. */\n boundaryClassName: string;\n /** Inline custom properties applied to the list root. */\n boundaryStyle: CSSProperties;\n};\n\n/** CSS custom property used for each token. */\nexport const PRODUCT_LIST_TOKEN_VARIABLES = {\n fontFamily: \"--bitsnap-products-font-family\",\n fontSize: \"--bitsnap-products-font-size\",\n background: \"--bitsnap-products-background\",\n surface: \"--bitsnap-products-surface\",\n foreground: \"--bitsnap-products-foreground\",\n mutedForeground: \"--bitsnap-products-muted-foreground\",\n border: \"--bitsnap-products-border\",\n buttonBackground: \"--bitsnap-products-button-background\",\n buttonForeground: \"--bitsnap-products-button-foreground\",\n buttonHoverBackground: \"--bitsnap-products-button-hover-background\",\n hoverSurface: \"--bitsnap-products-hover-surface\",\n focusRing: \"--bitsnap-products-focus-ring\",\n error: \"--bitsnap-products-error\",\n badgeBackground: \"--bitsnap-products-badge-background\",\n badgeForeground: \"--bitsnap-products-badge-foreground\",\n radius: \"--bitsnap-products-radius\",\n} as const;\n\nexport type ProductListTokenName = keyof typeof PRODUCT_LIST_TOKEN_VARIABLES;\n\n/**\n * Complete palettes. They carry colors and radius only, so typography is never\n * reset implicitly. `products.css` falls back to the light values, which keeps\n * the list usable even when the boundary style is missing.\n */\nexport const PRODUCT_LIST_THEME_PRESETS: Record<\n ProductListTheme,\n ProductListAppearanceTokens\n> = {\n light: {\n background: \"#ffffff\",\n surface: \"#f9fafb\",\n foreground: \"#18181b\",\n mutedForeground: \"#71717a\",\n border: \"#e4e4e7\",\n buttonBackground: \"#18181b\",\n buttonForeground: \"#fafafa\",\n buttonHoverBackground: \"#000000\",\n hoverSurface: \"#f4f4f5\",\n focusRing: \"#71717a\",\n error: \"#dc2626\",\n badgeBackground: \"#f4f4f5\",\n badgeForeground: \"#3f3f46\",\n radius: \"8px\",\n },\n dark: {\n background: \"#18181b\",\n surface: \"#27272a\",\n foreground: \"#fafafa\",\n mutedForeground: \"#a1a1aa\",\n border: \"#3f3f46\",\n buttonBackground: \"#fafafa\",\n buttonForeground: \"#18181b\",\n buttonHoverBackground: \"#e4e4e7\",\n hoverSurface: \"#3f3f46\",\n focusRing: \"#a1a1aa\",\n error: \"#f87171\",\n badgeBackground: \"#3f3f46\",\n badgeForeground: \"#e4e4e7\",\n radius: \"8px\",\n },\n};\n\n/** The list renders its own elements, so no shared primitive needs remapping. */\nconst PRODUCT_LIST_SHADCN_VARIABLES: ShadcnVariableMapping<ProductListTokenName> =\n [];\n\nexport function resolveProductListAppearance(\n appearance?: ProductListAppearance,\n): ResolvedProductListAppearance {\n const resolved = resolveAppearanceCore<\n ProductListTokenName,\n ProductListTheme,\n ProductListSlotName\n >(appearance, {\n defaultTheme: \"light\",\n presets: PRODUCT_LIST_THEME_PRESETS,\n variables: PRODUCT_LIST_TOKEN_VARIABLES,\n shadcnVariables: PRODUCT_LIST_SHADCN_VARIABLES,\n });\n\n return {\n theme: resolved.theme,\n tokens: resolved.tokens,\n elements: resolved.elements,\n boundaryClassName: resolved.theme,\n boundaryStyle: resolved.boundaryStyle,\n };\n}\n\n/** Caller overrides for a single slot, if any were provided. */\nexport function getProductListSlotAppearance(\n resolved: ResolvedProductListAppearance,\n slot: ProductListSlotName,\n): ProductListSlotAppearance | undefined {\n return getSlotAppearance(resolved.elements, slot);\n}\n","import { DEFAULT_LOCALE } from \"../checkout/locale\";\n\nfunction createFormatter(\n locale: string,\n currency: string,\n): Intl.NumberFormat | undefined {\n try {\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency,\n currencyDisplay: \"symbol\",\n });\n } catch {\n // RangeError: invalid locale or currency code.\n return undefined;\n }\n}\n\n/**\n * Formats a price in minor units (grosze, cents) for the locale, the same way\n * the cart does (`amount / 100`). An unknown locale falls back to Polish and an\n * invalid currency code to a plain number followed by the code.\n */\nexport function formatProductPrice(\n amount: number,\n currency: string,\n locale: string = DEFAULT_LOCALE,\n): string {\n const value = amount / 100;\n const formatter =\n createFormatter(locale, currency) ??\n createFormatter(DEFAULT_LOCALE, currency);\n\n return formatter != null\n ? formatter.format(value)\n : `${value.toFixed(2)} ${currency}`;\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { HOST } from \"../checkout/constants\";\nimport {\n clampPageSize,\n fetchProductList,\n pageCountFor,\n type ProductListData,\n type PublicListProduct,\n} from \"./fetch\";\n\nexport type UseProductsOptions = {\n /** Project (shop) ID. */\n projectID: string;\n /**\n * Origin of the Bitsnap backend. Defaults to the library host\n * (`https://bitsnap.pl`, or what `setCustomHost` had set when the component\n * first rendered; later `setCustomHost` calls do not move an existing list).\n * On a custom domain pass the domain itself, or an empty string for\n * same-origin requests.\n */\n host?: string;\n locale?: string;\n /** Products per page, 1 to 48. Defaults to 24. */\n pageSize?: number;\n search?: string;\n /**\n * First page, loaded on the server. It is always used for the first request\n * of the mounted list (the first fetch is skipped and the products are\n * available on the first render), so it has to be the page the props ask\n * for: page 1 with the same `pageSize`, `locale` and `search`. Later changes\n * of the props fetch again.\n */\n initialData?: ProductListData;\n};\n\nexport type UseProductsResult = {\n /** Products of the current page. Keeps the previous page while loading. */\n products: PublicListProduct[];\n totalCount: number;\n /** Current page, starting at 1. */\n page: number;\n pageCount: number;\n setPage: (page: number) => void;\n /** `true` until the current page is available, also during server rendering. */\n isLoading: boolean;\n error: Error | undefined;\n /** Loads the current page again. */\n refetch: () => void;\n};\n\ntype Snapshot = {\n /** Request the data belongs to; empty when it is not tied to one. */\n requestKey: string;\n data: ProductListData | undefined;\n error: Error | undefined;\n};\n\n/**\n * Loads the product catalog page by page. It uses a plain `fetch` without\n * credentials, never reads global state (`setProjectID`, `setCustomHost`) other\n * than the default host, and does nothing during server rendering - pass\n * `initialData` to render products in the server HTML.\n */\nexport function useProducts(options: UseProductsOptions): UseProductsResult {\n const { projectID, locale, search, initialData } = options;\n // The library host is a mutable global; read it once so a later\n // `setCustomHost` does not change the query of a mounted list.\n const [defaultHost] = useState(() => HOST);\n const host = options.host ?? defaultHost;\n const pageSize = clampPageSize(options.pageSize);\n\n // Everything that identifies a list; a change resets the page.\n const queryKey = JSON.stringify([\n projectID,\n host,\n locale ?? null,\n search?.trim() ?? null,\n pageSize,\n ]);\n\n const [pageState, setPageState] = useState({ queryKey, page: 1 });\n if (pageState.queryKey !== queryKey) {\n // Another list: start from page 1 (adjusting state while rendering).\n setPageState({ queryKey, page: 1 });\n }\n const [reloads, setReloads] = useState(0);\n const [snapshot, setSnapshot] = useState<Snapshot>(() => ({\n requestKey: initialData != null ? `${queryKey}|1|0` : \"\",\n data: initialData,\n error: undefined,\n }));\n\n // A page past the end (the catalog shrank) falls back to the last page once\n // the total is known.\n const totalCount = snapshot.data?.totalCount ?? 0;\n const pageCount = pageCountFor(totalCount, pageSize);\n const requestedPage = pageState.queryKey === queryKey ? pageState.page : 1;\n const page = totalCount > 0 ? Math.min(requestedPage, pageCount) : requestedPage;\n\n const requestKey = `${queryKey}|${page}|${reloads}`;\n\n const isCurrent = snapshot.requestKey === requestKey;\n\n useEffect(() => {\n if (isCurrent) {\n return;\n }\n\n const controller = new AbortController();\n fetchProductList(\n {\n projectID,\n host,\n locale,\n search,\n limit: pageSize,\n offset: (page - 1) * pageSize,\n },\n controller.signal,\n ).then(\n (data) => {\n if (controller.signal.aborted) {\n return;\n }\n setSnapshot({ requestKey, data, error: undefined });\n },\n (error: unknown) => {\n if (controller.signal.aborted) {\n return;\n }\n setSnapshot((previous) => ({\n requestKey,\n data: previous.data,\n error: error instanceof Error ? error : new Error(String(error)),\n }));\n },\n );\n\n return () => controller.abort();\n // `requestKey` carries projectID, host, locale, search, pageSize, page and\n // the reload counter.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [requestKey, isCurrent]);\n\n const setPage = useCallback(\n (next: number) => {\n const target = Math.max(1, Math.floor(next));\n setPageState({\n queryKey,\n page: totalCount > 0 ? Math.min(target, pageCount) : target,\n });\n },\n [queryKey, totalCount, pageCount],\n );\n\n const refetch = useCallback(() => setReloads((value) => value + 1), []);\n\n return useMemo(\n () => ({\n products: snapshot.data?.items ?? [],\n totalCount,\n page,\n pageCount,\n setPage,\n isLoading: !isCurrent,\n error: isCurrent ? snapshot.error : undefined,\n refetch,\n }),\n [snapshot, totalCount, page, pageCount, setPage, isCurrent, refetch],\n );\n}\n","import { withClientParam } from \"@/src/lib/client-header\";\nimport type { BitsnapModels } from \"@/src/models\";\n\nexport type PublicListProduct = BitsnapModels.PublicListProduct;\nexport type ProductListData = BitsnapModels.ProductListResponse;\n\nexport const DEFAULT_PAGE_SIZE = 24;\nexport const MAX_PAGE_SIZE = 48;\n\nexport type ProductListQuery = {\n projectID: string;\n /** Origin of the Bitsnap backend (or of a custom domain), without a path. */\n host: string;\n locale?: string;\n search?: string;\n limit: number;\n offset: number;\n};\n\nexport class ProductListError extends Error {\n readonly status: number | undefined;\n\n constructor(message: string, status?: number) {\n super(message);\n this.name = \"ProductListError\";\n this.status = status;\n }\n}\n\n/** Page size within what the backend accepts (1 to 48, default 24). */\nexport function clampPageSize(pageSize?: number): number {\n if (pageSize == null || !Number.isFinite(pageSize)) {\n return DEFAULT_PAGE_SIZE;\n }\n return Math.min(MAX_PAGE_SIZE, Math.max(1, Math.floor(pageSize)));\n}\n\nexport function pageCountFor(totalCount: number, pageSize: number): number {\n return Math.max(1, Math.ceil(totalCount / pageSize));\n}\n\n/** Origin without trailing slashes, so equal hosts compare equal as strings. */\nexport function normalizeHost(host: string): string {\n return host.replace(/\\/+$/, \"\");\n}\n\nexport function buildProductListURL(query: ProductListQuery): string {\n const params = new URLSearchParams();\n params.set(\"limit\", String(query.limit));\n params.set(\"offset\", String(query.offset));\n if (query.locale) {\n params.set(\"locale\", query.locale);\n }\n const search = query.search?.trim();\n if (search) {\n params.set(\"search\", search);\n }\n\n const host = normalizeHost(query.host);\n return `${host}/api/integrations/${encodeURIComponent(\n query.projectID,\n )}/public-commerce/product-list?${params.toString()}`;\n}\n\nfunction isProductListData(value: unknown): value is ProductListData {\n return (\n typeof value === \"object\" &&\n value != null &&\n Array.isArray((value as ProductListData).items) &&\n typeof (value as ProductListData).totalCount === \"number\"\n );\n}\n\n/**\n * Loads one page of the catalog with a plain, credential-less `fetch`. It does\n * not touch the global project ID or host.\n */\nexport async function fetchProductList(\n query: ProductListQuery,\n signal?: AbortSignal,\n): Promise<ProductListData> {\n const response = await fetch(withClientParam(buildProductListURL(query)), {\n method: \"GET\",\n credentials: \"omit\",\n headers: { Accept: \"application/json\" },\n signal,\n });\n\n if (!response.ok) {\n throw new ProductListError(\n `Could not load products (${response.status})`,\n response.status,\n );\n }\n\n const payload: unknown = await response.json();\n if (!isProductListData(payload)) {\n throw new ProductListError(\"Unexpected product list response\");\n }\n\n return payload;\n}\n","import {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { CSSProperties, ReactNode } from \"react\";\nimport { cn } from \"@/src/lib/utils\";\nimport {\n InstrumentProvider,\n useInstrument,\n useInstrumentContext,\n withCartAnalyticsMuted,\n type AnalyticsOption,\n type Instrument,\n} from \"@/src/analytics/instrument\";\nimport { DEFAULT_LOCALE } from \"../checkout/locale\";\nimport { addProductToCart, trackProductAdded } from \"./add-to-cart\";\nimport {\n getProductListSlotAppearance,\n resolveProductListAppearance,\n type ProductListAppearance,\n type ProductListSlotName,\n type ResolvedProductListAppearance,\n} from \"./appearance\";\nimport { clampPageSize, type PublicListProduct } from \"./fetch\";\nimport { formatProductPrice } from \"./format\";\nimport { createImpressionTracker } from \"./impressions\";\nimport {\n fillProductListText,\n resolveProductListTexts,\n type ProductListTexts,\n} from \"./texts\";\nimport { useProducts, type UseProductsOptions } from \"./useProducts\";\n\n/** What `renderItem` gets next to the product. */\nexport type ProductListItemContext = {\n /** Product page URL from `productHref`. */\n href: string;\n /** Price formatted for the locale and currency, without the \"from\" prefix. */\n price: string;\n /** Formatted regular price when the product is discounted. */\n compareAtPrice: string | null;\n texts: ProductListTexts;\n locale: string;\n /** Adds the product to the cart the way the built-in button does. */\n addToCart: () => Promise<void>;\n /**\n * Reports a click on the product (`product_clicked`). Call it from the link\n * a custom card renders; the built-in card does it itself.\n */\n trackClick: () => void;\n};\n\nexport type ProductListProps = UseProductsOptions & {\n /**\n * Product page URL. Defaults to the relative `/p/{uniqueSlug}`, which works\n * on a Bitsnap custom domain. Embedded on another site, return the full\n * URL of the product page.\n */\n productHref?: (product: PublicListProduct) => string;\n appearance?: ProductListAppearance;\n /** Text overrides, applied whatever the locale. */\n texts?: Partial<ProductListTexts>;\n /** Replaces the content of a card. The card frame stays. */\n renderItem?: (\n product: PublicListProduct,\n context: ProductListItemContext,\n ) => ReactNode;\n /**\n * Called by the \"Add to cart\" button instead of the default action\n * (`Bitsnap.addProductToCart`). A rejected promise shows the error message.\n */\n onAddToCart?: (product: PublicListProduct) => void | Promise<void>;\n /** Open the cart drawer after the default add to cart. Defaults to `true`. */\n showCartOnAdd?: boolean;\n className?: string;\n /**\n * Usage statistics for your Bitsnap dashboard (list views, impressions,\n * clicks, add to cart). On by default; `false` turns it off. An object\n * lets you forward every event: `{ onEvent }`. Nothing is stored on the\n * visitor's device.\n */\n analytics?: AnalyticsOption;\n};\n\ntype ListContext = {\n appearance: ResolvedProductListAppearance;\n texts: ProductListTexts;\n locale: string;\n};\n\nconst ProductListContext = createContext<ListContext | undefined>(undefined);\n\ntype CardAnalytics = {\n observe: (element: Element, id: string, position: number) => () => void;\n clicked: (product: PublicListProduct, position: number) => void;\n};\n\nconst noCardAnalytics: CardAnalytics = {\n observe: () => () => {},\n clicked: () => {},\n};\n\nconst CardAnalyticsContext = createContext<CardAnalytics>(noCardAnalytics);\n\nfunction useListContext(): ListContext {\n const value = useContext(ProductListContext);\n if (value == null) {\n throw new Error(\"ProductList parts must be rendered inside ProductList\");\n }\n return value;\n}\n\n/** Stable slot attribute, built-in classes and the caller overrides for a slot. */\nfunction useSlot(slot: ProductListSlotName, className?: string) {\n const { appearance } = useListContext();\n const override = getProductListSlotAppearance(appearance, slot);\n\n return {\n \"data-bitsnap-products-slot\": slot,\n className: cn(className, override?.className),\n style: override?.style,\n };\n}\n\nconst BUTTON_CLASS =\n \"inline-flex cursor-pointer items-center justify-center px-4 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 aria-disabled:cursor-not-allowed aria-disabled:opacity-50\";\nconst BLOCK_BUTTON_CLASS = `${BUTTON_CLASS} w-full`;\nconst LINK_BUTTON_CLASS = `${BLOCK_BUTTON_CLASS} no-underline`;\n\ntype AddStatus = \"idle\" | \"adding\" | \"added\" | \"error\";\n\nfunction AddToCartButton({\n product,\n onAdd,\n}: {\n product: PublicListProduct;\n onAdd: () => Promise<void>;\n}) {\n const { texts } = useListContext();\n const [status, setStatus] = useState<AddStatus>(\"idle\");\n const button = useSlot(\"addToCartButton\", BLOCK_BUTTON_CLASS);\n const message = useSlot(\"message\", \"mt-2 text-xs\");\n\n useEffect(() => {\n if (status !== \"added\") {\n return;\n }\n const timer = setTimeout(() => setStatus(\"idle\"), 2000);\n return () => clearTimeout(timer);\n }, [status]);\n\n const click = useCallback(async () => {\n setStatus(\"adding\");\n try {\n await onAdd();\n setStatus(\"added\");\n } catch (error) {\n console.error(\"bitsnap-react: could not add to the cart\", error);\n setStatus(\"error\");\n }\n }, [onAdd]);\n\n const label =\n status === \"adding\"\n ? texts.addingToCart\n : status === \"added\"\n ? texts.addedToCart\n : texts.addToCart;\n\n return (\n <>\n <button\n type=\"button\"\n {...button}\n disabled={status === \"adding\"}\n aria-label={`${label}: ${product.name}`}\n onClick={click}\n >\n {label}\n </button>\n {status === \"error\" ? (\n <p {...message} role=\"alert\">\n {texts.addToCartError}\n </p>\n ) : null}\n </>\n );\n}\n\nfunction ProductCard({\n product,\n position,\n href,\n onAdd,\n renderItem,\n}: {\n product: PublicListProduct;\n /** Index in the whole catalog (not in the current page). */\n position: number;\n href: string;\n onAdd: () => Promise<void>;\n renderItem?: ProductListProps[\"renderItem\"];\n}) {\n const { texts, locale } = useListContext();\n const analytics = useContext(CardAnalyticsContext);\n const element = useRef<HTMLLIElement>(null);\n useEffect(() => {\n if (element.current == null) {\n return;\n }\n return analytics.observe(element.current, product.id, position);\n }, [analytics, product.id, position]);\n const trackClick = useCallback(\n () => analytics.clicked(product, position),\n [analytics, product, position],\n );\n const card = useSlot(\n \"card\",\n \"relative flex flex-col overflow-hidden border transition-colors\",\n );\n const cardLink = useSlot(\"cardLink\", \"flex flex-1 flex-col no-underline\");\n const imageFrame = useSlot(\"image\", \"aspect-square w-full overflow-hidden\");\n const placeholder = useSlot(\"imagePlaceholder\", \"aspect-square w-full\");\n const body = useSlot(\"body\", \"flex flex-1 flex-col gap-1 p-4\");\n const name = useSlot(\"name\", \"text-base font-medium leading-snug\");\n const description = useSlot(\"description\", \"line-clamp-2 text-sm\");\n const price = useSlot(\"price\", \"mt-auto pt-2 text-base font-semibold\");\n const comparePrice = useSlot(\"comparePrice\", \"ml-2 text-sm font-normal\");\n const badge = useSlot(\n \"badge\",\n \"absolute left-3 top-3 px-2 py-0.5 text-xs font-medium\",\n );\n const actions = useSlot(\"actions\", \"p-4 pt-0\");\n const selectButton = useSlot(\"selectButton\", LINK_BUTTON_CLASS);\n\n const formattedPrice = formatProductPrice(\n product.price,\n product.currency,\n locale,\n );\n const formattedCompare =\n product.compareAtPrice != null && product.compareAtPrice > product.price\n ? formatProductPrice(product.compareAtPrice, product.currency, locale)\n : null;\n\n if (renderItem != null) {\n return (\n <li\n ref={element}\n {...card}\n data-unavailable={product.available ? undefined : \"\"}\n >\n {renderItem(product, {\n href,\n price: formattedPrice,\n compareAtPrice: formattedCompare,\n texts,\n locale,\n addToCart: onAdd,\n trackClick,\n })}\n </li>\n );\n }\n\n const imageSource = product.image?.thumbnailUrl ?? product.image?.url;\n const badgeText = !product.available\n ? texts.unavailable\n : product.isRecurring\n ? texts.subscription\n : null;\n\n return (\n <li ref={element} {...card} data-unavailable={product.available ? undefined : \"\"}>\n <a {...cardLink} href={href} onClick={trackClick}>\n {imageSource != null ? (\n <div {...imageFrame}>\n <img\n src={imageSource}\n alt=\"\"\n loading=\"lazy\"\n decoding=\"async\"\n className=\"h-full w-full object-cover\"\n />\n </div>\n ) : (\n <div {...placeholder} aria-hidden=\"true\" />\n )}\n <div {...body}>\n <h3 {...name}>{product.name}</h3>\n {product.shortDescription ? (\n <p {...description}>{product.shortDescription}</p>\n ) : null}\n <p {...price}>\n {product.priceFrom\n ? fillProductListText(texts.priceFrom, { price: formattedPrice })\n : formattedPrice}\n {formattedCompare != null ? (\n <>\n <span className=\"sr-only\">{texts.originalPrice}: </span>\n <del {...comparePrice}>{formattedCompare}</del>\n </>\n ) : null}\n </p>\n </div>\n </a>\n {badgeText != null ? (\n <span\n {...badge}\n data-kind={product.available ? \"subscription\" : \"unavailable\"}\n >\n {badgeText}\n </span>\n ) : null}\n <div {...actions}>\n {!product.available ? (\n <button type=\"button\" {...selectButton} disabled>\n {texts.unavailable}\n </button>\n ) : product.addToCart ? (\n <AddToCartButton product={product} onAdd={onAdd} />\n ) : (\n <a {...selectButton} href={href} onClick={trackClick}>\n {product.variantCount > 1 ? texts.chooseOptions : texts.viewProduct}\n </a>\n )}\n </div>\n </li>\n );\n}\n\nconst GRID_CLASS =\n \"m-0 grid list-none grid-cols-[repeat(auto-fill,minmax(min(100%,15rem),1fr))] gap-5 p-0\";\n\nfunction SkeletonGrid({ count, label }: { count: number; label: string }) {\n const grid = useSlot(\"grid\", GRID_CLASS);\n const skeleton = useSlot(\"skeleton\", \"aspect-[3/4] animate-pulse\");\n\n return (\n <div {...grid} role=\"status\" aria-busy=\"true\" aria-label={label}>\n {Array.from({ length: count }, (_, index) => (\n <div key={index} {...skeleton} aria-hidden=\"true\" />\n ))}\n </div>\n );\n}\n\nfunction Pagination({\n page,\n pageCount,\n isLoading,\n onPage,\n}: {\n page: number;\n pageCount: number;\n isLoading: boolean;\n onPage: (page: number) => void;\n}) {\n const { texts } = useListContext();\n const nav = useSlot(\n \"pagination\",\n \"mt-8 flex items-center justify-center gap-4\",\n );\n const button = useSlot(\"paginationButton\", BUTTON_CLASS);\n const indicator = useSlot(\"pageIndicator\", \"text-sm\");\n\n return (\n <nav {...nav} aria-label={texts.pagination}>\n <button\n type=\"button\"\n {...button}\n aria-disabled={isLoading || page <= 1}\n onClick={() => {\n if (!isLoading && page > 1) {\n onPage(page - 1);\n }\n }}\n >\n {texts.previousPage}\n </button>\n <span {...indicator} aria-live=\"polite\">\n {fillProductListText(texts.pageOf, { page, pageCount })}\n </span>\n <button\n type=\"button\"\n {...button}\n aria-disabled={isLoading || page >= pageCount}\n onClick={() => {\n if (!isLoading && page < pageCount) {\n onPage(page + 1);\n }\n }}\n >\n {texts.nextPage}\n </button>\n </nav>\n );\n}\n\nfunction ProductListContent({\n options,\n productHref,\n renderItem,\n onAddToCart,\n showCartOnAdd,\n}: {\n options: UseProductsOptions;\n productHref: (product: PublicListProduct) => string;\n renderItem?: ProductListProps[\"renderItem\"];\n onAddToCart?: ProductListProps[\"onAddToCart\"];\n showCartOnAdd: boolean;\n}) {\n const { texts } = useListContext();\n const { products, page, pageCount, setPage, isLoading, error, refetch } =\n useProducts(options);\n const instrument = useInstrumentContext();\n // The search text is never reported, only that the list was searched.\n const listId = options.search?.trim() ? \"search\" : \"catalog\";\n const pageSize = clampPageSize(options.pageSize);\n\n const viewed = useRef(false);\n useEffect(() => {\n if (viewed.current || isLoading || error != null) {\n return;\n }\n viewed.current = true;\n instrument.track(\"product_list_viewed\", {\n list_id: listId,\n item_count: products.length,\n });\n }, [instrument, isLoading, error, listId, products.length]);\n\n const impressions = useMemo(\n () =>\n createImpressionTracker(({ productIds, positions }) =>\n instrument.track(\"product_impression\", {\n list_id: listId,\n product_ids: productIds,\n positions,\n }),\n ),\n [instrument, listId],\n );\n useEffect(() => () => impressions.destroy(), [impressions]);\n const cardAnalytics = useMemo<CardAnalytics>(\n () => ({\n observe: impressions.observe,\n clicked: (product, position) =>\n instrument.track(\n \"product_clicked\",\n { list_id: listId, position },\n { product_id: product.id },\n ),\n }),\n [impressions, instrument, listId],\n );\n\n // After a page change by the user, move focus to the products (the button\n // that was pressed stays where it is, but the content above it changes) and\n // bring them into view once the page has loaded.\n const content = useRef<HTMLDivElement>(null);\n const movedPage = useRef(false);\n const changePage = useCallback(\n (next: number) => {\n movedPage.current = true;\n setPage(next);\n },\n [setPage],\n );\n useEffect(() => {\n if (isLoading || !movedPage.current) {\n return;\n }\n movedPage.current = false;\n content.current?.focus({ preventScroll: true });\n content.current?.scrollIntoView({ block: \"start\" });\n }, [isLoading]);\n\n const grid = useSlot(\"grid\", GRID_CLASS);\n const empty = useSlot(\"emptyState\", \"py-12 text-center text-sm\");\n const errorSlot = useSlot(\"error\", \"flex flex-col items-center gap-3 py-12 text-center text-sm\");\n const retry = useSlot(\"retryButton\", BUTTON_CLASS);\n\n const { projectID, host } = options;\n const addFor = useCallback(\n (product: PublicListProduct) => async () => {\n if (onAddToCart != null) {\n // The list reports the add itself; a cart helper called inside must not report it again.\n await withCartAnalyticsMuted(() => onAddToCart(product));\n trackProductAdded(instrument, product);\n return;\n }\n await addProductToCart(product, {\n projectID,\n host,\n showCart: showCartOnAdd,\n analytics: instrument,\n });\n },\n [onAddToCart, projectID, host, showCartOnAdd, instrument],\n );\n\n let body: ReactNode;\n if (isLoading && products.length === 0) {\n body = (\n <SkeletonGrid\n count={Math.min(clampPageSize(options.pageSize), 8)}\n label={texts.loading}\n />\n );\n } else if (error != null) {\n body = (\n <div {...errorSlot} role=\"alert\">\n <p>{texts.error}</p>\n <button type=\"button\" {...retry} onClick={refetch}>\n {texts.retry}\n </button>\n </div>\n );\n } else if (products.length === 0) {\n body = <p {...empty}>{texts.empty}</p>;\n } else {\n body = (\n <ul\n {...grid}\n aria-busy={isLoading || undefined}\n className={cn(grid.className, isLoading && \"opacity-60\")}\n >\n {products.map((product, index) => (\n <ProductCard\n key={product.id}\n product={product}\n position={(page - 1) * pageSize + index}\n href={productHref(product)}\n onAdd={addFor(product)}\n renderItem={renderItem}\n />\n ))}\n </ul>\n );\n }\n\n return (\n <CardAnalyticsContext.Provider value={cardAnalytics}>\n <div\n ref={content}\n tabIndex={-1}\n className=\"p-1 outline-none scroll-mt-4\"\n >\n {body}\n {pageCount > 1 && error == null ? (\n <Pagination\n page={page}\n pageCount={pageCount}\n isLoading={isLoading}\n onPage={changePage}\n />\n ) : null}\n </div>\n </CardAnalyticsContext.Provider>\n );\n}\n\nconst defaultProductHref = (product: PublicListProduct) =>\n `/p/${encodeURIComponent(product.uniqueSlug)}`;\n\n/**\n * Responsive grid of the shop's products with pagination, loading, empty and\n * error states. Cards link to the product page and can add to the cart.\n *\n * ```tsx\n * <ProductList projectID=\"…\" locale=\"pl-PL\" initialData={firstPage} />\n * ```\n *\n * It renders on the server: pass `initialData` (the first page, fetched on the\n * server) to have the products in the HTML; without it the server renders the\n * loading skeleton and the browser fetches the first page.\n */\nexport function ProductList({\n productHref = defaultProductHref,\n appearance,\n texts,\n renderItem,\n onAddToCart,\n showCartOnAdd = true,\n className,\n analytics,\n ...options\n}: ProductListProps) {\n const instrument: Instrument = useInstrument(\n options.projectID,\n analytics,\n \"catalog\",\n );\n const locale = options.locale ?? DEFAULT_LOCALE;\n const resolvedAppearance = useMemo(\n () => resolveProductListAppearance(appearance),\n [appearance],\n );\n const resolvedTexts = useMemo(\n () => resolveProductListTexts(locale, texts),\n [locale, texts],\n );\n const context = useMemo(\n () => ({ appearance: resolvedAppearance, texts: resolvedTexts, locale }),\n [resolvedAppearance, resolvedTexts, locale],\n );\n const root = getProductListSlotAppearance(resolvedAppearance, \"root\");\n\n return (\n <InstrumentProvider value={instrument}>\n <ProductListContext.Provider value={context}>\n <div\n data-bitsnap-products=\"root\"\n data-bitsnap-products-slot=\"root\"\n className={cn(\n \"bitsnap-react\",\n resolvedAppearance.boundaryClassName,\n className,\n root?.className,\n )}\n style={\n { ...resolvedAppearance.boundaryStyle, ...root?.style } as CSSProperties\n }\n >\n <ProductListContent\n options={options}\n productHref={productHref}\n renderItem={renderItem}\n onAddToCart={onAddToCart}\n showCartOnAdd={showCartOnAdd}\n />\n </div>\n </ProductListContext.Provider>\n </InstrumentProvider>\n );\n}\n","import { normalizeHost } from \"./fetch\";\n\nexport type CartState = {\n /** Project the page cart is set up for, `null` or `undefined` when none yet. */\n projectID: string | null | undefined;\n /** Backend origin the page cart currently talks to. */\n host: string;\n /** Backend origin used when the page did not choose another one. */\n defaultHost: string;\n};\n\nexport type CartTarget = {\n projectID: string;\n /** Omitted or empty keeps the current host. */\n host?: string;\n};\n\nexport type CartPlan =\n | { ok: true; setProjectID: string | null; setHost: string | null }\n | { ok: false; reason: string };\n\n/**\n * Decides, without changing anything, whether the page cart can serve the\n * target and what has to be filled in first. Both the project and the host are\n * checked before the caller changes either of them, so a refused click leaves\n * the page cart untouched.\n */\nexport function planCartTarget(state: CartState, target: CartTarget): CartPlan {\n if (state.projectID != null && state.projectID !== target.projectID) {\n return {\n ok: false,\n reason: `the page cart already belongs to project \"${state.projectID}\"`,\n };\n }\n\n let setHost: string | null = null;\n const targetHost = target.host ? normalizeHost(target.host) : \"\";\n const currentHost = normalizeHost(state.host);\n if (targetHost && targetHost !== currentHost) {\n if (currentHost !== normalizeHost(state.defaultHost)) {\n return {\n ok: false,\n reason: `the page cart already uses the host \"${state.host}\"`,\n };\n }\n setHost = targetHost;\n }\n\n return {\n ok: true,\n setProjectID: state.projectID == null ? target.projectID : null,\n setHost,\n };\n}\n","import { noopInstrument, type Instrument } from \"@/src/analytics/instrument\";\nimport { DEFAULT_HOST, HOST, setCustomHost } from \"../checkout/constants\";\nimport { planCartTarget } from \"./cart-target\";\nimport type { PublicListProduct } from \"./fetch\";\n\nexport type AddToCartTarget = {\n projectID: string;\n /** Backend origin the cart talks to. Omitted or empty keeps the current one. */\n host?: string;\n /** Open the cart drawer afterwards. */\n showCart: boolean;\n /** Where `add_to_cart` is reported. Omitted: nothing is reported. */\n analytics?: Instrument;\n};\n\n/** `add_to_cart` for a product of the list (quantity 1, price in minor units). */\nexport function trackProductAdded(\n instrument: Instrument,\n product: PublicListProduct,\n) {\n const variant =\n product.cartItemId != null && product.cartItemId !== product.id\n ? product.cartItemId\n : null;\n instrument.track(\n \"add_to_cart\",\n { qty: 1, value_minor: product.price, currency: product.currency },\n { product_id: product.id, variant_id: variant },\n );\n}\n\n/**\n * Default \"add to cart\" action of `ProductList`: `Bitsnap.addProductToCart`\n * with quantity 1, then the cart drawer.\n *\n * The checkout is a heavy module (RPC client, cart state, payment buttons), so\n * it is loaded on the first click and never ends up in the first paint of a\n * catalog page. The cart only knows one project and one host at a time, and\n * they are page-wide (the cart is kept in localStorage, `setProjectID` also\n * changes the panel configuration). So the list only fills them in when the\n * page has not set them yet; when the page already works for another project\n * or host, nothing is changed and the call fails (pass `onAddToCart` to the\n * list in that case).\n */\nexport async function addProductToCart(\n product: PublicListProduct,\n target: AddToCartTarget,\n): Promise<void> {\n const [{ Bitsnap }, { getProjectID, setProjectID }] = await Promise.all([\n import(\"../checkout/methods\"),\n import(\"../checkout/CartProvider\"),\n ]);\n\n const plan = planCartTarget(\n { projectID: getProjectID(), host: HOST, defaultHost: DEFAULT_HOST },\n target,\n );\n if (!plan.ok) {\n return failConflict(plan.reason);\n }\n if (plan.setProjectID != null) {\n setProjectID(plan.setProjectID);\n }\n if (plan.setHost != null) {\n setCustomHost(plan.setHost);\n }\n\n // Single-variant products are added by their variant, not the product ID.\n const error = await Bitsnap.addProductToCart(\n product.cartItemId ?? product.id,\n 1,\n undefined,\n {\n name: product.name,\n price: product.price,\n currency: product.currency,\n // Reported below from the list's own data.\n analytics: noopInstrument,\n },\n );\n if (error != null) {\n throw new Error(\"Could not add the product to the cart\");\n }\n if (target.analytics != null) {\n trackProductAdded(target.analytics, product);\n }\n\n if (target.showCart) {\n Bitsnap.showCart();\n }\n}\n\nfunction failConflict(reason: string): never {\n console.warn(\n `bitsnap-react: ProductList did not add to the cart because ${reason}. ` +\n \"Pass onAddToCart to use another cart.\",\n );\n throw new Error(\"The page cart belongs to another project or host\");\n}\n","import { getTracker } from \"@/src/analytics/core\";\n\n/** Matches the contract's `positions` / `product_ids` array limit. */\nconst MAX_PER_EVENT = 50;\nconst FLUSH_DELAY_MS = 1000;\n\nexport type ImpressionBatch = { productIds: string[]; positions: number[] };\n\n/**\n * Collects the products that were at least half visible, each one once, and\n * hands them over in batches. Without `IntersectionObserver` nothing is\n * reported. Never throws.\n */\nexport function createImpressionTracker(\n onBatch: (batch: ImpressionBatch) => void,\n delayMs = FLUSH_DELAY_MS,\n) {\n const seen = new Set<string>();\n const targets = new Map<Element, { id: string; position: number }>();\n let pendingIds: string[] = [];\n let pendingPositions: number[] = [];\n let observer: IntersectionObserver | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let listening = false;\n\n function flush() {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n while (pendingIds.length > 0) {\n const productIds = pendingIds.slice(0, MAX_PER_EVENT);\n const positions = pendingPositions.slice(0, MAX_PER_EVENT);\n pendingIds = pendingIds.slice(MAX_PER_EVENT);\n pendingPositions = pendingPositions.slice(MAX_PER_EVENT);\n try {\n onBatch({ productIds, positions });\n } catch {}\n }\n }\n\n // The tracker flushes its own queue on `pagehide`; ours must be in it by then.\n function flushAll() {\n flush();\n try {\n getTracker()?.flush();\n } catch {}\n }\n const onVisibility = () => {\n if (typeof document !== \"undefined\" && document.visibilityState === \"hidden\") flushAll();\n };\n\n function listen() {\n if (listening || typeof window === \"undefined\") return;\n listening = true;\n window.addEventListener(\"pagehide\", flushAll, true);\n document.addEventListener(\"visibilitychange\", onVisibility, true);\n }\n\n function getObserver(): IntersectionObserver | undefined {\n if (observer) return observer;\n if (typeof IntersectionObserver === \"undefined\") return undefined;\n observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n const target = targets.get(entry.target);\n if (!target || !entry.isIntersecting || entry.intersectionRatio < 0.5) continue;\n targets.delete(entry.target);\n observer?.unobserve(entry.target);\n if (seen.has(target.id)) continue;\n seen.add(target.id);\n pendingIds.push(target.id);\n pendingPositions.push(target.position);\n }\n if (pendingIds.length > 0 && timer === undefined) {\n timer = setTimeout(flush, delayMs);\n (timer as { unref?: () => void }).unref?.();\n }\n },\n { threshold: [0.5] },\n );\n listen();\n return observer;\n }\n\n return {\n /** Starts watching a card. Returns a function that stops. */\n observe(element: Element, id: string, position: number): () => void {\n try {\n if (seen.has(id)) return () => {};\n const watcher = getObserver();\n if (!watcher) return () => {};\n targets.set(element, { id, position });\n watcher.observe(element);\n return () => {\n targets.delete(element);\n watcher.unobserve(element);\n };\n } catch {\n return () => {};\n }\n },\n flush,\n destroy() {\n try {\n flush();\n observer?.disconnect();\n if (listening) {\n window.removeEventListener(\"pagehide\", flushAll, true);\n document.removeEventListener(\"visibilitychange\", onVisibility, true);\n listening = false;\n }\n } catch {}\n observer = undefined;\n targets.clear();\n },\n };\n}\n","import {\n lookupText,\n resolveTexts,\n type LocaleTables,\n} from \"@/src/lib/texts\";\n\n/**\n * Every string `ProductList` renders. Pass a partial object through the\n * `texts` prop to override any of them, whatever the locale. Placeholders\n * (`{price}`, `{page}`, `{pageCount}`) are filled by the component.\n */\nexport type ProductListTexts = {\n /** \"Add to cart\" button of products that can be bought straight from the list. */\n addToCart: string;\n /** Button label while the product is being added. */\n addingToCart: string;\n /** Button label after the product was added. */\n addedToCart: string;\n /** Message shown when adding to the cart failed. */\n addToCartError: string;\n /** Link of products with variants, to pick one on the product page. */\n chooseOptions: string;\n /** Link of products that cannot be added from the list (subscriptions). */\n viewProduct: string;\n /** Label of products that are out of stock. */\n unavailable: string;\n /** Badge of subscription products. */\n subscription: string;\n /** Price of products whose variants differ in price. `{price}` is the lowest one. */\n priceFrom: string;\n /** Screen reader label of the struck-through regular price. */\n originalPrice: string;\n /** Accessible label of the loading skeleton. */\n loading: string;\n /** Shown when the shop has no products (or none matches the search). */\n empty: string;\n /** Shown when the products could not be loaded. */\n error: string;\n /** Retry button of the error state. */\n retry: string;\n /** Accessible label of the pagination. */\n pagination: string;\n previousPage: string;\n nextPage: string;\n /** Page indicator. `{page}` and `{pageCount}` are filled in. */\n pageOf: string;\n};\n\nexport type ProductListTextKey = keyof ProductListTexts;\n\nexport const PRODUCT_LIST_TEXT_TABLES: LocaleTables<ProductListTextKey> = {\n en: {\n addToCart: \"Add to cart\",\n addingToCart: \"Adding…\",\n addedToCart: \"Added to cart\",\n addToCartError: \"Could not add to the cart. Try again.\",\n chooseOptions: \"Choose\",\n viewProduct: \"View\",\n unavailable: \"Unavailable\",\n subscription: \"Subscription\",\n priceFrom: \"from {price}\",\n originalPrice: \"Original price\",\n loading: \"Loading products\",\n empty: \"There are no products to show.\",\n error: \"Could not load the products.\",\n retry: \"Try again\",\n pagination: \"Pagination\",\n previousPage: \"Previous\",\n nextPage: \"Next\",\n pageOf: \"Page {page} of {pageCount}\",\n },\n pl: {\n addToCart: \"Dodaj do koszyka\",\n addingToCart: \"Dodawanie…\",\n addedToCart: \"Dodano do koszyka\",\n addToCartError: \"Nie udało się dodać do koszyka. Spróbuj ponownie.\",\n chooseOptions: \"Wybierz\",\n viewProduct: \"Zobacz\",\n unavailable: \"Niedostępny\",\n subscription: \"Subskrypcja\",\n priceFrom: \"od {price}\",\n originalPrice: \"Cena przed obniżką\",\n loading: \"Ładowanie produktów\",\n empty: \"Brak produktów do wyświetlenia.\",\n error: \"Nie udało się załadować produktów.\",\n retry: \"Spróbuj ponownie\",\n pagination: \"Paginacja\",\n previousPage: \"Poprzednia\",\n nextPage: \"Następna\",\n pageOf: \"Strona {page} z {pageCount}\",\n },\n};\n\n/** Default texts for a locale merged with the caller overrides. */\nexport function resolveProductListTexts(\n locale: string,\n overrides?: Partial<ProductListTexts>,\n): ProductListTexts {\n return resolveTexts(PRODUCT_LIST_TEXT_TABLES, locale, overrides);\n}\n\nexport function getProductListText(\n key: ProductListTextKey,\n locale: string,\n overrides?: Partial<ProductListTexts>,\n): string {\n return lookupText(resolveProductListTexts(locale, overrides), key);\n}\n\n/** Replaces `{name}` placeholders. Unknown placeholders stay untouched. */\nexport function fillProductListText(\n text: string,\n values: Record<string, string | number>,\n): string {\n return text.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n name in values ? String(values[name]) : match,\n );\n}\n"],"mappings":"0NA2DO,IAAMA,GAA0B,CACrC,OACA,OACA,OACA,WACA,QACA,mBACA,OACA,OACA,cACA,QACA,eACA,QACA,UACA,kBACA,eACA,UACA,aACA,mBACA,gBACA,aACA,QACA,cACA,UACF,EA8BaC,GAA+B,CAC1C,WAAY,iCACZ,SAAU,+BACV,WAAY,gCACZ,QAAS,6BACT,WAAY,gCACZ,gBAAiB,sCACjB,OAAQ,4BACR,iBAAkB,uCAClB,iBAAkB,uCAClB,sBAAuB,6CACvB,aAAc,mCACd,UAAW,gCACX,MAA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,EACZ,YAAayC,EACb,cAAeC,EACjB,EACF,EACF,EACA,CAEJ","names":["PRODUCT_LIST_SLOT_NAMES","PRODUCT_LIST_TOKEN_VARIABLES","PRODUCT_LIST_THEME_PRESETS","PRODUCT_LIST_SHADCN_VARIABLES","resolveProductListAppearance","appearance","resolved","resolveAppearanceCore","getProductListSlotAppearance","slot","getSlotAppearance","createFormatter","locale","currency","formatProductPrice","amount","DEFAULT_LOCALE","value","formatter","useCallback","useEffect","useMemo","useState","DEFAULT_PAGE_SIZE","MAX_PAGE_SIZE","ProductListError","message","status","clampPageSize","pageSize","pageCountFor","totalCount","normalizeHost","host","buildProductListURL","query","params","search","isProductListData","value","fetchProductList","signal","response","withClientParam","payload","useProducts","options","projectID","locale","search","initialData","defaultHost","useState","HOST","host","pageSize","clampPageSize","queryKey","pageState","setPageState","reloads","setReloads","snapshot","setSnapshot","totalCount","pageCount","pageCountFor","requestedPage","page","requestKey","isCurrent","useEffect","controller","fetchProductList","data","error","previous","setPage","useCallback","next","target","refetch","value","useMemo","createContext","useCallback","useContext","useEffect","useMemo","useRef","useState","planCartTarget","state","target","setHost","targetHost","normalizeHost","currentHost","trackProductAdded","instrument","product","variant","addProductToCart","target","Bitsnap","getProjectID","setProjectID","plan","planCartTarget","HOST","DEFAULT_HOST","failConflict","setCustomHost","noopInstrument","reason","MAX_PER_EVENT","FLUSH_DELAY_MS","createImpressionTracker","onBatch","delayMs","seen","targets","pendingIds","pendingPositions","observer","timer","listening","flush","productIds","positions","flushAll","getTracker","onVisibility","listen","getObserver","entries","entry","target","element","id","position","watcher","PRODUCT_LIST_TEXT_TABLES","resolveProductListTexts","locale","overrides","resolveTexts","fillProductListText","text","values","match","name","Fragment","jsx","jsxs","ProductListContext","createContext","noCardAnalytics","CardAnalyticsContext","useListContext","value","useContext","useSlot","slot","className","appearance","override","getProductListSlotAppearance","cn","BUTTON_CLASS","BLOCK_BUTTON_CLASS","LINK_BUTTON_CLASS","AddToCartButton","product","onAdd","texts","status","setStatus","useState","button","message","useEffect","timer","click","useCallback","error","label","ProductCard","position","href","renderItem","locale","analytics","element","useRef","trackClick","card","cardLink","imageFrame","placeholder","body","name","description","price","comparePrice","badge","actions","selectButton","formattedPrice","formatProductPrice","formattedCompare","imageSource","badgeText","fillProductListText","GRID_CLASS","SkeletonGrid","count","grid","skeleton","_","index","Pagination","page","pageCount","isLoading","onPage","nav","indicator","ProductListContent","options","productHref","onAddToCart","showCartOnAdd","products","setPage","refetch","useProducts","instrument","useInstrumentContext","listId","pageSize","clampPageSize","viewed","impressions","useMemo","createImpressionTracker","productIds","positions","cardAnalytics","content","movedPage","changePage","next","empty","errorSlot","retry","projectID","host","addFor","withCartAnalyticsMuted","trackProductAdded","addProductToCart","defaultProductHref","ProductList","useInstrument","DEFAULT_LOCALE","resolvedAppearance","resolveProductListAppearance","resolvedTexts","resolveProductListTexts","context","root","InstrumentProvider"]}
@@ -0,0 +1,2 @@
1
+ import{a as Xe,b as Ge}from"./chunk-KOVKUJAW.mjs";import{i as xe,j as _,m as Ye,n as He,q as v,r as Se,t as We,u as Ze,v as $e}from"./chunk-HKVMSMDF.mjs";import{d as i,i as Je,m as et}from"./chunk-RA452LXZ.mjs";import{j as Qe,k as se,l as Ve}from"./chunk-XVQKEGPO.mjs";var vr=["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"],zt={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"},Dt={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"}},Ot=[{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 ve(e){let r=Xe(e,{defaultTheme:"light",presets:Dt,variables:zt,shadcnVariables:Ot});return{theme:r.theme,tokens:r.tokens,elements:r.elements,boundaryClassName:r.theme,boundaryStyle:r.boundaryStyle}}function tt(e,r){return Ge(e.elements,r)}import{createContext as Ft,useContext as Mt,useMemo as qt}from"react";import{jsx as Kt}from"react/jsx-runtime";var rt=Ft(ve());function nt({appearance:e,children:r}){let t=qt(()=>ve(e),[e]);return Kt(rt.Provider,{value:t,children:r})}function Ne(){return Mt(rt)}function l(e){let r=Ne();return tt(r,e)??{}}function ot(e){return e==="test"||e===1?1:0}var st={title:["emailStepTitle"],email:["emailLabel"],sendCode:["emailSubmit"],code:["codeLabel"],verify:["codeSubmit"],orders:["ordersTitle"],submit:["confirmationSubmit"],note:["noteLabel"],history:["myReturnsTitle","myReturnsLink"]};function at(e){if(e==null)return;let r={};for(let[t,n]of Object.entries(st)){let o=e[t];if(typeof o=="string")for(let u of n)r[u]=o}for(let t of Object.keys(e)){if(t in st)continue;let n=e[t];typeof n=="string"&&(r[t]=n)}return r}function it(e,r){let t=r?.brandColor?.trim();return t==null||t===""?e:{...e,tokens:{...We(t),...e?.tokens}}}function he(e,r){return typeof e=="object"&&e!=null?{pageSize:e.pageSize??20,explicitPageToken:void 0}:typeof e=="number"||r!==void 0?{pageSize:e??20,explicitPageToken:r??""}:{pageSize:20,explicitPageToken:void 0}}var _t={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",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.",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",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.",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 ke(e,r){return Je(_t,e,r)}function ut(e,r){return e.replace(/\{(\w+)\}/g,(t,n)=>Object.prototype.hasOwnProperty.call(r,n)?String(r[n]):t)}var jt={submitted:"statusSubmitted",approved:"statusApproved",rejected:"statusRejected",awaiting_receipt:"statusAwaitingReceipt",received:"statusReceived",completed:"statusCompleted",cancelled:"statusCancelled",refunded:"statusRefunded"},Ut={not_started:"refundStatusNotStarted",pending:"refundStatusPending",succeeded:"refundStatusSucceeded",failed:"refundStatusFailed"};function lt(e){return jt[e]??"statusFallback"}function ct(e){return Ut[e]??"refundStatusFallback"}import{createContext as Qt,useCallback as Vt,useContext as dt,useMemo as Yt}from"react";import{jsx as Ht}from"react/jsx-runtime";var Te=Qt({locale:"pl-PL",texts:ke("pl-PL")});function pt({texts:e,locale:r,children:t}){let n=r??et(),o=Yt(()=>({locale:n,texts:ke(n,e)}),[n,e]);return Ht(Te.Provider,{value:o,children:t})}function h(){let{texts:e}=dt(Te);return Vt((r,t)=>t==null?e[r]:ut(e[r],t),[e])}function Y(){return dt(Te).locale}import{createClient as $t}from"@connectrpc/connect";import{createConnectQueryKey as Xt,TransportProvider as Gt}from"@connectrpc/connect-query";import{QueryClient as Jt,QueryClientContext as er,QueryClientProvider as tr,useQueryClient as rr}from"@tanstack/react-query";import{createContext as nr,useCallback as Ee,useContext as gt,useEffect as ft,useMemo as ie,useRef as sr,useState as ue}from"react";import{timestampMs as Wt}from"@bufbuild/protobuf/wkt";var Zt="bitsnap-returns-session:";function we(e){return`${Zt}${e}`}function oe(){try{return typeof window<"u"?window.sessionStorage:void 0}catch{return}}function mt(e,r,t=Date.now()){if(e==null)return;let n=we(r);try{let o=e.getItem(n);if(o==null)return;let u=JSON.parse(o);if(u!=null&&typeof u=="object"&&typeof u.token=="string"&&u.token.length>0&&typeof u.expiresAt=="number"&&u.expiresAt>t){let{token:s,expiresAt:a}=u;return{token:s,expiresAt:a}}e.removeItem(n)}catch{try{e.removeItem(n)}catch{}}}function yt(e,r,t){try{e?.setItem(we(r),JSON.stringify(t))}catch{}}function Ie(e,r){try{e?.removeItem(we(r))}catch{}}function ae(e){return e==null?void 0:Wt(e)}import{jsx as j}from"react/jsx-runtime";var Rt=nr(void 0);function T(e){let r=gt(Rt);if(r==null)throw new Error(`${e} must be rendered inside <ReturnsProvider>`);return r}function Ce(){return Xt({schema:xe,cardinality:void 0})}var or=2**31-1;function ar({projectID:e,environment:r,transport:t,panelAccessToken:n,className:o,children:u}){let s=rr(),{boundaryClassName:a,boundaryStyle:y}=Ne(),m=l("root"),[p,f]=ue({status:"hydrating"}),[c,b]=ue(),[g,C]=ue(),I=sr(void 0),N=Ee(()=>{s.removeQueries({queryKey:Ce()})},[s]),B=Ee(()=>{Ie(oe(),e),C(void 0),f({status:"anonymous"}),N()},[e,N]),w=Ee(k=>{yt(oe(),e,k),b(void 0),C(void 0),f({status:"authenticated",token:k.token,expiresAt:k.expiresAt})},[e]);ft(()=>{let k=!1,Q=oe();if(n==null||n===""){let O=I.current!=null;if(I.current=void 0,O){B();return}let q=mt(Q,e);f(q!=null?{status:"authenticated",token:q.token,expiresAt:q.expiresAt}:{status:"anonymous"});return}return I.current=n,Ie(Q,e),N(),b(void 0),f({status:"exchanging"}),$t(xe,t).exchangePanelSession({projectId:e,accessToken:n,environment:r}).then(O=>{if(k)return;let q=ae(O.expiresAt);if(O.sessionToken===""||q==null)throw new Error("EMPTY_SESSION");w({token:O.sessionToken,expiresAt:q})}).catch(O=>{k||(b(O),f({status:"anonymous"}))}),()=>{k=!0}},[n,e,r,t]),ft(()=>{if(p.status!=="authenticated"||p.expiresAt==null)return;let k=p.expiresAt-Date.now();if(k<=0){B();return}let Q=setTimeout(B,Math.min(k,or));return()=>clearTimeout(Q)},[p.status,p.expiresAt,B]);let P=ie(()=>({projectID:e,environment:r,status:p.status,token:p.token,exchangeError:c,challenge:g,setChallenge:C,authenticate:w,clearSession:B}),[e,r,p.status,p.token,c,g,w,B]);return j(Rt.Provider,{value:P,children:j("div",{"data-bitsnap-returns":"root","data-bitsnap-returns-slot":"root",className:i("bitsnap-react",a,o,m.className),style:{...y,...m.style},children:u})})}function ir({projectID:e,host:r,environment:t,appearance:n,texts:o,theme:u,locale:s,panelAccessToken:a,className:y,analytics:m,children:p}){let f=Ve(e,m,"returns"),c=gt(er),[b]=ue(()=>c==null?new Jt({defaultOptions:{queries:{staleTime:5e3}}}):void 0),g=r??Ye(),C=ie(()=>He(g),[g]),I=u?.brandColor,N=ie(()=>it(n,{brandColor:I}),[n,I]),B=ie(()=>at(o),[o]),w=j(Qe,{value:f,children:j(Gt,{transport:C,children:j(nt,{appearance:N,children:j(pt,{texts:B,locale:s,children:j(ar,{projectID:e,environment:ot(t),transport:C,panelAccessToken:a,className:y,children:p})})})})});return c==null&&b!=null?j(tr,{client:b,children:w}):w}var Xr=ir;import{useMutation as Ae,useQuery as le}from"@connectrpc/connect-query";import{useQueryClient as lr}from"@tanstack/react-query";import{useCallback as K,useEffect as vt,useRef as cr,useState as dr}from"react";var ur="SESSION_EXPIRED",bt={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 xt(e){if(e==null||typeof e!="object")return;let{rawMessage:r,message:t}=e;if(typeof r=="string"&&r.length>0)return r;if(typeof t=="string")return Object.keys(bt).find(n=>t.includes(n))}function Pe(e){return xt(e)===ur}function St(e){let r=xt(e);return(r!=null?bt[r]:void 0)??"errorGeneric"}function Le(){let e=typeof globalThis<"u"?globalThis.crypto:void 0;if(typeof e?.randomUUID=="function")return e.randomUUID();let r=new Uint8Array(16);if(typeof e?.getRandomValues=="function")e.getRandomValues(r);else for(let t=0;t<r.length;t++)r[t]=Math.floor(Math.random()*256);return Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}function $(e){return e==null?null:e instanceof Error?e:new Error(String(e))}function X(e){return e==null?void 0:St(e)}function ce(e,r){vt(()=>{Pe(e)&&r()},[e,r])}function Nt(e){let[r,t]=dr([""]);return vt(()=>{t([""])},[e]),{pageToken:r[r.length-1]??"",page:r.length,push:n=>t(o=>[...o,n]),pop:()=>t(n=>n.length>1?n.slice(0,-1):n)}}function de(){let e=T("useReturnSession"),r=Ae(_.returns.startReturnSession),t=Ae(_.returns.verifyReturnSession),{setChallenge:n,authenticate:o,clearSession:u}=e,s=K(async c=>{t.reset();let b=c.trim(),g=await r.mutateAsync({projectId:e.projectID,email:b,environment:e.environment});return n({challengeId:g.challengeId,email:b,resendAvailableAt:Date.now()+Math.max(0,g.resendAfterSeconds)*1e3}),g},[e.projectID,e.environment,n,r,t]),a=K(async c=>{let b=await t.mutateAsync({projectId:e.projectID,challengeId:c.challengeId,code:c.code,environment:e.environment}),g=ae(b.expiresAt);if(b.sessionToken===""||g==null)throw new Error("EMPTY_SESSION");return o({token:b.sessionToken,expiresAt:g}),b},[e.projectID,e.environment,o,t]),y=K(async c=>{try{return await s(c),!0}catch{return!1}},[s]),m=K(async c=>{if(e.challenge==null)return!1;try{return await a({challengeId:e.challenge.challengeId,code:c.trim()}),!0}catch{return!1}},[e.challenge,a]),p=K(()=>e.challenge!=null?y(e.challenge.email):Promise.resolve(!1),[e.challenge,y]),f=$(r.error??t.error??e.exchangeError);return{status:e.status,isAuthenticated:e.status==="authenticated",challenge:e.challenge,isStarting:r.isPending,isVerifying:t.isPending,starting:r.isPending,verifying:t.isPending,error:f,errorKey:X(f),start:y,startSession:s,verifySession:a,verify:m,resend:p,logout:u}}function pe(e){return e.status==="hydrating"||e.status==="exchanging"}function ht(e,r){let t=T("useReturnOrders"),{pageSize:n,explicitPageToken:o}=he(e,r),u=Nt(t.token),s=le(_.returns.listReturnOrders,{projectId:t.projectID,sessionToken:t.token??"",pageSize:n,pageToken:o??u.pageToken},{enabled:t.token!=null});ce(s.error,t.clearSession);let a=s.data?.nextPageToken??"";return{orders:s.data?.orders??[],total:s.data?.total??0,data:s.data,isLoading:pe(t)||s.isLoading,isFetching:s.isFetching,error:$(s.error),errorKey:X(s.error),status:s.status,isError:s.isError,isSuccess:s.isSuccess,page:u.page,hasNext:a!=="",hasPrevious:u.page>1,next:()=>{a!==""&&u.push(a)},previous:u.pop,refetch:()=>s.refetch()}}function Be(e){let r=T("useReturnableOrder"),t=le(_.returns.getReturnableOrder,{projectId:r.projectID,sessionToken:r.token??"",canonicalOrderId:e??""},{enabled:r.token!=null&&e!=null&&e!==""});return ce(t.error,r.clearSession),{order:t.data?.order,returnHistory:t.data?.returnHistory??[],data:t.data,isLoading:e!=null&&e!==""&&(pe(r)||t.isLoading),error:$(t.error),errorKey:X(t.error),status:t.status,isError:t.isError,isSuccess:t.isSuccess,refetch:()=>t.refetch()}}function kt(){let e=T("useCreateReturn"),r=lr(),t=Ae(_.returns.createReturnRequest),n=se(),o=cr(void 0),{clearSession:u}=e,s=K(async(p,f)=>{try{let c=await t.mutateAsync({projectId:e.projectID,sessionToken:e.token??"",canonicalOrderId:p.orderId,items:p.items,note:p.note??"",idempotencyKey:f});return r.invalidateQueries({queryKey:Ce()}),n.track("return_submitted",{reason_code:"unspecified",item_count:p.items.length},{order_ref:null}),c}catch(c){throw Pe(c)&&u(),c}},[e.projectID,e.token,t,r,u,n]),a=K(async p=>{o.current??=Le();try{let f=await s(p,o.current);return o.current=void 0,f.request}catch{return}},[s]),y=K(async p=>{if(e.token==null)throw new Error("Verify your email to continue.");return s({orderId:p.canonicalOrderID,items:p.items,note:p.note},p.idempotencyKey??Le())},[e.token,s]),m=K((p,f)=>{y(p).then(c=>f?.onSuccess?.(c),c=>f?.onError?.($(c)))},[y]);return{submit:a,isPending:t.isPending,error:$(t.error),errorKey:X(t.error),mutateAsync:y,mutate:m,data:t.data,reset:t.reset,status:t.status,isError:t.isError,isSuccess:t.isSuccess}}function Tt(e,r){let t=T("useMyReturns"),{pageSize:n,explicitPageToken:o}=he(e,r),u=Nt(t.token),s=le(_.returns.listMyReturns,{projectId:t.projectID,sessionToken:t.token??"",pageSize:n,pageToken:o??u.pageToken},{enabled:t.token!=null});ce(s.error,t.clearSession);let a=s.data?.nextPageToken??"";return{returns:s.data?.returns??[],total:s.data?.total??0,data:s.data,isLoading:pe(t)||s.isLoading,isFetching:s.isFetching,error:$(s.error),errorKey:X(s.error),status:s.status,isError:s.isError,isSuccess:s.isSuccess,page:u.page,hasNext:a!=="",hasPrevious:u.page>1,next:()=>{a!==""&&u.push(a)},previous:u.pop,refetch:()=>s.refetch()}}function me(e){let r=T("useMyReturn"),t=le(_.returns.getMyReturn,{projectId:r.projectID,sessionToken:r.token??"",returnId:e},{enabled:r.token!=null});return ce(t.error,r.clearSession),{request:t.data?.request,isLoading:pe(r)||t.isLoading,error:t.error,errorKey:X(t.error),refetch:()=>t.refetch()}}import{useEffect as fr,useState as De}from"react";import*as wt from"@radix-ui/react-label";import{jsx as pr}from"react/jsx-runtime";function te({className:e,...r}){return pr(wt.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),...r})}import{Loader2Icon as mr}from"lucide-react";import{jsx as yr}from"react/jsx-runtime";function re({className:e,...r}){return yr(mr,{role:"status","aria-label":"Loading",className:i("size-4 animate-spin",e),...r})}import{jsx as z,jsxs as ye}from"react/jsx-runtime";var H="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",L="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",G="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";function M({title:e,description:r,onBack:t,className:n,children:o}){let u=h(),s=l("header"),a=l("title"),y=l("description"),m=l("backButton");return ye("section",{className:i("flex flex-col gap-5",n),children:[ye("div",{"data-bitsnap-returns-slot":"header",className:i("flex flex-col gap-2",s.className),style:s.style,children:[t!=null&&z(v,{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)]",m.className),style:m.style,onClick:t,children:u("back")}),z("h2",{"data-bitsnap-returns-slot":"title",className:i("text-2xl font-semibold",a.className),style:a.style,children:e}),r!=null&&z("p",{"data-bitsnap-returns-slot":"description",className:i("text-sm",y.className),style:y.style,children:r})]}),o]})}function A({errorKey:e,onRetry:r}){let t=h(),n=l("error"),o=l("secondaryButton");return ye("div",{role:"alert","data-bitsnap-returns-slot":"error",className:i("flex flex-col items-start gap-2 text-sm",n.className),style:n.style,children:[z("p",{children:t(e)}),r!=null&&z(v,{type:"button",variant:"secondary",size:"sm","data-bitsnap-returns-slot":"secondaryButton",className:i(L,o.className),style:o.style,onClick:r,children:t("errorRetry")})]})}function fe({children:e}){let r=l("emptyState");return z("p",{"data-bitsnap-returns-slot":"emptyState",className:i("py-6 text-center text-sm",r.className),style:r.style,children:e})}function U({rows:e=3}){let r=h(),t=l("skeleton");return z("div",{role:"status","aria-busy":"true","aria-label":r("loading"),className:"flex flex-col gap-3",children:Array.from({length:e},(n,o)=>z(Ze,{"data-bitsnap-returns-slot":"skeleton",className:i("h-16 w-full bg-[var(--bitsnap-returns-hover-surface,#f4f4f5)]",t.className),style:t.style},o))})}function J({status:e}){let r=h(),t=l("statusBadge");return z("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",t.className),style:t.style,children:r(lt(e))})}function ze(){let e=h();return r=>e(ct(r))}function ge({page:e,total:r,hasNext:t,hasPrevious:n,isFetching:o,onNext:u,onPrevious:s}){let a=h(),y=l("pagination"),m=l("secondaryButton");return!t&&!n?null:ye("nav",{"data-bitsnap-returns-slot":"pagination",className:i("flex items-center justify-between gap-3 text-sm",y.className),style:y.style,children:[z(v,{type:"button",variant:"secondary",size:"sm","data-bitsnap-returns-slot":"secondaryButton",className:i(L,m.className),style:m.style,disabled:!n||o,onClick:s,children:a("paginationPrevious")}),z("span",{"aria-live":"polite",children:a("paginationInfo",{page:e,total:r})}),z(v,{type:"button",variant:"secondary",size:"sm","data-bitsnap-returns-slot":"secondaryButton",className:i(L,m.className),style:m.style,disabled:!t||o,onClick:u,children:a("paginationNext")})]})}import{jsx as D,jsxs as W}from"react/jsx-runtime";function Kn({onSubmitted:e,className:r}){T("ReturnsEmailStep");let t=h(),n=de(),[o,u]=De(""),s=l("emailForm"),a=l("emailInput"),y=l("submitButton");async function m(p){p.preventDefault(),!n.isStarting&&await n.start(o)&&e?.(o.trim())}return D(M,{className:r,title:t("emailStepTitle"),description:t("emailStepDescription"),children:W("form",{"data-bitsnap-returns-slot":"emailForm",className:i("flex flex-col gap-4",s.className),style:s.style,onSubmit:m,children:[W("div",{className:"flex flex-col gap-2",children:[D(te,{htmlFor:"bitsnap-returns-email",children:t("emailLabel")}),D(Se,{id:"bitsnap-returns-email",type:"email",name:"email",autoComplete:"email",required:!0,value:o,placeholder:t("emailPlaceholder"),disabled:n.isStarting,"data-bitsnap-returns-slot":"emailInput",className:i(G,a.className),style:a.style,onChange:p=>u(p.target.value)})]}),n.errorKey!=null&&D(A,{errorKey:n.errorKey}),W(v,{type:"submit",disabled:n.isStarting,"data-bitsnap-returns-slot":"submitButton",className:i(H,y.className),style:y.style,children:[n.isStarting&&D(re,{}),t("emailSubmit")]})]})})}function gr(e){let[r,t]=De();return fr(()=>{if(e==null)return;t(Date.now());let n=setInterval(()=>{let o=Date.now();t(o),o>=e&&clearInterval(n)},1e3);return()=>clearInterval(n)},[e]),e!=null&&r!=null?Math.max(0,Math.ceil((e-r)/1e3)):0}function _n({onVerified:e,onBack:r,className:t}){T("ReturnsCodeStep");let n=h(),o=de(),[u,s]=De(""),a=gr(o.challenge?.resendAvailableAt),y=l("codeForm"),m=l("codeInput"),p=l("submitButton"),f=l("resendButton"),c=o.isVerifying||o.isStarting;async function b(g){g.preventDefault(),!c&&await o.verify(u)&&e?.()}return D(M,{className:t,onBack:r,title:n("codeStepTitle"),description:n("codeStepDescription",{email:o.challenge?.email??""}),children:W("form",{"data-bitsnap-returns-slot":"codeForm",className:i("flex flex-col gap-4",y.className),style:y.style,onSubmit:b,children:[W("div",{className:"flex flex-col gap-2",children:[D(te,{htmlFor:"bitsnap-returns-code",children:n("codeLabel")}),D(Se,{id:"bitsnap-returns-code",name:"code",inputMode:"numeric",autoComplete:"one-time-code",required:!0,value:u,disabled:c,"data-bitsnap-returns-slot":"codeInput",className:i(G,m.className),style:m.style,onChange:g=>s(g.target.value)})]}),o.errorKey!=null&&D(A,{errorKey:o.errorKey}),W("div",{className:"flex flex-wrap items-center gap-3",children:[W(v,{type:"submit",disabled:c||o.challenge==null,"data-bitsnap-returns-slot":"submitButton",className:i(H,p.className),style:p.style,children:[o.isVerifying&&D(re,{}),n("codeSubmit")]}),D(v,{type:"button",variant:"secondary",disabled:c||a>0||o.challenge==null,"data-bitsnap-returns-slot":"resendButton",className:i(L,f.className),style:f.style,onClick:()=>void o.resend(),children:a>0?n("resendIn",{seconds:a}):n("resend")})]})]})})}function It(){let e=h(),r=de(),t=l("logoutButton");return D(v,{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)]",t.className),style:t.style,onClick:r.logout,children:e("logout")})}import{useEffect as br,useState as Fe}from"react";import{timestampDate as Rr}from"@bufbuild/protobuf/wkt";function Z(e,r){if(e==null)return"";let t=Rr(e);try{return new Intl.DateTimeFormat(r,{dateStyle:"medium"}).format(t)}catch{return t.toISOString().slice(0,10)}}function ee(e,r,t){let n=typeof e=="bigint"?e:BigInt(Math.trunc(e));try{let o=new Intl.NumberFormat(t,{style:"currency",currency:r}),u=o.resolvedOptions().maximumFractionDigits??2;return o.format(Et(n,u))}catch{return`${Et(n,2)} ${r}`}}function Et(e,r){let t=e<BigInt(0),n=t?-e:e;if(r<=0)return`${t?"-":""}${n}`;let o=BigInt(10)**BigInt(r),u=n/o,s=(n%o).toString().padStart(r,"0");return`${t?"-":""}${u}.${s}`}function Ct(e,r){return Number.isFinite(e)?Math.min(Math.max(0,Math.trunc(e)),Math.max(0,r)):0}function Oe(e){return e.eligible&&e.availableQuantity>0}function Pt(e,r){return e.map(t=>({lineId:t,quantity:r[t]??0})).filter(t=>t.quantity>0)}import{Fragment as Lt,jsx as d,jsxs as x}from"react/jsx-runtime";function cs({onSelectOrder:e,onOpenMyReturns:r,showLogout:t=!0,pageSize:n,className:o}){T("ReturnsOrderList");let u=h(),s=Y(),a=ht({pageSize:n}),y=l("orderList"),m=l("orderCard"),p=l("orderReference"),f=l("orderDate"),c=l("orderTotal"),b=l("secondaryButton");return x(M,{className:o,title:u("ordersTitle"),description:u("ordersDescription"),children:[(t||r!=null)&&x("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[r!=null?d(v,{type:"button",variant:"secondary",size:"sm","data-bitsnap-returns-slot":"secondaryButton",className:i(L,b.className),style:b.style,onClick:r,children:u("myReturnsLink")}):d("span",{}),t&&d(It,{})]}),a.isLoading?d(U,{}):a.errorKey!=null?d(A,{errorKey:a.errorKey,onRetry:a.refetch}):a.orders.length===0?d(fe,{children:u("ordersEmpty")}):x(Lt,{children:[d("ul",{"data-bitsnap-returns-slot":"orderList",className:i("flex flex-col gap-3",y.className),style:y.style,children:a.orders.map(g=>x("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:[x("div",{className:"flex flex-col gap-1",children:[d("span",{"data-bitsnap-returns-slot":"orderReference",className:i("font-medium",p.className),style:p.style,children:u("orderTitle",{reference:g.displayReference})}),d("span",{"data-bitsnap-returns-slot":"orderDate",className:i("text-sm",f.className),style:f.style,children:Z(g.purchasedAt,s)}),d("span",{className:"text-sm",children:u("orderReturnableLines",{count:g.returnableLineCount})})]}),x("div",{className:"flex items-center gap-4",children:[d("span",{"data-bitsnap-returns-slot":"orderTotal",className:i("font-medium",c.className),style:c.style,children:ee(g.totalMinor,g.currency,s)}),d(v,{type:"button",variant:"secondary",size:"sm","aria-label":`${u("orderSelect")}: ${u("orderTitle",{reference:g.displayReference})}`,"data-bitsnap-returns-slot":"secondaryButton",className:i(L,b.className),style:b.style,onClick:()=>e?.(g.canonicalOrderId),children:u("orderSelect")})]})]},g.canonicalOrderId))}),d(ge,{page:a.page,total:a.total,hasNext:a.hasNext,hasPrevious:a.hasPrevious,isFetching:a.isFetching,onNext:a.next,onPrevious:a.previous})]})]})}function ds({orderId:e,onContinue:r,onBack:t,initialItems:n,initialNote:o,className:u}){T("ReturnsOrderDetail");let s=se();br(()=>{s.track("return_started",{},{order_ref:null})},[s]);let a=h(),y=Y(),{order:m,returnHistory:p,isLoading:f,errorKey:c,refetch:b}=Be(e),[g,C]=Fe(()=>Object.fromEntries((n??[]).map(R=>[R.lineId,R.quantity]))),[I,N]=Fe(o??""),[B,w]=Fe(!1),P=l("lineList"),k=l("line"),Q=l("lineName"),O=l("linePrice"),q=l("lineQuantityControl"),ne=l("quantityButton"),Me=l("quantityInput"),qe=l("lineIneligibleReason"),Ke=l("noteInput"),_e=l("submitButton"),je=l("history"),Ue=l("historyEntry");function Re(R,V){w(!1),C(F=>({...F,[R.lineId]:Ct(V,R.availableQuantity)}))}function At(R){if(R.preventDefault(),m==null)return;let V=Pt(m.lines.filter(Oe).map(F=>F.lineId),g);if(V.length===0){w(!0);return}r?.({items:V,note:I.trim()})}return d(M,{className:u,onBack:t,title:a("orderDetailTitle",{reference:m?.displayReference??""}),description:a("orderDetailDescription"),children:f?d(U,{}):c!=null?d(A,{errorKey:c,onRetry:b}):m==null?null:x("form",{className:"flex flex-col gap-5",onSubmit:At,children:[d("ul",{"data-bitsnap-returns-slot":"lineList",className:i("flex flex-col gap-3",P.className),style:P.style,children:m.lines.map(R=>{let V=Oe(R),F=g[R.lineId]??0,be=`bitsnap-returns-quantity-${R.lineId}`;return x("li",{"data-bitsnap-returns-slot":"line","data-selected":F>0?"":void 0,"data-ineligible":V?void 0:"",className:i("flex flex-col gap-3 border p-4",k.className),style:k.style,children:[x("div",{className:"flex flex-wrap items-baseline justify-between gap-2",children:[d("span",{"data-bitsnap-returns-slot":"lineName",className:i("font-medium",Q.className),style:Q.style,children:R.name}),d("span",{"data-bitsnap-returns-slot":"linePrice",className:i("text-sm",O.className),style:O.style,children:ee(R.paidUnitMinor,R.currency,y)})]}),V?x("div",{role:"group","aria-label":a("quantityLabel",{name:R.name}),"data-bitsnap-returns-slot":"lineQuantityControl",className:i("flex items-center gap-2",q.className),style:q.style,children:[d(v,{type:"button",variant:"secondary",size:"icon-sm","aria-label":a("quantityDecrease",{name:R.name}),"aria-controls":be,disabled:F<=0,"data-bitsnap-returns-slot":"quantityButton",className:i(L,ne.className),style:ne.style,onClick:()=>Re(R,F-1),children:d("span",{"aria-hidden":"true",children:"-"})}),d("input",{id:be,type:"number",inputMode:"numeric",min:0,max:R.availableQuantity,step:1,value:F,"aria-label":a("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]",G,Me.className),style:Me.style,onChange:Bt=>Re(R,Bt.target.valueAsNumber)}),d(v,{type:"button",variant:"secondary",size:"icon-sm","aria-label":a("quantityIncrease",{name:R.name}),"aria-controls":be,disabled:F>=R.availableQuantity,"data-bitsnap-returns-slot":"quantityButton",className:i(L,ne.className),style:ne.style,onClick:()=>Re(R,F+1),children:d("span",{"aria-hidden":"true",children:"+"})}),d("span",{className:"text-sm",children:a("quantityOfAvailable",{available:R.availableQuantity})})]}):d("p",{"data-bitsnap-returns-slot":"lineIneligibleReason",className:i("text-sm",qe.className),style:qe.style,children:R.exclusionReason!==""?R.exclusionReason:a("lineIneligibleFallback")})]},R.lineId)})}),x("div",{className:"flex flex-col gap-2",children:[d(te,{htmlFor:"bitsnap-returns-note",children:a("noteLabel")}),d($e,{id:"bitsnap-returns-note",name:"note",rows:3,maxLength:1e3,value:I,placeholder:a("notePlaceholder"),"data-bitsnap-returns-slot":"noteInput",className:i(G,"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)]",Ke.className),style:Ke.style,onChange:R=>N(R.target.value)})]}),B&&d(A,{errorKey:"selectionEmpty"}),d(v,{type:"submit","data-bitsnap-returns-slot":"submitButton",className:i(H,_e.className),style:_e.style,children:a("selectionContinue")}),p.length>0&&x("div",{className:"flex flex-col gap-2",children:[d("h3",{className:"text-sm font-medium",children:a("previousReturnsTitle")}),d("ul",{"data-bitsnap-returns-slot":"history",className:i("flex flex-col gap-2",je.className),style:je.style,children:p.map(R=>x("li",{"data-bitsnap-returns-slot":"historyEntry",className:i("flex flex-wrap items-center justify-between gap-2 text-sm",Ue.className),style:Ue.style,children:[d("span",{children:R.reference}),d("span",{children:Z(R.createdAt,y)}),d(J,{status:R.status})]},R.id))})]})]})})}function ps({orderId:e,items:r,note:t,onSubmitted:n,onBack:o,className:u}){T("ReturnsConfirmation");let s=h(),a=Y(),{order:y,isLoading:m,errorKey:p,refetch:f}=Be(e),c=kt(),b=l("summary"),g=l("line"),C=l("lineName"),I=l("linePrice"),N=l("submitButton");async function B(w){if(w.preventDefault(),c.isPending)return;let P=await c.submit({orderId:e,items:r.map(k=>({lineId:k.lineId,quantity:k.quantity})),note:t});P!=null&&n?.(P.id,P)}return d(M,{className:u,onBack:o,title:s("confirmationTitle"),description:s("confirmationDescription"),children:m?d(U,{rows:2}):p!=null?d(A,{errorKey:p,onRetry:f}):x("form",{className:"flex flex-col gap-5",onSubmit:B,children:[x("div",{"data-bitsnap-returns-slot":"summary",className:i("flex flex-col gap-3 border p-4",b.className),style:b.style,children:[d("h3",{className:"text-sm font-medium",children:s("confirmationSummary")}),d("ul",{className:"flex flex-col gap-3",children:r.map(w=>{let P=y?.lines.find(k=>k.lineId===w.lineId);return x("li",{"data-bitsnap-returns-slot":"line",className:i("flex flex-wrap items-baseline justify-between gap-2",g.className),style:g.style,children:[d("span",{"data-bitsnap-returns-slot":"lineName",className:i("font-medium",C.className),style:C.style,children:P?.name??w.lineId}),x("span",{"data-bitsnap-returns-slot":"linePrice",className:i("text-sm",I.className),style:I.style,children:[s("confirmationQuantity",{quantity:w.quantity}),P!=null&&` \xB7 ${ee(P.paidUnitMinor*BigInt(w.quantity),P.currency,a)}`]})]},w.lineId)})}),t!=null&&t!==""&&x("div",{className:"flex flex-col gap-1 text-sm",children:[d("span",{className:"font-medium",children:s("confirmationNote")}),d("span",{className:"whitespace-pre-wrap",children:t})]})]}),c.errorKey!=null&&d(A,{errorKey:c.errorKey}),x(v,{type:"submit",disabled:c.isPending||r.length===0,"data-bitsnap-returns-slot":"submitButton",className:i(H,N.className),style:N.style,children:[c.isPending&&d(re,{}),s("confirmationSubmit")]})]})})}function ms({returnId:e,onContinue:r,onOpenMyReturns:t,className:n}){T("ReturnsResult");let o=h(),{request:u,isLoading:s,errorKey:a,refetch:y}=me(e),m=l("successState"),p=l("returnReference"),f=l("returnInstructions"),c=l("submitButton"),b=l("secondaryButton");return x("section",{className:i("flex flex-col gap-5",n),children:[x("div",{role:"status","data-bitsnap-returns-slot":"successState",className:i("flex flex-col gap-4 border p-5",m.className),style:m.style,children:[d("h2",{className:"text-2xl font-semibold",children:o("successTitle")}),d("p",{className:"text-sm",children:o("successDescription")}),s?d(U,{rows:2}):a!=null?d(A,{errorKey:a,onRetry:y}):u!=null&&x(Lt,{children:[x("div",{className:"flex flex-col gap-1",children:[d("span",{className:"text-sm",children:o("successReference")}),d("span",{"data-bitsnap-returns-slot":"returnReference",className:i("text-lg font-semibold",p.className),style:p.style,children:u.reference})]}),u.returnInstructions!==""&&x("div",{className:"flex flex-col gap-1",children:[d("span",{className:"text-sm font-medium",children:o("successInstructions")}),d("p",{"data-bitsnap-returns-slot":"returnInstructions",className:i("whitespace-pre-wrap border p-3 text-sm",f.className),style:f.style,children:u.returnInstructions})]})]})]}),x("div",{className:"flex flex-wrap gap-3",children:[d(v,{type:"button","data-bitsnap-returns-slot":"submitButton",className:i(H,c.className),style:c.style,onClick:r,children:o("successDone")}),t!=null&&d(v,{type:"button",variant:"secondary","data-bitsnap-returns-slot":"secondaryButton",className:i(L,b.className),style:b.style,onClick:t,children:o("myReturnsLink")})]})]})}import{Fragment as xr,jsx as S,jsxs as E}from"react/jsx-runtime";function Ts({onSelectReturn:e,onBack:r,pageSize:t,className:n}){T("ReturnsMyReturnsList");let o=h(),u=Y(),s=ze(),a=Tt({pageSize:t}),y=l("returnList"),m=l("returnCard"),p=l("returnReference"),f=l("secondaryButton");return S(M,{className:n,onBack:r,title:o("myReturnsTitle"),description:o("myReturnsDescription"),children:a.isLoading?S(U,{}):a.errorKey!=null?S(A,{errorKey:a.errorKey,onRetry:a.refetch}):a.returns.length===0?S(fe,{children:o("myReturnsEmpty")}):E(xr,{children:[S("ul",{"data-bitsnap-returns-slot":"returnList",className:i("flex flex-col gap-3",y.className),style:y.style,children:a.returns.map(c=>E("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:[E("div",{className:"flex flex-col gap-1",children:[S("span",{"data-bitsnap-returns-slot":"returnReference",className:i("font-medium",p.className),style:p.style,children:c.reference}),S("span",{className:"text-sm",children:Z(c.createdAt,u)}),E("span",{className:"text-sm",children:[o("myReturnRefund"),": ",s(c.refundStatus)]})]}),E("div",{className:"flex items-center gap-3",children:[S(J,{status:c.status}),S(v,{type:"button",variant:"secondary",size:"sm","aria-label":`${o("myReturnOpen")}: ${c.reference}`,"data-bitsnap-returns-slot":"secondaryButton",className:i(L,f.className),style:f.style,onClick:()=>e?.(c.id),children:o("myReturnOpen")})]})]},c.id))}),S(ge,{page:a.page,total:a.total,hasNext:a.hasNext,hasPrevious:a.hasPrevious,isFetching:a.isFetching,onNext:a.next,onPrevious:a.previous})]})})}function ws({returnId:e,onBack:r,className:t}){T("ReturnsMyReturnDetail");let n=h(),o=Y(),u=ze(),{request:s,isLoading:a,errorKey:y,refetch:m}=me(e),p=l("summary"),f=l("lineList"),c=l("line"),b=l("lineName"),g=l("returnInstructions"),C=l("history"),I=l("historyEntry");return S(M,{className:t,onBack:r,title:s!=null?n("myReturnTitle",{reference:s.reference}):n("myReturnDetailTitle"),children:a?S(U,{}):y!=null?S(A,{errorKey:y,onRetry:m}):s!=null&&E("div",{className:"flex flex-col gap-5",children:[E("div",{"data-bitsnap-returns-slot":"summary",className:i("flex flex-col gap-2 border p-4 text-sm",p.className),style:p.style,children:[E("div",{className:"flex items-center justify-between gap-2",children:[S(J,{status:s.status}),E("span",{children:[n("myReturnCreatedAt"),":"," ",Z(s.createdAt,o)]})]}),E("span",{children:[n("myReturnRefund"),": ",u(s.refundStatus),s.refundAmountMinor>BigInt(0)&&` \xB7 ${ee(s.refundAmountMinor,s.currency,o)}`]}),s.customerNote!==""&&E("span",{className:"whitespace-pre-wrap",children:[n("myReturnNote"),": ",s.customerNote]})]}),s.returnInstructions!==""&&S("p",{"data-bitsnap-returns-slot":"returnInstructions",className:i("whitespace-pre-wrap border p-3 text-sm",g.className),style:g.style,children:s.returnInstructions}),E("div",{className:"flex flex-col gap-2",children:[S("h3",{className:"text-sm font-medium",children:n("myReturnLines")}),S("ul",{"data-bitsnap-returns-slot":"lineList",className:i("flex flex-col gap-3",f.className),style:f.style,children:s.lines.map(N=>E("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:[S("span",{"data-bitsnap-returns-slot":"lineName",className:i("font-medium",b.className),style:b.style,children:N.name}),S("span",{className:"text-sm",children:n("myReturnLineQuantities",{requested:N.requestedQuantity,approved:N.approvedQuantity,received:N.receivedQuantity})})]},N.lineId))})]}),s.history.length>0&&E("div",{className:"flex flex-col gap-2",children:[S("h3",{className:"text-sm font-medium",children:n("myReturnHistory")}),S("ul",{"data-bitsnap-returns-slot":"history",className:i("flex flex-col gap-2",C.className),style:C.style,children:s.history.map(N=>E("li",{"data-bitsnap-returns-slot":"historyEntry",className:i("flex flex-wrap items-center justify-between gap-2 text-sm",I.className),style:I.style,children:[S(J,{status:N.status}),S("span",{children:Z(N.createdAt,o)})]},N.id))})]})]})})}export{te as a,re as b,vr as c,nt as d,Ne as e,l as f,Pe as g,St as h,h as i,T as j,ir as k,Xr as l,de as m,ht as n,Be as o,kt as p,Tt as q,me as r,U as s,Kn as t,_n as u,cs as v,ds as w,ps as x,ms as y,Ts as z,ws as A};
2
+ //# sourceMappingURL=chunk-SZ256RCC.mjs.map