bitsnap-react 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +40 -3
  2. package/dist/CartProvider-F7ER3WSS.js +2 -0
  3. package/dist/CartProvider-F7ER3WSS.js.map +1 -0
  4. package/dist/CartProvider-N73XNL7S.mjs +2 -0
  5. package/dist/analytics.js +1 -1
  6. package/dist/analytics.js.map +1 -1
  7. package/dist/analytics.mjs +1 -1
  8. package/dist/catalog.js +1 -1
  9. package/dist/catalog.js.map +1 -1
  10. package/dist/catalog.mjs +1 -1
  11. package/dist/{chunk-ICFYSZTV.js → chunk-3A4YOO7Z.js} +2 -2
  12. package/dist/chunk-3A4YOO7Z.js.map +1 -0
  13. package/dist/{chunk-UCESDAEC.mjs → chunk-3DGHF373.mjs} +2 -2
  14. package/dist/chunk-5GMWRCHK.mjs +4 -0
  15. package/dist/chunk-5GMWRCHK.mjs.map +1 -0
  16. package/dist/{chunk-MLSKHOA3.js → chunk-6CUCRTIK.js} +2 -2
  17. package/dist/chunk-6CUCRTIK.js.map +1 -0
  18. package/dist/{chunk-DGUIG334.js → chunk-EWLOGFF2.js} +2 -2
  19. package/dist/chunk-EWLOGFF2.js.map +1 -0
  20. package/dist/chunk-GAVLY6RX.mjs +2 -0
  21. package/dist/chunk-GAVLY6RX.mjs.map +1 -0
  22. package/dist/{chunk-XTIY6PXH.js → chunk-IP4OOWZ6.js} +2 -2
  23. package/dist/chunk-IP4OOWZ6.js.map +1 -0
  24. package/dist/chunk-JSDGZ4NY.js.map +1 -1
  25. package/dist/{chunk-3QG7H2AI.mjs → chunk-K2EITRNW.mjs} +2 -2
  26. package/dist/{chunk-5R3WR22A.mjs → chunk-KH7DFTJY.mjs} +2 -2
  27. package/dist/chunk-KOYBZORL.js.map +1 -1
  28. package/dist/{chunk-E5DCEFI2.mjs → chunk-L6J6H73J.mjs} +2 -2
  29. package/dist/chunk-M4KEUK6I.js +2 -0
  30. package/dist/chunk-M4KEUK6I.js.map +1 -0
  31. package/dist/{chunk-QSIKRVZL.mjs → chunk-OC7YS3UY.mjs} +2 -2
  32. package/dist/chunk-TMBC2BHN.js +4 -0
  33. package/dist/chunk-TMBC2BHN.js.map +1 -0
  34. package/dist/{chunk-DF2IK2GN.js → chunk-TSJCVFOX.js} +2 -2
  35. package/dist/chunk-TSJCVFOX.js.map +1 -0
  36. package/dist/{chunk-6IACFTJR.js → chunk-UFQVOGBS.js} +2 -2
  37. package/dist/chunk-UFQVOGBS.js.map +1 -0
  38. package/dist/chunk-XIHGWNTS.js.map +1 -1
  39. package/dist/{chunk-FF2ICGFQ.mjs → chunk-YNGXQJPE.mjs} +2 -2
  40. package/dist/{chunk-FF2ICGFQ.mjs.map → chunk-YNGXQJPE.mjs.map} +1 -1
  41. package/dist/consent.js.map +1 -1
  42. package/dist/course.js +1 -1
  43. package/dist/course.js.map +1 -1
  44. package/dist/course.mjs +1 -1
  45. package/dist/embed/analytics.js +1 -1
  46. package/dist/errors.js.map +1 -1
  47. package/dist/index.css +1 -1
  48. package/dist/index.css.map +1 -1
  49. package/dist/index.d.mts +59 -2
  50. package/dist/index.d.ts +59 -2
  51. package/dist/index.js +1 -1
  52. package/dist/index.js.map +1 -1
  53. package/dist/index.mjs +1 -1
  54. package/dist/index.mjs.map +1 -1
  55. package/dist/internal.js.map +1 -1
  56. package/dist/methods-ADH5XI4I.js +2 -0
  57. package/dist/methods-ADH5XI4I.js.map +1 -0
  58. package/dist/methods-BCR54EWX.mjs +2 -0
  59. package/dist/models.js.map +1 -1
  60. package/dist/returns.js +1 -1
  61. package/dist/returns.js.map +1 -1
  62. package/dist/returns.mjs +1 -1
  63. package/package.json +26 -51
  64. package/dist/CartProvider-XNFSUOCB.js +0 -2
  65. package/dist/CartProvider-XNFSUOCB.js.map +0 -1
  66. package/dist/CartProvider-YMJ7RFO4.mjs +0 -2
  67. package/dist/chunk-4BW6J7FP.js +0 -4
  68. package/dist/chunk-4BW6J7FP.js.map +0 -1
  69. package/dist/chunk-6IACFTJR.js.map +0 -1
  70. package/dist/chunk-DF2IK2GN.js.map +0 -1
  71. package/dist/chunk-DGUIG334.js.map +0 -1
  72. package/dist/chunk-ERL4Z7M7.js +0 -2
  73. package/dist/chunk-ERL4Z7M7.js.map +0 -1
  74. package/dist/chunk-ICFYSZTV.js.map +0 -1
  75. package/dist/chunk-MLSKHOA3.js.map +0 -1
  76. package/dist/chunk-P4Q5KXKS.mjs +0 -2
  77. package/dist/chunk-P4Q5KXKS.mjs.map +0 -1
  78. package/dist/chunk-PNTO3L2C.mjs +0 -4
  79. package/dist/chunk-PNTO3L2C.mjs.map +0 -1
  80. package/dist/chunk-XTIY6PXH.js.map +0 -1
  81. package/dist/methods-DDGOXLP6.mjs +0 -2
  82. package/dist/methods-RQPDIUUN.js +0 -2
  83. package/dist/methods-RQPDIUUN.js.map +0 -1
  84. /package/dist/{CartProvider-YMJ7RFO4.mjs.map → CartProvider-N73XNL7S.mjs.map} +0 -0
  85. /package/dist/{chunk-UCESDAEC.mjs.map → chunk-3DGHF373.mjs.map} +0 -0
  86. /package/dist/{chunk-3QG7H2AI.mjs.map → chunk-K2EITRNW.mjs.map} +0 -0
  87. /package/dist/{chunk-5R3WR22A.mjs.map → chunk-KH7DFTJY.mjs.map} +0 -0
  88. /package/dist/{chunk-E5DCEFI2.mjs.map → chunk-L6J6H73J.mjs.map} +0 -0
  89. /package/dist/{chunk-QSIKRVZL.mjs.map → chunk-OC7YS3UY.mjs.map} +0 -0
  90. /package/dist/{methods-DDGOXLP6.mjs.map → methods-BCR54EWX.mjs.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-DF2IK2GN.js","../src/analytics/pageviews.ts","../src/version.ts","../src/analytics/random.ts","../src/analytics/visitor.ts"],"names":["REGISTRY","registry","win","holder","watchNavigation","onChange","check","name","original","args","result","startAutoPageViews","send","reg","starter","path","resetAutoPageViews","SDK_VERSION","randomBytes","n","bytes","c","i","VISITOR_HEADER","MAX_AGE_SECONDS","VISITOR_ID_RE","consentApi","readCookie","doc","part","index","isBitsnapHost","hostname","host","consentBelongsTo","projectKey","api","onBitsnap","analyticsGranted","newVisitorId","binary","byte","rawVisitorCookie","clientIdCookieName","readVisitorCookie","value","writeVisitorCookie","id","base"],"mappings":"AAAA,uuBAA2G,ICYrGA,EAAAA,CAAW,MAAA,CAAO,GAAA,CAAI,mBAAmB,CAAA,CAE/C,SAASC,EAAAA,CAASC,CAAAA,CAAuB,CACvC,IAAMC,CAAAA,CAASD,CAAAA,CACf,OAAQC,CAAAA,CAAOH,EAAQ,CAAA,GAAM,CAAE,IAAA,CAAM,IAAA,CAAM,QAAA,CAAU,IAAI,GAAA,CAAO,QAAA,CAAU,CAAA,CAAM,CAClF,CAGA,SAASI,EAAAA,CAAgBF,CAAAA,CAAaG,CAAAA,CAAsB,CAC1D,IAAMC,CAAAA,CAAQ,CAAA,CAAA,EAAM,CAClB,GAAI,CACFD,CAAAA,CAAS,CACX,CAAA,UAAQ,CAAC,CACX,CAAA,CACA,GAAA,CAAA,IAAWE,EAAAA,EAAQ,CAAC,WAAA,CAAa,cAAc,CAAA,CAAY,CACzD,IAAMC,CAAAA,CAAWN,CAAAA,CAAI,OAAA,CAAQK,CAAI,CAAA,CACjCL,CAAAA,CAAI,OAAA,CAAQK,CAAI,CAAA,CAAI,QAAA,CAAA,GAA4BE,CAAAA,CAAwC,CACtF,IAAMC,CAAAA,CAASF,CAAAA,CAAS,KAAA,CAAM,IAAA,CAAMC,CAAI,CAAA,CACxC,OAAAH,CAAAA,CAAM,CAAA,CACCI,CACT,CACF,CACAR,CAAAA,CAAI,gBAAA,CAAiB,UAAA,CAAYI,CAAK,CACxC,CAQO,SAASK,CAAAA,CAAmBC,CAAAA,CAAkBV,CAAAA,CAAc,MAAA,CAAoB,CACrF,GAAI,CACF,IAAMW,CAAAA,CAAMZ,EAAAA,CAAS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AAA,CAAmC,CAC1E,GAAI,CACF,OAAOR,EAAAA,CAAWC,CAAAA,CAAKe,gCAAAA,CAA6B,CAAC,CACvD,CAAA,UAAQ,CACN,OAAO,IACT,CACF,CAGO,SAASC,CAAAA,CAAkBhB,CAAAA,CAAeO,CAAAA,CAAmC,CAClF,IAAMU,CAAAA,CAAQH,EAAAA,CAAiBd,CAAAA,CAAKO,CAAU,CAAA,CAC9C,OAAOU,CAAAA,GAAU,IAAA,EAAQpB,EAAAA,CAAc,IAAA,CAAKoB,CAAK,CAAA,CAAIA,CAAAA,CAAQ,IAC/D,CAOO,SAASC,EAAAA,CAAmB5C,CAAAA,CAAaiC,CAAAA,CAAoBY,CAAAA,CAAkB,CACpF,GAAI,CACF,IAAMnB,CAAAA,CAAM1B,CAAAA,CAAI,QAAA,CACV8C,CAAAA,CACJ,CAAA,EAAA","file":"/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-DF2IK2GN.js","sourcesContent":[null,"/**\n * Page-wide state of the automatic page views. It lives on `window`, so the\n * npm package, a second copy of it and the `analytics.js` script agree on who\n * reports a path and the history is patched once.\n */\ntype Registry = {\n /** Last path some starter reported. */\n path: string | null;\n starters: Set<() => void>;\n watching: boolean;\n};\n\nconst REGISTRY = Symbol.for(\"bitsnap.pageViews\");\n\nfunction registry(win: Window): Registry {\n const holder = win as unknown as Record<symbol, Registry | undefined>;\n return (holder[REGISTRY] ??= { path: null, starters: new Set(), watching: false });\n}\n\n/** Calls `onChange` when the path changes through `history.pushState`/`replaceState` or Back/Forward. */\nfunction watchNavigation(win: Window, onChange: () => void) {\n const check = () => {\n try {\n onChange();\n } catch {}\n };\n for (const name of [\"pushState\", \"replaceState\"] as const) {\n const original = win.history[name];\n win.history[name] = function (this: History, ...args: Parameters<History[typeof name]>) {\n const result = original.apply(this, args);\n check();\n return result;\n };\n }\n win.addEventListener(\"popstate\", check);\n}\n\n/**\n * Calls `send` for the current path and again on every path change, unless\n * another starter on the page already reported that path: the page gets one\n * `page_view` per path change however many providers, components and embeds\n * start it. Returns the function that stops this starter.\n */\nexport function startAutoPageViews(send: () => void, win: Window = window): () => void {\n try {\n const reg = registry(win);\n const starter = () => send();\n if (!reg.watching) {\n reg.watching = true;\n watchNavigation(win, () => {\n const path = win.location.pathname;\n // Nobody listening: leave the path unreported so the next starter sends it.\n if (path === reg.path || reg.starters.size === 0) return;\n reg.path = path;\n reg.starters.values().next().value?.();\n });\n }\n reg.starters.add(starter);\n const path = win.location.pathname;\n if (path !== reg.path) {\n reg.path = path;\n starter();\n }\n return () => void reg.starters.delete(starter);\n } catch {\n return () => {};\n }\n}\n\n/** Forgets the reported path and the starters (tests, hot reload). The history patch stays. */\nexport function resetAutoPageViews(win: Window = window) {\n const reg = registry(win);\n reg.path = null;\n reg.starters.clear();\n}\n","// Generated by scripts/write-version.mjs from package.json. Do not edit.\nexport const SDK_VERSION = \"1.12.0\";\n","export function randomBytes(n: number): Uint8Array {\n const bytes = new Uint8Array(n);\n const c = typeof crypto !== \"undefined\" ? crypto : undefined;\n if (c && typeof c.getRandomValues === \"function\") c.getRandomValues(bytes);\n else for (let i = 0; i < n; i++) bytes[i] = Math.floor(Math.random() * 256);\n return bytes;\n}\n","import { domainCandidates } from \"../consent/core/cookie\";\nimport { clientIdCookieName } from \"./contract\";\nimport { randomBytes } from \"./random\";\n\n/** The part of `window.BitsnapConsent` (`bitsnap-react/consent`) the tracker reads. */\nexport type ConsentLike = {\n /** Absent on a consent script older than 1.9.0, which never counts as the project's banner. */\n scope?: \"global\" | \"project\";\n projectKey?: string | null;\n get(): { c: { analytics?: boolean } } | null;\n /** Also true for a refusal made on an older banner version, which `get()` no longer returns. */\n denied?(category: \"analytics\"): boolean;\n ready?: Promise<unknown>;\n};\n\n/** Sent to the Bitsnap server on the requests that create a checkout or payment link. */\nexport const VISITOR_HEADER = \"X-Bitsnap-Visitor\";\n// 390 days, under the 13 months CNIL allows. Set once, never extended.\nconst MAX_AGE_SECONDS = 390 * 24 * 60 * 60;\nconst VISITOR_ID_RE = /^[A-Za-z0-9_-]{22}$/;\n\nexport function consentApi(win: Window): ConsentLike | undefined {\n return (win as unknown as { BitsnapConsent?: ConsentLike }).BitsnapConsent;\n}\n\nfunction readCookie(doc: Document, name: string): string | null {\n for (const part of doc.cookie.split(\";\")) {\n const index = part.indexOf(\"=\");\n if (index !== -1 && part.slice(0, index).trim() === name) return part.slice(index + 1).trim();\n }\n return null;\n}\n\n/** bitsnap.pl and its subdomains: many merchants share them, and the site-wide choice is bitsnap's own. */\nfunction isBitsnapHost(hostname: string): boolean {\n const host = hostname.toLowerCase();\n return host === \"bitsnap.pl\" || host.endsWith(\".bitsnap.pl\");\n}\n\n/**\n * Whether the page's consent banner speaks for `projectKey`: a project-scope banner of that\n * key, or a site-scope banner on a merchant's own site. On bitsnap.pl a site-scope choice is\n * bitsnap's own, so only a project-scope one counts.\n */\nexport function consentBelongsTo(win: Window, projectKey: string): boolean {\n try {\n const api = consentApi(win);\n if (!api) return false;\n if (api.scope === \"project\") return api.projectKey === projectKey;\n const onBitsnap = isBitsnapHost(win.location.hostname);\n if (api.scope === \"global\") return !onBitsnap;\n // A consent script from before the scope info: it cannot be told apart from another project's banner.\n return false;\n } catch {\n return false;\n }\n}\n\n/** `true` only while a banner that speaks for `projectKey` holds a valid choice that grants `analytics`. */\nexport function analyticsGranted(win: Window, projectKey: string): boolean {\n try {\n return consentApi(win)?.get()?.c.analytics === true && consentBelongsTo(win, projectKey);\n } catch {\n return false;\n }\n}\n\n/** 16 random bytes as 22 base64url characters. */\nexport function newVisitorId(): string {\n let binary = \"\";\n randomBytes(16).forEach((byte) => (binary += String.fromCharCode(byte)));\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** Value of the `bs_vid_<projectKey>` cookie, whatever it holds; `null` when it is absent. */\nfunction rawVisitorCookie(doc: Document, projectKey: string): string | null {\n try {\n return readCookie(doc, clientIdCookieName(projectKey));\n } catch {\n return null;\n }\n}\n\n/** The project's client id from its first-party cookie (`bs_vid_<projectKey>`), or `null` if absent or malformed. */\nexport function readVisitorCookie(doc: Document, projectKey: string): string | null {\n const value = rawVisitorCookie(doc, projectKey);\n return value !== null && VISITOR_ID_RE.test(value) ? value : null;\n}\n\n/**\n * Sets the cookie on the widest registrable domain the browser accepts\n * (shortest suffix with two labels first, so `shop.example.co.uk` skips the\n * refused `co.uk`), host-only where no domain sticks (localhost, IP hosts).\n */\nexport function writeVisitorCookie(win: Window, projectKey: string, id: string): void {\n try {\n const doc = win.document;\n const base =\n `${clientIdCookieName(projectKey)}=${id}; Max-Age=${MAX_AGE_SECONDS}; Path=/; SameSite=Lax` +\n (win.location.protocol === \"https:\" ? \"; Secure\" : \"\");\n for (const domain of domainCandidates(win.location.hostname).reverse()) {\n doc.cookie = `${base}; Domain=${domain}`;\n if (readVisitorCookie(doc, projectKey) === id) return;\n }\n doc.cookie = base;\n } catch {\n // cookies blocked (sandboxed frame)\n }\n}\n\n/** Expires the cookie on the host and on every parent domain it may have been set on. */\nexport function deleteVisitorCookie(win: Window, projectKey: string): void {\n try {\n const doc = win.document;\n // Present under any value: a malformed one must go too.\n if (rawVisitorCookie(doc, projectKey) === null) return;\n const base =\n `${clientIdCookieName(projectKey)}=; Max-Age=0; Path=/; SameSite=Lax` +\n (win.location.protocol === \"https:\" ? \"; Secure\" : \"\");\n doc.cookie = base;\n for (const domain of domainCandidates(win.location.hostname)) doc.cookie = `${base}; Domain=${domain}`;\n } catch {\n // best effort\n }\n}\n\n/**\n * The project's client id to send, or `null`: analytics consent is granted,\n * Global Privacy Control is off, the browser is not automated and the cookie exists.\n */\nexport function readVisitorId(win: Window, projectKey: string): string | null {\n try {\n const nav = win.navigator as { globalPrivacyControl?: boolean; webdriver?: boolean } | undefined;\n if (nav?.globalPrivacyControl === true || nav?.webdriver === true) return null;\n return analyticsGranted(win, projectKey) ? readVisitorCookie(win.document, projectKey) : null;\n } catch {\n return null;\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-DGUIG334.js","../src/panel/config.ts","../src/panel/PanelProvider.tsx","../src/panel/session-storage.ts"],"names":["config","allowedReturnOrigins","setPanelConfig","newConfig","getPanelConfig","setProjectID","projectID","setTheme","theme","setLoginURL","loginURL","setHost","host","setAllowedReturnOrigins","origins","getAllowedReturnOrigins","PanelContext","createContext","PanelProvider","children","analytics","instrument","useInstrument","jsx","RpcProvider","InstrumentProvider","usePanelConfig","useContext","panelSessionKey"],"mappings":"AAAA,mOAAuC,sDAA+C,ICElFA,CAAAA,CAAsB,CACxB,SAAA,CAAW,KAAA,CAAA,CACX,QAAA,CAAU,cAAA,CACV,KAAA,CAAO,KAAA,CAAA,CACP,IAAA,CAAM,KAAA,CAAA,CACN,oBAAA,CAAsB,CAAC,CACzB,CAAA,CAEIC,CAAAA,CAAiC,CAAC,CAAA,CAU/B,SAASC,CAAAA,CAAeC,CAAAA,CAAuC,CACpEH,CAAAA,CAAS,CAAE,GAAGA,CAAAA,CAAQ,GAAGG,CAAU,CACrC,CAEO,SAASC,CAAAA,CAAAA,CAA8B,CAC5C,OAAOJ,CACT,CAEO,SAASK,CAAAA,CAAaC,CAAAA,CAAyB,CACpDN,CAAAA,CAAO,SAAA,CAAYM,CACrB,CAEO,SAASC,CAAAA,CAASC,CAAAA,CAA6B,CACpDR,CAAAA,CAAO,KAAA,CAAQQ,CACjB,CAEO,SAASC,CAAAA,CAAYC,CAAAA,CAAwB,CAClDV,CAAAA,CAAO,QAAA,CAAWU,CACpB,CAEO,SAASC,CAAAA,CAAQC,CAAAA,CAAoB,CAC1CZ,CAAAA,CAAO,IAAA,CAAOY,CAChB,CAEO,SAASC,CAAAA,CAAwBC,CAAAA,CAAyB,CAC/Db,CAAAA,CAAuBa,CAAAA,CACvBd,CAAAA,CAAS,CAAE,GAAGA,CAAAA,CAAQ,oBAAA,CAAsBc,CAAQ,CACtD,CAEO,SAASC,CAAAA,CAAAA,CAAoC,CAClD,OAAOd,CACT,CCnDA,8BAA0C,+CA2BhC,IAlBJe,CAAAA,CAAeC,kCAAAA,CAA2Bb,CAAe,CAAC,CAAA,CAEnDc,CAAAA,aASR,CAAC,CAAE,QAAA,CAAAC,CAAAA,CAAU,SAAA,CAAAC,CAAU,CAAA,CAAA,EAAM,CAChC,IAAMpB,CAAAA,CAASI,CAAAA,CAAe,CAAA,CACxBiB,CAAAA,CAAaC,gCAAAA,CAActB,CAAO,SAAA,CAAWoB,CAAAA,CAAW,OAAO,CAAA,CACrE,OACEG,6BAAAA,kBAACC,CAAA,CACC,QAAA,CAAAD,6BAAAA,CAACP,CAAa,QAAA,CAAb,CAAsB,KAAA,CAAO,CAAE,GAAGhB,CAAO,CAAA,CACxC,QAAA,CAAAuB,6BAAAA,kBAACE,CAAA,CAAmB,KAAA,CAAOJ,CAAAA,CACzB,QAAA,CAAAE,6BAAAA,KAAC,CAAA,CAAI,SAAA,CAAU,eAAA,CAAiB,QAAA,CAAAJ,CAAAA,CAAS,CAAA,CAC3C,CAAA,CACF,CAAA,CACF,CAEJ,CAAA,CAEaO,CAAAA,aAAiB,CAAA,CAAA,EAAMC,+BAAAA,CAAuB,CAAA,CClC3D,IAAMC,CAAAA,CAAkB,CAACtB,CAAAA,CAAmBM,CAAAA,CAAAA,EAC1C,CAAA,sBAAA,EAAyB,kBAAA,kBAAmBA,CAAAA,SAAQ,sBAAoB,CAAC,CAAA,CAAA,EAAI,kBAAA,CAAmBN,CAAS,CAAC,CAAA,CAAA","file":"/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-DGUIG334.js","sourcesContent":[null,"import type { GetThemeOutput } from \"./types\";\n\nlet config: PanelConfig = {\n projectID: undefined,\n loginURL: \"/panel/login\",\n theme: undefined,\n host: undefined,\n allowedReturnOrigins: [],\n};\n\nlet allowedReturnOrigins: string[] = [];\n\nexport interface PanelConfig {\n projectID?: string;\n loginURL?: string;\n theme?: GetThemeOutput;\n host?: string;\n allowedReturnOrigins: string[];\n}\n\nexport function setPanelConfig(newConfig: Partial<PanelConfig>): void {\n config = { ...config, ...newConfig };\n}\n\nexport function getPanelConfig(): PanelConfig {\n return config;\n}\n\nexport function setProjectID(projectID: string): void {\n config.projectID = projectID;\n}\n\nexport function setTheme(theme: GetThemeOutput): void {\n config.theme = theme;\n}\n\nexport function setLoginURL(loginURL: string): void {\n config.loginURL = loginURL;\n}\n\nexport function setHost(host: string): void {\n config.host = host;\n}\n\nexport function setAllowedReturnOrigins(origins: string[]): void {\n allowedReturnOrigins = origins;\n config = { ...config, allowedReturnOrigins: origins };\n}\n\nexport function getAllowedReturnOrigins(): string[] {\n return allowedReturnOrigins;\n}\n","import { createContext, useContext } from \"react\";\nimport {\n InstrumentProvider,\n useInstrument,\n type AnalyticsOption,\n} from \"../analytics/instrument\";\nimport { RpcProvider } from \"../rpc-provider\";\nimport { getPanelConfig, type PanelConfig } from \"./config\";\n\nconst PanelContext = createContext<PanelConfig>(getPanelConfig());\n\nexport const PanelProvider: React.FC<{\n children: React.ReactNode;\n /**\n * Usage statistics for your Bitsnap dashboard (panel logins, orders viewed,\n * downloads, course progress). On by default; `false` turns it off. An\n * object lets you forward every event: `{ onEvent }`. Nothing is stored on\n * the visitor's device.\n */\n analytics?: AnalyticsOption;\n}> = ({ children, analytics }) => {\n const config = getPanelConfig();\n const instrument = useInstrument(config.projectID, analytics, \"panel\");\n return (\n <RpcProvider>\n <PanelContext.Provider value={{ ...config }}>\n <InstrumentProvider value={instrument}>\n <div className=\"bitsnap-react\">{children}</div>\n </InstrumentProvider>\n </PanelContext.Provider>\n </RpcProvider>\n );\n};\n\nexport const usePanelConfig = () => useContext(PanelContext);\n","const panelSessionKey = (projectID: string, host?: string) =>\n `bitsnap-panel-session:${encodeURIComponent(host ?? \"https://bitsnap.pl\")}:${encodeURIComponent(projectID)}`;\n\nconst panelEmailKey = (projectID: string, host?: string) =>\n `bitsnap-panel-email:${encodeURIComponent(host ?? \"https://bitsnap.pl\")}:${encodeURIComponent(projectID)}`;\n\nexport function getPanelSession(projectID?: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return undefined;\n const token = window.localStorage.getItem(panelSessionKey(projectID, host));\n return token ?? undefined;\n}\n\nexport function savePanelSession(projectID: string | undefined, token: string, email: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return;\n window.localStorage.setItem(panelSessionKey(projectID, host), token);\n window.localStorage.setItem(panelEmailKey(projectID, host), email);\n}\n\nexport function getPanelEmail(projectID?: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return null;\n return window.localStorage.getItem(panelEmailKey(projectID, host));\n}\n\nexport function clearPanelSession(projectID?: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return;\n window.localStorage.removeItem(panelSessionKey(projectID, host));\n window.localStorage.removeItem(panelEmailKey(projectID, host));\n}\n"]}
@@ -1,2 +0,0 @@
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 _chunkDF2IK2GNjs = require('./chunk-DF2IK2GN.js');var u="X-Bitsnap-Client",i=`bitsnap-react@${_chunkDF2IK2GNjs.a}`,d="bs_client",b= exports.a ={[u]:i},z= exports.b =e=>t=>(t.header.set(u,i),e(t));function j(e){let t=e.indexOf("#"),n=t===-1?e:e.slice(0,t),a=t===-1?"":e.slice(t),o=n.includes("?")?/[?&]$/.test(n)?"":"&":"?";return`${n}${o}${d}=${encodeURIComponent(i)}${a}`}var g="https://bitsnap.pl",x= exports.f =g;function K(e){console.log("setCustomHost",e),x= exports.f =e}function T(e,t){return t.toLowerCase().startsWith("en")?e.en:e.pl}function k(e,t){let n={...e};if(t!=null)for(let[a,o]of Object.entries(t))o!=null&&(n[a]=o);return n}function l(e,t,n){return k(T(e,t),n)}function y(e,t){return _nullishCoalesce(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.",checkoutFailed:"Something went wrong. Please try again later.",noPaymentGateway:"This shop doesn't accept online payments yet. Try again later or contact the seller.",gatewayNotConfigured:"Payments in this shop are not set up correctly. Try again later or contact the seller.",shippingNotConfigured:"Delivery in this shop is not configured yet. Try again later or contact the seller.",mixedRecurring:"Subscriptions and one-time products cannot be paid for together. Pay for them in separate orders.",currencyUnsupported:"The shop doesn't accept payments in this currency. Contact the seller.",priceChanged:"The product price has changed. Refresh the page to see the current price.",close:"Close cart",remove:"Remove",quantity:"Quantity",increaseQuantity:"Increase quantity",decreaseQuantity:"Decrease quantity",openCart:"Open cart",cartItemsCount:"Items in cart",lowestPrice30Days:"Lowest price in the last 30 days:",noPriceHistory:"No price data for the last 30 days",redirectFailed:"Could not redirect to the payment. Please try again later.",subscriptionUnsupported:"Subscriptions cannot be added to the cart yet.",searchCountry:"Find a country",noCountriesFound:"No countries found",countryRequired:"Choose a country to continue.",paymentForCart:"Cart payment",coupon:"Coupon",extrasCalculatedNext:"Discounts, shipping and taxes are calculated at the next step",loadFailed:"Could not load your cart.",retry:"Try again"},pl:{cart:"Koszyk",emptyCart:"Brak produkt\xF3w w koszyku.",total:"Suma:",delivery:"+ dostawa",chooseCountry:"Wybierz kraj",nextStep:"Nast\u0119pny krok",unavailableProducts:"Nie wszystkie produkty s\u0105 dost\u0119pne w magazynie.",checkoutFailed:"Co\u015B posz\u0142o nie tak. Spr\xF3buj ponownie p\xF3\u017Aniej.",noPaymentGateway:"Ten sklep nie przyjmuje jeszcze p\u0142atno\u015Bci online. Spr\xF3buj ponownie p\xF3\u017Aniej lub skontaktuj si\u0119 ze sprzedawc\u0105.",gatewayNotConfigured:"P\u0142atno\u015Bci w tym sklepie nie s\u0105 poprawnie skonfigurowane. Spr\xF3buj ponownie p\xF3\u017Aniej lub skontaktuj si\u0119 ze sprzedawc\u0105.",shippingNotConfigured:"Dostawa w tym sklepie nie jest jeszcze skonfigurowana. Spr\xF3buj ponownie p\xF3\u017Aniej lub skontaktuj si\u0119 ze sprzedawc\u0105.",mixedRecurring:"Subskrypcji i produkt\xF3w jednorazowych nie mo\u017Cna op\u0142aci\u0107 razem. Op\u0142a\u0107 je w osobnych zam\xF3wieniach.",currencyUnsupported:"Sklep nie przyjmuje p\u0142atno\u015Bci w tej walucie. Skontaktuj si\u0119 ze sprzedawc\u0105.",priceChanged:"Cena produktu si\u0119 zmieni\u0142a. Od\u015Bwie\u017C stron\u0119, aby zobaczy\u0107 aktualn\u0105 cen\u0119.",close:"Zamknij koszyk",remove:"Usu\u0144",quantity:"Ilo\u015B\u0107",increaseQuantity:"Zwi\u0119ksz ilo\u015B\u0107",decreaseQuantity:"Zmniejsz ilo\u015B\u0107",openCart:"Otw\xF3rz koszyk",cartItemsCount:"Produkt\xF3w w koszyku",lowestPrice30Days:"Najni\u017Csza cena z 30 dni:",noPriceHistory:"Brak danych o cenie z ostatnich 30 dni",redirectFailed:"Nie uda\u0142o si\u0119 przekierowa\u0107 do p\u0142atno\u015Bci. Spr\xF3buj ponownie p\xF3\u017Aniej.",subscriptionUnsupported:"Subskrypcji nie mo\u017Cna jeszcze doda\u0107 do koszyka.",searchCountry:"Znajd\u017A kraj",noCountriesFound:"Nie znaleziono kraj\xF3w",countryRequired:"Wybierz kraj, aby przej\u015B\u0107 dalej.",paymentForCart:"P\u0142atno\u015B\u0107 za koszyk",coupon:"Kupon",extrasCalculatedNext:"Rabaty, dostawa i podatki w nast\u0119pnym kroku",loadFailed:"Nie uda\u0142o si\u0119 wczyta\u0107 koszyka.",retry:"Spr\xF3buj ponownie"}};function m(e,t){return l(C,e,t)}function R(e,t,n){return y(m(t,n),e)}var s="pl-PL",c="bitsnap-locale",r;function E(e){let t=_optionalChain([e, 'optionalAccess', _ => _.trim, 'call', _2 => _2()]);r=t?t.toLowerCase()==="en"?"en-US":t.toLowerCase()==="pl"?s:t:void 0,typeof localStorage<"u"&&(r==null?localStorage.removeItem(c):localStorage.setItem(c,r))}function F(){return _nullishCoalesce(r, () => ((typeof localStorage<"u"?_nullishCoalesce(localStorage.getItem(c), () => (s)):s)))}var _clsx = require('clsx');var _tailwindmerge = require('tailwind-merge');function H(...e){return _tailwindmerge.twMerge.call(void 0, _clsx.clsx.call(void 0, e))}exports.a = b; exports.b = z; exports.c = j; exports.d = H; exports.e = g; exports.f = x; exports.g = K; exports.h = T; exports.i = l; exports.j = R; exports.k = s; exports.l = E; exports.m = F;
2
- //# sourceMappingURL=chunk-ERL4Z7M7.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-ERL4Z7M7.js","../src/lib/client-header.ts"],"names":["CLIENT_HEADER_NAME","CLIENT_HEADER_VALUE","SDK_VERSION"],"mappings":"AAAA,uuBAAuC,ICG1BA,CAAAA,CAAqB,kBAAA,CACrBC,CAAAA,CAAsB,CAAA,cAAA,EAAiBC,kBAAW,CAAA,CAAA","file":"/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-ERL4Z7M7.js","sourcesContent":[null,"import type { Interceptor } from \"@connectrpc/connect\";\nimport { SDK_VERSION } from \"../version\";\n\nexport const CLIENT_HEADER_NAME = \"X-Bitsnap-Client\";\nexport const CLIENT_HEADER_VALUE = `bitsnap-react@${SDK_VERSION}`;\n\nexport const CLIENT_QUERY_PARAM = \"bs_client\";\n\n/**\n * Spread into the `headers` of a fetch that already triggers a CORS preflight\n * (JSON POST, Connect RPC). Never use it on a simple cross-origin GET: the\n * custom header would force a preflight that older servers and merchant\n * proxies do not allow. Use `withClientParam` there.\n */\nexport const clientHeaders: Record<string, string> = {\n [CLIENT_HEADER_NAME]: CLIENT_HEADER_VALUE,\n};\n\n/** Connect interceptor adding the client header to every RPC. */\nexport const clientHeaderInterceptor: Interceptor = (next) => (req) => {\n req.header.set(CLIENT_HEADER_NAME, CLIENT_HEADER_VALUE);\n return next(req);\n};\n\n/** Adds `bs_client=<pkg>@<ver>` to a URL, for simple GETs that must stay preflight-free. */\nexport function withClientParam(url: string): string {\n const hash = url.indexOf(\"#\");\n const base = hash === -1 ? url : url.slice(0, hash);\n const fragment = hash === -1 ? \"\" : url.slice(hash);\n const separator = base.includes(\"?\") ? (/[?&]$/.test(base) ? \"\" : \"&\") : \"?\";\n return `${base}${separator}${CLIENT_QUERY_PARAM}=${encodeURIComponent(CLIENT_HEADER_VALUE)}${fragment}`;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-ICFYSZTV.js","../src/components/returns/state-machine.ts","../src/components/returns/BitsnapReturns.tsx"],"names":["STEPS_WITH_SESSION","stepRequiresSession","step","initialReturnsStep","hasSession","reduceReturnsStep","event","STEP_NUMBERS","RETURNS_STEP_COUNT","returnsStepNumber","StepIndicator","current","text","useReturnsText","slot","useReturnsSlot","jsx","cn","ReturnsRouter","panelToken","status","useReturnsContext","dispatch","useReducer","useEffect","SkeletonRows","stepNumber","jsxs","ReturnsEmailStep","ReturnsCodeStep","ReturnsOrderList","orderId","ReturnsOrderDetail","items","note","ReturnsConfirmation","returnId","ReturnsResult","ReturnsMyReturnsList","ReturnsMyReturnDetail","BitsnapReturns","props","ReturnsProvider"],"mappings":"AAAA,+HAAsH,sDAAwC,IC8CxJA,CAAAA,CAAiD,CACrD,QAAA,CACA,OAAA,CACA,cAAA,CACA,QAAA,CACA,WAAA,CACA,UACF,CAAA,CAGO,SAASC,CAAAA,CAAoBC,CAAAA,CAAgC,CAClE,OAAOF,CAAAA,CAA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AGD,CAAAA,CACnB,QAAA,CAAAzB,6BAAAA,CAACE,CAAA,CAAc,UAAA,CAAYuB,CAAAA,CAAM,gBAAA,EAAoB,IAAA,EAAQA,CAAAA,CAAM,gBAAA,GAAqB,EAAA,CAAI,CAAA,CAC9F,CAEJ,CAAA,cAAA","file":"/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-ICFYSZTV.js","sourcesContent":[null,"/** One line chosen for return. */\nexport type SelectedReturnLine = {\n lineId: string;\n quantity: number;\n};\n\n/** Where the default flow of `BitsnapReturns` currently is. */\nexport type ReturnsStep =\n | { name: \"email\" }\n | { name: \"code\" }\n | { name: \"orders\" }\n | {\n name: \"order\";\n orderId: string;\n /** Selection to restore when coming back from the confirmation. */\n items?: SelectedReturnLine[];\n note?: string;\n }\n | {\n name: \"confirmation\";\n orderId: string;\n items: SelectedReturnLine[];\n note: string;\n }\n | { name: \"result\"; returnId: string }\n | { name: \"myReturns\" }\n | { name: \"myReturn\"; returnId: string };\n\nexport type ReturnsStepName = ReturnsStep[\"name\"];\n\nexport type ReturnsStepEvent =\n /** A verification code was requested. */\n | { type: \"CODE_SENT\" }\n /** The session became valid: code verified, stored session or panel token. */\n | { type: \"AUTHENTICATED\" }\n /** The session was dropped by the backend, expiry or logout. */\n | { type: \"SESSION_EXPIRED\" }\n | { type: \"SELECT_ORDER\"; orderId: string }\n | { type: \"REVIEW\"; items: SelectedReturnLine[]; note: string }\n | { type: \"SUBMITTED\"; returnId: string }\n | { type: \"OPEN_MY_RETURNS\" }\n | { type: \"SELECT_RETURN\"; returnId: string }\n | { type: \"BACK\" }\n /** Leave the result screen for the order list. */\n | { type: \"CONTINUE\" };\n\nconst STEPS_WITH_SESSION: readonly ReturnsStepName[] = [\n \"orders\",\n \"order\",\n \"confirmation\",\n \"result\",\n \"myReturns\",\n \"myReturn\",\n];\n\n/** Steps that cannot be shown without a returns session. */\nexport function stepRequiresSession(step: ReturnsStepName): boolean {\n return STEPS_WITH_SESSION.includes(step);\n}\n\n/** Starts at the orders when a session exists, otherwise at the email. */\nexport function initialReturnsStep(hasSession: boolean): ReturnsStep {\n return hasSession ? { name: \"orders\" } : { name: \"email\" };\n}\n\n/**\n * Pure transition function of the default flow. Events that do not apply to\n * the current step leave it unchanged.\n */\nexport function reduceReturnsStep(\n step: ReturnsStep,\n event: ReturnsStepEvent,\n): ReturnsStep {\n switch (event.type) {\n case \"SESSION_EXPIRED\":\n // Email and code do not need a session; keep a pending verification.\n return stepRequiresSession(step.name) ? { name: \"email\" } : step;\n case \"CODE_SENT\":\n return step.name === \"email\" ? { name: \"code\" } : step;\n case \"AUTHENTICATED\":\n return step.name === \"email\" || step.name === \"code\"\n ? { name: \"orders\" }\n : step;\n case \"SELECT_ORDER\":\n return step.name === \"orders\"\n ? { name: \"order\", orderId: event.orderId }\n : step;\n case \"REVIEW\":\n return step.name === \"order\"\n ? {\n name: \"confirmation\",\n orderId: step.orderId,\n items: event.items,\n note: event.note,\n }\n : step;\n case \"SUBMITTED\":\n return step.name === \"confirmation\"\n ? { name: \"result\", returnId: event.returnId }\n : step;\n case \"OPEN_MY_RETURNS\":\n return step.name === \"orders\" || step.name === \"result\"\n ? { name: \"myReturns\" }\n : step;\n case \"SELECT_RETURN\":\n return step.name === \"myReturns\"\n ? { name: \"myReturn\", returnId: event.returnId }\n : step;\n case \"CONTINUE\":\n return step.name === \"result\" ? { name: \"orders\" } : step;\n case \"BACK\":\n switch (step.name) {\n case \"code\":\n return { name: \"email\" };\n case \"order\":\n case \"myReturns\":\n return { name: \"orders\" };\n case \"confirmation\":\n return {\n name: \"order\",\n orderId: step.orderId,\n items: step.items,\n note: step.note,\n };\n case \"myReturn\":\n return { name: \"myReturns\" };\n default:\n return step;\n }\n }\n}\n\nconst STEP_NUMBERS: Partial<Record<ReturnsStepName, number>> = {\n email: 1,\n code: 2,\n orders: 3,\n order: 4,\n confirmation: 5,\n result: 6,\n};\n\nexport const RETURNS_STEP_COUNT = 6;\n\n/** Position of a step in the return flow, `undefined` for the \"my returns\" views. */\nexport function returnsStepNumber(step: ReturnsStepName): number | undefined {\n return STEP_NUMBERS[step];\n}\n","import { useEffect, useReducer } from \"react\";\nimport { cn } from \"@/src/lib/utils\";\nimport { useReturnsSlot } from \"./appearance.context\";\nimport { ReturnsCodeStep, ReturnsEmailStep } from \"./AuthSteps\";\nimport { SkeletonRows } from \"./internal\";\nimport { ReturnsMyReturnDetail, ReturnsMyReturnsList } from \"./MyReturns\";\nimport {\n ReturnsConfirmation,\n ReturnsOrderDetail,\n ReturnsOrderList,\n ReturnsResult,\n} from \"./OrderSteps\";\nimport {\n ReturnsProvider,\n useReturnsContext,\n type ReturnsProviderProps,\n} from \"./ReturnsProvider\";\nimport {\n initialReturnsStep,\n reduceReturnsStep,\n RETURNS_STEP_COUNT,\n returnsStepNumber,\n} from \"./state-machine\";\nimport { useReturnsText } from \"./texts.context\";\n\nexport type BitsnapReturnsProps = Omit<ReturnsProviderProps, \"children\">;\n\nfunction StepIndicator({ current }: { current: number }) {\n const text = useReturnsText();\n const slot = useReturnsSlot(\"stepIndicator\");\n\n return (\n <p\n data-bitsnap-returns-slot=\"stepIndicator\"\n className={cn(\"text-xs\", slot.className)}\n style={slot.style}\n >\n {text(\"stepIndicator\", { current, total: RETURNS_STEP_COUNT })}\n </p>\n );\n}\n\n/** Default step router. All transitions come from the pure state machine. */\nfunction ReturnsRouter({ panelToken }: { panelToken: boolean }) {\n const { status } = useReturnsContext(\"BitsnapReturns\");\n const [step, dispatch] = useReducer(\n reduceReturnsStep,\n initialReturnsStep(false),\n );\n\n // A valid session (verified code, stored session, exchanged panel token)\n // moves on to the orders; a dropped one returns to the start.\n useEffect(() => {\n if (status === \"authenticated\") {\n dispatch({ type: \"AUTHENTICATED\" });\n } else if (status === \"anonymous\") {\n dispatch({ type: \"SESSION_EXPIRED\" });\n }\n }, [status]);\n\n // Without a panel token the server render and the first client render show\n // the email step; a stored session switches to the orders after hydration.\n if (status === \"exchanging\" || (status === \"hydrating\" && panelToken)) {\n return <SkeletonRows />;\n }\n\n const stepNumber = returnsStepNumber(step.name);\n\n return (\n <div className=\"flex flex-col gap-4\">\n {stepNumber != null && <StepIndicator current={stepNumber} />}\n {step.name === \"email\" && (\n <ReturnsEmailStep onSubmitted={() => dispatch({ type: \"CODE_SENT\" })} />\n )}\n {step.name === \"code\" && (\n <ReturnsCodeStep\n onVerified={() => dispatch({ type: \"AUTHENTICATED\" })}\n onBack={() => dispatch({ type: \"BACK\" })}\n />\n )}\n {step.name === \"orders\" && (\n <ReturnsOrderList\n showLogout={!panelToken}\n onSelectOrder={(orderId) =>\n dispatch({ type: \"SELECT_ORDER\", orderId })\n }\n onOpenMyReturns={() => dispatch({ type: \"OPEN_MY_RETURNS\" })}\n />\n )}\n {step.name === \"order\" && (\n <ReturnsOrderDetail\n orderId={step.orderId}\n initialItems={step.items}\n initialNote={step.note}\n onBack={() => dispatch({ type: \"BACK\" })}\n onContinue={({ items, note }) =>\n dispatch({ type: \"REVIEW\", items, note })\n }\n />\n )}\n {step.name === \"confirmation\" && (\n <ReturnsConfirmation\n orderId={step.orderId}\n items={step.items}\n note={step.note}\n onBack={() => dispatch({ type: \"BACK\" })}\n onSubmitted={(returnId) =>\n dispatch({ type: \"SUBMITTED\", returnId })\n }\n />\n )}\n {step.name === \"result\" && (\n <ReturnsResult\n returnId={step.returnId}\n onContinue={() => dispatch({ type: \"CONTINUE\" })}\n onOpenMyReturns={() => dispatch({ type: \"OPEN_MY_RETURNS\" })}\n />\n )}\n {step.name === \"myReturns\" && (\n <ReturnsMyReturnsList\n onSelectReturn={(returnId) =>\n dispatch({ type: \"SELECT_RETURN\", returnId })\n }\n onBack={() => dispatch({ type: \"BACK\" })}\n />\n )}\n {step.name === \"myReturn\" && (\n <ReturnsMyReturnDetail\n returnId={step.returnId}\n onBack={() => dispatch({ type: \"BACK\" })}\n />\n )}\n </div>\n );\n}\n\n/**\n * Customer return flow: email, code, orders, line selection, confirmation and\n * result, plus the list of earlier returns. It is `ReturnsProvider` with the\n * default step router; compose your own page from the step components to\n * change the layout.\n *\n * ```tsx\n * <BitsnapReturns projectID=\"…\" appearance={brand} texts={{ emailStepTitle: \"Return a product\" }} />\n * ```\n */\nexport function BitsnapReturns(props: BitsnapReturnsProps) {\n return (\n <ReturnsProvider {...props}>\n <ReturnsRouter panelToken={props.panelAccessToken != null && props.panelAccessToken !== \"\"} />\n </ReturnsProvider>\n );\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-MLSKHOA3.js","../src/components/returns/appearance.ts","../src/components/returns/appearance.context.tsx","../src/components/returns/legacy.ts","../src/components/returns/texts.ts","../src/components/returns/texts.context.tsx","../src/components/returns/ReturnsProvider.tsx","../src/components/returns/session-storage.ts"],"names":["RETURNS_SLOT_NAMES","RETURNS_TOKEN_VARIABLES","RETURNS_THEME_PRESETS","RETURNS_SHADCN_VARIABLES","resolveReturnsAppearance","appearance","resolved","resolveAppearanceCore","getReturnsSlotAppearance","slot","getSlotAppearance","ReturnsAppearanceContext","createContext","ReturnsAppearanceProvider","children","useMemo","jsx","useReturnsAppearance","useContext","useReturnsSlot","resolveReturnsEnvironment","environment","LEGACY_TEXT_KEYS","mapLegacyTexts","texts","result","legacyKey","targets","value","target","key","resolveBrandAppearance","theme","color","brandColorTokens","resolvePagedArguments","first","pageToken","RETURNS_TEXT_TABLES","resolveReturnsTexts","locale","overrides","resolveTexts","fillText","template","values","match","name","STATUS_TEXT_KEYS","REFUND_STATUS_TEXT_KEYS","statusTextKey","status","refundStatusTextKey","ReturnsTextsContext","ReturnsTextsProvider","activeLocale","getLocale","useReturnsText","useCallback","useReturnsLocale","KEY_PREFIX","sessionStorageKey","projectID"],"mappings":"AAAA,y/BAAgD,sDAAuG,sDAAwD,sDAAyD,ICiE3PA,EAAAA,CAAqB,CAEhC,MAAA,CACA,QAAA,CACA,OAAA,CACA,aAAA,CACA,YAAA,CACA,eAAA,CACA,OAAA,CACA,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AGJ,CACV,GAAM,CAAE,KAAA,CAAAjC,CAAM,CAAA,CAAIN,+BAAAA,EAA8B,CAAA,CAEhD,OAAOwC,gCAAAA,CACJ5B,CAAAA,CAAKe,CAAAA,CAAAA,EACJA,CAAAA,EAAU,IAAA,CAAOrB,CAAAA,CAAMM,CAAG,CAAA,CAAIa,EAAAA,CAASnB,CAAAA,CAAMM,CAAG,CAAA,CAAGe,CAAM,CAAA,CAC3D,CAACrB,CAAK,CACR,CACF,CAGO,SAASmC,CAAAA,CAAAA,CAA2B,CACzC,OAAOzC,+BAAAA,EAA8B,CAAA,CAAE,MACzC,CCtEA,8CAA6B,yDAItB,mDAMA,6CCVqC,IAetC0C,EAAAA,CAAa,0BAAA,CAGZ,SAASC,EAAAA,CAAkBC,CAAAA,CAA2B,CAC3D,MAAO,CAAA,EAAA","file":"/home/emems/web/bitsnap/bitsnap/bitsnap-react/dist/chunk-MLSKHOA3.js","sourcesContent":[null,"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 * Returns appearance API.\n *\n * It mirrors `CheckoutAppearance` (theme, tokens, elements) so a shop can reuse\n * one brand object for both. The resolver is pure: it turns the caller input\n * into a theme name, the tokens in effect, the slot overrides and the inline\n * style for the theme boundary.\n */\n\nexport type ReturnsTheme = \"light\" | \"dark\";\n\nexport type ReturnsAppearanceTokens = {\n /** Font family of the returns views. The library never loads fonts. */\n fontFamily?: string;\n /** Base font size. */\n fontSize?: string;\n /** Page background. */\n background?: string;\n /** Raised surfaces: cards, skeletons, summaries. */\n surface?: string;\n /** Main text color. */\n foreground?: string;\n /** Secondary text: descriptions, dates, hints. */\n mutedForeground?: string;\n /** Borders of cards, inputs and separators. */\n border?: string;\n /** Primary button background. */\n buttonBackground?: string;\n /** Primary button text. */\n buttonForeground?: string;\n /** Primary button background on hover. */\n buttonHoverBackground?: string;\n /** Hover surface of secondary buttons and selectable cards. */\n hoverSurface?: string;\n /** Focus ring color. Also applied to shared UI primitives through `--ring`. */\n focusRing?: string;\n /** Error color. */\n error?: string;\n /** Success color: result screen, completed and refunded statuses. */\n success?: string;\n /** Warning color: statuses that need attention. */\n warning?: string;\n /** Status badge background. */\n badgeBackground?: string;\n /** Status badge text. */\n badgeForeground?: string;\n /** Background of text inputs and the note field. */\n inputBackground?: string;\n /** Corner radius, applied through `--radius`. */\n radius?: string;\n};\n\n/**\n * Stable slot names. They are exposed as `data-bitsnap-returns-slot`\n * attributes so they can also be targeted from plain CSS.\n */\nexport const RETURNS_SLOT_NAMES = [\n // Frame\n \"root\",\n \"header\",\n \"title\",\n \"description\",\n \"backButton\",\n \"stepIndicator\",\n \"error\",\n \"emptyState\",\n \"skeleton\",\n // Auth\n \"emailForm\",\n \"emailInput\",\n \"codeForm\",\n \"codeInput\",\n \"resendButton\",\n \"logoutButton\",\n // Orders\n \"orderList\",\n \"orderCard\",\n \"orderReference\",\n \"orderDate\",\n \"orderTotal\",\n \"pagination\",\n // Selection\n \"lineList\",\n \"line\",\n \"lineName\",\n \"linePrice\",\n \"lineQuantityControl\",\n \"quantityButton\",\n \"quantityInput\",\n \"lineIneligibleReason\",\n \"noteInput\",\n // Confirmation and result\n \"summary\",\n \"submitButton\",\n \"secondaryButton\",\n \"successState\",\n \"returnReference\",\n \"returnInstructions\",\n // My returns\n \"returnList\",\n \"returnCard\",\n \"statusBadge\",\n \"history\",\n \"historyEntry\",\n] as const;\n\nexport type ReturnsSlotName = (typeof RETURNS_SLOT_NAMES)[number];\n\nexport type ReturnsSlotAppearance = SlotAppearance;\n\nexport type ReturnsAppearanceElements = AppearanceElements<ReturnsSlotName>;\n\nexport type ReturnsAppearance = {\n /** `\"light\"` or `\"dark\"`. Omitted means `\"light\"`. */\n theme?: ReturnsTheme;\n /** Partial overrides applied over the theme preset. */\n tokens?: ReturnsAppearanceTokens;\n /** Per element `className`/`style` overrides. */\n elements?: ReturnsAppearanceElements;\n};\n\nexport type ResolvedReturnsAppearance = {\n theme: ReturnsTheme;\n /** Tokens that are in effect (the theme preset plus caller overrides). */\n tokens: ReturnsAppearanceTokens;\n elements: ReturnsAppearanceElements;\n /** Theme marker class for the theme boundary. */\n boundaryClassName: string;\n /** Inline custom properties applied to the returns root. */\n boundaryStyle: CSSProperties;\n};\n\n/** CSS custom property used for each token. */\nexport const RETURNS_TOKEN_VARIABLES = {\n fontFamily: \"--bitsnap-returns-font-family\",\n fontSize: \"--bitsnap-returns-font-size\",\n background: \"--bitsnap-returns-background\",\n surface: \"--bitsnap-returns-surface\",\n foreground: \"--bitsnap-returns-foreground\",\n mutedForeground: \"--bitsnap-returns-muted-foreground\",\n border: \"--bitsnap-returns-border\",\n buttonBackground: \"--bitsnap-returns-button-background\",\n buttonForeground: \"--bitsnap-returns-button-foreground\",\n buttonHoverBackground: \"--bitsnap-returns-button-hover-background\",\n hoverSurface: \"--bitsnap-returns-hover-surface\",\n focusRing: \"--bitsnap-returns-focus-ring\",\n error: \"--bitsnap-returns-error\",\n success: \"--bitsnap-returns-success\",\n warning: \"--bitsnap-returns-warning\",\n badgeBackground: \"--bitsnap-returns-badge-background\",\n badgeForeground: \"--bitsnap-returns-badge-foreground\",\n inputBackground: \"--bitsnap-returns-input-background\",\n radius: \"--bitsnap-returns-radius\",\n} as const;\n\nexport type ReturnsTokenName = keyof typeof RETURNS_TOKEN_VARIABLES;\n\n/**\n * Complete palettes. They carry colors and radius only, so typography is never\n * reset implicitly. `returns.css` falls back to the light values, which keeps\n * the views usable even when the boundary style is missing.\n */\nexport const RETURNS_THEME_PRESETS: Record<\n ReturnsTheme,\n ReturnsAppearanceTokens\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 success: \"#16a34a\",\n warning: \"#d97706\",\n badgeBackground: \"#f4f4f5\",\n badgeForeground: \"#3f3f46\",\n inputBackground: \"#ffffff\",\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 success: \"#4ade80\",\n warning: \"#fbbf24\",\n badgeBackground: \"#3f3f46\",\n badgeForeground: \"#e4e4e7\",\n inputBackground: \"#27272a\",\n radius: \"8px\",\n },\n};\n\n/**\n * Shared UI primitives (`Button`, `Input`, `Label`, ...) read the shadcn theme\n * variables, so those follow the returns tokens inside the boundary.\n */\nconst RETURNS_SHADCN_VARIABLES: ShadcnVariableMapping<ReturnsTokenName> = [\n { token: \"background\", variable: \"--background\" },\n { token: \"foreground\", variable: \"--foreground\" },\n { token: \"surface\", variable: \"--card\" },\n { token: \"foreground\", variable: \"--card-foreground\" },\n { token: \"surface\", variable: \"--popover\" },\n { token: \"foreground\", variable: \"--popover-foreground\" },\n { token: \"buttonBackground\", variable: \"--primary\" },\n { token: \"buttonForeground\", variable: \"--primary-foreground\" },\n { token: \"surface\", variable: \"--secondary\" },\n { token: \"foreground\", variable: \"--secondary-foreground\" },\n { token: \"hoverSurface\", variable: \"--accent\" },\n { token: \"foreground\", variable: \"--accent-foreground\" },\n { token: \"mutedForeground\", variable: \"--muted-foreground\" },\n { token: \"border\", variable: \"--border\" },\n { token: \"border\", variable: \"--input\" },\n { token: \"focusRing\", variable: \"--ring\" },\n { token: \"error\", variable: \"--destructive\" },\n { token: \"radius\", variable: \"--radius\" },\n];\n\nexport function resolveReturnsAppearance(\n appearance?: ReturnsAppearance,\n): ResolvedReturnsAppearance {\n const resolved = resolveAppearanceCore<\n ReturnsTokenName,\n ReturnsTheme,\n ReturnsSlotName\n >(appearance, {\n defaultTheme: \"light\",\n presets: RETURNS_THEME_PRESETS,\n variables: RETURNS_TOKEN_VARIABLES,\n shadcnVariables: RETURNS_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 getReturnsSlotAppearance(\n resolved: ResolvedReturnsAppearance,\n slot: ReturnsSlotName,\n): ReturnsSlotAppearance | undefined {\n return getSlotAppearance(resolved.elements, slot);\n}\n","import { createContext, useContext, useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n getReturnsSlotAppearance,\n resolveReturnsAppearance,\n type ResolvedReturnsAppearance,\n type ReturnsAppearance,\n type ReturnsSlotAppearance,\n type ReturnsSlotName,\n} from \"./appearance\";\n\nconst ReturnsAppearanceContext = createContext<ResolvedReturnsAppearance>(\n resolveReturnsAppearance(),\n);\n\n/**\n * Returns scoped appearance provider. It only wraps the returns views, so the\n * configuration never leaks into checkout, the panel or the host page.\n */\nexport function ReturnsAppearanceProvider({\n appearance,\n children,\n}: {\n appearance?: ReturnsAppearance;\n children: ReactNode;\n}) {\n const resolved = useMemo(\n () => resolveReturnsAppearance(appearance),\n [appearance],\n );\n\n return (\n <ReturnsAppearanceContext.Provider value={resolved}>\n {children}\n </ReturnsAppearanceContext.Provider>\n );\n}\n\nexport function useReturnsAppearance(): ResolvedReturnsAppearance {\n return useContext(ReturnsAppearanceContext);\n}\n\n/**\n * Returns the caller overrides for a slot, meant to be merged with the\n * built-in presentation:\n *\n * ```tsx\n * const slot = useReturnsSlot(\"title\");\n *\n * return <h2 className={cn(\"text-xl font-semibold\", slot.className)} style={slot.style} />;\n * ```\n */\nexport function useReturnsSlot(slot: ReturnsSlotName): ReturnsSlotAppearance {\n const resolved = useReturnsAppearance();\n\n return getReturnsSlotAppearance(resolved, slot) ?? {};\n}\n","import { Environment } from \"@/src/gen/proto/common/v1/environment_pb\";\nimport type { ReturnsAppearance } from \"./appearance\";\nimport { brandColorTokens } from \"./color\";\nimport type { ReturnsTexts } from \"./texts\";\n\n/**\n * Compatibility layer for the `bitsnap-react` 1.6.0 returns widget. Everything\n * here is pure; the components and hooks apply it at their boundary.\n */\n\n/** Environment as a string or as the proto enum used by 1.6.0. */\nexport type ReturnsEnvironmentInput = \"production\" | \"test\" | Environment;\n\n/** Text keys of the 1.6.0 widget. */\nexport type LegacyReturnsTexts = Partial<{\n title: string;\n email: string;\n sendCode: string;\n code: string;\n verify: string;\n orders: string;\n submit: string;\n note: string;\n loading: string;\n history: string;\n}>;\n\n/** Our text keys plus the 1.6.0 ones. Our keys win when both are given. */\nexport type ReturnsTextsInput = Partial<ReturnsTexts> & LegacyReturnsTexts;\n\n/** 1.6.0 `theme` prop. */\nexport type LegacyReturnsTheme = { brandColor?: string };\n\n/** Backend environment for a string or enum value. Defaults to production. */\nexport function resolveReturnsEnvironment(\n environment?: ReturnsEnvironmentInput,\n): Environment {\n return environment === \"test\" || environment === Environment.TEST\n ? Environment.TEST\n : Environment.PRODUCTION;\n}\n\nconst LEGACY_TEXT_KEYS: Record<\n Exclude<keyof LegacyReturnsTexts, \"loading\">,\n readonly (keyof ReturnsTexts)[]\n> = {\n title: [\"emailStepTitle\"],\n email: [\"emailLabel\"],\n sendCode: [\"emailSubmit\"],\n code: [\"codeLabel\"],\n verify: [\"codeSubmit\"],\n orders: [\"ordersTitle\"],\n submit: [\"confirmationSubmit\"],\n note: [\"noteLabel\"],\n history: [\"myReturnsTitle\", \"myReturnsLink\"],\n};\n\n/**\n * Maps 1.6.0 text keys onto ours. A key of the new API always wins over the\n * legacy key that maps to it. `loading` has the same name in both.\n */\nexport function mapLegacyTexts(\n texts: ReturnsTextsInput | undefined,\n): Partial<ReturnsTexts> | undefined {\n if (texts == null) {\n return undefined;\n }\n\n const result: Partial<ReturnsTexts> = {};\n for (const [legacyKey, targets] of Object.entries(LEGACY_TEXT_KEYS) as [\n keyof typeof LEGACY_TEXT_KEYS,\n readonly (keyof ReturnsTexts)[],\n ][]) {\n const value = texts[legacyKey];\n if (typeof value === \"string\") {\n for (const target of targets) {\n result[target] = value;\n }\n }\n }\n\n for (const key of Object.keys(texts) as (keyof ReturnsTextsInput)[]) {\n if (key in LEGACY_TEXT_KEYS) {\n continue;\n }\n const value = texts[key];\n if (typeof value === \"string\") {\n result[key as keyof ReturnsTexts] = value;\n }\n }\n\n return result;\n}\n\n/**\n * Appearance with the 1.6.0 `brandColor` applied as button background, focus\n * ring and readable button foreground. Explicit `appearance.tokens` win.\n */\nexport function resolveBrandAppearance(\n appearance: ReturnsAppearance | undefined,\n theme: LegacyReturnsTheme | undefined,\n): ReturnsAppearance | undefined {\n const color = theme?.brandColor?.trim();\n if (color == null || color === \"\") {\n return appearance;\n }\n return {\n ...appearance,\n tokens: { ...brandColorTokens(color), ...appearance?.tokens },\n };\n}\n\n/** Arguments of the paged hooks in either call style. */\nexport type PagedArguments = {\n pageSize: number;\n /** Explicit page token of the positional (1.6.0) form. */\n explicitPageToken: string | undefined;\n};\n\n/**\n * Normalizes `(pageSize?, pageToken?)` (1.6.0) and `({ pageSize })` (ours).\n * Both forms default to 20 items, like 1.6.0.\n */\nexport function resolvePagedArguments(\n first: number | { pageSize?: number } | undefined,\n pageToken: string | undefined,\n): PagedArguments {\n if (typeof first === \"object\" && first != null) {\n return { pageSize: first.pageSize ?? 20, explicitPageToken: undefined };\n }\n if (typeof first === \"number\" || pageToken !== undefined) {\n return { pageSize: first ?? 20, explicitPageToken: pageToken ?? \"\" };\n }\n return { pageSize: 20, explicitPageToken: undefined };\n}\n","import { lookupText, resolveTexts, type LocaleTables } from \"@/src/lib/texts\";\n\n/**\n * Every string the returns views render. Pass a partial object through the\n * `texts` prop of `BitsnapReturns`/`ReturnsProvider` to override any of them,\n * whatever the locale. Strings with `{name}` placeholders keep them in\n * overrides; unknown placeholders are left untouched.\n */\nexport type ReturnsTexts = {\n // Frame\n /** Label of the back buttons. */\n back: string;\n /** Step indicator, placeholders `{current}` and `{total}`. */\n stepIndicator: string;\n /** Skeleton accessible label. */\n loading: string;\n /** Button that opens the list of previous returns. */\n myReturnsLink: string;\n\n // Email step\n emailStepTitle: string;\n emailStepDescription: string;\n emailLabel: string;\n emailPlaceholder: string;\n emailSubmit: string;\n\n // Code step\n codeStepTitle: string;\n /** Placeholder `{email}`. */\n codeStepDescription: string;\n codeLabel: string;\n codeSubmit: string;\n resend: string;\n /** Placeholder `{seconds}`. */\n resendIn: string;\n logout: string;\n\n // Orders\n ordersTitle: string;\n ordersDescription: string;\n ordersEmpty: string;\n /** Placeholder `{reference}`. */\n orderTitle: string;\n /** Placeholder `{count}`. */\n orderReturnableLines: string;\n orderSelect: string;\n paginationPrevious: string;\n paginationNext: string;\n /** Placeholders `{page}` and `{total}` (number of orders). */\n paginationInfo: string;\n\n // Order detail\n /** Placeholder `{reference}`. */\n orderDetailTitle: string;\n orderDetailDescription: string;\n /** Placeholder `{name}`. */\n quantityLabel: string;\n /** Placeholder `{name}`. */\n quantityDecrease: string;\n /** Placeholder `{name}`. */\n quantityIncrease: string;\n /** Placeholder `{available}`. */\n quantityOfAvailable: string;\n /** Shown for an ineligible line without a reason from the backend. */\n lineIneligibleFallback: string;\n noteLabel: string;\n notePlaceholder: string;\n selectionContinue: string;\n selectionEmpty: string;\n previousReturnsTitle: string;\n\n // Confirmation\n confirmationTitle: string;\n confirmationDescription: string;\n confirmationSummary: string;\n /** Placeholder `{quantity}`. */\n confirmationQuantity: string;\n confirmationNote: string;\n confirmationSubmit: string;\n\n // Result\n successTitle: string;\n successDescription: string;\n successReference: string;\n successInstructions: string;\n successDone: string;\n\n // My returns\n myReturnsTitle: string;\n myReturnsDescription: string;\n myReturnsEmpty: string;\n myReturnOpen: string;\n myReturnDetailTitle: string;\n /** Placeholder `{reference}`. */\n myReturnTitle: string;\n myReturnCreatedAt: string;\n myReturnRefund: string;\n myReturnLines: string;\n /** Placeholders `{requested}`, `{approved}`, `{received}`. */\n myReturnLineQuantities: string;\n myReturnNote: string;\n myReturnHistory: string;\n\n // Request status labels\n statusSubmitted: string;\n statusApproved: string;\n statusRejected: string;\n statusAwaitingReceipt: string;\n statusReceived: string;\n statusCompleted: string;\n statusCancelled: string;\n statusRefunded: string;\n /** Any status the backend adds later. */\n statusFallback: string;\n\n // Refund status labels\n refundStatusNotStarted: string;\n refundStatusPending: string;\n refundStatusSucceeded: string;\n refundStatusFailed: string;\n refundStatusFallback: string;\n\n // Error messages\n errorGeneric: string;\n errorInvalidEmail: string;\n errorInvalidCode: string;\n errorSessionExpired: string;\n errorOrderNotFound: string;\n errorReturnNotFound: string;\n errorQuantityUnavailable: string;\n errorItemNotReturnable: string;\n errorReturnsDisabled: string;\n errorRateLimited: string;\n errorIdempotencyConflict: string;\n errorDeliveryFailed: string;\n errorRetry: string;\n};\n\nexport type ReturnsTextKey = keyof ReturnsTexts;\n\nexport const RETURNS_TEXT_TABLES: LocaleTables<ReturnsTextKey> = {\n en: {\n back: \"Back\",\n stepIndicator: \"Step {current} of {total}\",\n loading: \"Loading\",\n myReturnsLink: \"My returns\",\n\n emailStepTitle: \"Return a product\",\n emailStepDescription:\n \"Enter the email address you used for the order. We will send you a verification code.\",\n emailLabel: \"Email address\",\n emailPlaceholder: \"name@example.com\",\n emailSubmit: \"Send code\",\n\n codeStepTitle: \"Enter the code\",\n codeStepDescription: \"We sent a verification code to {email}.\",\n codeLabel: \"Verification code\",\n codeSubmit: \"Verify\",\n resend: \"Send the code again\",\n resendIn: \"Send again in {seconds} s\",\n logout: \"Sign out\",\n\n ordersTitle: \"Your orders\",\n ordersDescription: \"Choose the order that contains the product to return.\",\n ordersEmpty: \"There are no orders eligible for return.\",\n orderTitle: \"Order {reference}\",\n orderReturnableLines: \"Products available to return: {count}\",\n orderSelect: \"Choose\",\n paginationPrevious: \"Previous\",\n paginationNext: \"Next\",\n paginationInfo: \"Page {page}, {total} orders\",\n\n orderDetailTitle: \"Order {reference}\",\n orderDetailDescription: \"Select the products and quantities to return.\",\n quantityLabel: \"Quantity to return: {name}\",\n quantityDecrease: \"Decrease quantity: {name}\",\n quantityIncrease: \"Increase quantity: {name}\",\n quantityOfAvailable: \"of {available}\",\n lineIneligibleFallback: \"This product cannot be returned.\",\n noteLabel: \"Note (optional)\",\n notePlaceholder: \"Tell us why you are returning the product\",\n selectionContinue: \"Continue\",\n selectionEmpty: \"Select at least one item to return.\",\n previousReturnsTitle: \"Earlier returns for this order\",\n\n confirmationTitle: \"Confirm the return\",\n confirmationDescription: \"Check the products before you submit the request.\",\n confirmationSummary: \"Products to return\",\n confirmationQuantity: \"Quantity: {quantity}\",\n confirmationNote: \"Your note\",\n confirmationSubmit: \"Submit return request\",\n\n successTitle: \"Return request submitted\",\n successDescription: \"We received your request and will keep you posted.\",\n successReference: \"Request number\",\n successInstructions: \"What to do next\",\n successDone: \"Back to orders\",\n\n myReturnsTitle: \"My returns\",\n myReturnsDescription: \"Track the status of your return requests.\",\n myReturnsEmpty: \"You have not submitted any return requests yet.\",\n myReturnOpen: \"Details\",\n myReturnDetailTitle: \"Return details\",\n myReturnTitle: \"Return {reference}\",\n myReturnCreatedAt: \"Submitted\",\n myReturnRefund: \"Refund\",\n myReturnLines: \"Products\",\n myReturnLineQuantities:\n \"Requested: {requested}, approved: {approved}, received: {received}\",\n myReturnNote: \"Your note\",\n myReturnHistory: \"History\",\n\n statusSubmitted: \"Submitted\",\n statusApproved: \"Approved\",\n statusRejected: \"Rejected\",\n statusAwaitingReceipt: \"Awaiting the package\",\n statusReceived: \"Package received\",\n statusCompleted: \"Completed\",\n statusCancelled: \"Cancelled\",\n statusRefunded: \"Refunded\",\n statusFallback: \"In progress\",\n\n refundStatusNotStarted: \"Not started\",\n refundStatusPending: \"Refund in progress\",\n refundStatusSucceeded: \"Refunded\",\n refundStatusFailed: \"Refund failed\",\n refundStatusFallback: \"Unknown\",\n\n errorGeneric: \"Something went wrong. Please try again.\",\n errorInvalidEmail: \"Enter a valid email address.\",\n errorInvalidCode: \"The code is invalid or has expired.\",\n errorSessionExpired: \"Your session has expired. Verify your email again.\",\n errorOrderNotFound: \"We could not find this order.\",\n errorReturnNotFound: \"We could not find this return request.\",\n errorQuantityUnavailable:\n \"The selected quantity is no longer available for return.\",\n errorItemNotReturnable: \"One of the selected products cannot be returned.\",\n errorReturnsDisabled: \"Returns are not available in this shop.\",\n errorRateLimited: \"Too many attempts. Please try again later.\",\n errorIdempotencyConflict:\n \"This request was already submitted with different contents. Reload and try again.\",\n errorDeliveryFailed: \"We could not send the code. Please try again.\",\n errorRetry: \"Try again\",\n },\n pl: {\n back: \"Wstecz\",\n stepIndicator: \"Krok {current} z {total}\",\n loading: \"Ładowanie\",\n myReturnsLink: \"Moje zwroty\",\n\n emailStepTitle: \"Zwróć produkt\",\n emailStepDescription:\n \"Podaj adres e-mail użyty w zamówieniu. Wyślemy na niego kod weryfikacyjny.\",\n emailLabel: \"Adres e-mail\",\n emailPlaceholder: \"jan@example.com\",\n emailSubmit: \"Wyślij kod\",\n\n codeStepTitle: \"Wpisz kod\",\n codeStepDescription: \"Wysłaliśmy kod weryfikacyjny na adres {email}.\",\n codeLabel: \"Kod weryfikacyjny\",\n codeSubmit: \"Zweryfikuj\",\n resend: \"Wyślij kod ponownie\",\n resendIn: \"Wyślij ponownie za {seconds} s\",\n logout: \"Wyloguj się\",\n\n ordersTitle: \"Twoje zamówienia\",\n ordersDescription: \"Wybierz zamówienie z produktem do zwrotu.\",\n ordersEmpty: \"Brak zamówień, które można zwrócić.\",\n orderTitle: \"Zamówienie {reference}\",\n orderReturnableLines: \"Produkty do zwrotu: {count}\",\n orderSelect: \"Wybierz\",\n paginationPrevious: \"Poprzednia\",\n paginationNext: \"Następna\",\n paginationInfo: \"Strona {page}, zamówień: {total}\",\n\n orderDetailTitle: \"Zamówienie {reference}\",\n orderDetailDescription: \"Wybierz produkty i ilości do zwrotu.\",\n quantityLabel: \"Ilość do zwrotu: {name}\",\n quantityDecrease: \"Zmniejsz ilość: {name}\",\n quantityIncrease: \"Zwiększ ilość: {name}\",\n quantityOfAvailable: \"z {available}\",\n lineIneligibleFallback: \"Ten produkt nie podlega zwrotowi.\",\n noteLabel: \"Uwagi (opcjonalnie)\",\n notePlaceholder: \"Napisz, dlaczego zwracasz produkt\",\n selectionContinue: \"Dalej\",\n selectionEmpty: \"Wybierz co najmniej jedną sztukę do zwrotu.\",\n previousReturnsTitle: \"Wcześniejsze zwroty tego zamówienia\",\n\n confirmationTitle: \"Potwierdź zwrot\",\n confirmationDescription: \"Sprawdź produkty przed wysłaniem zgłoszenia.\",\n confirmationSummary: \"Produkty do zwrotu\",\n confirmationQuantity: \"Ilość: {quantity}\",\n confirmationNote: \"Twoje uwagi\",\n confirmationSubmit: \"Wyślij zgłoszenie zwrotu\",\n\n successTitle: \"Zgłoszenie zwrotu zostało wysłane\",\n successDescription: \"Otrzymaliśmy zgłoszenie i będziemy informować o jego statusie.\",\n successReference: \"Numer zgłoszenia\",\n successInstructions: \"Co dalej\",\n successDone: \"Wróć do zamówień\",\n\n myReturnsTitle: \"Moje zwroty\",\n myReturnsDescription: \"Sprawdź status swoich zgłoszeń zwrotu.\",\n myReturnsEmpty: \"Nie masz jeszcze żadnych zgłoszeń zwrotu.\",\n myReturnOpen: \"Szczegóły\",\n myReturnDetailTitle: \"Szczegóły zwrotu\",\n myReturnTitle: \"Zwrot {reference}\",\n myReturnCreatedAt: \"Zgłoszono\",\n myReturnRefund: \"Zwrot środków\",\n myReturnLines: \"Produkty\",\n myReturnLineQuantities:\n \"Zgłoszono: {requested}, zaakceptowano: {approved}, odebrano: {received}\",\n myReturnNote: \"Twoje uwagi\",\n myReturnHistory: \"Historia\",\n\n statusSubmitted: \"Zgłoszony\",\n statusApproved: \"Zaakceptowany\",\n statusRejected: \"Odrzucony\",\n statusAwaitingReceipt: \"Oczekiwanie na paczkę\",\n statusReceived: \"Paczka odebrana\",\n statusCompleted: \"Zakończony\",\n statusCancelled: \"Anulowany\",\n statusRefunded: \"Środki zwrócone\",\n statusFallback: \"W trakcie\",\n\n refundStatusNotStarted: \"Nie rozpoczęto\",\n refundStatusPending: \"Zwrot środków w toku\",\n refundStatusSucceeded: \"Środki zwrócone\",\n refundStatusFailed: \"Zwrot środków nie powiódł się\",\n refundStatusFallback: \"Nieznany\",\n\n errorGeneric: \"Coś poszło nie tak. Spróbuj ponownie.\",\n errorInvalidEmail: \"Podaj poprawny adres e-mail.\",\n errorInvalidCode: \"Kod jest nieprawidłowy lub wygasł.\",\n errorSessionExpired: \"Sesja wygasła. Zweryfikuj adres e-mail ponownie.\",\n errorOrderNotFound: \"Nie znaleziono tego zamówienia.\",\n errorReturnNotFound: \"Nie znaleziono tego zgłoszenia zwrotu.\",\n errorQuantityUnavailable:\n \"Wybrana ilość nie jest już dostępna do zwrotu.\",\n errorItemNotReturnable: \"Jeden z wybranych produktów nie podlega zwrotowi.\",\n errorReturnsDisabled: \"Zwroty nie są dostępne w tym sklepie.\",\n errorRateLimited: \"Zbyt wiele prób. Spróbuj ponownie później.\",\n errorIdempotencyConflict:\n \"To zgłoszenie zostało już wysłane z inną zawartością. Odśwież stronę i spróbuj ponownie.\",\n errorDeliveryFailed: \"Nie udało się wysłać kodu. Spróbuj ponownie.\",\n errorRetry: \"Spróbuj ponownie\",\n },\n};\n\n/** Default texts for a locale merged with the caller overrides. */\nexport function resolveReturnsTexts(\n locale: string,\n overrides?: Partial<ReturnsTexts>,\n): ReturnsTexts {\n return resolveTexts(RETURNS_TEXT_TABLES, locale, overrides);\n}\n\nexport function getReturnsText(\n key: ReturnsTextKey,\n locale: string,\n overrides?: Partial<ReturnsTexts>,\n): string {\n return lookupText(resolveReturnsTexts(locale, overrides), key);\n}\n\n/** Replaces `{name}` placeholders. Unknown placeholders stay as they are. */\nexport function fillText(\n template: string,\n values: Record<string, string | number>,\n): string {\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n Object.prototype.hasOwnProperty.call(values, name)\n ? String(values[name])\n : match,\n );\n}\n\nconst STATUS_TEXT_KEYS: Record<string, ReturnsTextKey> = {\n submitted: \"statusSubmitted\",\n approved: \"statusApproved\",\n rejected: \"statusRejected\",\n awaiting_receipt: \"statusAwaitingReceipt\",\n received: \"statusReceived\",\n completed: \"statusCompleted\",\n cancelled: \"statusCancelled\",\n refunded: \"statusRefunded\",\n};\n\nconst REFUND_STATUS_TEXT_KEYS: Record<string, ReturnsTextKey> = {\n not_started: \"refundStatusNotStarted\",\n pending: \"refundStatusPending\",\n succeeded: \"refundStatusSucceeded\",\n failed: \"refundStatusFailed\",\n};\n\n/** Text key for a backend request status, with a fallback for unknown ones. */\nexport function statusTextKey(status: string): ReturnsTextKey {\n return STATUS_TEXT_KEYS[status] ?? \"statusFallback\";\n}\n\n/** Text key for a backend refund status, with a fallback for unknown ones. */\nexport function refundStatusTextKey(status: string): ReturnsTextKey {\n return REFUND_STATUS_TEXT_KEYS[status] ?? \"refundStatusFallback\";\n}\n","import { createContext, useCallback, useContext, useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { getLocale } from \"@/src/components/checkout/locale\";\nimport {\n fillText,\n resolveReturnsTexts,\n type ReturnsTextKey,\n type ReturnsTexts,\n} from \"./texts\";\n\ntype ReturnsTextsContextValue = {\n /** Active locale (the `locale` prop or the library locale). */\n locale: string;\n texts: ReturnsTexts;\n};\n\nconst ReturnsTextsContext = createContext<ReturnsTextsContextValue>({\n locale: \"pl-PL\",\n texts: resolveReturnsTexts(\"pl-PL\"),\n});\n\n/**\n * Returns scoped texts provider. Carries the `texts` overrides and the\n * `locale` prop down to the returns tree.\n */\nexport function ReturnsTextsProvider({\n texts,\n locale,\n children,\n}: {\n texts?: Partial<ReturnsTexts>;\n locale?: string;\n children: ReactNode;\n}) {\n const activeLocale = locale ?? getLocale();\n const value = useMemo(\n () => ({\n locale: activeLocale,\n texts: resolveReturnsTexts(activeLocale, texts),\n }),\n [activeLocale, texts],\n );\n\n return (\n <ReturnsTextsContext.Provider value={value}>\n {children}\n </ReturnsTextsContext.Provider>\n );\n}\n\n/**\n * Returns a lookup for the returns strings: the caller override when provided,\n * otherwise the default for the locale. Optional `values` fill `{placeholders}`.\n */\nexport function useReturnsText(): (\n key: ReturnsTextKey,\n values?: Record<string, string | number>,\n) => string {\n const { texts } = useContext(ReturnsTextsContext);\n\n return useCallback(\n (key, values) =>\n values == null ? texts[key] : fillText(texts[key], values),\n [texts],\n );\n}\n\n/** Active locale of the returns views, for date and money formatting. */\nexport function useReturnsLocale(): string {\n return useContext(ReturnsTextsContext).locale;\n}\n","import { createClient } from \"@connectrpc/connect\";\nimport {\n createConnectQueryKey,\n TransportProvider,\n} from \"@connectrpc/connect-query\";\nimport {\n QueryClient,\n QueryClientContext,\n QueryClientProvider,\n useQueryClient,\n} from \"@tanstack/react-query\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { CSSProperties, ReactNode } from \"react\";\nimport { Environment } from \"@/src/gen/proto/common/v1/environment_pb\";\nimport { ReturnsService } from \"@/src/gen/proto/public/v1/returns_pb\";\nimport {\n InstrumentProvider,\n useInstrument,\n type AnalyticsOption,\n} from \"@/src/analytics/instrument\";\nimport { cn } from \"@/src/lib/utils\";\nimport { getRpcTransport, getTransportHost } from \"@/src/rpc-provider\";\nimport type { Transport } from \"@connectrpc/connect\";\nimport type { ReturnsAppearance } from \"./appearance\";\nimport {\n ReturnsAppearanceProvider,\n useReturnsAppearance,\n useReturnsSlot,\n} from \"./appearance.context\";\nimport {\n clearStoredSession,\n expiryToMillis,\n getBrowserSessionStorage,\n readStoredSession,\n writeStoredSession,\n type StoredReturnsSession,\n} from \"./session-storage\";\nimport {\n mapLegacyTexts,\n resolveBrandAppearance,\n resolveReturnsEnvironment,\n type LegacyReturnsTheme,\n type ReturnsEnvironmentInput,\n type ReturnsTextsInput,\n} from \"./legacy\";\nimport { ReturnsTextsProvider } from \"./texts.context\";\n\n/**\n * Backend environment the returns calls run against. The library has no other\n * environment switch for public API calls, so this defaults to `\"production\"`.\n */\nexport type ReturnsEnvironment = \"production\" | \"test\";\n\nexport type ReturnsSessionStatus =\n /** Server render and first client render: storage has not been read yet. */\n | \"hydrating\"\n /** A `panelAccessToken` is being exchanged for a returns session. */\n | \"exchanging\"\n | \"anonymous\"\n | \"authenticated\";\n\n/** A pending email verification. */\nexport type ReturnsChallenge = {\n challengeId: string;\n email: string;\n /** Unix milliseconds when the next code may be requested. */\n resendAvailableAt: number;\n};\n\nexport type ReturnsContextValue = {\n projectID: string;\n environment: Environment;\n status: ReturnsSessionStatus;\n /** Session token. Never log it. */\n token: string | undefined;\n /** Failure of the last panel token exchange, if any. */\n exchangeError: unknown;\n challenge: ReturnsChallenge | undefined;\n setChallenge: (challenge: ReturnsChallenge | undefined) => void;\n /** Stores a freshly issued session in state and `sessionStorage`. */\n authenticate: (session: StoredReturnsSession) => void;\n /** Drops the session, the pending challenge and cached customer data. */\n clearSession: () => void;\n};\n\nconst ReturnsContext = createContext<ReturnsContextValue | undefined>(\n undefined,\n);\n\n/**\n * Context of the nearest `ReturnsProvider`. Throws a clear error outside of\n * it, naming the component or hook that was misplaced.\n */\nexport function useReturnsContext(name: string): ReturnsContextValue {\n const value = useContext(ReturnsContext);\n\n if (value == null) {\n throw new Error(`${name} must be rendered inside <ReturnsProvider>`);\n }\n\n return value;\n}\n\nexport type ReturnsProviderProps = {\n /** Bitsnap project ID. */\n projectID: string;\n /**\n * API host. Defaults to the host set with `setCustomHost`/`setHost`, then to\n * `https://bitsnap.pl`. Each provider keeps its own transport.\n */\n host?: string;\n /**\n * Backend environment, `\"production\"` unless set to `\"test\"`. The proto\n * `Environment` enum is accepted too.\n */\n environment?: ReturnsEnvironmentInput;\n /** Theme, tokens and per-element overrides. */\n appearance?: ReturnsAppearance;\n /**\n * Text overrides, applied whatever the locale. The keys of `bitsnap-react`\n * 1.6.0 (`title`, `email`, `sendCode`, ...) are accepted too; our own keys\n * win when both are given.\n */\n texts?: ReturnsTextsInput;\n /** `bitsnap-react` 1.6.0 brand color. Explicit `appearance.tokens` win. */\n theme?: LegacyReturnsTheme;\n /** Locale of texts, dates and money. Defaults to the library locale. */\n locale?: string;\n /**\n * Customer panel access token. When set, it is exchanged for a returns\n * session on mount, so the customer needs no second verification code.\n * Changing or removing it drops the session.\n */\n panelAccessToken?: string;\n /** Class of the themed root element. */\n className?: string;\n /**\n * Usage statistics for your Bitsnap dashboard (return started, return\n * submitted). On by default; `false` turns it off. An object lets you\n * forward every event: `{ onEvent }`. Inside `<Panel>` the panel's setting\n * applies unless this is given. Nothing is stored on the visitor's device.\n */\n analytics?: AnalyticsOption;\n children?: ReactNode;\n};\n\n/** Key prefix that matches every returns query, for invalidation and removal. */\nexport function returnsQueryKey(): readonly unknown[] {\n return createConnectQueryKey({\n schema: ReturnsService,\n cardinality: undefined,\n });\n}\n\n/** Longest delay `setTimeout` accepts. */\nconst MAX_TIMEOUT_MS = 2 ** 31 - 1;\n\nfunction SessionProvider({\n projectID,\n environment,\n transport,\n panelAccessToken,\n className,\n children,\n}: {\n projectID: string;\n environment: Environment;\n transport: Transport;\n panelAccessToken?: string;\n className?: string;\n children?: ReactNode;\n}) {\n const queryClient = useQueryClient();\n const { boundaryClassName, boundaryStyle } = useReturnsAppearance();\n const root = useReturnsSlot(\"root\");\n\n const [session, setSession] = useState<{\n status: ReturnsSessionStatus;\n token?: string;\n expiresAt?: number;\n }>({ status: \"hydrating\" });\n const [exchangeError, setExchangeError] = useState<unknown>();\n const [challenge, setChallenge] = useState<ReturnsChallenge>();\n const previousPanelToken = useRef<string | undefined>(undefined);\n\n const dropCachedData = useCallback(() => {\n // Query inputs carry the session token, so cached customer data must not\n // outlive the session. Only returns queries are touched.\n queryClient.removeQueries({ queryKey: returnsQueryKey() });\n }, [queryClient]);\n\n const clearSession = useCallback(() => {\n clearStoredSession(getBrowserSessionStorage(), projectID);\n setChallenge(undefined);\n setSession({ status: \"anonymous\" });\n dropCachedData();\n }, [projectID, dropCachedData]);\n\n const authenticate = useCallback(\n (next: StoredReturnsSession) => {\n writeStoredSession(getBrowserSessionStorage(), projectID, next);\n setExchangeError(undefined);\n setChallenge(undefined);\n setSession({\n status: \"authenticated\",\n token: next.token,\n expiresAt: next.expiresAt,\n });\n },\n [projectID],\n );\n\n // Hydrates from `sessionStorage`, or exchanges the panel token. Runs after\n // mount, so render never touches `window`.\n useEffect(() => {\n let cancelled = false;\n const storage = getBrowserSessionStorage();\n\n if (panelAccessToken == null || panelAccessToken === \"\") {\n const hadPanelToken = previousPanelToken.current != null;\n previousPanelToken.current = undefined;\n\n if (hadPanelToken) {\n clearSession();\n return;\n }\n\n const stored = readStoredSession(storage, projectID);\n setSession(\n stored != null\n ? {\n status: \"authenticated\",\n token: stored.token,\n expiresAt: stored.expiresAt,\n }\n : { status: \"anonymous\" },\n );\n return;\n }\n\n previousPanelToken.current = panelAccessToken;\n clearStoredSession(storage, projectID);\n dropCachedData();\n setExchangeError(undefined);\n setSession({ status: \"exchanging\" });\n\n createClient(ReturnsService, transport)\n .exchangePanelSession({\n projectId: projectID,\n accessToken: panelAccessToken,\n environment,\n })\n .then((response) => {\n if (cancelled) {\n return;\n }\n const expiresAt = expiryToMillis(response.expiresAt);\n if (response.sessionToken === \"\" || expiresAt == null) {\n throw new Error(\"EMPTY_SESSION\");\n }\n authenticate({ token: response.sessionToken, expiresAt });\n })\n .catch((error: unknown) => {\n if (cancelled) {\n return;\n }\n setExchangeError(error);\n setSession({ status: \"anonymous\" });\n });\n\n return () => {\n cancelled = true;\n };\n // `clearSession`, `authenticate` and `dropCachedData` only change with the\n // project or the query client, which are already covered.\n }, [panelAccessToken, projectID, environment, transport]);\n\n // Expired sessions are dropped even when the page stays open.\n useEffect(() => {\n if (session.status !== \"authenticated\" || session.expiresAt == null) {\n return;\n }\n const remaining = session.expiresAt - Date.now();\n if (remaining <= 0) {\n clearSession();\n return;\n }\n const timer = setTimeout(\n clearSession,\n Math.min(remaining, MAX_TIMEOUT_MS),\n );\n return () => clearTimeout(timer);\n }, [session.status, session.expiresAt, clearSession]);\n\n const value = useMemo<ReturnsContextValue>(\n () => ({\n projectID,\n environment,\n status: session.status,\n token: session.token,\n exchangeError,\n challenge,\n setChallenge,\n authenticate,\n clearSession,\n }),\n [\n projectID,\n environment,\n session.status,\n session.token,\n exchangeError,\n challenge,\n authenticate,\n clearSession,\n ],\n );\n\n return (\n <ReturnsContext.Provider value={value}>\n <div\n data-bitsnap-returns=\"root\"\n data-bitsnap-returns-slot=\"root\"\n className={cn(\"bitsnap-react\", boundaryClassName, className, root.className)}\n style={{ ...boundaryStyle, ...root.style } as CSSProperties}\n >\n {children}\n </div>\n </ReturnsContext.Provider>\n );\n}\n\n/**\n * Holds everything the returns views share: the per-instance transport, the\n * query client (when the app has none), appearance, texts and the returns\n * session. It renders the themed root element, so step components composed\n * under it are themed without extra markup.\n *\n * ```tsx\n * <ReturnsProvider projectID=\"…\" appearance={brand}>\n * <ReturnsOrderList onSelectOrder={setOrderId} />\n * </ReturnsProvider>\n * ```\n */\nexport function ReturnsProvider({\n projectID,\n host,\n environment,\n appearance,\n texts,\n theme,\n locale,\n panelAccessToken,\n className,\n analytics,\n children,\n}: ReturnsProviderProps) {\n const instrument = useInstrument(projectID, analytics, \"returns\");\n const existingQueryClient = useContext(QueryClientContext);\n const [ownQueryClient] = useState(() =>\n existingQueryClient == null\n ? new QueryClient({ defaultOptions: { queries: { staleTime: 5000 } } })\n : undefined,\n );\n\n const resolvedHost = host ?? getTransportHost();\n const transport = useMemo(\n () => getRpcTransport(resolvedHost),\n [resolvedHost],\n );\n\n const brandColor = theme?.brandColor;\n const resolvedAppearance = useMemo(\n () => resolveBrandAppearance(appearance, { brandColor }),\n [appearance, brandColor],\n );\n const resolvedTexts = useMemo(() => mapLegacyTexts(texts), [texts]);\n\n const content = (\n <InstrumentProvider value={instrument}>\n <TransportProvider transport={transport}>\n <ReturnsAppearanceProvider appearance={resolvedAppearance}>\n <ReturnsTextsProvider texts={resolvedTexts} locale={locale}>\n <SessionProvider\n projectID={projectID}\n environment={resolveReturnsEnvironment(environment)}\n transport={transport}\n panelAccessToken={panelAccessToken}\n className={className}\n >\n {children}\n </SessionProvider>\n </ReturnsTextsProvider>\n </ReturnsAppearanceProvider>\n </TransportProvider>\n </InstrumentProvider>\n );\n\n return existingQueryClient == null && ownQueryClient != null ? (\n <QueryClientProvider client={ownQueryClient}>{content}</QueryClientProvider>\n ) : (\n content\n );\n}\n\n/** Name of {@link ReturnsProvider} in `bitsnap-react` 1.6.0. */\nexport const BitsnapReturnsProvider = ReturnsProvider;\n\nexport type BitsnapReturnsProviderProps = ReturnsProviderProps;\n","import { timestampMs, type Timestamp } from \"@bufbuild/protobuf/wkt\";\n\n/** Returns session as kept in `sessionStorage`. */\nexport type StoredReturnsSession = {\n token: string;\n /** Expiry as unix milliseconds. */\n expiresAt: number;\n};\n\n/** The part of `Storage` the session code needs. */\nexport type SessionStorageLike = Pick<\n Storage,\n \"getItem\" | \"setItem\" | \"removeItem\"\n>;\n\nconst KEY_PREFIX = \"bitsnap-returns-session:\";\n\n/** One key per project, so projects on the same page never share a session. */\nexport function sessionStorageKey(projectID: string): string {\n return `${KEY_PREFIX}${projectID}`;\n}\n\n/**\n * `window.sessionStorage` when it is usable, otherwise `undefined`. Safe to\n * call on the server and where storage access throws (blocked cookies).\n */\nexport function getBrowserSessionStorage(): SessionStorageLike | undefined {\n try {\n return typeof window !== \"undefined\" ? window.sessionStorage : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Reads the stored session. Malformed and expired entries are removed and\n * reported as no session.\n */\nexport function readStoredSession(\n storage: SessionStorageLike | undefined,\n projectID: string,\n now: number = Date.now(),\n): StoredReturnsSession | undefined {\n if (storage == null) {\n return undefined;\n }\n\n const key = sessionStorageKey(projectID);\n\n try {\n const raw = storage.getItem(key);\n if (raw == null) {\n return undefined;\n }\n\n const parsed: unknown = JSON.parse(raw);\n if (\n parsed != null &&\n typeof parsed === \"object\" &&\n typeof (parsed as StoredReturnsSession).token === \"string\" &&\n (parsed as StoredReturnsSession).token.length > 0 &&\n typeof (parsed as StoredReturnsSession).expiresAt === \"number\" &&\n (parsed as StoredReturnsSession).expiresAt > now\n ) {\n const { token, expiresAt } = parsed as StoredReturnsSession;\n return { token, expiresAt };\n }\n\n storage.removeItem(key);\n } catch {\n try {\n storage.removeItem(key);\n } catch {\n // Storage is unusable; nothing else to clean up.\n }\n }\n\n return undefined;\n}\n\nexport function writeStoredSession(\n storage: SessionStorageLike | undefined,\n projectID: string,\n session: StoredReturnsSession,\n): void {\n try {\n storage?.setItem(sessionStorageKey(projectID), JSON.stringify(session));\n } catch {\n // The session still works in memory when storage is full or blocked.\n }\n}\n\nexport function clearStoredSession(\n storage: SessionStorageLike | undefined,\n projectID: string,\n): void {\n try {\n storage?.removeItem(sessionStorageKey(projectID));\n } catch {\n // Nothing to do when storage is blocked.\n }\n}\n\n/** Expiry of a backend session in unix milliseconds, `undefined` when missing. */\nexport function expiryToMillis(\n expiresAt: Timestamp | undefined,\n): number | undefined {\n return expiresAt == null ? undefined : timestampMs(expiresAt);\n}\n"]}
@@ -1,2 +0,0 @@
1
- import{a as p}from"./chunk-FF2ICGFQ.mjs";var u="X-Bitsnap-Client",i=`bitsnap-react@${p}`,d="bs_client",b={[u]:i},z=e=>t=>(t.header.set(u,i),e(t));function j(e){let t=e.indexOf("#"),n=t===-1?e:e.slice(0,t),a=t===-1?"":e.slice(t),o=n.includes("?")?/[?&]$/.test(n)?"":"&":"?";return`${n}${o}${d}=${encodeURIComponent(i)}${a}`}var g="https://bitsnap.pl",x=g;function K(e){console.log("setCustomHost",e),x=e}function T(e,t){return t.toLowerCase().startsWith("en")?e.en:e.pl}function k(e,t){let n={...e};if(t!=null)for(let[a,o]of Object.entries(t))o!=null&&(n[a]=o);return n}function l(e,t,n){return k(T(e,t),n)}function y(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.",checkoutFailed:"Something went wrong. Please try again later.",noPaymentGateway:"This shop doesn't accept online payments yet. Try again later or contact the seller.",gatewayNotConfigured:"Payments in this shop are not set up correctly. Try again later or contact the seller.",shippingNotConfigured:"Delivery in this shop is not configured yet. Try again later or contact the seller.",mixedRecurring:"Subscriptions and one-time products cannot be paid for together. Pay for them in separate orders.",currencyUnsupported:"The shop doesn't accept payments in this currency. Contact the seller.",priceChanged:"The product price has changed. Refresh the page to see the current price.",close:"Close cart",remove:"Remove",quantity:"Quantity",increaseQuantity:"Increase quantity",decreaseQuantity:"Decrease quantity",openCart:"Open cart",cartItemsCount:"Items in cart",lowestPrice30Days:"Lowest price in the last 30 days:",noPriceHistory:"No price data for the last 30 days",redirectFailed:"Could not redirect to the payment. Please try again later.",subscriptionUnsupported:"Subscriptions cannot be added to the cart yet.",searchCountry:"Find a country",noCountriesFound:"No countries found",countryRequired:"Choose a country to continue.",paymentForCart:"Cart payment",coupon:"Coupon",extrasCalculatedNext:"Discounts, shipping and taxes are calculated at the next step",loadFailed:"Could not load your cart.",retry:"Try again"},pl:{cart:"Koszyk",emptyCart:"Brak produkt\xF3w w koszyku.",total:"Suma:",delivery:"+ dostawa",chooseCountry:"Wybierz kraj",nextStep:"Nast\u0119pny krok",unavailableProducts:"Nie wszystkie produkty s\u0105 dost\u0119pne w magazynie.",checkoutFailed:"Co\u015B posz\u0142o nie tak. Spr\xF3buj ponownie p\xF3\u017Aniej.",noPaymentGateway:"Ten sklep nie przyjmuje jeszcze p\u0142atno\u015Bci online. Spr\xF3buj ponownie p\xF3\u017Aniej lub skontaktuj si\u0119 ze sprzedawc\u0105.",gatewayNotConfigured:"P\u0142atno\u015Bci w tym sklepie nie s\u0105 poprawnie skonfigurowane. Spr\xF3buj ponownie p\xF3\u017Aniej lub skontaktuj si\u0119 ze sprzedawc\u0105.",shippingNotConfigured:"Dostawa w tym sklepie nie jest jeszcze skonfigurowana. Spr\xF3buj ponownie p\xF3\u017Aniej lub skontaktuj si\u0119 ze sprzedawc\u0105.",mixedRecurring:"Subskrypcji i produkt\xF3w jednorazowych nie mo\u017Cna op\u0142aci\u0107 razem. Op\u0142a\u0107 je w osobnych zam\xF3wieniach.",currencyUnsupported:"Sklep nie przyjmuje p\u0142atno\u015Bci w tej walucie. Skontaktuj si\u0119 ze sprzedawc\u0105.",priceChanged:"Cena produktu si\u0119 zmieni\u0142a. Od\u015Bwie\u017C stron\u0119, aby zobaczy\u0107 aktualn\u0105 cen\u0119.",close:"Zamknij koszyk",remove:"Usu\u0144",quantity:"Ilo\u015B\u0107",increaseQuantity:"Zwi\u0119ksz ilo\u015B\u0107",decreaseQuantity:"Zmniejsz ilo\u015B\u0107",openCart:"Otw\xF3rz koszyk",cartItemsCount:"Produkt\xF3w w koszyku",lowestPrice30Days:"Najni\u017Csza cena z 30 dni:",noPriceHistory:"Brak danych o cenie z ostatnich 30 dni",redirectFailed:"Nie uda\u0142o si\u0119 przekierowa\u0107 do p\u0142atno\u015Bci. Spr\xF3buj ponownie p\xF3\u017Aniej.",subscriptionUnsupported:"Subskrypcji nie mo\u017Cna jeszcze doda\u0107 do koszyka.",searchCountry:"Znajd\u017A kraj",noCountriesFound:"Nie znaleziono kraj\xF3w",countryRequired:"Wybierz kraj, aby przej\u015B\u0107 dalej.",paymentForCart:"P\u0142atno\u015B\u0107 za koszyk",coupon:"Kupon",extrasCalculatedNext:"Rabaty, dostawa i podatki w nast\u0119pnym kroku",loadFailed:"Nie uda\u0142o si\u0119 wczyta\u0107 koszyka.",retry:"Spr\xF3buj ponownie"}};function m(e,t){return l(C,e,t)}function R(e,t,n){return y(m(t,n),e)}var s="pl-PL",c="bitsnap-locale",r;function E(e){let t=e?.trim();r=t?t.toLowerCase()==="en"?"en-US":t.toLowerCase()==="pl"?s:t:void 0,typeof localStorage<"u"&&(r==null?localStorage.removeItem(c):localStorage.setItem(c,r))}function F(){return r??(typeof localStorage<"u"?localStorage.getItem(c)??s:s)}import{clsx as h}from"clsx";import{twMerge as f}from"tailwind-merge";function H(...e){return f(h(e))}export{b as a,z as b,j as c,H as d,g as e,x as f,K as g,T as h,l as i,R as j,s as k,E as l,F as m};
2
- //# sourceMappingURL=chunk-P4Q5KXKS.mjs.map
@@ -1 +0,0 @@
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 /** Error shown when the checkout fails and the server gave no reason. */\n checkoutFailed: string;\n /** Error shown when the shop has no payment gateway connected. */\n noPaymentGateway: string;\n /** Error shown when the payment gateway of the shop is not set up. */\n gatewayNotConfigured: string;\n /** Error shown when delivery of the shop is not set up. */\n shippingNotConfigured: string;\n /** Error shown when the cart mixes subscriptions with one-time products. */\n mixedRecurring: string;\n /** Error shown when the cart currency cannot be paid in. */\n currencyUnsupported: string;\n /** Error shown when a price changed after the product was added. */\n priceChanged: string;\n /** Accessible name of the close button of the drawer. */\n close: string;\n /** Remove button of a cart line (also read together with the product name). */\n remove: string;\n /** Accessible name of the quantity control and its input. */\n quantity: string;\n /** Accessible name of the \"+\" quantity button. */\n increaseQuantity: string;\n /** Accessible name of the \"-\" quantity button. */\n decreaseQuantity: string;\n /** Accessible name of the cart button when it only shows an icon. */\n openCart: string;\n /** Hidden label of the number of products badge; the number is appended after a colon. */\n cartItemsCount: string;\n /** Label before the lowest price of the last 30 days; the price is appended. */\n lowestPrice30Days: string;\n /** Shown instead of the lowest price when the price has no history. */\n noPriceHistory: string;\n /** Error shown when redirecting to the payment failed. */\n redirectFailed: string;\n /** Error shown when a subscription is added to the cart. */\n subscriptionUnsupported: string;\n /** Country search placeholder. */\n searchCountry: string;\n /** Shown when the country search has no match. */\n noCountriesFound: string;\n /** Hint under the checkout button when no country is chosen. */\n countryRequired: string;\n /** Title of the Apple Pay and Google Pay sheet total. */\n paymentForCart: string;\n /** Coupon label in the Google Pay sheet; the code is appended. */\n coupon: string;\n /** Note under the cart total. */\n extrasCalculatedNext: string;\n /** Error shown when the products of the cart could not be loaded. */\n loadFailed: string;\n /** Button that loads the cart again. */\n retry: string;\n};\n\nexport type CheckoutTextKey = keyof CheckoutTexts;\n\nexport const CHECKOUT_TEXT_TABLES: LocaleTables<CheckoutTextKey> = {\n en: {\n cart: \"Cart\",\n emptyCart: \"Your cart is empty.\",\n total: \"Total:\",\n delivery: \"+ delivery\",\n chooseCountry: \"Choose a country\",\n nextStep: \"Next step\",\n unavailableProducts: \"Not all products are available.\",\n checkoutFailed: \"Something went wrong. Please try again later.\",\n noPaymentGateway:\n \"This shop doesn't accept online payments yet. Try again later or contact the seller.\",\n gatewayNotConfigured:\n \"Payments in this shop are not set up correctly. Try again later or contact the seller.\",\n shippingNotConfigured:\n \"Delivery in this shop is not configured yet. Try again later or contact the seller.\",\n mixedRecurring:\n \"Subscriptions and one-time products cannot be paid for together. Pay for them in separate orders.\",\n currencyUnsupported:\n \"The shop doesn't accept payments in this currency. Contact the seller.\",\n priceChanged: \"The product price has changed. Refresh the page to see the current price.\",\n close: \"Close cart\",\n remove: \"Remove\",\n quantity: \"Quantity\",\n increaseQuantity: \"Increase quantity\",\n decreaseQuantity: \"Decrease quantity\",\n openCart: \"Open cart\",\n cartItemsCount: \"Items in cart\",\n lowestPrice30Days: \"Lowest price in the last 30 days:\",\n noPriceHistory: \"No price data for the last 30 days\",\n redirectFailed: \"Could not redirect to the payment. Please try again later.\",\n subscriptionUnsupported: \"Subscriptions cannot be added to the cart yet.\",\n searchCountry: \"Find a country\",\n noCountriesFound: \"No countries found\",\n countryRequired: \"Choose a country to continue.\",\n paymentForCart: \"Cart payment\",\n coupon: \"Coupon\",\n extrasCalculatedNext:\n \"Discounts, shipping and taxes are calculated at the next step\",\n loadFailed: \"Could not load your cart.\",\n retry: \"Try again\",\n },\n pl: {\n cart: \"Koszyk\",\n emptyCart: \"Brak produktów w koszyku.\",\n total: \"Suma:\",\n delivery: \"+ dostawa\",\n chooseCountry: \"Wybierz kraj\",\n nextStep: \"Następny krok\",\n unavailableProducts: \"Nie wszystkie produkty są dostępne w magazynie.\",\n checkoutFailed: \"Coś poszło nie tak. Spróbuj ponownie później.\",\n noPaymentGateway:\n \"Ten sklep nie przyjmuje jeszcze płatności online. Spróbuj ponownie później lub skontaktuj się ze sprzedawcą.\",\n gatewayNotConfigured:\n \"Płatności w tym sklepie nie są poprawnie skonfigurowane. Spróbuj ponownie później lub skontaktuj się ze sprzedawcą.\",\n shippingNotConfigured:\n \"Dostawa w tym sklepie nie jest jeszcze skonfigurowana. Spróbuj ponownie później lub skontaktuj się ze sprzedawcą.\",\n mixedRecurring:\n \"Subskrypcji i produktów jednorazowych nie można opłacić razem. Opłać je w osobnych zamówieniach.\",\n currencyUnsupported:\n \"Sklep nie przyjmuje płatności w tej walucie. Skontaktuj się ze sprzedawcą.\",\n priceChanged: \"Cena produktu się zmieniła. Odśwież stronę, aby zobaczyć aktualną cenę.\",\n close: \"Zamknij koszyk\",\n remove: \"Usuń\",\n quantity: \"Ilość\",\n increaseQuantity: \"Zwiększ ilość\",\n decreaseQuantity: \"Zmniejsz ilość\",\n openCart: \"Otwórz koszyk\",\n cartItemsCount: \"Produktów w koszyku\",\n lowestPrice30Days: \"Najniższa cena z 30 dni:\",\n noPriceHistory: \"Brak danych o cenie z ostatnich 30 dni\",\n redirectFailed:\n \"Nie udało się przekierować do płatności. Spróbuj ponownie później.\",\n subscriptionUnsupported: \"Subskrypcji nie można jeszcze dodać do koszyka.\",\n searchCountry: \"Znajdź kraj\",\n noCountriesFound: \"Nie znaleziono krajów\",\n countryRequired: \"Wybierz kraj, aby przejść dalej.\",\n paymentForCart: \"Płatność za koszyk\",\n coupon: \"Kupon\",\n extrasCalculatedNext: \"Rabaty, dostawa i podatki w następnym kroku\",\n loadFailed: \"Nie udało się wczytać koszyka.\",\n retry: \"Spróbuj ponownie\",\n },\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,QAA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C1C,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"]}
@@ -1,4 +0,0 @@
1
- import{A as Ln,a as Ie,g as vn,h as wn,i as kn,j as Cn,k as Nn,s as In,v as Sn,w as Rn,x as An,y as Tn,z as Dn}from"./chunk-5R3WR22A.mjs";import{a as Ot,g as Ve,h as We,j as Pe,k as Ke,l as yn,m as Pn,n as Le}from"./chunk-3QG7H2AI.mjs";import{a as At,b as Tt,c as st,d as Dt,e as Lt,f as mn,j as B,k as De,l as ee,p as gn,q as S,r as lt,t as hn,u as Ee,v as bn}from"./chunk-UCESDAEC.mjs";import{a as St,b as un,c as Rt,d as x,f as K,g as fn,h as xn,j as he,m as V}from"./chunk-P4Q5KXKS.mjs";import{h as Et,l as ct,m as dt,n as Te,o as pn}from"./chunk-FF2ICGFQ.mjs";import{useAutoAnimate as ia}from"@formkit/auto-animate/react";import{useEffect as jn,useState as oe}from"react";import{jsx as Ze}from"react/jsx-runtime";function ue({className:e,...t}){return Ze("div",{"data-slot":"card",className:x("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function be({className:e,...t}){return Ze("div",{"data-slot":"card-header",className:x("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function ve({className:e,...t}){return Ze("div",{"data-slot":"card-title",className:x("leading-none font-semibold",e),...t})}function Ut({className:e,...t}){return Ze("div",{"data-slot":"card-description",className:x("text-muted-foreground text-sm",e),...t})}function me({className:e,...t}){return Ze("div",{"data-slot":"card-content",className:x("px-6",e),...t})}import*as En from"react";import{OTPInput as Qr,OTPInputContext as Yr}from"input-otp";import{MinusIcon as Xr}from"lucide-react";import{jsx as Oe,jsxs as ea}from"react/jsx-runtime";function On({className:e,containerClassName:t,...r}){return Oe(Qr,{"data-slot":"input-otp",containerClassName:x("flex items-center gap-2 has-disabled:opacity-50",t),className:x("disabled:cursor-not-allowed",e),...r})}function Mt({className:e,...t}){return Oe("div",{"data-slot":"input-otp-group",className:x("flex items-center",e),...t})}function Se({index:e,className:t,...r}){let o=En.useContext(Yr),{char:n,hasFakeCaret:a,isActive:i}=o?.slots[e]??{};return ea("div",{"data-slot":"input-otp-slot","data-active":i,className:x("data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:ring-destructive/20 dark:data-[active=true]:aria-invalid:ring-destructive/40 aria-invalid:border-destructive data-[active=true]:aria-invalid:border-destructive dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md data-[active=true]:z-10 data-[active=true]:ring-[3px]",t),...r,children:[n,a&&Oe("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:Oe("div",{className:"animate-caret-blink bg-foreground h-4 w-px duration-1000"})})]})}function Un({...e}){return Oe("div",{"data-slot":"input-otp-separator",role:"separator",...e,children:Oe(Xr,{})})}import{REGEXP_ONLY_DIGITS as sa}from"input-otp";import{jsx as jt,jsxs as na}from"react/jsx-runtime";function ta(){return na("div",{className:"flex items-center gap-2",children:[jt("div",{className:"h-3 w-3 animate-bounce rounded-full bg-current [animation-delay:-0.3s]"}),jt("div",{className:"h-3 w-3 animate-bounce rounded-full bg-current [animation-delay:-0.15s]"}),jt("div",{className:"h-3 w-3 animate-bounce rounded-full bg-current"})]})}var Z=ta;var ra="return_url",_t="__return_url",aa="accessToken";function Je(e){let t=new URLSearchParams(e).get(ra);return t?Mn(t):null}function Qe(e){typeof window>"u"||(e?window.sessionStorage.setItem(_t,e):window.sessionStorage.removeItem(_t))}function Ue(){if(typeof window>"u")return null;let e=window.sessionStorage.getItem(_t);return e?Mn(e):null}function oa(e,t){return t.some(r=>{if(e===r)return!0;let o=new URL(r).hostname,n=new URL(e).hostname;return n.endsWith(`.${o}`)||n===o})}function Mn(e){try{let t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="http:"||!oa(t.origin,We())?null:t.toString()}catch{return null}}function Me(e,t){let r=new URL(e);return r.searchParams.set(aa,t),r.toString()}import{jsx as w,jsxs as O}from"react/jsx-runtime";if(typeof window<"u"){let t=[window.location.origin,"https://bitsnap.pl","https://kursy.bitsnap.pl"];We().length===0&&Ve(Array.from(new Set(t)))}var ca=({projectID:e,host:t,reveal:r,email:o,setEmail:n,loginUser:a,isLoginLoading:i,errMsg:c})=>{let{projectID:d,host:l}=Pe();if(typeof window<"u"&&Ke(e??d,t??l)!=null)return window.location.href=window.location.href.replaceAll("login",""),null;let[u,g]=oe(!1),k=s=>/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(s.trim())?g(!0):g(!1),m=s=>{let{value:h}=s.target;k(h),n(h)};function v(){r()}function C(s){s.preventDefault(),a()}return w("main",{className:"mx-auto flex max-w-sm flex-1 flex-col justify-center space-y-12",children:w("div",{className:x("flex min-w-sm flex-col gap-6"),children:O(ue,{children:[O(be,{children:[w(ve,{className:"text-2xl",children:"Zaloguj si\u0119"}),w(Ut,{children:"Wy\u015Blemy do Ciebie kod na maila, dzi\u0119ki kt\xF3remu si\u0119 zalogujesz."})]}),w(me,{children:O("form",{onSubmit:C,children:[O("div",{className:"flex flex-col gap-6",children:[O("div",{className:"grid gap-2",children:[w(Ie,{htmlFor:"email",children:"Email"}),w(lt,{id:"email",onChange:m,type:"email",placeholder:"m@example.com",required:!0}),w("span",{className:x(!u&&o.length>0?"font-bold text-red-500":"text-neutral-700 dark:text-neutral-400","text-xs"),children:!u&&o.length>0?"Nieprawid\u0142owy adres email":"Wpisz sw\xF3j adres email"})]}),O("div",{children:[O(S,{type:"submit",disabled:i,className:"relative w-full",onClick:a,children:[i&&w("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",children:w(Z,{})}),"Zaloguj si\u0119"]}),c.length>0&&w("p",{className:"text-xs font-medium text-red-500",children:c})]})]}),O("div",{className:"mt-4 text-center text-sm",children:["Masz ju\u017C kod?"," ",w("button",{type:"button",onClick:v,className:"underline underline-offset-4",children:"Mam ju\u017C kod"})]})]})})]})})})},da=({projectID:e,host:t,email:r,reveal:o,setEmail:n,isLoginLoading:a,loginUserResponse:i,setLoginUserResponse:c,setResponseStatus:d,errMsg:l})=>{let u=dt(),{mutateAsync:g,isPending:k}=ee(B.publicApi.userPanelLoginWithCode),[m,v]=oe(""),[C,s]=oe(!1),[h,R]=oe(!1),[q,F]=oe(0),A=U=>/^\d+$/.test(U.trim())?s(!0):s(!1),E=U=>{A(U),v(U)};async function z(){if(R(!0),m.length==0){s(!1);return}let U=parseInt(m),X=await g({code:U}),ye,Ce,re;if(X.result.case==="accessToken"?(s(!0),ye="ok",Ce=void 0,re=X.result.value):(s(!1),ye="error",Ce=X.result.value,re=void 0),ye==="error"&&(s(!1),console.warn("error:",`Kod b\u0142\u0119du: ${Ce}`),console.warn("Nieprawid\u0142owy kod, spr\xF3buj ponownie.")),ye==="ok"){u.track("panel_login",{}),re&&yn(e,re,r,t);let P=typeof window<"u"?Ue():null;setTimeout(()=>{if(re&&P){window.location.href=Me(P,re);return}window.location.reload()},100)}}function D(){let U=setInterval(()=>{F(X=>X>0?X-1:(clearInterval(U),0))},1e3);return()=>{clearInterval(U)}}jn(()=>{i?.status==="ok"&&i?.retryIn>0&&(F(i.retryIn),D())},[i]);function $(){n(""),c(null),d("default"),o()}function ge(U){U.preventDefault(),z()}return w("main",{className:"mx-auto flex max-w-md flex-1 flex-col justify-center space-y-8",children:w("div",{className:x("flex min-w-sm flex-col gap-6"),children:O(ue,{children:[O(be,{children:[w(ve,{className:"text-2xl",children:"Wpisz kod z maila"}),w(Ut,{children:"Sprawd\u017A czy przypadkiem nie wyl\u0105dowa\u0142 w spamie."})]}),O(me,{children:[O("form",{onSubmit:ge,className:"flex flex-col gap-6",children:[w("div",{className:"grid gap-2",children:w("div",{className:"my-5 flex w-full items-center justify-center",children:O("div",{className:"flex flex-col gap-2",children:[O(On,{id:"verify-code",maxLength:6,pattern:sa,onChange:U=>{E(U)},children:[O(Mt,{children:[w(Se,{index:0}),w(Se,{index:1}),w(Se,{index:2})]}),w(Un,{}),O(Mt,{children:[w(Se,{index:3}),w(Se,{index:4}),w(Se,{index:5})]})]}),w("span",{className:x(!C&&h?"text-red-500":"text-neutral-700 dark:text-neutral-400","text-xs"),children:!C&&h?m.length==0?"Kod nie mo\u017Ce by\u0107 pusty":"Kod musi sk\u0142ada\u0107 si\u0119 z cyfr":"Wpisz kod z maila"})]})})}),O("div",{children:[O(S,{type:"submit",disabled:a||k,className:"relative w-full",children:[(a||k)&&w("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2",children:w(Z,{})}),"Zaloguj si\u0119"]}),l.length>0&&w("p",{className:"text-xs font-medium text-red-500",children:l})]})]}),O("div",{className:"mt-4 text-center text-sm",children:["Nie masz kodu?"," ",w("button",{type:"button",onClick:$,className:"underline underline-offset-4",children:"Wr\xF3\u0107"})]})]})]})})})},la=({analytics:e})=>{let{theme:t,allowedReturnOrigins:r,projectID:o,host:n}=Pe(),a=Te(o,e,"panel"),i={"--button-background-color":t?.colors?.brand??"#FFFFFF","--button-background-color-dark":t?.colors?.brandDark??"#000000","--button-text-color":t?.colors?.brandDark??"#000000","--button-text-color-dark":t?.colors?.brand??"#FFFFFF"},[c,d]=oe("login"),[l]=ia({duration:300,easing:"ease-in-out",disrespectUserMotionPreference:!1}),u=()=>d(E=>E==="login"?"verifyCode":"login"),[g,k]=oe(""),[m,v]=oe("default"),[C,s]=oe(null),{mutateAsync:h,isPending:R}=ee(B.publicApi.userPanelLogin),[q,F]=oe("");jn(()=>{if(typeof window>"u"||window.parent!==window)return;let E=Je(window.location.search);E&&Qe(E);let z=E??Ue();if(!z)return;let D=Ke(o,n);D&&(window.location.href=Me(z,D))},[r,o,n]);async function A(){F(""),v("default");let E=await h({email:g}),z=E.result.case==="success"?"ok":"error",D=0,$;E.result.case==="success"&&(D=E.result.value.retryIn),z==="error"&&($="Nieprawid\u0142owy adres email, spr\xF3buj ponownie."),s({status:z,retryIn:D,message:$}),z==="ok"&&c==="login"?u():z==="ok"&&c==="verifyCode"?v("success"):z==="error"&&F($??"Nieprawid\u0142owy adres email, spr\xF3buj ponownie.")}return w(ct,{value:a,children:w("div",{className:"bg-white text-black dark:bg-black dark:text-white",children:O("div",{className:"font-inter flex h-screen w-screen flex-col p-4",style:i,ref:l,children:[O("header",{children:[t?.logoDarkURL&&w("img",{src:t?.logoDarkURL,className:"hidden dark:inline",alt:"Company Logo",draggable:!1}),t?.logoURL&&w("img",{src:t?.logoURL,className:"dark:hidden",alt:"Company Logo",draggable:!1})]}),c==="login"&&w(ca,{projectID:o,host:n,reveal:u,email:g,setEmail:k,loginUser:A,isLoginLoading:R,errMsg:q}),c==="verifyCode"&&w(da,{projectID:o,host:n,email:g,reveal:u,setEmail:k,loginUser:A,isLoginLoading:R,loginUserResponse:C,setLoginUserResponse:s,responseStatus:m,setResponseStatus:v,errMsg:q})]})})})},ua=({analytics:e}={})=>w(la,{analytics:e});import{useAutoAnimate as ko}from"@formkit/auto-animate/react";import{useEffect as bt,useState as Co}from"react";import{useState as ma,useCallback as pa,useEffect as fa}from"react";function _n(e){let[t,r]=ma(()=>{if(typeof window>"u")return e;let n=new URLSearchParams(window.location.search),a={};return Object.keys(e).forEach(i=>{let c=n.get(i);if(c!==null)try{a[i]=JSON.parse(c)}catch{a[i]=c}}),{...e,...a}}),o=pa(n=>{r(a=>{let i={...a,...n};if(typeof window<"u"){let c=new URLSearchParams;Object.keys(i).forEach(l=>{let u=i[l];u!=null&&c.set(l,JSON.stringify(u))});let d=`${window.location.pathname}?${c.toString()}`;window.history.pushState({},"",d)}return i})},[]);return fa(()=>{let n=()=>{let a=new URLSearchParams(window.location.search),i={};Object.keys(e).forEach(c=>{let d=a.get(c);if(d!==null)try{i[c]=JSON.parse(d)}catch{i[c]=d}}),r({...e,...i})};return window.addEventListener("popstate",n),()=>window.removeEventListener("popstate",n)},[e]),[t,o]}function zn(e,t){if(e!=null)return e;let r=t?.trim();if(!(r==null||r===""))return{tokens:hn(r)}}import*as ut from"@radix-ui/react-switch";import{jsx as qn}from"react/jsx-runtime";function Fn({className:e,...t}){return qn(ut.Root,{"data-slot":"switch",className:x("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:qn(ut.Thumb,{"data-slot":"switch-thumb",className:x("bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}import{useState as ga}from"react";import{Fragment as Pa,jsx as Ye,jsxs as zt}from"react/jsx-runtime";function ya({}){let[e,t]=ga({disableAll:!1});return zt(Pa,{children:[Ye("h3",{className:"text-2xl",children:"Powiadomienia"}),Ye("p",{className:"text-sm text-neutral-500",children:"Zarz\u0105dzaj swoimi powiadomieniami"}),Ye("div",{className:"mt-6",children:zt("div",{className:"flex items-center space-x-2",children:[Ye(Fn,{id:"disable-all-notifications",checked:e.disableAll,onCheckedChange:r=>t(o=>({...o,disableAll:r}))}),zt(Ie,{htmlFor:"disable-all-notifications",className:"flex flex-col gap-1 text-base",children:["Wszystkie powiadomienia",Ye("span",{className:"text-xs font-normal text-neutral-500 md:text-sm",children:"Ten przycisk mo\u017Ce wy\u0142\u0105czy\u0107 wszystkie powiadomienia"})]})]})})]})}var Bn=ya;import{ChevronLeftIcon as ha,ChevronRightIcon as ba,MoreHorizontalIcon as va}from"lucide-react";import{jsx as ie,jsxs as Ft}from"react/jsx-runtime";function Gn({className:e,...t}){return ie("nav",{role:"navigation","aria-label":"pagination","data-slot":"pagination",className:x("mx-auto flex w-full justify-center",e),...t})}function $n({className:e,...t}){return ie("ul",{"data-slot":"pagination-content",className:x("flex flex-row items-center gap-1",e),...t})}function we({...e}){return ie("li",{"data-slot":"pagination-item",...e})}function je({className:e,isActive:t,size:r="icon",...o}){return ie("a",{"aria-current":t?"page":void 0,"data-slot":"pagination-link","data-active":t,className:x(gn({variant:t?"outline":"ghost",size:r}),e),...o})}function Hn({className:e,...t}){return Ft(je,{"aria-label":"Go to previous page",size:"default",className:x("gap-1 px-2.5 sm:pl-2.5",e),...t,children:[ie(ha,{}),ie("span",{className:"hidden sm:block",children:"Previous"})]})}function Vn({className:e,...t}){return Ft(je,{"aria-label":"Go to next page",size:"default",className:x("gap-1 px-2.5 sm:pr-2.5",e),...t,children:[ie("span",{className:"hidden sm:block",children:"Next"}),ie(ba,{})]})}function qt({className:e,...t}){return Ft("span",{"aria-hidden":!0,"data-slot":"pagination-ellipsis",className:x("flex size-9 items-center justify-center",e),...t,children:[ie(va,{className:"size-4"}),ie("span",{className:"sr-only",children:"More pages"})]})}import{useState as wa}from"react";import{Fragment as Sa,jsx as N,jsxs as J}from"react/jsx-runtime";var xa=e=>new Date(e*1e3).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),ka=(e,t)=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase()}).format(e/100),Ca={draft:"Szkic",unpaid:"Nieop\u0142acona",paid:"Op\u0142acona",overdue:"Zaleg\u0142a",cancelled:"Anulowana",completed:"Zako\u0144czone",processing:"Przetwarzane",refunded:"Zwr\xF3cone"},Na={draft:"text-neutral-400",unpaid:"text-yellow-500",paid:"text-green-600",overdue:"text-red-500",cancelled:"text-neutral-400 line-through",completed:"text-green-600",processing:"text-blue-500",refunded:"text-purple-500"};function Ia({openOrderDetails:e,projectID:t,accessToken:r}){let[o,n]=wa(0),a=20,{data:i,isFetching:c}=De(B.publicApi.getOrders,{projectId:t,accessToken:r,offset:o,limit:a}),d=i?.orders??[],l=i?.totalCount??0,u=Math.floor(o/a)+1,g=Math.ceil(l/a),k=m=>{n(m)};return J(Sa,{children:[N("h3",{className:"text-2xl",children:"Historia zam\xF3wie\u0144"}),N("p",{className:"text-sm text-neutral-500 dark:text-neutral-400",children:"Twoje zam\xF3wienia"}),c?N("div",{className:"mt-6 flex w-full flex-col gap-3",children:[...Array(5)].map((m,v)=>J("div",{className:"rounded-xl bg-white p-4 shadow-sm dark:bg-neutral-800",children:[J("div",{className:"flex items-center justify-between",children:[J("div",{className:"space-y-2",children:[N(Ee,{className:"h-4 w-24"}),N(Ee,{className:"h-3 w-32"})]}),J("div",{className:"space-y-2 text-right",children:[N(Ee,{className:"ml-auto h-4 w-16"}),N(Ee,{className:"ml-auto h-3 w-12"})]})]}),N("div",{className:"mt-3",children:N(Ee,{className:"h-3 w-40"})})]},v))}):d.length===0?N("div",{className:"mt-6 text-sm text-neutral-400",children:"Brak zam\xF3wie\u0144."}):J("div",{children:[N("div",{className:"mt-6 flex w-full flex-col gap-3",children:d.map(m=>J("button",{onClick:()=>e(m.id),className:"block rounded-xl bg-white p-4 text-left shadow-sm transition-colors hover:bg-neutral-50 dark:bg-neutral-800 dark:hover:bg-neutral-700",children:[J("div",{className:"flex items-center justify-between",children:[J("div",{children:[J("p",{className:"font-medium",children:["Zam\xF3wienie #",m.id]}),N("p",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:m.customerName||"Klient"})]}),J("div",{className:"text-right",children:[N("p",{className:"font-semibold",children:ka(m.totalAmount,m.currency)}),N("p",{className:`text-xs font-medium ${Na[m.status]??"text-neutral-400"}`,children:Ca[m.status]??m.status})]})]}),N("div",{className:"mt-2 flex items-center justify-between text-xs text-neutral-500 dark:text-neutral-400",children:J("span",{children:["Data:"," ",m.createdAt?xa(Number(m.createdAt.seconds)):"-"]})})]},m.id))}),g>1&&!c&&N("div",{className:"mt-4 flex justify-center",children:N(Gn,{children:J($n,{children:[u>1&&N(we,{children:N(Hn,{onClick:()=>k(o-a)})}),u>2&&N(we,{children:N(je,{onClick:()=>k(0),children:"1"})}),u>3&&N(we,{children:N(qt,{})}),[u-1,u,u+1].filter(m=>m>0&&m<=g).map(m=>N(we,{children:N(je,{onClick:()=>k((m-1)*a),isActive:u===m,children:m})},m)),u<g-2&&N(we,{children:N(qt,{})}),u<g&&N(we,{children:N(je,{onClick:()=>k((g-1)*a),children:g})}),u<g&&N(we,{children:N(Vn,{onClick:()=>k(o+a)})})]})})})]})]})}var Wn=Ia;import{useState as Kn}from"react";import{Fragment as Da,jsx as te,jsxs as xe}from"react/jsx-runtime";var Zn=e=>new Date(e*1e3).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),Ra={active:"Aktywny",cancelled:"Anulowany",paused:"Wstrzymany"},Aa={active:"text-green-600",cancelled:"text-red-500",paused:"text-yellow-500"};function Ta({projectID:e}){let[t,r]=Kn([]),[o,n]=Kn(!0);return xe(Da,{children:[te("h3",{className:"text-2xl",children:"Plany"}),te("p",{className:"text-sm text-neutral-500",children:"Twoje aktywne subskrypcje"}),o?te("div",{className:"mt-6 text-sm text-neutral-400",children:"\u0141adowanie..."}):t.length===0?te("div",{className:"mt-6 text-sm text-neutral-400",children:"Brak aktywnych plan\xF3w."}):te("div",{className:"mt-6 flex flex-col gap-4",children:t.map(a=>xe("div",{className:"rounded-xl bg-white p-5 shadow-sm dark:bg-neutral-800",children:[xe("div",{className:"flex items-start justify-between",children:[xe("div",{children:[te("p",{className:"font-semibold",children:a.tierName}),a.configName&&te("p",{className:"text-sm text-neutral-500",children:a.configName})]}),te("span",{className:`text-sm font-medium ${Aa[a.status]??"text-neutral-500"}`,children:Ra[a.status]??a.status})]}),xe("div",{className:"mt-3 grid grid-cols-2 gap-2 text-sm text-neutral-600 dark:text-neutral-400",children:[xe("div",{children:[te("span",{className:"font-medium",children:"Dzie\u0144 rozliczenia:"})," ",a.billingDay]}),xe("div",{children:[te("span",{className:"font-medium",children:"Data startu:"})," ",Zn(a.startDate)]}),a.endDate&&xe("div",{children:[te("span",{className:"font-medium",children:"Data zako\u0144czenia:"})," ",Zn(a.endDate)]})]})]},a.id))})]})}var Jn=Ta;import{useEffect as La,useState as Bt}from"react";import{jsx as ne,jsxs as Ua}from"react/jsx-runtime";function Ea(e,t,r,o){typeof window>"u"||(t&&Le(r,o),window.location.href=e)}function Oa({projectID:e,host:t,loginURL:r,screen:o,params:n,setParams:a,setActiveScreen:i}){let{status:c,exchangeError:d}=Cn("PanelReturns"),l=kn(),u=c==="anonymous"&&(d==null||vn(d));La(()=>{u&&Ea(r,d!=null,e,t)},[u,r,d,e,t]);let[g,k]=Bt("orders"),[m,v]=Bt({items:[],note:""}),[C,s]=Bt();if(c==="anonymous"&&!u)return Ua("div",{role:"alert",className:"flex flex-col items-start gap-3",children:[ne("p",{className:"text-sm",children:l(wn(d))}),ne(S,{type:"button",onClick:()=>window.location.reload(),children:l("errorRetry")})]});if(c!=="authenticated")return ne(In,{});let h=R=>{k(R),a({state:"returns",orderId:void 0,returnId:void 0}),i("returns")};if(o==="return-details"&&n.returnId)return ne(Ln,{returnId:n.returnId,onBack:()=>h("myReturns")});if(g==="myReturns")return ne(Dn,{onBack:()=>h("orders"),onSelectReturn:R=>{a({state:"return-details",returnId:R,orderId:void 0}),i("return-details")}});if(g==="result"&&C!=null)return ne(Tn,{returnId:C,onContinue:()=>h("orders"),onOpenMyReturns:()=>h("myReturns")});if(n.orderId){let R=n.orderId;return g==="confirmation"?ne(An,{orderId:R,items:m.items,note:m.note,onBack:()=>k("orders"),onSubmitted:q=>{s(q),v({items:[],note:""}),k("result"),a({orderId:void 0})}}):ne(Rn,{orderId:R,initialItems:m.items.length>0?m.items:void 0,initialNote:m.note,onBack:()=>{v({items:[],note:""}),a({orderId:void 0})},onContinue:q=>{v(q),k("confirmation")}})}return ne(Sn,{showLogout:!1,onSelectOrder:R=>{v({items:[],note:""}),k("orders"),a({orderId:R})},onOpenMyReturns:()=>h("myReturns")})}function Gt({accessToken:e,appearance:t,texts:r,...o}){return ne(Nn,{projectID:o.projectID,host:o.host,appearance:t,texts:r,panelAccessToken:e,children:ne(Oa,{...o})})}import{useState as Ja}from"react";import{jsx as za}from"react/jsx-runtime";var Ma=/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g,ja=e=>[...e.matchAll(Ma)].map(r=>({url:r[0],startIndex:r.index,endIndex:r.index+r[0].length-1})),_a=(e,t)=>{let r="",o=0;t.sort((n,a)=>n.startIndex-a.startIndex);for(let{startIndex:n,endIndex:a,replacementText:i}of t)r+=e.slice(o,n),r+=i,o=a+1;return r+=e.slice(o),r},Qn=e=>{let t=ja(e);return za("p",{dangerouslySetInnerHTML:{__html:_a(e,t.map(r=>(r.replacementText=`<a key=${r.url} href=${r.url} style="text-decoration: underline;" target="_blank">
2
- ${r.url}
3
- </a>`,r)))}})};import{fromJsonString as Qa,toJsonString as Ya}from"@bufbuild/protobuf";import{useAutoAnimate as Wa}from"@formkit/auto-animate/react";import{ChevronLeft as Ka,Download as sr}from"lucide-react";import{useEffect as cr,useRef as dr,useState as ze}from"react";import rr from"hls.js";import{Pause as qa,Play as Fa}from"lucide-react";import{forwardRef as Ba,useEffect as mt,useImperativeHandle as Ga,useRef as Xe,useState as _e}from"react";function Yn(){typeof navigator>"u"||typeof navigator.mediaSession>"u"||(navigator.mediaSession.playbackState="playing")}function Xn(){typeof navigator>"u"||typeof navigator.mediaSession>"u"||(navigator.mediaSession.playbackState="paused")}function er(e,t){typeof navigator>"u"||typeof navigator.mediaSession>"u"||e!=null&&isNaN(e)||t!=null&&isNaN(t)||navigator.mediaSession.setPositionState({playbackRate:1,duration:e,position:t})}function tr(e){typeof navigator>"u"||typeof navigator.mediaSession>"u"||(navigator.mediaSession.metadata=new MediaMetadata({title:e.title,artwork:e.artwork?[{type:"image/png",src:e.artwork}]:void 0}),navigator.mediaSession.setActionHandler("play",t=>{e.action(t)}),navigator.mediaSession.setActionHandler("pause",t=>{e.action(t)}),navigator.mediaSession.setActionHandler("stop",t=>{e.action(t)}),navigator.mediaSession.setActionHandler("seekbackward",t=>{e.action(t)}),navigator.mediaSession.setActionHandler("seekforward",t=>{e.action(t)}),navigator.mediaSession.setActionHandler("seekto",t=>{e.action(t)}))}function nr(){navigator.mediaSession.metadata=null}import{jsx as se,jsxs as pt}from"react/jsx-runtime";var $a=Ba(({chapters:e,styles:t,updateCurrentTime:r,setCurrentTimeHandler:o,title:n,imageURL:a,uniqueProductID:i,onChapterChange:c},d)=>{let l;(H=>(H[H.Playing=0]="Playing",H[H.Paused=1]="Paused"))(l||={});let[u,g]=_e(1);mt(()=>{switch(u){case 0:Yn();break;case 1:Xn();break}},[u]),Ga(d,()=>({selectChapter:f=>{He(f)}}));let[k,m]=_e(void 0),[v,C]=_e(void 0),s=Xe(null),h=Xe(void 0),R=Xe(void 0),q=Xe(null),F=Xe(null),[A,E]=_e(!0),[z,D]=_e(!1),[$,ge]=_e(!Ha());function U(f){f<10||localStorage.setItem(`__player__${i}_${F.current?.id}`,`${f}`)}function X(){let f=localStorage.getItem(`__player__${i}_${F.current?.id}`);if(f!=null)try{let M=parseInt(f);return isNaN(M)||M<0?void 0:M}catch{return}}function ye(){let f=localStorage.getItem(`__player__${i}_last_chapter`);if(f!=null)return f}function Ce(f){localStorage.setItem(`__player__${i}_last_chapter`,f)}function re(f){localStorage.removeItem(`__player__${i}_${f}`)}function P(){s.current!=null&&(s.current.onloadeddata=()=>{if(s.current!=null){if(s.current.readyState<2&&ge(!0),s.current.readyState>=2&&ge(!1),!z){let f=X();f!=null&&it(f),D(!0)}if(A){E(!1);try{Nt()}catch(f){console.log("play error",f)}}}},s.current.onplay=()=>{},s.current.onseeked=()=>{},s.current.onseeking=()=>{},s.current.onpause=()=>{},s.current.onended=()=>{ae()},tr({title:n??"",artwork:a,action:f=>{switch(f.action){case"play":Nt();break;case"pause":It();break;case"seekbackward":ot(-15);break;case"seekforward":ot(15);break;case"seekto":f.seekTime&&it(f.seekTime);break;case"stop":It();break;default:break}}}),Ne())}function ae(){if(e==null||e.length==0)return;let f=e.findIndex(H=>H.id==F.current?.id);f==-1||(re(e[f].id),f+1>=e.length)||He(e[f+1])}function Ne(){Re(),R.current==null&&(R.current=setTimeout(()=>{Re(),R.current=void 0,Ne()},500))}function $e(){R.current!=null&&clearTimeout(R.current)}function Re(){s.current!=null&&(g(s.current.paused?1:0),C(s.current.duration),m(s.current.currentTime),U(s.current.currentTime),er(s.current.duration,s.current.currentTime),s.current.networkState===s.current.NETWORK_LOADING&&s.current.readyState<=s.current.HAVE_FUTURE_DATA?ge(!0):ge(!1),r&&r(s.current.currentTime))}function Nt(){s.current?.play().then().catch(),Re()}function It(){s.current?.pause(),Re()}function Hr(){if(u===0){It();return}Nt()}function ot(f){if(s.current==null)return;let M=s.current.currentTime+f;if(M<0){s.current.currentTime=0;return}if(M>s.current.duration){s.current.currentTime=s.current.duration;return}s.current.currentTime+=f}function it(f){if(s.current!=null){if(m(f),f<0){s.current.currentTime=0;return}if(f>s.current.duration){s.current.currentTime=s.current.duration;return}s.current.currentTime=f}}function Vr(){s.current!=null&&(s.current.onplay=null,s.current.onseeked=null,s.current.onseeking=null,s.current.onpause=null,s.current.onended=null,s.current.src="",h.current?.destroy())}function dn(f){if(f.length==0)return;let M=ye();if(M==null){He(f[0]);return}let H=f.find(Ae=>Ae.id==M);if(H==null){He(f[0]);return}He(H)}function He(f){D(!1),E(!0),F.current=f,Wr(f.publicUrl),c?.(f),Ce(f.id)}function Wr(f){s.current!=null&&(s.current.canPlayType("application/vnd.apple.mpegurl")?s.current.src=f:rr.isSupported()&&(h.current==null&&(h.current=new rr,h.current?.attachMedia(s.current)),h.current?.loadSource(f)))}mt(()=>{s.current!=null&&(P(),dn(e))},[s.current]),mt(()=>{dn(e)},[e]),mt(()=>(o?.(it),()=>{m(void 0),s.current?.pause(),Vr(),nr()}),[]);let ln=f=>{let M=Math.floor(f/3600),H=Math.floor(f/60)%60,Ae=Math.floor(f%60),Zr=M>0?M<10?`0${M}:`:`${M}:`:"",Jr=Ae<10?`0${Ae}`:`${Ae}`;return isNaN(Ae)||isNaN(H)||isNaN(M)?"":`${Zr}${H}:${Jr}`},Kr=f=>{let M=parseFloat(f.value)/parseFloat(f.max)*100;q.current.style.setProperty("--seek-before-width",M+"%");let H=v*M/100;it(H)};return pt("div",{id:"audio-player-container",className:"flex flex-col",style:t,ref:q,children:[se("video",{ref:s,className:"hidden",poster:a,title:n}),se("input",{type:"range",min:"0",max:v!=null?Math.floor(v).toString():100,value:k??0,onChange:f=>Kr(f.target),className:"w-full"}),pt("section",{className:"flex w-full items-center justify-between text-sm font-medium",children:[se("span",{id:"current-time",children:ln(k)}),se("span",{id:"duration",children:ln(v)})]}),pt("div",{className:"mt-6 flex items-center justify-center gap-x-12",children:[se(S,{variant:"outline",onClick:()=>ot(-10),"aria-label":"Rewind 10 Seconds",children:"-10"}),pt(S,{variant:"outline",onClick:Hr,"aria-label":"Play Or Pause",children:[u===1&&se(Fa,{className:"h-5 w-5"}),u===0&&se(qa,{className:"h-5 w-5"})]}),se(S,{variant:"outline",onClick:()=>ot(10),"aria-label":"Fast Forward 10 Seconds",children:"+10"})]}),$&&se("div",{className:"mt-2 flex w-full justify-center",children:se(Z,{})})]})});function Ha(){return navigator.userAgent.toLowerCase().indexOf("safari/")>-1}var ar=$a;var Va={pl:{returnsNavLabel:"Zwroty",openCourse:"Otw\xF3rz kurs"},en:{returnsNavLabel:"Returns",openCourse:"Open the course"}};function et(e=V()){return xn(Va,e)}import*as ft from"react";import{jsx as or}from"react/jsx-runtime";function ir(){let[e,t]=ft.useState(13);return ft.useEffect(()=>{let r=setTimeout(()=>t(66),500);return()=>clearTimeout(r)},[]),or("div",{className:"w-[60%] h-2 bg-gray-200 rounded-full overflow-hidden",children:or("div",{className:"h-full bg-blue-600 transition-all duration-300",style:{width:`${e}%`}})})}import{Fragment as gt,jsx as b,jsxs as j}from"react/jsx-runtime";function pe(e,...t){console.warn(e,...t)}function $t(e){console.error(e)}var Za=({accessToken:e,product:t,styles:r,reveal:o,onOpenCourse:n})=>{let a=t.productType,i=dt(),c=()=>i.track("panel_download",{},{product_id:t.productId.length<=64?t.productId:null}),d=dr(null),[l]=Wa(),[u,g]=ze(null),{mutateAsync:k,isPending:m}=ee(B.publicApi.userPanelGetFileDetails),v=dr(void 0),[C,s]=ze(null),[h,R]=ze(null),[q,F]=ze(!1),{mutateAsync:A,isPending:E}=ee(B.publicApi.userPanelGetAudiobookDetails),{mutateAsync:z,isPending:D}=ee(B.publicApi.userPanelGetAudiobookDetailsDownloadURLs),[$,ge]=ze(null),[U,X]=ze(null);async function ye(){try{let P=await k({accessId:t.accessId,accessToken:e});if(P.result.case==="success"){g(P.result.value.files);return}else pe("Pobranie plik\xF3w nie powiod\u0142o si\u0119. Zalecamy kontakt."),pe("Kod b\u0142\u0119du: ",P.result.value)}catch(P){pe("Nieoczekiwany b\u0142\u0105d. Spr\xF3buj ponownie za chwil\u0119."),$t("B\u0142\u0105d podczas pobierania danych:"+P)}}async function Ce(){try{let P=await A({accessId:t.accessId,accessToken:e});if(P.result.case==="audiobook"){s(P.result.value);return}else pe("Pobranie plik\xF3w nie powiod\u0142o si\u0119. Zalecamy kontakt."),pe("Kod b\u0142\u0119du: ",P.result.value)}catch(P){pe("Nieoczekiwany b\u0142\u0105d. Spr\xF3buj ponownie za chwil\u0119."),$t("B\u0142\u0105d podczas pobierania danych:"+P)}}async function re(){try{let P=await z({accessId:t.accessId,accessToken:e,isBrowser:!0});if(P.result.case==="success"){R(P.result.value.audiobookDownloadDetails),F(P.result.value.isAvailableToDownloadInMobileApp===!0);return}else pe("Pobranie plik\xF3w nie powiod\u0142o si\u0119. Zalecamy kontakt."),pe("Kod b\u0142\u0119du: ",P.result.value)}catch(P){pe("Nieoczekiwany b\u0142\u0105d. Spr\xF3buj ponownie za chwil\u0119."),$t("B\u0142\u0105d podczas pobierania danych:"+P)}}return cr(()=>{a===1&&(Ce().then().catch(),re().then().catch())},[]),cr(()=>{if(C!=null&&h!=null){let P=C.chapters;if(!P)return;let ae=P.map(Ne=>{let $e=h?.find(Re=>Re.chapterId===Ne.id);if($e!=null)return{...Ne,publicUrl:$e.publicUrl,downloadableUrl:$e.downloadableUrl,duration:$e.duration}}).filter(Ne=>Ne!=null);ae!=null&&ae.length>0&&X(ae)}},[C,h]),j("div",{children:[b("div",{className:"mb-3 space-y-4 rounded bg-white p-4 dark:bg-black",children:j(S,{onClick:()=>o(),variant:"ghost",className:"w-fit",children:[b(Ka,{className:"h-6 w-6"}),b("span",{className:"font-inter text-sm font-medium",children:"Wr\xF3\u0107"})]})}),j("main",{className:"grid grid-cols-1 justify-center gap-6 sm:justify-start lg:grid-cols-2",children:[j("div",{className:"flex w-full max-w-xl flex-col gap-6",children:[a===2&&j("div",{ref:l,className:"flex flex-col space-y-4 rounded bg-white p-6 drop-shadow-xl dark:border dark:border-neutral-700 dark:bg-neutral-800 dark:drop-shadow-none",children:[j("div",{className:"flex items-center justify-between gap-x-4",children:[b("h4",{className:"text-xl font-semibold",children:"Twoje pliki"}),(u==null||u.length==0)&&b(S,{onClick:ye,"aria-label":"Download Product",className:"text-sm font-medium transition-opacity duration-300 ease-in-out hover:opacity-80 active:opacity-80",style:r,children:m?b(Z,{}):"Wy\u015Bwietl"})]}),m&&j("div",{className:"flex flex-col items-start gap-2",children:[b(ir,{}),b("p",{className:"font-bold transition hover:text-blue-600",children:"Trwa przygotowanie plik\xF3w..."})]}),u!=null&&u.length>0&&b("div",{className:"flex flex-col items-start justify-start gap-2",children:u.map((P,ae)=>j("a",{target:"_blank",className:"flex w-fit items-center gap-2 rounded-md bg-neutral-800 px-3 py-2 text-neutral-200 dark:bg-neutral-200 dark:text-neutral-800",href:P,download:!0,onClick:c,children:[`Plik numer ${ae+1}`,b(sr,{width:14,height:14})]},ae))})]}),a===4&&b("div",{className:"flex flex-col items-center justify-center rounded-xl bg-white p-6 drop-shadow-xl dark:bg-neutral-900 dark:drop-shadow-none",children:b(S,{onClick:()=>n(t.accessId),className:"text-sm font-medium transition-opacity duration-300 ease-in-out hover:opacity-80 active:opacity-80",style:r,children:et().openCourse})}),a===1&&b(gt,{children:j("div",{className:"flex flex-col space-y-6 rounded-xl bg-white p-3 drop-shadow-xl dark:bg-neutral-900 dark:drop-shadow-none",children:[b("h4",{className:"text-xl font-semibold",children:$?.name??"Odtwarzacz"}),$?.description&&b("p",{className:"text-sm",children:$?.description}),b(gt,{children:E?j("div",{className:"flex gap-2",children:[b(Z,{}),b("p",{className:"text-xl font-semibold",children:"Trwa pobierania audiobooka..."})]}):b(gt,{children:U!=null?b(gt,{children:b(ar,{ref:d,chapters:U,title:C?.name??t.productName??void 0,imageURL:C?.coverImage??t.productImageUrl??void 0,styles:r,setCurrentTimeHandler:P=>{v.current=P},uniqueProductID:t.productId,onChapterChange:P=>{ge(P)}})}):b("p",{className:"mt-2",children:"Wybierz rozdzia\u0142, kt\xF3ry ci\u0119 interesuje."})})}),j("div",{className:"rounded-xl bg-neutral-100 p-3 dark:bg-neutral-800",children:[b("p",{className:"mt-3 mb-3 text-xs",children:q?"Mo\u017Cesz s\u0142ucha\u0107 tego audiobooka w aplikacji r\xF3wnie\u017C bez dost\u0119pu do internetu.":"Mo\u017Cesz s\u0142ucha\u0107 tego audiobooka w aplikacji."}),j("div",{className:"flex gap-3",children:[b("a",{href:"https://apps.apple.com/us/app/bitsnap/id6741902807",children:b("img",{width:"100",src:"https://bitsnap.pl/appstore.svg",alt:"Pobierz aplikacje z AppStore"})}),b("a",{href:"https://docs.bitsnap.pl/guides/audiobook",children:b("img",{width:"100",src:"https://bitsnap.pl/playstore.svg",alt:"Pobierz aplikacj\u0119 z GooglePlay"})})]})]})]})}),b("div",{className:"flex items-center justify-center rounded-xl bg-white p-3 drop-shadow-xl dark:bg-neutral-900 dark:drop-shadow-none",children:a===1&&b("div",{className:"max-h-96 w-full overflow-y-auto",children:E?j("div",{className:"jusitfy-center flex flex-col items-center gap-2",children:[b(Z,{}),b("p",{children:"\u0141adowanie rozdzia\u0142\xF3w..."})]}):j("div",{children:[b("h2",{className:"mb-3 text-xl font-semibold",children:"Rozdzia\u0142y"}),U==null?b("p",{children:"Brak rozdzia\u0142\xF3w do wy\u015Bwietlenia."}):b("ul",{className:"flex w-full flex-col gap-2",children:U.map((P,ae)=>j("li",{className:"flex items-center justify-between",children:[j("button",{className:x("w-full rounded-lg p-2 text-left transition hover:bg-neutral-200 active:bg-neutral-200 dark:hover:bg-neutral-700 dark:active:bg-neutral-700",$?.id==P.id?"bg-neutral-200 dark:bg-neutral-700":"bg-neutral-100 dark:bg-neutral-800 dark:text-neutral-300"),onClick:()=>{d.current.selectChapter(P)},children:[j("div",{className:"flex items-center justify-between",children:[b("p",{className:"text-sm font-medium",children:P.name}),P.duration&&j("span",{className:"text-xs text-neutral-500",children:[Math.floor(P.duration/60),":",String(Math.floor(P.duration%60)).padStart(2,"0")]})]}),P.description&&b("p",{className:"mt-3 text-xs",children:P.description})]}),C&&C.isDownloadable&&P.downloadableUrl&&b("a",{href:P.downloadableUrl,onClick:c,children:b(sr,{width:14,height:14})})]},ae))})]})})})]}),j("div",{className:"w-full max-w-3xl space-y-6 rounded-xl bg-white p-6 drop-shadow-xl dark:bg-neutral-900 dark:drop-shadow-none",children:[b("h2",{className:"text-3xl font-semibold",children:t.productName}),b("p",{className:"text-sm font-normal text-neutral-600 dark:text-neutral-300",children:t.productDescription}),b("img",{src:t.productImageUrl,alt:"Product Photo",width:384,height:384,className:"max-h-sm max-w-sm",draggable:!1})]})]})]})},lr=Za;import{Fragment as to,jsx as W,jsxs as tt}from"react/jsx-runtime";var Xa=({accessToken:e,projectID:t,loginURL:r,styles:o,activeScreen:n,params:a,setParams:i,openCourse:c})=>{let{data:d,isLoading:l}=De(B.publicApi.userPanelGetProducts,{accessToken:e});if(l)return tt("div",{className:"flex items-center gap-2 bg-white p-2 dark:bg-black",children:[W("p",{className:"text-dark font-inter font-medium dark:text-white",children:"\u0141adowanie..."}),W(Z,{})]});if(d&&d.result.case==="failure")return console.warn("error:",`Kod b\u0142\u0119du: ${d.result.value}`),Le(t),window.location.href=r,null;let u=d&&d.result.case==="success"?d.result.value.products:[];return W(eo,{accessToken:e,products:u,styles:o,loginURL:r,activeScreen:n,params:a,setParams:i,openCourse:c})},ur=Xa,eo=({accessToken:e,products:t,styles:r,loginURL:o,activeScreen:n,params:a,setParams:i,openCourse:c})=>{if(t.length===0)return window.location.href=o,null;let[d,l]=Ja(a.product?Qa(Lt,a.product):void 0),u=m=>{m==null?(l(void 0),i({product:void 0,state:"products"})):i({product:Ya(Lt,m),state:"products"})};function g(m){switch(m){case 1:return"Audio";case 2:return"Plik";case 3:return"Bilet";case 4:return"Kurs";default:return}}function k(m){if(m.productType===4){c(m.accessId);return}l(m),u(m)}return n==="products"&&d!=null?W(lr,{accessToken:e,product:d,styles:r,reveal:u,onOpenCourse:c}):tt(to,{children:[W("h3",{className:"text-2xl",children:"Hej \u{1F44B}"}),W("p",{className:"text-sm text-neutral-500",children:"Poni\u017Cej znajdziesz swoje produkty"}),W("div",{className:"mt-6 flex flex-wrap items-center justify-center gap-9 sm:justify-start",children:t?.map((m,v)=>tt("section",{onClick:()=>k(m),className:"w-full max-w-xs cursor-pointer rounded drop-shadow-xl dark:border dark:border-slate-600 dark:drop-shadow-none",children:[tt("section",{className:"flex flex-col items-center space-y-2 rounded bg-slate-100 p-4 dark:bg-neutral-900",children:[m.productType&&W("div",{className:"w-fit self-end rounded bg-red-900 px-4 py-1",children:W("span",{className:"text-sm font-medium text-white dark:text-slate-100",children:g(m.productType)})}),W("div",{className:"jusitfy-center flex max-h-40 items-center",children:W("img",{src:m.productImageUrl,alt:`Product ${v} Photo`,draggable:!1,className:"aspect-auto max-h-40"})})]}),tt("div",{className:"space-y-4 rounded bg-white p-4 dark:bg-black",children:[W("h2",{className:"text-xl font-semibold",children:m.productName}),W("p",{title:m.productDescription,className:"line-clamp-3 text-sm font-normal text-neutral-600 dark:text-neutral-300",children:Qn(m.productDescription)}),W(S,{onClick:C=>{C.stopPropagation(),k(m)},className:"w-full text-sm font-medium transition-opacity duration-300 ease-in-out hover:opacity-80 active:opacity-80",style:r,children:"Zobacz"})]})]},v))})]})};import{useAutoAnimate as no}from"@formkit/auto-animate/react";import{LogOut as ro,Undo2 as pr}from"lucide-react";import{useState as ao}from"react";import{Fragment as gr,jsx as I,jsxs as ce}from"react/jsx-runtime";function oo({activeScreen:e,setActiveScreen:t,setParams:r,styles:o,theme:n,logout:a}){return ce("header",{className:"md:border-r-neutral-150 md:bg-beige-50 fixed right-0 bottom-0 left-0 z-10 flex h-12 w-full items-center bg-neutral-800 md:static md:z-0 md:min-h-screen md:w-auto md:border-r dark:md:border-r-neutral-900",children:[I(io,{activeScreen:e,setActiveScreen:t,setParams:r}),I(so,{activeScreen:e,setActiveScreen:t,setParams:r,theme:n,logout:a})]})}var fr=oo;function io({activeScreen:e,setActiveScreen:t,setParams:r}){let{returnsNavLabel:o}=et();return ce("nav",{className:"flex w-full items-center justify-evenly gap-4 md:hidden",children:[I(yt,{panelScreen:"products",label:"Produkty",imageURL:"/icons/bitsnap-24x24.svg",activeScreen:e,setActiveScreen:t,setParams:r}),I(yt,{panelScreen:"orders",label:"Faktury",imageURL:"/icons/category-24x24.svg",activeScreen:e,setActiveScreen:t,setParams:r}),I(yt,{panelScreen:"returns",label:o,icon:I(pr,{className:"h-5 w-5 text-white","aria-hidden":!0}),activeScreen:e,setActiveScreen:t,setParams:r}),I(yt,{panelScreen:"profile",label:"Profil",imageURL:"/icons/profile-24x24.svg",activeScreen:e,setActiveScreen:t,setParams:r})]})}function yt({panelScreen:e,label:t,imageURL:r,icon:o,activeScreen:n,setActiveScreen:a,setParams:i}){return ce(S,{onClick:()=>{a(e),i({product:void 0,state:e})},"aria-label":t,variant:null,className:x("flex flex-col gap-0",n===e?"opacity-100":"opacity-50"),children:[o??I("img",{src:r,alt:t,className:"scale-75"}),I("span",{className:"text-xs font-normal text-white",children:t})]})}function Pt({panelScreen:e,label:t,imageURL:r,darkImageURL:o,icon:n,activeScreen:a,setActiveScreen:i,setParams:c,isExpanded:d}){return ce(S,{onClick:()=>{i(e),c({product:void 0,state:e})},variant:a===e?"secondary":"ghost",className:"justify-start",children:[n!=null?I("span",{className:x("inline-flex h-5 w-5 items-center justify-center",d?"mr-4":"mr-2"),children:n}):ce(gr,{children:[I("img",{src:r,alt:t,className:x("aspect-auto h-5 w-5 dark:hidden",d?"mr-4":"mr-2")}),I("img",{src:o,alt:t,className:x("hidden aspect-auto h-5 w-5 dark:inline",d?"mr-4":"mr-2")})]}),d&&I("span",{className:"md:text-medium hidden md:inline",children:t})]})}function so({activeScreen:e,setActiveScreen:t,setParams:r,theme:o,logout:n}){let[a]=no(),[i,c]=ao(!0),{returnsNavLabel:d}=et();return ce("div",{ref:a,className:x("hidden px-4 pt-4 pb-12 md:flex md:h-full md:flex-col dark:bg-neutral-900",i?"md:w-52":"md:w-16"),children:[I("div",{className:"flex items-center justify-between",children:I(co,{theme:o,isExpanded:i})}),I(mr,{className:"my-6"}),ce("div",{className:"flex flex-1 flex-col gap-2",children:[I(Pt,{panelScreen:"products",label:"Produkty",imageURL:"/icons/bitsnap-dark-24x24.svg",darkImageURL:"/icons/bitsnap-24x24.svg",activeScreen:e,setActiveScreen:t,setParams:r,isExpanded:i}),I(Pt,{panelScreen:"orders",label:"Zam\xF3wienia",imageURL:"/icons/category-dark-24x24.svg",darkImageURL:"/icons/category-24x24.svg",activeScreen:e,setActiveScreen:t,setParams:r,isExpanded:i}),I(Pt,{panelScreen:"returns",label:d,icon:I(pr,{className:"h-5 w-5","aria-hidden":!0}),activeScreen:e,setActiveScreen:t,setParams:r,isExpanded:i}),I(Pt,{panelScreen:"profile",label:"Profil",imageURL:"/icons/profile-dark-24x24.svg",darkImageURL:"/icons/profile-24x24.svg",activeScreen:e,setActiveScreen:t,setParams:r,isExpanded:i})]}),I(mr,{className:"mb-6"}),ce(S,{onClick:n,children:[I(ro,{className:"mr-2",width:16,height:16}),i&&I("p",{className:"md:text-medium hidden md:inline md:text-center",children:"Wyloguj si\u0119"})]})]})}function mr({className:e}){return ce("div",{className:x("relative h-px w-full bg-neutral-300",e),children:[I("div",{className:"absolute -top-px left-0 h-1 w-1 rounded-full bg-neutral-500"}),I("div",{className:"absolute -top-px right-0 h-1 w-1 rounded-full bg-neutral-500"})]})}function co({theme:e,isExpanded:t}){return ce(gr,{children:[e==null&&I("p",{className:"text-xl tracking-wider md:inline dark:text-neutral-200",children:"bitsnap."}),(e?.logoDarkURL||e?.logoURL)&&I("img",{src:e.logoDarkURL??e.logoURL,alt:"Company Logo",className:"hidden h-6 w-6 dark:inline",draggable:!1}),e?.logoURL&&I("img",{src:e.logoURL,alt:"Company Logo",className:"h-6 w-6 dark:hidden",draggable:!1})]})}import{LogOut as lo}from"lucide-react";import{Fragment as mo,jsx as qe,jsxs as Ht}from"react/jsx-runtime";function uo({email:e,logout:t}){return Ht(mo,{children:[qe("h3",{className:"text-2xl",children:"Profil"}),Ht("div",{className:"mt-6 flex-1 md:flex-none",children:[qe("span",{className:"text-sm text-neutral-500",children:"Email"}),qe("p",{className:"mt-2 text-base",children:e||"Brak danych"})]}),qe("div",{className:"flex w-full flex-col items-center space-y-2",children:Ht(S,{onClick:t,className:"max-w-64 md:hidden",children:[qe(lo,{className:"mr-2",width:16,height:16}),qe("p",{className:"text-medium inline text-center",children:"Wyloguj si\u0119"})]})})]})}var yr=uo;import{lazy as po,Suspense as fo}from"react";import{jsx as ht}from"react/jsx-runtime";var go=po(()=>import("./course.mjs").then(e=>({default:e.PanelCourse})));function Vt(e){return ht(fo,{fallback:ht("div",{className:"flex items-center gap-2 p-2",role:"status",children:ht(Z,{})}),children:ht(go,{...e})})}import{AlertCircle as wr,CheckCircle2 as Pr,ChevronLeft as yo,Loader2 as Kt,Lock as hr,Package as Po,Truck as xr}from"lucide-react";import{useEffect as ho,useState as Wt}from"react";import{Fragment as kr,jsx as p,jsxs as y}from"react/jsx-runtime";function bo({status:e}){let t={created:{color:"bg-neutral-100 text-neutral-700",icon:null},paid:{color:"bg-green-100 text-green-700",icon:Pr},completed:{color:"bg-blue-100 text-blue-700",icon:Pr},canceled:{color:"bg-red-100 text-red-700",icon:wr},sent:{color:"bg-purple-100 text-purple-700",icon:xr},processing:{color:"bg-yellow-100 text-yellow-700",icon:Kt}},r=t[e]||t.created,o=r.icon,n={created:"Utworzone",paid:"Op\u0142acone",completed:"Zako\u0144czone",canceled:"Anulowane",sent:"Wys\u0142ane",processing:"Przetwarzane"};return y("span",{className:`inline-flex items-center gap-1 rounded-full px-3 py-1 text-sm font-medium ${r.color}`,children:[o&&p(o,{className:"h-4 w-4"}),n[e]||e]})}function vo({orderID:e,email:t}){let[r,o]=Wt(""),n=ee(B.publicApi.addPublicOrderComment);return y("form",{onSubmit:async i=>{if(i.preventDefault(),!!r.trim())try{await n.mutateAsync({projectId:"",orderId:e,message:r.trim(),accessToken:t}),o("")}catch(c){console.error("Failed to add comment:",c)}},className:"mt-4 space-y-2",children:[p(Ie,{htmlFor:"comment",children:"Dodaj komentarz"}),p(bn,{id:"comment",value:r,onChange:i=>o(i.target.value),placeholder:"Wpisz komentarz...",rows:3,disabled:n.isPending}),p(S,{type:"submit",disabled:!r.trim()||n.isPending,children:n.isPending?y(kr,{children:[p(Kt,{className:"mr-2 h-4 w-4 animate-spin"}),"Wysy\u0142anie..."]}):"Dodaj komentarz"})]})}function br(e){return e?new Date(Number(e.seconds)*1e3).toLocaleDateString("pl-PL",{year:"numeric",month:"long",day:"numeric"}):"N/A"}function vr(e,t){return new Intl.NumberFormat("pl-PL",{style:"currency",currency:t.toUpperCase()}).format(e/100)}function wo({orderID:e,initialEmail:t,onBack:r,accessToken:o,analytics:n}){let{theme:a,projectID:i}=Pe(),c=Te(i,n,"order"),[d,l]=Wt(t||""),[u,g]=Wt(!1),{data:k,isLoading:m,error:v,refetch:C}=De(B.publicApi.getPublicOrderDetails,{projectId:i??"",orderId:e,email:d||void 0,accessToken:o},{enabled:!!e}),s=k?.result.case==="order"?k.result.value:null,h=s?.isVerified??!1,R=s!=null;ho(()=>{R&&c.track("panel_order_viewed",{},{order_ref:null})},[c,R]);let q=()=>{C(),g(!1)},F={"--button-background-color":a?.colors?.brand??"#000000","--button-background-color-dark":a?.colors?.brandDark??"#ffffff","--button-text-color":a?.colors?.brandDark??"#000000","--button-text-color-dark":a?.colors?.brand??"#000000"};return m?p("div",{className:"flex min-h-screen items-center justify-center",children:y("div",{className:"text-center",children:[p(Kt,{className:"mx-auto h-8 w-8 animate-spin text-neutral-400"}),p("p",{className:"mt-2 text-neutral-600 dark:text-neutral-400",children:"\u0141adowanie zam\xF3wienia..."})]})}):v||!s?p("div",{className:"flex min-h-screen items-center justify-center",children:p(ue,{className:"w-full max-w-md",children:p(me,{className:"pt-6",children:y("div",{className:"text-center",children:[p(wr,{className:"mx-auto h-12 w-12 text-red-500"}),p("h2",{className:"mt-4 text-xl font-semibold",children:"Zam\xF3wienie nie znalezione"}),p("p",{className:"mt-2 text-neutral-600 dark:text-neutral-400",children:"Nie znaleziono zam\xF3wienia o podanym numerze."})]})})})}):p("div",{className:"w-full bg-white py-8 dark:bg-black",style:F,children:y("div",{className:"w-full px-4",children:[r&&y(S,{onClick:r,variant:"ghost",className:"mb-4 w-fit",children:[p(yo,{className:"h-4 w-4"}),"Wr\xF3\u0107 do historii zam\xF3wie\u0144"]}),y("div",{className:"mb-6 flex items-center gap-4",children:[a?.logoURL&&y(kr,{children:[p("img",{src:a.logoURL,alt:"Project logo",className:`h-12 w-auto ${a.logoDarkURL?"dark:hidden":""}`}),a.logoDarkURL&&p("img",{src:a.logoDarkURL,alt:"Project logo",className:"hidden h-12 w-auto dark:block"})]}),y("div",{children:[p("h1",{className:"text-3xl font-bold",children:"Zam\xF3wienie"}),y("p",{className:"text-neutral-600 dark:text-neutral-400",children:["Numer zam\xF3wienia: #",s.orderId]})]})]}),y(ue,{className:"mb-6",children:[p(be,{children:y(ve,{className:"flex items-center",children:[p(Po,{className:"mr-2 h-5 w-5"}),"Status zam\xF3wienia"]})}),y(me,{className:"space-y-6",children:[y("div",{children:[y("div",{className:"flex items-center gap-2",children:[p(bo,{status:s.status}),s.processingStatus&&y("span",{className:"text-sm text-neutral-600",children:["\xB7 ",s.processingStatus]})]}),y("p",{className:"mt-2 text-sm text-neutral-600",children:["Zam\xF3wienie z\u0142o\u017Cone ",br(s.createdAt)]})]}),y("div",{className:"border-t pt-4",children:[p("h3",{className:"mb-3 font-semibold",children:"Dane klienta"}),y("div",{className:"space-y-2",children:[y("div",{children:[p("span",{className:"font-medium",children:"Imi\u0119 i nazwisko:"})," ",p("span",{className:h?"":"text-neutral-500",children:s.customerName})]}),y("div",{children:[p("span",{className:"font-medium",children:"Email:"})," ",p("span",{className:h?"":"text-neutral-500",children:s.customerEmail})]}),s.customerPhone&&y("div",{children:[p("span",{className:"font-medium",children:"Telefon:"})," ",p("span",{className:h?"":"text-neutral-500",children:s.customerPhone})]})]})]}),!h&&p("div",{className:"border-t pt-4",children:y(S,{onClick:()=>g(!0),variant:"outline",className:"w-full",children:[p(hr,{className:"mr-2 h-4 w-4"}),"Zweryfikuj sw\xF3j email"]})})]})]}),y(ue,{className:"mb-6",children:[p(be,{children:p(ve,{children:"Produkty"})}),y(me,{className:"space-y-6",children:[p("div",{className:"space-y-4",children:s.items.map((A,E)=>y("div",{className:"flex items-center gap-4",children:[A.imageUrl&&p("img",{src:A.imageUrl,alt:A.name,className:"h-16 w-16 rounded object-cover"}),y("div",{className:"flex-1",children:[p("p",{className:"font-medium",children:A.name}),y("p",{className:"text-sm text-neutral-600",children:["Ilo\u015B\u0107: ",A.quantity]})]}),p("div",{className:"text-right",children:p("p",{className:"font-medium",children:vr(Number(A.price),A.currency)})})]},E))}),(s.deliveryAddress||s.deliveryMethod)&&y("div",{className:"border-t pt-4",children:[y("h3",{className:"mb-3 flex items-center font-semibold",children:[p(xr,{className:"mr-2 h-5 w-5"}),"Informacje o dostawie"]}),y("div",{className:"space-y-2",children:[s.deliveryAddress&&y("div",{children:[p("span",{className:"font-medium",children:"Adres:"})," ",p("span",{className:h?"":"text-neutral-500",children:s.deliveryAddress})]}),s.deliveryMethod&&y("div",{children:[p("span",{className:"font-medium",children:"Metoda:"})," ",s.deliveryMethod]}),s.trackingNumber&&h&&y("div",{children:[p("span",{className:"font-medium",children:"Tracking:"})," ",s.trackingNumber]})]})]}),p("div",{className:"border-t pt-4",children:y("div",{className:"flex justify-between text-lg font-bold",children:[p("span",{children:"Suma:"}),p("span",{children:vr(Number(s.totalAmount),s.currency)})]})})]})]}),y(ue,{children:[p(be,{children:y(ve,{children:["Komentarze ",s.commentCount>0&&`(${s.commentCount})`]})}),y(me,{children:[s.comments.length>0?p("div",{className:"space-y-4",children:s.comments.map(A=>y("div",{className:"border-b pb-4 last:border-b-0",children:[y("div",{className:"mb-1 flex items-center gap-2",children:[p("span",{className:"font-medium",children:A.authorName||"System"}),p("span",{className:"text-xs text-neutral-500",children:br(A.createdAt)}),A.authorType==="admin"&&p("span",{className:"rounded bg-blue-100 px-2 py-0.5 text-xs text-blue-700",children:"Admin"})]}),p("p",{className:h?"":"text-neutral-500",children:A.message})]},A.id))}):p("p",{className:"text-neutral-600",children:"Brak komentarzy."}),h?p(vo,{orderID:s.orderId,email:d}):p("div",{className:"mt-4",children:y(S,{onClick:()=>g(!0),variant:"outline",className:"w-full",children:[p(hr,{className:"mr-2 h-4 w-4"}),"Zweryfikuj sw\xF3j email"]})})]})]}),u&&p("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",children:y(ue,{className:"w-full max-w-md",children:[p(be,{children:p(ve,{children:"Zweryfikuj sw\xF3j email"})}),y(me,{className:"space-y-4",children:[p("p",{className:"text-sm text-neutral-700",children:"Podaj adres email u\u017Cyty przy sk\u0142adaniu zam\xF3wienia."}),y("div",{className:"space-y-2",children:[p(Ie,{htmlFor:"verify-email",children:"Adres email"}),p(lt,{id:"verify-email",type:"email",placeholder:"twoj@email.com",value:d,onChange:A=>l(A.target.value)})]}),y("div",{className:"flex gap-2",children:[p(S,{variant:"outline",onClick:()=>g(!1),className:"flex-1",children:"Anuluj"}),p(S,{onClick:q,className:"flex-1",children:"Zweryfikuj"})]})]})]})})]})})}function xo(e){return p(wo,{...e})}var Zt=xo;import{jsx as de,jsxs as Cr}from"react/jsx-runtime";var No=({returnsAppearance:e,returnsTexts:t,analytics:r}={})=>{let{projectID:o,theme:n,loginURL:a,host:i}=Pe(),c=Te(o,r,"panel"),d=Ke(o,i),l=Pn(o,i),{mutateAsync:u}=ee(B.publicApi.userPanelLogout);async function g(){d&&await u({accessToken:d}),typeof window<"u"&&(Le(o,i),window.location.reload())}let[k]=ko(),m=D=>["products","notifications","profile","plans","orders","order-details","returns","return-details","course"].includes(D),[v,C]=_n({product:void 0,state:"products",orderId:void 0,returnId:void 0,course:void 0,item:void 0}),[s,h]=Co(m(v.state)?v.state:"products"),R=D=>{C({state:"order-details",orderId:D}),h("order-details")},q=()=>{C({state:"orders",orderId:void 0}),h("orders")},F=D=>C({orderId:void 0,returnId:void 0,course:void 0,item:void 0,...D}),A=D=>{C({state:"course",course:D,item:void 0,product:void 0}),h("course")},E=()=>{C({state:"products",course:void 0,item:void 0,product:void 0}),h("products")};bt(()=>{m(v.state)&&(v.state==="course"||s==="course")&&h(v.state)},[v.state]);let z={"--button-background-color":n?.colors?.brand??"#000000","--button-background-color-dark":n?.colors?.brandDark??"#ffffff","--button-text-color":n?.colors?.brandDark??"#000000","--button-text-color-dark":n?.colors?.brand??"#000000"};return bt(()=>{if(d==null||d.length===0){window.location.href=a??"/panel/login";return}},[]),bt(()=>{if(d==null||d.length===0){window.location.href=a??"/panel/login";return}},[s]),bt(()=>{if(typeof window>"u"||window.parent!==window||!d)return;let D=Je(window.location.search);D&&Qe(D);let $=D??Ue();$&&(window.location.href=Me($,d))},[d]),de(ct,{value:c,children:Cr("div",{ref:k,className:"font-inter relative min-h-screen w-screen bg-beige-100 text-black dark:bg-black dark:text-white md:flex",children:[de(fr,{activeScreen:s,setActiveScreen:h,setParams:F,styles:z,theme:n,logout:g}),Cr("main",{className:"flex h-[calc(100vh-80px)] flex-col overflow-y-auto w-full p-5 md:h-screen",children:[s==="products"&&de(ur,{projectID:o??"",accessToken:d,loginURL:a??"/panel/login",styles:z,activeScreen:s,params:v,setParams:C,openCourse:A}),s==="course"&&v.course&&d&&de(Vt,{accessId:v.course,accessToken:d,theme:n,itemId:v.item,onItemChange:D=>C({item:D}),onBack:E}),s==="notifications"&&de(Bn,{}),s==="plans"&&de(Jn,{projectID:o??""}),s==="orders"&&de(Wn,{projectID:o??"",accessToken:d??"",openOrderDetails:R}),s==="order-details"&&v.orderId&&de(Zt,{orderID:v.orderId,onBack:q}),(s==="returns"||s==="return-details")&&d&&de(Gt,{projectID:o??"",host:i,accessToken:d,loginURL:a??"/panel/login",appearance:zn(e,n?.colors?.brand),texts:t,screen:s,params:v,setParams:C,setActiveScreen:h}),s==="profile"&&de(yr,{email:l,logout:g})]})]})})},Io=No;import{create as fe}from"@bufbuild/protobuf";import{QueryClient as Go,QueryClientProvider as $o}from"@tanstack/react-query";import{createContext as Ho,useContext as Vo,useEffect as _r,useState as Wo}from"react";import{createClient as So}from"@connectrpc/connect";import{createConnectTransport as Ro}from"@connectrpc/connect-web";var le;(o=>{function e(n){return So(mn,r(n))}o.get=e;let t=new Map;function r(n){let a=t.get(n);return a==null&&(a=Ro({useBinaryFormat:!0,baseUrl:n+"/api/rpc",interceptors:[un]}),t.set(n,a)),a}})(le||={});import T from"zod";import Q from"zod";function _(e,t=2){return+(Math.round(+(e+"e+"+t))+"e-"+t)}function Nr(e,t){let r=typeof navigator>"u"?"pl-PL":navigator.language;return Intl.NumberFormat(r,{style:"currency",currency:t,currencyDisplay:"symbol"}).format(e/100)}var jd=Q.object({event:Q.enum(["purchase","addToCart","customizeProduct","viewCart","removeFromCart","initiateCheckout","lead"]),step:Q.string().optional(),value:Q.number().optional(),currency:Q.string().optional(),content_name:Q.string().optional(),items:Q.array(Q.object({id:Q.string(),name:Q.string(),price:Q.number().default(0),currency:Q.string().default("PLN"),quantity:Q.number().default(1)})).optional()});function Jt(e){typeof window>"u"||(Ao(e),Do(e),Lo(e))}function Ao(e){try{typeof window.dataLayer>"u"&&(window.dataLayer=[]);let t=To(e);window.dataLayer.push(t)}catch(t){console.warn("cannot send google analytics event",t)}}function To(e){let t=e.value??e.items?.reduce((a,i)=>a+(i.price||0)*(i.quantity||1),0)??0,r=e.items?.map(a=>({item_id:a.id,item_name:a.name||a.id,price:_((a.price||0)/100,2),quantity:a.quantity||1})),o={currency:e.currency||"PLN",value:_(t/100,2)};r&&r.length>0&&(o.items=r);let n;switch(e.event){case"purchase":n="purchase",o.transaction_id=e.step||`txn_${Date.now()}`;break;case"addToCart":n="add_to_cart";break;case"viewCart":n="view_cart";break;case"removeFromCart":n="remove_from_cart";break;case"initiateCheckout":n="begin_checkout";break;case"customizeProduct":n="customize_product";break;default:n=e.event}return{event:n,ecommerce:o,...e.step&&{step:e.step},...e.content_name&&{content_name:e.content_name}}}function Do(e){if(typeof window.fbq>"u")return;let t="",r="",o={};switch(e.event){case"purchase":t="track",r="Purchase",o={category_name:e.step,...e};break;case"lead":t="track",r="Lead",o={category_name:e.step,...e};break;case"addToCart":t="track",r="Add to Cart",o={category_name:e.step,...e};break;case"customizeProduct":t="track",r="Customize Product",o={category_name:e.step,...e};break;case"viewCart":t="track",r="View Cart",o={category_name:e.step,...e};break;case"removeFromCart":t="track",r="Remove from Cart",o={category_name:e.step,...e};break;case"initiateCheckout":t="track",r="Initiate Checkout",o={category_name:e.step,...e};break;default:break}window.location.search.includes("analytics")&&console.log("Pushing FB event",t,r,o),window.fbq(t,r,o)}function Lo(e){try{if(typeof window.ttq>"u")return;let t=Eo(e);if(!t)return;window.location.search.includes("analytics")&&console.log("Pushing TikTok event",t.eventName,t.eventPayload),window.ttq.track(t.eventName,t.eventPayload)}catch(t){console.warn("cannot send tiktok analytics event",t)}}function Eo(e){let t=e.value??e.items?.reduce((a,i)=>a+(i.price||0)*(i.quantity||1),0)??0,r=e.items?.map(a=>({content_id:a.id,content_type:"product",content_name:a.name||a.id,quantity:a.quantity||1,price:_((a.price||0)/100,2)}))||[];r.length===0&&e.content_name&&r.push({content_id:e.step||"unknown",content_type:"product",content_name:e.content_name,quantity:1,price:_(t/100,2)});let o={currency:e.currency||"PLN",value:_(t/100,2)};r.length>0&&(o.contents=r);let n=null;switch(e.event){case"purchase":n="Purchase";break;case"addToCart":n="AddToCart";break;case"initiateCheckout":n="InitiateCheckout";break;case"customizeProduct":n="CustomizeProduct";break;case"viewCart":return;case"removeFromCart":return;case"lead":return;default:return null}return{eventName:n,eventPayload:o}}function Ir(e){let{items:t,googlePayConfig:r,checkout:o,result:n,cartRequiresShipping:a}=e,i=e.locale??V();if(n.totalAmount==null)return;let c=[];return a&&(c.push("SHIPPING_ADDRESS"),c.push("SHIPPING_OPTION")),{apiVersion:2,apiVersionMinor:0,callbackIntents:c,allowedPaymentMethods:[{type:"CARD",parameters:{allowedAuthMethods:["PAN_ONLY","CRYPTOGRAM_3DS"],allowedCardNetworks:["MASTERCARD","VISA"]},tokenizationSpecification:{type:"PAYMENT_GATEWAY",parameters:{gateway:r.gateway,gatewayMerchantId:r.gatewayId}}}],emailRequired:!0,shippingAddressParameters:{phoneNumberRequired:a},shippingAddressRequired:a,shippingOptionRequired:a,shippingOptionParameters:a?{shippingOptions:n.methods.slice(0,5).map(l=>({id:l.id,label:l.name+` - ${Nr(l.amount,n.currency)}`,description:l.description??""})),defaultSelectedOptionId:n.selectedDeliveryMethod}:void 0,merchantInfo:{merchantId:r.merchantId+"",merchantName:r.merchantName},transactionInfo:{totalPriceStatus:"FINAL",totalPriceLabel:he("paymentForCart",i,e.texts),totalPrice:`${_(n.totalAmount/100,2)}`,currencyCode:n.currency,countryCode:n.country,checkoutOption:"COMPLETE_IMMEDIATE_PURCHASE",displayItems:Oo(t,n.methods,n.selectedDeliveryMethod??(n.methods.length>0?n.methods[0].id:void 0),o.couponCode,n.couponValue,he("coupon",i,e.texts))}}}function Oo(e,t,r,o,n,a="Coupon"){let i=[],c=0;for(let l of e){if(l.details==null)continue;let u=l.details.pricing?.effectivePrice??l.details.price;c+=u*l.quantity,i.push({label:l.details.name+" x "+l.quantity,price:`${_(u/100,2)}`,type:"LINE_ITEM",status:"FINAL"})}let d=t.find(l=>l.id===r);return d!=null&&i.push({label:d.name,price:`${_(d.amount/100,2)}`,type:"SHIPPING_OPTION",status:"FINAL"}),o!=null&&n!=null&&i.push({label:`${a} ${o}`,price:`${_(n/100,2)}`,type:"DISCOUNT",status:"FINAL"}),c>0&&i.push({label:"Subtotal",price:`${_(c/100,2)}`,type:"SUBTOTAL",status:"FINAL"}),i}function nt(e,t){return`${K}/api/integrations/${e}/public-commerce${t}`}function ke(e){return typeof e=="object"&&e!=null&&"ERR"in e}function G(e,t,r){return{ERR:!0,error:e,type:t,data:r}}function Sr(e,t){return t?.find(r=>r.id===e||(r.variants?.some(o=>o.id===e)??!1))}function Rr(e,t){let r=new Set(t.map(o=>o.productID));return Array.from(new Set(e.filter(o=>!r.has(o))))}function Ar(e,t){let r=e?.trim();if(!(r==null||r.length===0))try{let o=new URL(r,t);return o.protocol!=="http:"&&o.protocol!=="https:"?void 0:o.href}catch{return}}import{create as Uo}from"zustand";var Fe=Uo(e=>({isCartVisible:!1,notice:void 0,setNotice:t=>e(r=>({...r,notice:t})),numberOfProductsInCart:0,showCart:()=>e(t=>({...t,isCartVisible:!0})),hideCart:()=>e(t=>({...t,isCartVisible:!1})),setNumberOfProductsInCart:t=>e(r=>({...r,numberOfProductsInCart:t}))}));import{createContext as Mo,useContext as Qt,useMemo as Tr}from"react";import{jsx as jo}from"react/jsx-runtime";var vt=Mo({});function Yd({texts:e,locale:t,children:r}){let o=Tr(()=>({texts:e,locale:t}),[e,t]);return jo(vt.Provider,{value:o,children:r})}function Dr(){return Qt(vt)}function Xd(e){let{texts:t,locale:r}=Qt(vt);return he(e,r??V(),t)}function el(){let{texts:e,locale:t}=Qt(vt),r=t??V();return Tr(()=>o=>he(o,r,e),[r,e])}var Xt="bitsnap-pending-order";function Or(e,t){let r=new Map;for(let n of t)r.set(n.id,(r.get(n.id)??0)+n.quantity);let o=[];for(let n of e){let a=r.get(n.id);a==null?o.push(n):n.quantity>a&&o.push({...n,quantity:n.quantity-a})}return o}var _o=60*1e3;function Ur(e,t=Date.now,r=_o){let o;return n=>{let a=`${n.orderId}:${n.ts}`,i=t();return o?.key===a&&i-o.at<r?Promise.reject(new Error("pending order was asked about recently")):(o={key:a,at:i},e(n))}}function zo(e){if(!(e==null||e.length===0))try{let t=new URL(e,"https://bitsnap.invalid").pathname,r=/\/payment\/common\/([^/]+)\/([^/]+)\/?$/.exec(t);return r==null?void 0:{projectId:decodeURIComponent(r[1]),orderId:decodeURIComponent(r[2])}}catch{return}}function qo(e,t=Date.now(),r={}){let o=zo(e.url),n=Lr(e.orderId)??o?.orderId,a=Lr(e.projectId)??o?.projectId;if(!(n==null||a==null))return{orderId:n,projectId:a,...r.cartProjectId!=null?{cartProjectId:r.cartProjectId}:{},lines:r.lines??[],ts:t}}function rl(e,t={}){let r=qo(e,t.now,t);return r!=null&&Fo(r,t.storage)}function Lr(e){return e!=null&&e.length>0?e:void 0}function wt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Fo(e,t=wt()){try{return t?.setItem(Xt,JSON.stringify(e)),t!=null}catch{return!1}}function Er(e=wt()){try{let t=e?.getItem(Xt);if(t==null)return;let r=JSON.parse(t);if(typeof r=="object"&&r!=null&&typeof r.orderId=="string"&&typeof r.projectId=="string"&&typeof r.ts=="number"&&r.orderId.length>0){let{orderId:o,projectId:n,cartProjectId:a,ts:i,lines:c}=r;return{orderId:o,projectId:n,...typeof a=="string"?{cartProjectId:a}:{},lines:Array.isArray(c)?c.filter(d=>typeof d?.id=="string"&&typeof d.quantity=="number"):[],ts:i}}}catch{}Yt(e)}function Yt(e=wt()){try{e?.removeItem(Xt)}catch{}}function Mr(e){let t=e.details?.status??Bo(e.details?.$unknown);return t==="created"||t==="paid"||t==="canceled"?t:"unknown"}function Bo(e){if(Array.isArray(e)){for(let t of e)if(t?.no===3&&t.wireType===2&&t.data instanceof Uint8Array){let r=0,o=0;for(let n=0;o<t.data.length&&n<35;n+=7){let a=t.data[o++];if(r|=(a&127)<<n,!(a&128))break}if(o+r!==t.data.length)return;try{return new TextDecoder().decode(t.data.subarray(o))}catch{return}}}}async function jr(e){let t=e.storage??wt(),r=Er(t);if(r==null)return"none";if((e.now??Date.now)()-r.ts>864e5)return Yt(t),"expired";if(e.projectId!=null&&r.cartProjectId!=null&&r.cartProjectId!==e.projectId)return"pending";let n;try{n=await e.fetchStatus(r)}catch{return"pending"}let a=Er(t);if(a?.orderId!==r.orderId||a.ts!==r.ts)return"pending";if(n==="paid"){try{await e.removeLines(r.lines)}catch{return"pending"}return Yt(t),"paid"}return"pending"}import{Fragment as ii,jsx as tn}from"react/jsx-runtime";var Ko="__m_a",Fr=Ho(void 0),rn=void 0;function Tl(e){Ot({projectID:e}),rn=e,typeof window<"u"&&Ve([window.location.origin])}function rt(){return rn??document.querySelector('script[data-id][data-name="internal-cart"]')?.getAttribute("data-id")??void 0}function Zo(){return document.querySelector('script[data-id][data-name="internal-cart"]')?.getAttribute("data-custom-host")??void 0}var Jo=({children:e,locale:t})=>{let[r]=Wo(()=>new Go),o=Dr();_r(()=>{Ge()},[]);let n=rt();if(_r(()=>{if(n==null)return;let i=()=>{Xo(n).then(d=>{d==="paid"&&r.invalidateQueries({queryKey:["cart"]})})},c=()=>{document.visibilityState==="visible"&&i()};return i(),window.addEventListener("pageshow",i),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("pageshow",i),document.removeEventListener("visibilitychange",c)}},[n,r]),n==null)return tn(ii,{});let a=on(n,t??o.locale,o.texts);return tn($o,{client:r,children:tn(Fr.Provider,{value:a,children:e})})},en,Qo=Ur(async e=>Mr(await le.get(K).getOrder({id:e.orderId,projectId:e.projectId})));function Dl(){let{country:e,couponCode:t,selectedDeliveryMethod:r,postalCode:o}=L()??kt;return{country:e,couponCode:t,selectedDeliveryMethod:r,postalCode:o}}function Ll(){return(L()?.products??[]).map(e=>({id:e.id,quantity:e.quantity}))}function Yo(e){let t=L();Y({...t,products:Or(t?.products??[],e)}),Ge()}function Xo(e){return en??=jr({projectId:e,fetchStatus:Qo,removeLines:Yo}).catch(t=>{console.warn("cannot check the pending order",t)}).finally(()=>{en=void 0}),en}var Be=async(e,t)=>{let r=[];t?.items!=null&&t.items.length>0?r=t.items:r=L()?.products??[];let o=Array.from(new Set(r.map(i=>i.productID)));if(o.length===0)return[];let n=new URLSearchParams;n.set("ids",o.join(",")),n.set("locale",t?.locale??V());let a;try{let i=await fetch(Rt(nt(e,`/products?${n.toString()}`)),{method:"GET"});if(i.status!=200)return G("products-load-failed","internal");a=await i.json()}catch(i){return console.warn("cannot load the products of the cart",i),G("products-load-failed","internal")}return r.flatMap(i=>{let c=Sr(i.productID,a.result);return c==null?[]:[{...i,details:oi(i.productID,c),catalogProductID:c.id}]})},El=()=>{let e=Vo(Fr);if(e===void 0)throw new Error("useCartProvider must be used within a CartProvider");return e},Ol=Jo,ei=T.object({isAvailable:T.boolean(),merchantId:T.string(),merchantName:T.string(),gateway:T.string(),gatewayId:T.string()}),ti=T.object({id:T.string(),productID:T.string(),quantity:T.number(),priceVersion:T.string().optional(),metadata:T.record(T.string(),T.string().optional()).optional(),url:T.string().optional()}),ni=T.object({country:T.string().optional(),couponCode:T.string().optional(),selectedDeliveryMethod:T.string().optional(),postalCode:T.string().optional(),email:T.string().optional(),products:T.array(ti).optional(),googlePayConfig:ei.optional()}),kt={country:void 0,couponCode:void 0,email:void 0,selectedDeliveryMethod:void 0,postalCode:void 0,products:[],googlePayConfig:void 0},Br="checkout";function L(){try{let e=localStorage.getItem(Br);return e==null?kt:ni.parse(JSON.parse(e))}catch{return kt}}async function zr(e,t){let r=await Be(e,{items:t.map((a,i)=>({...a,id:`price-check-${i}`}))});if(ke(r))return r;let o=Rr(t.map(a=>a.productID),r);if(o.length>0)return G("item-ids-not-found","notFound",o);let n=L();n.products==null&&(n.products=[]),n.products.push(...t.map(a=>({id:Math.random().toString(36).substring(7),productID:a.productID,quantity:a.quantity,priceVersion:r.find(i=>i.productID===a.productID)?.details?.pricing?.priceVersion,metadata:a.metadata,url:Ar(a.url,typeof window<"u"?window.location.href:void 0)}))),ri(t,r),Jt({event:"addToCart",currency:"PLN",items:t.map(a=>({id:a.productID,name:a.name??"",price:a.price??0,quantity:a.quantity,currency:a.currency??"PLN"}))}),Y(n),Ge()}function ri(e,t){for(let r of e)try{let o=t.find(c=>c.productID===r.productID),n=o?.details?.pricing?.effectivePrice??o?.details?.price??r.price,a=o?.details?.currency??r.currency;if(n==null||a==null)continue;let i=o?.catalogProductID??r.productID;(r.analytics??pn()).track("add_to_cart",{qty:r.quantity,value_minor:Math.round(n*r.quantity),currency:a},{product_id:i,variant_id:i!==r.productID?r.productID:null})}catch{}}function qr(e){let t=L(),r={...t,products:t?.products?.filter(o=>!e.includes(o.productID)&&!e.includes(o.id))};Jt({event:"removeFromCart",items:e.map(o=>({id:o,name:"",price:0,quantity:1,currency:"PLN"}))}),Y(r),Ge()}function Y(e){localStorage.setItem(Br,JSON.stringify(e))}var on=(e,t=V(),r)=>{let o=Zo();return o!=null&&fn(o),{async checkIfApplePayIsAvailable(){if(typeof window>"u"||typeof document>"u"||!("ApplePaySession"in window))return!1;try{return(await le.get(K).isOneClickPaymentAvailable({projectId:e})).applePay}catch(n){return console.error("Error checking if Apple Pay is available",n),!1}},async getGooglePayConfiguration(n){if(typeof window>"u"||typeof document>"u")return{isAvailable:!1};try{let a=await ai(e);if(a?.isAvailable!=!0)return{isAvailable:!1};let i=L();if(i==null)return console.log("checkout is null"),{isAvailable:!1};let c=await Be(e,{locale:t,items:n.items.map(g=>({id:Math.random().toString(36).substring(7),quantity:g.quantity,metadata:g.metadata,productID:g.productID}))});if(ke(c))return{isAvailable:!1};let d=await le.get(K).getPreOrderDetails({items:c.map(g=>fe(st,{id:g.productID,quantity:g.quantity})),projectId:e,postCode:i.postalCode,couponCode:i.couponCode,countryCode:i.country,selectedDeliveryMethod:i.selectedDeliveryMethod});if(d.totalAmount==null)return{isAvailable:!1};let l=c.find(g=>g.details?.isDeliverable==!0)!=null,u=await Ir({items:c,googlePayConfig:a,checkout:i,cartRequiresShipping:l,result:d,locale:t,texts:r});return u==null?{isAvailable:!1}:{isAvailable:!0,config:u}}catch(a){return console.error("Error resolving Google Pay configuration",a),{isAvailable:!1}}},async clearCart(){let n=structuredClone(kt);n.country=L()?.country,Y(n),Ge()},async getAvailableCountries(){let n=await fetch(Rt(nt(e,"/countries")),{method:"GET"});if(n.status!=200)return[];try{return T.array(T.object({name:T.string(),code:T.string()})).parse(await n.json())}catch(a){return G(a.toString(),"internal")}},async getCountry(){let n=L()?.country;if(n==null){n="PL";let a=L();a.country=n,Y(a)}return n},async getNumberOfElementsInCart(){return L()?.products?.reduce((n,a)=>n+a.quantity,0)??0},async getProducts(){return await Be(e,{locale:t})},async removeProductFromCart(n){return qr([n.id])},async setCountry(n){let a=L();a.country=n,Y(a)},async setCouponCodeIfPossible(n){let a=L();a.couponCode=n,Y(a)},async setPostalCode(n){let a=L();a.postalCode=n,Y(a)},async setDeliveryMethod(n){let a=L();a.selectedDeliveryMethod=n,Y(a)},async setEmail(n){let a=L();a.email=n,Y(a)},async addProduct(n){return await zr(e,[n])},async updateQuantity(n){let a=L();a.products=a.products?.map(i=>(i.id===n.id&&(i.quantity=n.quantity),i)),Y(a),Ge()},async redirectToNextStep(){let n=L();if(n.products==null||n.products.length==0)return G("cart-is-empty","badInput");let a=n.products.reduce((d,l)=>(l.metadata!=null&&Object.keys(l.metadata).forEach(u=>{let g=l.metadata?.[u];g!=null&&(d[u]=g)}),d),{}),i={items:n.products.map(d=>({id:d.productID,quantity:d.quantity,priceVersion:d.priceVersion})),askForNote:!0,countries:n.country?[n.country]:void 0,metadata:a,locale:t},c=await nn(i);return ke(c)?(console.warn("cannot create payment URL",c.error),c):{url:c.url,...c.orderId!=null?{orderId:c.orderId}:{},...c.projectId!=null?{projectId:c.projectId}:{}}},async justRedirectToPayment(n){let a={items:[{id:n.productID,quantity:1}],askForNote:!1,details:n.email||n.name?{name:n.name,email:n.email}:void 0,locale:n.locale??t};a=an(a),n.country==null&&(n.country="pl"),a.details==null&&(a.details={}),a.details.address==null&&(a.details.address={}),a.details.address.country=n.country,n.marketingAgreement===!0&&(a.additionalAgreements=[{id:Ko,name:"",required:!0,answer:!0}]);let i=await nn(a);return ke(i)?i:{url:i.url}},async getApplePayPreview(n){let a=L();try{let i=await le.get(K).getPreOrderDetails({items:n.items.map(c=>fe(st,{id:c.productID,quantity:c.quantity})),projectId:e,postCode:a.postalCode,couponCode:a.couponCode,countryCode:a.country,selectedDeliveryMethod:a.selectedDeliveryMethod});return i.totalAmount==null||i.currency.length===0?G("pre-order-unavailable","internal"):{countryCode:i.country||a.country||"PL",currencyCode:i.currency,totalAmount:`${_(i.totalAmount/100,2)}`}}catch(i){return console.warn("cannot load the Apple Pay preview",i),G("pre-order-unavailable","internal")}},async completeApplePayPayment(n){let a=L();if(a==null)return G("Checkout not found");let i=await Be(e,{locale:t});if(ke(i))return i;try{let c=n.shippingContact?.givenName;n.shippingContact?.familyName!=null?c+=" "+n.shippingContact?.familyName:n.billingContact?.familyName!=null&&(c+=" "+n.billingContact?.familyName);let d={},l=xt();l!=null&&(d.ref=l);let u=await le.get(K).authorizeOneClickPayment({gateway:0,paymentData:JSON.stringify(n.token.paymentData),paymentMethod:JSON.stringify(n.token.paymentMethod),transactionIdentifier:n.token.transactionIdentifier,order:fe(Dt,{items:i.map(g=>({id:g.productID,quantity:g.quantity})),couponCode:a.couponCode,email:n.shippingContact?.emailAddress??n.billingContact?.emailAddress??a.email??void 0,phone:n.shippingContact?.phoneNumber??n.billingContact?.phoneNumber??void 0,selectedDeliveryMethod:a.selectedDeliveryMethod,postCode:a.postalCode,projectId:e}),shippingAddress:fe(At,{line1:n.shippingContact?.addressLines?.[0]??"",city:n.shippingContact?.locality??"",country:n.shippingContact?.countryCode??"",zipCode:n.shippingContact?.postalCode??"",name:c}),billingAddress:fe(Tt,{name:n.billingContact?.givenName??" "+(n.billingContact?.familyName??""),line1:n.billingContact?.addressLines?.[0]??"",city:n.billingContact?.locality??"",country:n.billingContact?.countryCode??"",zipCode:n.billingContact?.postalCode??""}),metadata:Object.keys(d).length>0?JSON.stringify(d):void 0});return{isSuccess:u.isSuccess,redirectURL:u.redirectUrl}}catch(c){return console.error(c),G("Failed to authorize payment")}},async completeGooglePayPayment(n){let a=L();if(a==null)return G("Checkout not found");let i=await Be(e,{locale:t});if(ke(i))return i;try{let c=n.paymentData.shippingAddress?.name,d={},l=xt();l!=null&&(d.ref=l);let u=await le.get(K).authorizeOneClickPayment({gateway:1,paymentData:n.paymentData.paymentMethodData.tokenizationData.token,paymentMethod:n.paymentData.paymentMethodData.type,transactionIdentifier:"",order:fe(Dt,{items:i.map(g=>({id:g.productID,quantity:g.quantity})),couponCode:a.couponCode,email:n.paymentData.email??void 0,phone:n.paymentData.shippingAddress?.phoneNumber??void 0,selectedDeliveryMethod:n.paymentData.shippingOptionData?.id??a.selectedDeliveryMethod,postCode:n.paymentData.shippingAddress?.postalCode,projectId:e}),shippingAddress:fe(At,{line1:n.paymentData.shippingAddress?.address1??"",city:n.paymentData.shippingAddress?.locality??"",country:n.paymentData.shippingAddress?.countryCode??"",zipCode:n.paymentData.shippingAddress?.postalCode??"",name:c}),billingAddress:fe(Tt,{name:n.paymentData.paymentMethodData.info?.billingAddress?.name,line1:n.paymentData.paymentMethodData.info?.billingAddress?.address1??"",city:n.paymentData.paymentMethodData.info?.billingAddress?.locality??"",country:n.paymentData.paymentMethodData.info?.billingAddress?.countryCode??"",zipCode:n.paymentData.paymentMethodData.info?.billingAddress?.postalCode??""}),metadata:Object.keys(d).length>0?JSON.stringify(d):void 0});return{isSuccess:u.isSuccess,redirectURL:u.redirectUrl}}catch(c){return console.error(c),G("Failed to authorize payment")}return{isSuccess:!0}},async getApplePayPaymentRequest(n){let a=L();if(a==null)return G("Checkout not found");n&&n.expectedItems!=null&&n.expectedItems.length>0&&(a.products&&qr(a.products.map(l=>l.productID)),await zr(e,n.expectedItems));let i=await Be(e,{locale:t});if(ke(i))return i;let c=await le.get(K).getPreOrderDetails({items:i.map(l=>fe(st,{id:l.productID,quantity:l.quantity})),projectId:e,postCode:a.postalCode,couponCode:a.couponCode,countryCode:a.country,selectedDeliveryMethod:a.selectedDeliveryMethod}),d=i.map(l=>({amount:`${_(l.quantity*(l.details?.pricing?.effectivePrice??l.details?.price??0)/100,2)}`,label:l.details?.name+" - "+l.quantity,type:"final"}));if(c.selectedDeliveryMethod!=null){let l=c.methods.find(u=>u.id==c.selectedDeliveryMethod);l!=null&&d.push({amount:`${_(l.amount/100,2)}`,label:l.name,type:"final"})}return c.couponCode!=null&&c.couponValue!=null&&d.push({amount:`-${_(c.couponValue/100,2)}`,label:c.couponCode,type:"final"}),{countryCode:c.country||a.country||"PL",merchantCapabilities:["supports3DS","supportsCredit","supportsDebit"],supportedNetworks:["visa","masterCard"],total:{amount:`${_((c.totalAmount??0)/100,2)}`,label:he("paymentForCart",t,r),type:"final"},shippingMethods:c.methods.map(l=>({amount:`${_(l.amount/100,2)}`,detail:l.description??"",identifier:l.id,label:l.name,dateComponentsRange:{startDateComponents:{days:l.minDays??1,hours:0,months:0,years:0},endDateComponents:{days:l.maxDays??14,hours:0,months:0,years:0}}})),lineItems:d,currencyCode:c.currency||i[0]?.details?.currency||"PLN"}}}};async function ai(e){let t=L();if(t.googlePayConfig?.isAvailable!=!0){let r=await le.get(K).isOneClickPaymentAvailable({projectId:e});r.googlePay==!0&&r.googlePayConfig!=null?t.googlePayConfig={isAvailable:!0,gateway:r.googlePayConfig.gateway,gatewayId:r.googlePayConfig.gatewayMerchantId,merchantName:r.googlePayConfig.merchantName,merchantId:r.googlePayConfig.merchantId}:t.googlePayConfig={isAvailable:!1,gateway:"",gatewayId:"",merchantName:"",merchantId:""}}return Y(t),t.googlePayConfig}function oi(e,t){if(e==t.id){let o=t.variants?.findIndex(n=>n.id===e);if(o!=null&&o!=-1){let n=t.variants[o];return{...t,availableQuantity:n.availableQuantity,isDeliverable:n.isDeliverable,images:n.images??t.images,name:t.name+" "+n.name,baseName:t.name,variantName:n.name,price:n.price,currency:n.currency,pricing:n.pricing}}return t}let r=t.variants?.find(o=>o.id===e);return r==null?t:{...t,id:r.id,name:t.name+" "+r.name,baseName:t.name,variantName:r.name,price:r.price,currency:r.currency,pricing:r.pricing,metadata:t.metadata,availableQuantity:r.availableQuantity,isDeliverable:r.isDeliverable,images:r.images??t.images}}function Ge(){let e=L(),t=0;if(e==null){Fe.setState(r=>({...r,numberOfProductsInCart:t}));return}t=e.products?.reduce((r,o)=>r+o.quantity,0)??0,Fe.setState(r=>({...r,numberOfProductsInCart:t}))}var si=200,ci="item-ids-not-found",at="internal-error",Gr={"no-payment-gateway":"noPaymentGateway","gateway-not-configured":"gatewayNotConfigured","shipping-not-configured":"shippingNotConfigured","mixed-recurring":"mixedRecurring","currency-unsupported":"currencyUnsupported","price-changed":"priceChanged","product-not-found":"unavailableProducts","product-not-available":"unavailableProducts"},di=new Set(["internal","invalid-request"]),li=new Set(["product-not-available","product-not-found"]);function ui(e){return typeof e=="string"&&Object.hasOwn(Gr,e)?Gr[e]:void 0}function mi(e){return/<\/?[a-z!?][^>]*>/i.test(e)}function pi(e){return/^[A-Za-z][A-Za-z0-9]*(?:[-_.:][A-Za-z0-9]+)*$/.test(e)&&!/^[A-Z][a-z]+$/.test(e)||/^\[object \w+\]$|^(?:undefined|null)$/.test(e)}function fi(e){return/Error:/.test(e)||/\n\s+at /.test(e)}function sn(e){let t=e.trim();if(!(t.length===0||t.length>si||/[\r\n]/.test(t)||mi(t)||pi(t)||fi(t)))return t}var gi=3;function Ct(e,t=0){if(typeof e=="object"&&e!=null){if(Array.isArray(e)||t>=gi)return{};let r=e,o=Ct(r.error,t+1);if(o.message==null&&r.message!=null){let n=Ct(r.message,t+1);o={...n,code:o.code??n.code}}return typeof r.code=="string"&&r.code.length>0&&(o.code=r.code),o}if(typeof e!="string")return{};try{let r=JSON.parse(e);return typeof r=="object"&&r!=null?Ct(r,t+1):{}}catch{}return{message:sn(e)}}function yi(e){let t;try{t=JSON.parse(e)}catch{return{code:at,message:sn(e)}}if(typeof t=="string")return{code:at,message:sn(t)};if(typeof t!="object"||t==null)return{code:at};let r=t,{message:o,code:n}=Ct(r.error),a={code:typeof r.code=="string"&&r.code.length>0?r.code:n??at,message:o};return Array.isArray(r.itemIds)&&(a.itemIds=r.itemIds.filter(i=>typeof i=="string")),a}function cn(e,t){let{code:r,message:o,itemIds:n}=yi(t),a=n!=null&&n.length>0;if(a&&(r===at||li.has(r)))return G(ci,"badInput",n);let i={message:o};return a&&(i.itemIds=n),G(r,e>=500?"internal":"badInput",i)}function zl(e,t){let r=ui(e.error);if(r!=null)return t(r);if(e.type==="internal"||typeof e.error=="string"&&di.has(e.error))return t("checkoutFailed");let o=e.data?.message;return typeof o=="string"&&o.length>0?o:t("checkoutFailed")}var Pi;(o=>{async function e(n,a=1,i,c){let d=rt();if(d==null)throw new Error("No project ID found");let u=await on(d).addProduct({productID:n,quantity:a,metadata:i,...c});if(u!=null)return u}o.addProductToCart=e;function t(){Fe.setState({isCartVisible:!0})}o.showCart=t;function r(){Fe.setState({isCartVisible:!1})}o.hideCart=r})(Pi||={});async function $r(e){try{return await e.text()}catch{return""}}async function nn(e){let t=rt();if(t==null)throw new Error("No project ID found");e=an(e),e.locale??=V();let r=await fetch(nt(t,"/buy"),{method:"POST",headers:{...St,...Et(t),"Content-Type":"application/json"},body:JSON.stringify(e)});if(r.status!=200){let n=cn(r.status,await $r(r));return console.warn("cannot create payment URL",r.status,n.error),n}let o=await r.json();return{url:o.url,...o.orderId!=null?{orderId:o.orderId}:{},...o.projectId!=null?{projectId:o.projectId}:{}}}async function Kl(e){let t=rt();if(t==null)throw new Error("No project ID found");let r={...St,...Et(t),"Content-Type":"application/json",...e.apiKey!=null?{Authorization:`Bearer ${e.apiKey}`}:{}},o=e.testMode?`/api/payment/link/auto/${t}/test`:`/api/payment/link/auto/${t}`;delete e.apiKey,delete e.testMode,e.locale??=V();let n=await fetch(K+o,{method:"POST",headers:r,body:JSON.stringify(e)});return n.ok?{status:"ok",redirectURL:(await n.json()).url}:{...cn(n.status,await $r(n)),status:"error"}}function xt(){if(typeof localStorage>"u")return;let e=localStorage.getItem("bitsnap-ref");if(e!=null)return e}function an(e){let t=xt();return t==null||(e.metadata==null&&(e.metadata={}),e.metadata.ref=t),e}export{le as a,ue as b,be as c,ve as d,Ut as e,me as f,On as g,Mt as h,Se as i,Je as j,Qe as k,Ue as l,Me as m,ua as n,Fn as o,Zt as p,Io as q,_ as r,Nr as s,Jt as t,ke as u,ci as v,zl as w,Fe as x,Pi as y,nn as z,Kl as A,xt as B,an as C,Yd as D,Xd as E,el as F,rl as G,Ko as H,rn as I,Tl as J,rt as K,Dl as L,Ll as M,Xo as N,El as O,Ol as P,on as Q};
4
- //# sourceMappingURL=chunk-PNTO3L2C.mjs.map