bitsnap-react 1.20.0 → 1.21.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 (117) hide show
  1. package/dist/BitsnapCart-73ESTTTH.mjs +2 -0
  2. package/dist/BitsnapCart-TWT7LVGJ.js +2 -0
  3. package/dist/BitsnapCart-TWT7LVGJ.js.map +1 -0
  4. package/dist/{CartProvider-G7FQUPXL.mjs → CartProvider-4WXJPQJB.mjs} +2 -2
  5. package/dist/CartProvider-CPF2E7JA.js +2 -0
  6. package/dist/CartProvider-CPF2E7JA.js.map +1 -0
  7. package/dist/PanelModelFiles-EKQRLF46.js.map +1 -1
  8. package/dist/analytics.js +1 -1
  9. package/dist/analytics.js.map +1 -1
  10. package/dist/analytics.mjs +1 -1
  11. package/dist/catalog.js +1 -1
  12. package/dist/catalog.js.map +1 -1
  13. package/dist/catalog.mjs +1 -1
  14. package/dist/chat.d.mts +2 -2
  15. package/dist/chat.d.ts +2 -2
  16. package/dist/chat.js +1 -1
  17. package/dist/chat.js.map +1 -1
  18. package/dist/chat.mjs +1 -1
  19. package/dist/chat.mjs.map +1 -1
  20. package/dist/{chunk-IXQCN7MR.mjs → chunk-27JN2GIQ.mjs} +2 -2
  21. package/dist/{chunk-URQBHNJK.mjs → chunk-6ALA5M44.mjs} +2 -2
  22. package/dist/{chunk-4Y233NII.js → chunk-6DEKVABT.js} +2 -2
  23. package/dist/chunk-6DEKVABT.js.map +1 -0
  24. package/dist/chunk-6Q3VGPSF.js.map +1 -1
  25. package/dist/{chunk-AQYHQY2Y.js → chunk-E5MMKBC4.js} +2 -2
  26. package/dist/chunk-E5MMKBC4.js.map +1 -0
  27. package/dist/chunk-EFN4OW2C.js.map +1 -1
  28. package/dist/{chunk-IRZJIPUF.js → chunk-EK3D44XW.js} +2 -2
  29. package/dist/chunk-EK3D44XW.js.map +1 -0
  30. package/dist/{chunk-BTERIY6N.mjs → chunk-EXC5Z5VM.mjs} +2 -2
  31. package/dist/{chunk-RJPQMDIQ.js → chunk-EZGL6DPG.js} +2 -2
  32. package/dist/chunk-EZGL6DPG.js.map +1 -0
  33. package/dist/{chunk-HP3I6D2R.js → chunk-FORZ5AH4.js} +2 -2
  34. package/dist/chunk-FORZ5AH4.js.map +1 -0
  35. package/dist/{chunk-KO7ZERN5.mjs → chunk-HLULQA3B.mjs} +2 -2
  36. package/dist/{chunk-YPA6MMGJ.js → chunk-I2RHVELR.js} +2 -2
  37. package/dist/chunk-I2RHVELR.js.map +1 -0
  38. package/dist/{chunk-GHBRR665.js → chunk-IKKMSLKC.js} +2 -2
  39. package/dist/chunk-IKKMSLKC.js.map +1 -0
  40. package/dist/{chunk-TW25G7XX.mjs → chunk-J6WKSO33.mjs} +2 -2
  41. package/dist/{chunk-TW25G7XX.mjs.map → chunk-J6WKSO33.mjs.map} +1 -1
  42. package/dist/chunk-JSDGZ4NY.js.map +1 -1
  43. package/dist/{chunk-IXX6SUMB.mjs → chunk-KO7Z3E23.mjs} +2 -2
  44. package/dist/chunk-KOYBZORL.js.map +1 -1
  45. package/dist/chunk-KYSMT6ZK.js +2 -0
  46. package/dist/chunk-KYSMT6ZK.js.map +1 -0
  47. package/dist/{chunk-LHQEM3CU.mjs → chunk-LRUBBPTV.mjs} +2 -2
  48. package/dist/chunk-MDAFPGPA.js.map +1 -1
  49. package/dist/chunk-Q337IQNA.js.map +1 -1
  50. package/dist/{chunk-5M3OUOMU.mjs → chunk-T5JO4SP7.mjs} +2 -2
  51. package/dist/{chunk-C736F727.js → chunk-TM3E3L57.js} +2 -2
  52. package/dist/chunk-TM3E3L57.js.map +1 -0
  53. package/dist/{chunk-LHNTSQYO.mjs → chunk-TMEII7BM.mjs} +2 -2
  54. package/dist/chunk-W3RGQYPD.js.map +1 -1
  55. package/dist/{chunk-A2ZDFN3J.mjs → chunk-WOA6W5RM.mjs} +2 -2
  56. package/dist/{chunk-KZWCVKLU.js → chunk-XMRGA5AN.js} +3 -3
  57. package/dist/chunk-XMRGA5AN.js.map +1 -0
  58. package/dist/chunk-Z3YOJ6NZ.js.map +1 -1
  59. package/dist/consent.js.map +1 -1
  60. package/dist/course.js +1 -1
  61. package/dist/course.js.map +1 -1
  62. package/dist/course.mjs +1 -1
  63. package/dist/embed/analytics.js +1 -1
  64. package/dist/errors.js.map +1 -1
  65. package/dist/index.css +1 -1
  66. package/dist/index.css.map +1 -1
  67. package/dist/index.d.mts +2 -2
  68. package/dist/index.d.ts +2 -2
  69. package/dist/index.js +1 -1
  70. package/dist/index.js.map +1 -1
  71. package/dist/index.mjs +1 -1
  72. package/dist/index.mjs.map +1 -1
  73. package/dist/internal.js.map +1 -1
  74. package/dist/methods-43RQLLWD.mjs +2 -0
  75. package/dist/methods-SZVF3HMF.js +2 -0
  76. package/dist/methods-SZVF3HMF.js.map +1 -0
  77. package/dist/model-files-client-P4PORZJ6.js.map +1 -1
  78. package/dist/models.js.map +1 -1
  79. package/dist/returns.js +1 -1
  80. package/dist/returns.js.map +1 -1
  81. package/dist/returns.mjs +1 -1
  82. package/dist/viewer3d.js.map +1 -1
  83. package/dist/viewer3d.mjs +1 -1
  84. package/dist/{widgets-Bsojw94g.d.ts → widgets-BL6pCMdc.d.ts} +34 -2
  85. package/dist/{widgets-u7xMJbsY.d.mts → widgets-DmHlIbp8.d.mts} +34 -2
  86. package/package.json +1 -1
  87. package/dist/BitsnapCart-V4S4EXYV.js +0 -2
  88. package/dist/BitsnapCart-V4S4EXYV.js.map +0 -1
  89. package/dist/BitsnapCart-Z6JFYNH2.mjs +0 -2
  90. package/dist/CartProvider-5NP4WACK.js +0 -2
  91. package/dist/CartProvider-5NP4WACK.js.map +0 -1
  92. package/dist/chunk-4Y233NII.js.map +0 -1
  93. package/dist/chunk-AQYHQY2Y.js.map +0 -1
  94. package/dist/chunk-C736F727.js.map +0 -1
  95. package/dist/chunk-GHBRR665.js.map +0 -1
  96. package/dist/chunk-HP3I6D2R.js.map +0 -1
  97. package/dist/chunk-IRZJIPUF.js.map +0 -1
  98. package/dist/chunk-KDL35KEI.js +0 -2
  99. package/dist/chunk-KDL35KEI.js.map +0 -1
  100. package/dist/chunk-KZWCVKLU.js.map +0 -1
  101. package/dist/chunk-RJPQMDIQ.js.map +0 -1
  102. package/dist/chunk-YPA6MMGJ.js.map +0 -1
  103. package/dist/methods-33CWGKNA.mjs +0 -2
  104. package/dist/methods-4GB652MQ.js +0 -2
  105. package/dist/methods-4GB652MQ.js.map +0 -1
  106. /package/dist/{BitsnapCart-Z6JFYNH2.mjs.map → BitsnapCart-73ESTTTH.mjs.map} +0 -0
  107. /package/dist/{CartProvider-G7FQUPXL.mjs.map → CartProvider-4WXJPQJB.mjs.map} +0 -0
  108. /package/dist/{chunk-IXQCN7MR.mjs.map → chunk-27JN2GIQ.mjs.map} +0 -0
  109. /package/dist/{chunk-URQBHNJK.mjs.map → chunk-6ALA5M44.mjs.map} +0 -0
  110. /package/dist/{chunk-BTERIY6N.mjs.map → chunk-EXC5Z5VM.mjs.map} +0 -0
  111. /package/dist/{chunk-KO7ZERN5.mjs.map → chunk-HLULQA3B.mjs.map} +0 -0
  112. /package/dist/{chunk-IXX6SUMB.mjs.map → chunk-KO7Z3E23.mjs.map} +0 -0
  113. /package/dist/{chunk-LHQEM3CU.mjs.map → chunk-LRUBBPTV.mjs.map} +0 -0
  114. /package/dist/{chunk-5M3OUOMU.mjs.map → chunk-T5JO4SP7.mjs.map} +0 -0
  115. /package/dist/{chunk-LHNTSQYO.mjs.map → chunk-TMEII7BM.mjs.map} +0 -0
  116. /package/dist/{chunk-A2ZDFN3J.mjs.map → chunk-WOA6W5RM.mjs.map} +0 -0
  117. /package/dist/{methods-33CWGKNA.mjs.map → methods-43RQLLWD.mjs.map} +0 -0
package/dist/chat.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } 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 _chunkZ3YOJ6NZjs = require('./chunk-Z3YOJ6NZ.js');var _chunkC736F727js = require('./chunk-C736F727.js');var _chunkMDAFPGPAjs = require('./chunk-MDAFPGPA.js');require('./chunk-EFN4OW2C.js');var _chunk4Y233NIIjs = require('./chunk-4Y233NII.js');require('./chunk-IRZJIPUF.js');require('./chunk-W3RGQYPD.js');var _chunkQ337IQNAjs = require('./chunk-Q337IQNA.js');require('./chunk-JSDGZ4NY.js');var _react = require('react');async function te(e){await _chunkC736F727js.e.call(void 0, {id:e.productId,name:_nullishCoalesce(e.name, () => ("")),price:_nullishCoalesce(e.priceCents, () => (0)),currency:"",amount:e.amount},{projectID:e.projectID,host:e.host,showCart:!0})}var ke="https://chat.bitsnap.pl",xe= exports.DEFAULT_CHAT_REALTIME_URL ="wss://bitsnap-nats-queue-production.up.railway.app";var W=class extends Error{constructor(t,a,n={}){super(`chat: ${t} (${a})`),this.name="ChatError",this.code=t,this.status=a,this.data=n;let r=Number(n.retry_after);Number.isFinite(r)&&r>0&&(this.retryAfter=r)}};function ne(e){let t=(e.baseUrl||ke).replace(/\/+$/,""),a=_nullishCoalesce(e.fetch, () => (((...u)=>fetch(...u))));async function n(u,l,p){let h;try{h=await a(t+l,{method:u,headers:{Authorization:`Bearer ${e.token}`,"X-Bitsnap-Project":e.projectId,...p===void 0?{}:{"Content-Type":"application/json"}},body:p===void 0?void 0:JSON.stringify(p)})}catch (e2){throw new W("network",0)}let d=null;try{let b=await h.text();d=b?JSON.parse(b):null}catch (e3){d=null}if(!h.ok){let b=F(d)?d:{},w=typeof b.error=="string"?b.error:"internal_error";throw new W(w,h.status,b)}return{status:h.status,json:d}}let r=encodeURIComponent,c;return{baseUrl:t,projectId:e.projectId,async me(){let{json:u}=await n("GET","/v1/me");return rt(u)},async openThread(u){let{json:l}=await n("POST","/v1/threads",{product_id:u});return Be(l)},async messages(u,l={}){let p=new URLSearchParams;l.before&&p.set("before",l.before),l.limit&&p.set("limit",String(l.limit));let h=p.toString(),d=h?`?${h}`:"",{json:b}=await n("GET",`/v1/threads/${r(u)}/messages${d}`),w=F(b)?b:{};return{messages:J(w.messages).map(le),hasMore:w.has_more===!0}},async send(u,l){let{json:p}=await n("POST",`/v1/threads/${r(u)}/messages`,{body:l.body,...l.clientId?{client_id:l.clientId}:{}}),h=F(p)?p:{};return{message:le(h.message),thread:Ae(h.thread)}},async deleteMessage(u,l){await n("DELETE",`/v1/threads/${r(u)}/messages/${r(l)}`)},async mute(u,l){await n("POST",`/v1/threads/${r(u)}/mute`,{muted:l})},async report(u){await n("POST","/v1/reports",{thread_id:u.threadId,...u.messageId?{message_id:u.messageId}:{},reason:u.reason,...u.note?{note:u.note}:{}})},async markRead(u,l){await n("POST",`/v1/threads/${r(u)}/receipts`,{state:"read",message_id:l})},async realtimeToken(u={}){if(!u.fresh&&c&&Date.parse(c.expiresAt)-Date.now()>9e4)return c;let{json:l}=await n("POST","/v1/realtime/token"),p=F(l)?l:{};return c={jwt:E(p.jwt),expiresAt:E(p.expires_at),servers:J(p.servers).filter(h=>typeof h=="string"),subjects:J(p.subjects).filter(h=>typeof h=="string"),truncated:p.truncated===!0}}}}function Ce(e){if(!F(e)||typeof e.type!="string")return null;let t=E(e.id);switch(e.type){case"message.created":return{type:"message.created",message:le(e)};case"message.rejected":return{type:"message.rejected",id:t,reason:E(e.reason)};case"message.deleted":case"message.pinned":case"message.unpinned":return{type:e.type,id:t};default:return null}}function F(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}function J(e){return Array.isArray(e)?e:[]}function E(e){return typeof e=="string"?e:e==null?"":String(e)}function q(e){let t=Number(e);return Number.isFinite(t)?t:0}function Q(e){return typeof e=="string"&&e!==""?e:void 0}function we(e){return typeof e=="string"&&e!==""?e:null}function le(e){let t=F(e)?e:{};return{id:E(t.id),threadId:E(t.thread_id),authorEmail:E(t.author_email),body:E(t.body),attachmentKey:Q(t.attachment_key),attachmentKind:Q(t.attachment_kind),createdAt:E(t.created_at),pinned:t.pinned===!0,deleted:t.deleted===!0,system:t.system===!0,...t.status==="pending"?{status:"pending"}:{}}}function nt(e){let t=F(e)?e:{};return{orderId:E(t.order_id),productId:Q(t.product_id),replies:q(t.replies),used:q(t.used),left:q(t.left),expiresAt:we(t.expires_at),expired:t.expired===!0}}function Ae(e){let t=F(e)?e:{};return{id:E(t.id),kind:t.kind==="channel"?"channel":"pack",repliesTotal:q(t.replies_total),repliesUsed:q(t.replies_used),repliesLeft:q(t.replies_left),expiresAt:we(t.expires_at),composerLocked:t.composer_locked===!0,responseHours:q(t.response_hours)}}function Be(e){let t=F(e)?e:{};return{...Ae(t),channelId:Q(t.channel_id),title:E(t.title),lastMessage:F(t.last_message)?le(t.last_message):void 0,unread:q(t.unread),productId:Q(t.product_id),packs:J(t.packs).map(nt),muted:t.muted===!0}}function at(e){let t=F(e)?e:{};return{id:E(t.id),name:E(t.name),topic:E(t.topic),welcome:E(t.welcome),whoCanPost:t.who_can_post==="members"?"members":"creator",productId:E(t.product_id),role:E(t.role),memberCount:q(t.member_count),createdAt:E(t.created_at),blockLinks:t.block_links===!0,blockMedia:t.block_media===!0,cooldownSeconds:q(t.cooldown_seconds)}}function rt(e){let t=F(e)?e:{},a=F(t.entitlements)?t.entitlements:{};return{email:E(t.email),threads:J(t.threads).map(Be),entitlements:{packs:J(a.packs).map(n=>{let r=F(n)?n:{};return{productId:E(r.product_id),name:E(r.name),repliesLeftHint:q(r.replies_left_hint),expiresAt:we(r.expires_at)}}),channels:J(a.channels).map(n=>{let r=F(n)?n:{};return{productId:E(r.product_id),channelId:Q(r.channel_id)}})},channels:J(t.channels).map(at)}}var _lucidereact = require('lucide-react');var Oe={pl:{inboxHeading:"Wiadomo\u015Bci",inboxIntro:"Rozmowy z tw\xF3rcami i kana\u0142y, do kt\xF3rych nale\u017Cysz.",inboxEmpty:"Nie masz jeszcze rozm\xF3w. Po zakupie pakietu konsultacji lub dost\u0119pu do spo\u0142eczno\u015Bci rozmowa pojawi si\u0119 tutaj.",inboxError:"Nie uda\u0142o si\u0119 wczyta\u0107 wiadomo\u015Bci.",loading:"Wczytywanie\u2026",retry:"Spr\xF3buj ponownie",back:"Wr\xF3\u0107",selectConversation:"Wybierz rozmow\u0119 z listy.",kindChat:"Czat",kindChannel:"Kana\u0142",startSection:"Do rozpocz\u0119cia",startChat:"Rozpocznij rozmow\u0119",openChannel:"Otw\xF3rz kana\u0142",channelNotReady:"Tw\xF3rca jeszcze nie otworzy\u0142 tego kana\u0142u.",chatFallbackTitle:"Czat z tw\xF3rc\u0105",channelFallbackTitle:"Kana\u0142",repliesLeftOne:"Zosta\u0142a {count} odpowied\u017A",repliesLeftFew:"Zosta\u0142y {count} odpowiedzi",repliesLeftMany:"Zosta\u0142o {count} odpowiedzi",noRepliesLeft:"Brak odpowiedzi w pakiecie",expiresOn:"Wa\u017Cny do {date}",expiredOn:"Wygas\u0142 {date}",responseHours:"Odpowied\u017A w ci\u0105gu {hours} h",unread:"Nieprzeczytane: {count}",members:"Cz\u0142onkowie: {count}",mutedBadge:"Wyciszony",noMessagesYet:"Brak wiadomo\u015Bci",emptyThread:"Napisz pierwsz\u0105 wiadomo\u015B\u0107. Tw\xF3rca odpowie w ramach Twojego pakietu.",emptyChannel:"W kanale nie ma jeszcze wiadomo\u015Bci.",privacyNote:"Wiadomo\u015Bci czyta druga strona rozmowy. Bitsnap przechowuje je przez 90 dni.",loadOlder:"Wcze\u015Bniejsze wiadomo\u015Bci",you:"Ty",creator:"Tw\xF3rca",systemLabel:"Wiadomo\u015B\u0107 automatyczna",pinned:"Przypi\u0119ta",deletedPlaceholder:"Wiadomo\u015B\u0107 zosta\u0142a usuni\u0119ta",attachment:"Za\u0142\u0105cznik",composerLabel:"Wiadomo\u015B\u0107",composerPlaceholder:"Napisz wiadomo\u015B\u0107\u2026",send:"Wy\u015Blij",composerExpired:"Pakiet wygas\u0142, wi\u0119c nie mo\u017Cesz ju\u017C pisa\u0107 w tej rozmowie.",composerCreatorOnly:"W tym kanale pisze tylko tw\xF3rca.",composerMuted:"Masz wyciszone pisanie w tym kanale.",composerReadOnly:"Ten dost\u0119p pozwala tylko czyta\u0107.",lockRepliesTitle:"Odpowiedzi w pakiecie si\u0119 sko\u0144czy\u0142y",lockRepliesBody:"Mo\u017Cesz dalej pisa\u0107, ale tw\xF3rca odpowie dopiero po zakupie kolejnego pakietu.",lockExpiredTitle:"Pakiet wygas\u0142",lockExpiredBody:"Rozmowa zostaje do wgl\u0105du. Kup nowy pakiet, aby j\u0105 kontynuowa\u0107.",lockThreadTitle:"Nie masz pakietu odpowiedzi",lockThreadBody:"Kup pakiet, aby napisa\u0107 do tw\xF3rcy.",lockChannelTitle:"Kana\u0142 dla cz\u0142onk\xF3w",lockChannelBody:"Kup dost\u0119p, aby czyta\u0107 i pisa\u0107 w tym kanale.",buyPack:"Kup pakiet",buyAccess:"Kup dost\u0119p",buying:"Dodawanie do koszyka\u2026",buyError:"Nie uda\u0142o si\u0119 doda\u0107 do koszyka. Spr\xF3buj ponownie.",pending:"Wysy\u0142anie\u2026",notConfirmed:"Czekamy na potwierdzenie wys\u0142ania",rejectedLink:"Linki s\u0105 w tym kanale zablokowane. Usu\u0144 link i wy\u015Blij ponownie.",rejectedBannedWord:"Wiadomo\u015B\u0107 zawiera s\u0142owo zablokowane w tym kanale. Popraw j\u0105 i wy\u015Blij ponownie.",rejectedMedia:"Za\u0142\u0105czniki s\u0105 w tym kanale zablokowane.",rejectedCooldown:"Piszesz za szybko. Spr\xF3buj ponownie za {seconds} s.",rejectedBlocked:"Tw\xF3rca zablokowa\u0142 Ci mo\u017Cliwo\u015B\u0107 pisania w tym sklepie.",rejectedMuted:"Masz wyciszone pisanie w tym kanale.",rejectedReadOnly:"Ten dost\u0119p pozwala tylko czyta\u0107.",rejectedPackEmpty:"Pakiet nie ma ju\u017C odpowiedzi.",rejectedForbidden:"Nie mo\u017Cesz pisa\u0107 w tej rozmowie.",rejectedGeneric:"Nie uda\u0142o si\u0119 wys\u0142a\u0107 wiadomo\u015Bci.",failedNetwork:"Brak po\u0142\u0105czenia. Wiadomo\u015B\u0107 nie zosta\u0142a wys\u0142ana.",editMessage:"Popraw",retrySend:"Wy\u015Blij ponownie",dismiss:"Odrzu\u0107",messageActions:"Opcje wiadomo\u015Bci",deleteMessage:"Usu\u0144 wiadomo\u015B\u0107",deleteConfirm:"Na pewno usun\u0105\u0107?",reportMessage:"Zg\u0142o\u015B wiadomo\u015B\u0107",conversationActions:"Opcje rozmowy",muteThread:"Wycisz powiadomienia",unmuteThread:"W\u0142\u0105cz powiadomienia",muteError:"Nie uda\u0142o si\u0119 zmieni\u0107 powiadomie\u0144.",reportConversation:"Zg\u0142o\u015B rozmow\u0119",reportTitle:"Zg\u0142o\u015B wiadomo\u015B\u0107",reportConversationTitle:"Zg\u0142o\u015B rozmow\u0119",reportReason:"Pow\xF3d zg\u0142oszenia",reasonSpam:"Spam",reasonAbuse:"N\u0119kanie lub obra\u017Aliwe tre\u015Bci",reasonIllegal:"Tre\u015Bci niezgodne z prawem",reasonOther:"Inny pow\xF3d",reportNote:"Opis (opcjonalnie)",reportSend:"Wy\u015Blij zg\u0142oszenie",reportCancel:"Anuluj",reportSent:"Dzi\u0119kujemy. Zg\u0142oszenie trafi\u0142o do moderacji.",reportError:"Nie uda\u0142o si\u0119 wys\u0142a\u0107 zg\u0142oszenia. Spr\xF3buj ponownie.",liveLabel:"Nowe wiadomo\u015Bci pojawiaj\u0105 si\u0119 na bie\u017C\u0105co",pollingLabel:"Nowe wiadomo\u015Bci od\u015Bwie\u017Caj\u0105 si\u0119 co kilka sekund",errorNoToken:"Zaloguj si\u0119 w panelu klienta, aby zobaczy\u0107 rozmow\u0119.",errorUnauthorized:"Sesja wygas\u0142a. Zaloguj si\u0119 ponownie.",errorPlan:"Czat nie jest dost\u0119pny w tym sklepie.",errorNotFound:"Nie znaleziono tej rozmowy.",errorUnavailable:"Czat jest chwilowo niedost\u0119pny. Spr\xF3buj za chwil\u0119.",errorGeneric:"Nie uda\u0142o si\u0119 wczyta\u0107 rozmowy."},en:{inboxHeading:"Messages",inboxIntro:"Your conversations with creators and the channels you belong to.",inboxEmpty:"No conversations yet. When you buy a consultation pack or community access, it shows up here.",inboxError:"Your messages could not be loaded.",loading:"Loading\u2026",retry:"Try again",back:"Back",selectConversation:"Pick a conversation from the list.",kindChat:"Chat",kindChannel:"Channel",startSection:"Ready to start",startChat:"Start the conversation",openChannel:"Open the channel",channelNotReady:"The creator has not opened this channel yet.",chatFallbackTitle:"Chat with the creator",channelFallbackTitle:"Channel",repliesLeftOne:"{count} reply left",repliesLeftFew:"{count} replies left",repliesLeftMany:"{count} replies left",noRepliesLeft:"No replies left in your pack",expiresOn:"Valid until {date}",expiredOn:"Expired on {date}",responseHours:"Replies within {hours} h",unread:"Unread: {count}",members:"Members: {count}",mutedBadge:"Muted",noMessagesYet:"No messages yet",emptyThread:"Write the first message. The creator replies within your pack.",emptyChannel:"There are no messages in this channel yet.",privacyNote:"The other side of the conversation reads your messages. Bitsnap keeps them for 90 days.",loadOlder:"Earlier messages",you:"You",creator:"Creator",systemLabel:"Automatic message",pinned:"Pinned",deletedPlaceholder:"This message was deleted",attachment:"Attachment",composerLabel:"Message",composerPlaceholder:"Write a message\u2026",send:"Send",composerExpired:"Your pack has expired, so you can no longer write here.",composerCreatorOnly:"Only the creator posts in this channel.",composerMuted:"You are muted in this channel.",composerReadOnly:"This access is read only.",lockRepliesTitle:"Your pack has no replies left",lockRepliesBody:"You can keep writing, but the creator can reply only after you buy another pack.",lockExpiredTitle:"Your pack has expired",lockExpiredBody:"You can still read the conversation. Buy a new pack to continue it.",lockThreadTitle:"You have no reply pack",lockThreadBody:"Buy a pack to write to the creator.",lockChannelTitle:"Members-only channel",lockChannelBody:"Buy access to read and post in this channel.",buyPack:"Buy a pack",buyAccess:"Buy access",buying:"Adding to cart\u2026",buyError:"Could not add it to the cart. Try again.",pending:"Sending\u2026",notConfirmed:"Waiting for the send to be confirmed",rejectedLink:"Links are blocked in this channel. Remove the link and send again.",rejectedBannedWord:"Your message contains a word blocked in this channel. Edit it and send again.",rejectedMedia:"Attachments are blocked in this channel.",rejectedCooldown:"You are posting too fast. Try again in {seconds} s.",rejectedBlocked:"The creator has blocked you from posting in this shop.",rejectedMuted:"You are muted in this channel.",rejectedReadOnly:"This access is read only.",rejectedPackEmpty:"The pack has no replies left.",rejectedForbidden:"You cannot post in this conversation.",rejectedGeneric:"Your message could not be sent.",failedNetwork:"No connection. Your message was not sent.",editMessage:"Edit",retrySend:"Send again",dismiss:"Discard",messageActions:"Message options",deleteMessage:"Delete message",deleteConfirm:"Delete for sure?",reportMessage:"Report message",conversationActions:"Conversation options",muteThread:"Mute notifications",unmuteThread:"Unmute notifications",muteError:"Notifications could not be changed.",reportConversation:"Report conversation",reportTitle:"Report message",reportConversationTitle:"Report conversation",reportReason:"Reason",reasonSpam:"Spam",reasonAbuse:"Harassment or abusive content",reasonIllegal:"Illegal content",reasonOther:"Something else",reportNote:"Details (optional)",reportSend:"Send report",reportCancel:"Cancel",reportSent:"Thank you. Your report went to moderation.",reportError:"Your report could not be sent. Try again.",liveLabel:"New messages appear live",pollingLabel:"New messages refresh every few seconds",errorNoToken:"Log in to the customer panel to see this conversation.",errorUnauthorized:"Your session has expired. Log in again.",errorPlan:"Chat is not available in this shop.",errorNotFound:"This conversation was not found.",errorUnavailable:"Chat is unavailable right now. Try again in a moment.",errorGeneric:"The conversation could not be loaded."}};function ee(e,t=_chunkQ337IQNAjs.f.call(void 0, )){return _chunkQ337IQNAjs.b.call(void 0, Oe,t,e)}function H(e,t){return e.replace(/\{(\w+)\}/g,(a,n)=>n in t?String(t[n]):a)}function ae(e,t,a=_chunkQ337IQNAjs.f.call(void 0, )){if(t<=0)return e.noRepliesLeft;let n="other";try{n=new Intl.PluralRules(a).select(t)}catch (e4){}let r=n==="one"?e.repliesLeftOne:n==="few"?e.repliesLeftFew:e.repliesLeftMany;return H(r,{count:t})}function re(e,t=_chunkQ337IQNAjs.f.call(void 0, )){let a=new Date(e);return Number.isNaN(a.getTime())?"":new Intl.DateTimeFormat(t,{day:"numeric",month:"numeric",year:"numeric"}).format(a)}function de(e,t=_chunkQ337IQNAjs.f.call(void 0, ),a=new Date){let n=new Date(e);if(Number.isNaN(n.getTime()))return"";let r=n.toDateString()===a.toDateString();return new Intl.DateTimeFormat(t,r?{hour:"2-digit",minute:"2-digit"}:{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}).format(n)}function De(e,t,a){switch(t){case"moderation_link":return e.rejectedLink;case"moderation_banned_word":return e.rejectedBannedWord;case"moderation_media":return e.rejectedMedia;case"cooldown":return H(e.rejectedCooldown,{seconds:_nullishCoalesce(a, () => (30))});case"blocked":return e.rejectedBlocked;case"muted":return e.rejectedMuted;case"read_only":return e.rejectedReadOnly;case"pack_empty":case"replies_exhausted":return e.rejectedPackEmpty;case"forbidden":case"locked":return e.rejectedForbidden;case"network":case"unavailable":return e.failedNetwork;default:return e.rejectedGeneric}}var _jsxruntime = require('react/jsx-runtime');var Te="focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-500",G=_chunk4Y233NIIjs.g.call(void 0, "inline-flex min-h-11 items-center gap-2 rounded-md px-3 text-sm text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800",Te),ue=_chunk4Y233NIIjs.g.call(void 0, "inline-flex min-h-11 items-center justify-center gap-2 rounded-md bg-neutral-900 px-4 text-sm font-medium text-white hover:bg-neutral-800 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white dark:text-neutral-900 dark:hover:bg-neutral-200",Te);function Ne({host:e,conversation:t,texts:a,locale:n,kind:r,title:c,onBack:u,onBuy:l,className:p}){let[h,d]=_react.useState.call(void 0, !1),[b,w]=_react.useState.call(void 0, null),[R,f]=_react.useState.call(void 0, ),[v,I]=_react.useState.call(void 0, ""),[T,k]=_react.useState.call(void 0, !1);_react.useEffect.call(void 0, ()=>{if(!T)return;let j=setTimeout(()=>k(!1),6e3);return()=>clearTimeout(j)},[T]);let L=c||_optionalChain([t, 'access', _2 => _2.channel, 'optionalAccess', _3 => _3.name])||(r==="channel"?a.channelFallbackTitle:a.chatFallbackTitle),B=mt(t,a,n);return _jsxruntime.jsxs.call(void 0, "section",{"data-bitsnap-chat":r,"aria-label":L,className:_chunk4Y233NIIjs.g.call(void 0, "flex h-full min-h-[28rem] w-full min-w-0 flex-col overflow-hidden rounded-xl border border-neutral-200 bg-white text-neutral-900 dark:border-neutral-800 dark:bg-neutral-900 dark:text-neutral-50",p),children:[_jsxruntime.jsxs.call(void 0, "header",{className:"flex items-start gap-2 border-b border-neutral-200 px-3 py-2 dark:border-neutral-800",children:[u&&_jsxruntime.jsx.call(void 0, "button",{type:"button",onClick:u,"aria-label":a.back,className:_chunk4Y233NIIjs.g.call(void 0, G,"w-11 justify-center px-0"),children:_jsxruntime.jsx.call(void 0, _lucidereact.ArrowLeft,{className:"size-5","aria-hidden":"true"})}),_jsxruntime.jsxs.call(void 0, "div",{className:"min-w-0 flex-1 py-1.5",children:[_jsxruntime.jsxs.call(void 0, "h2",{className:"flex items-center gap-2 text-base font-semibold",children:[_jsxruntime.jsx.call(void 0, "span",{className:"truncate",children:L}),_jsxruntime.jsx.call(void 0, pt,{live:t.live,texts:a})]}),B.length>0&&_jsxruntime.jsx.call(void 0, "p",{className:"mt-0.5 flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-neutral-600 dark:text-neutral-400",children:B.map(j=>_jsxruntime.jsx.call(void 0, "span",{children:j},j))})]}),t.status==="ready"&&_jsxruntime.jsx.call(void 0, "button",{type:"button","aria-label":a.conversationActions,"aria-expanded":h,onClick:()=>d(j=>!j),className:_chunk4Y233NIIjs.g.call(void 0, G,"w-11 justify-center px-0"),children:_jsxruntime.jsx.call(void 0, _lucidereact.MoreHorizontal,{className:"size-5","aria-hidden":"true"})})]}),h&&t.status==="ready"&&_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap gap-1 border-b border-neutral-200 bg-neutral-50 px-3 py-1 dark:border-neutral-800 dark:bg-neutral-950",children:[r==="thread"&&t.thread&&_jsxruntime.jsx.call(void 0, "button",{type:"button",className:G,onClick:async()=>{d(!1);try{await t.setMuted(!t.thread.muted),f(void 0)}catch (e5){f(a.muteError)}},children:t.thread.muted?a.unmuteThread:a.muteThread}),_jsxruntime.jsx.call(void 0, "button",{type:"button",className:G,onClick:()=>{d(!1),w({})},children:a.reportConversation})]}),t.status==="loading"&&_jsxruntime.jsx.call(void 0, ht,{texts:a}),t.status==="error"&&_jsxruntime.jsx.call(void 0, ft,{conversation:t,texts:a}),t.status==="locked"&&t.lock&&_jsxruntime.jsx.call(void 0, "div",{className:"flex flex-1 flex-col justify-center overflow-y-auto p-4",children:_jsxruntime.jsx.call(void 0, Ue,{host:e,lock:t.lock,kind:r,texts:a,locale:n,onBuy:l,prominent:!0})}),t.status==="ready"&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, bt,{conversation:t,texts:a,locale:n,kind:r,onReport:j=>w({messageId:j}),onEdit:j=>{I(j.body),t.discard(j.id)}}),R&&_jsxruntime.jsx.call(void 0, "p",{role:"status",className:"px-4 pb-2 text-xs text-red-700 dark:text-red-400",children:R}),t.lock&&_jsxruntime.jsx.call(void 0, "div",{className:"border-t border-neutral-200 p-3 dark:border-neutral-800",children:_jsxruntime.jsx.call(void 0, Ue,{host:e,lock:t.lock,kind:r,texts:a,locale:n,onBuy:l})}),b?_jsxruntime.jsx.call(void 0, vt,{texts:a,messageId:b.messageId,onCancel:()=>w(null),onSubmit:async(j,U)=>{await t.report({messageId:b.messageId,reason:j,note:U}),w(null),f(void 0),k(!0)}}):_jsxruntime.jsx.call(void 0, Ct,{conversation:t,texts:a,kind:r,draft:v,setDraft:I})]}),T&&_jsxruntime.jsx.call(void 0, "p",{role:"status",className:"border-t border-neutral-200 px-4 py-2 text-xs text-neutral-700 dark:border-neutral-800 dark:text-neutral-300",children:a.reportSent})]})}function mt(e,t,a){let n=[];if(e.thread&&e.thread.kind==="pack"){if(n.push(ae(t,e.thread.repliesLeft,a)),e.thread.expiresAt){let r=re(e.thread.expiresAt,a);n.push(H(e.thread.composerLocked?t.expiredOn:t.expiresOn,{date:r}))}e.thread.responseHours>0&&n.push(H(t.responseHours,{hours:e.thread.responseHours})),e.thread.muted&&n.push(t.mutedBadge)}return e.channel&&(e.channel.topic&&n.push(e.channel.topic),e.channel.memberCount>0&&n.push(H(t.members,{count:e.channel.memberCount}))),n}function pt({live:e,texts:t}){if(e!=="live"&&e!=="polling")return null;let a=e==="live"?t.liveLabel:t.pollingLabel;return _jsxruntime.jsx.call(void 0, "span",{title:a,"data-live":e,className:_chunk4Y233NIIjs.g.call(void 0, "inline-block size-2 shrink-0 rounded-full",e==="live"?"bg-emerald-500":"bg-neutral-400 dark:bg-neutral-500"),children:_jsxruntime.jsx.call(void 0, "span",{className:"sr-only",children:a})})}function ht({texts:e}){return _jsxruntime.jsx.call(void 0, "div",{role:"status","aria-busy":"true","aria-label":e.loading,className:"flex flex-1 flex-col gap-3 p-4",children:[60,40,70].map((t,a)=>_jsxruntime.jsx.call(void 0, "div",{"aria-hidden":"true",style:{width:`${t}%`},className:_chunk4Y233NIIjs.g.call(void 0, "h-10 rounded-2xl bg-neutral-100 motion-safe:animate-pulse dark:bg-neutral-800",a===1&&"self-end")},a))})}function gt(e,t){switch(e){case"no_token":return t.errorNoToken;case"unauthorized":return t.errorUnauthorized;case"plan_required":return t.errorPlan;case"not_found":return t.errorNotFound;case"unavailable":case"network":return t.errorUnavailable;default:return t.errorGeneric}}function ft({conversation:e,texts:t}){let a=_nullishCoalesce(_optionalChain([e, 'access', _4 => _4.error, 'optionalAccess', _5 => _5.code]), () => ("")),n=a!=="no_token"&&a!=="plan_required"&&a!=="unauthorized";return _jsxruntime.jsxs.call(void 0, "div",{role:"alert",className:"flex flex-1 flex-col items-start justify-center gap-3 p-4",children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-700 dark:text-neutral-300",children:gt(a,t)}),n&&_jsxruntime.jsx.call(void 0, "button",{type:"button",className:ue,onClick:e.reload,children:t.retry})]})}function Ue({host:e,lock:t,kind:a,texts:n,locale:r,onBuy:c,prominent:u}){let[l,p]=_react.useState.call(void 0, !1),[h,d]=_react.useState.call(void 0, ""),[b,w]=_react.useState.call(void 0, String((_nullishCoalesce(t.priceCents, () => (0)))/100)),R=b.trim().replace(",","."),f=/^\d+(\.\d{0,2})?$/.test(R)?Math.round(Number(R)*100):NaN,v=t.priceType==="pay_what_you_want",I=_nullishCoalesce(t.minimumCents, () => (0)),T=_nullishCoalesce(t.maximumCents, () => (Number.MAX_SAFE_INTEGER)),k=Number.isInteger(f)&&f>=I&&f<=T&&(f>0||t.freeClaimLimit!=null),L=t.freeClaimLimit!=null&&(t.priceType==="free"||v&&I===0&&f===0),[B,j]=_react.useState.call(void 0, ""),[U,m]=_react.useState.call(void 0, ""),[M,$]=_react.useState.call(void 0, !1),[s,o]=_react.useState.call(void 0, null),[g,y]=_react.useState.call(void 0, 0),[P,S]=_react.useState.call(void 0, 0),K=_react.useRef.call(void 0, null);_react.useEffect.call(void 0, ()=>{M&&_optionalChain([K, 'access', _6 => _6.current, 'optionalAccess', _7 => _7.focus, 'call', _8 => _8()])},[M]),_react.useEffect.call(void 0, ()=>{if(P<=0)return;let Y=window.setTimeout(()=>S(P-1),1e3);return()=>window.clearTimeout(Y)},[P]);let _=()=>{$(!1),m(""),o(null),y(Y=>Y+1),d("")},z=r.toLowerCase().startsWith("en"),[O,ye]=t.reason==="replies"?[n.lockRepliesTitle,n.lockRepliesBody]:t.reason==="expired"?[n.lockExpiredTitle,n.lockExpiredBody]:a==="channel"?[n.lockChannelTitle,n.lockChannelBody]:[n.lockThreadTitle,n.lockThreadBody],Qe=a==="channel"?n.buyAccess:n.buyPack,et=c!=null&&t.productId!=null;return _jsxruntime.jsxs.call(void 0, "div",{"data-testid":"chat-lock","data-lock":t.reason,className:_chunk4Y233NIIjs.g.call(void 0, "flex gap-3 rounded-xl bg-neutral-100 p-3 dark:bg-neutral-800",u?"flex-col items-start p-5":"flex-col sm:flex-row sm:items-center"),children:[_jsxruntime.jsx.call(void 0, _lucidereact.Lock,{className:_chunk4Y233NIIjs.g.call(void 0, "shrink-0 text-neutral-500 dark:text-neutral-400",u?"size-6":"hidden size-5 sm:block"),"aria-hidden":"true"}),_jsxruntime.jsxs.call(void 0, "div",{className:"min-w-0 flex-1",children:[_jsxruntime.jsx.call(void 0, "p",{className:_chunk4Y233NIIjs.g.call(void 0, "font-semibold",u?"text-lg":"text-sm"),children:O}),_jsxruntime.jsx.call(void 0, "p",{className:"mt-0.5 text-sm text-neutral-600 dark:text-neutral-300",children:ye}),L&&_jsxruntime.jsxs.call(void 0, "div",{className:"mt-3 grid max-w-sm gap-2",children:[_jsxruntime.jsxs.call(void 0, "label",{className:"grid gap-1 text-sm",children:[_jsxruntime.jsx.call(void 0, "span",{children:z?"Email":"E-mail"}),_jsxruntime.jsx.call(void 0, "input",{type:"email",autoComplete:"email",value:B,onChange:Y=>{j(Y.currentTarget.value),_()},disabled:l,className:"h-11 rounded-md border border-neutral-300 bg-white px-3 text-neutral-900 dark:border-neutral-700 dark:bg-neutral-950 dark:text-neutral-50"})]}),M?_jsxruntime.jsxs.call(void 0, "label",{className:"grid gap-1 text-sm",children:[_jsxruntime.jsx.call(void 0, "span",{children:z?"Email code":"Kod z\xA0e-maila"}),_jsxruntime.jsx.call(void 0, "input",{ref:K,inputMode:"numeric",autoComplete:"one-time-code",value:U,onChange:Y=>m(Y.currentTarget.value),className:"h-11 rounded-md border border-neutral-300 bg-white px-3 text-neutral-900 dark:border-neutral-700 dark:bg-neutral-950 dark:text-neutral-50"})]}):B.includes("@")?_jsxruntime.jsx.call(void 0, _chunkZ3YOJ6NZjs.a,{host:e,action:"free_chat_claim",locale:r,onToken:o,onFailure:()=>o(null)},g):null,M&&_jsxruntime.jsxs.call(void 0, "button",{type:"button",disabled:l||P>0,className:"min-h-11 text-sm underline disabled:opacity-50",onClick:_,children:[z?"Request a new code":"Popro\u015B o\xA0nowy kod",P>0?` (${P}s)`:""]})]}),v&&_jsxruntime.jsxs.call(void 0, "label",{className:"mt-3 grid max-w-xs gap-1 text-sm",children:[_jsxruntime.jsx.call(void 0, "span",{children:z?`Amount (${(I/100).toFixed(2)}\u2013${Number.isFinite(T)?(T/100).toFixed(2):"\u221E"} PLN)`:`Kwota (${(I/100).toFixed(2)}\u2013${Number.isFinite(T)?(T/100).toFixed(2):"\u221E"} z\u0142)`}),_jsxruntime.jsx.call(void 0, "input",{"aria-label":z?"Amount":"Kwota",inputMode:"decimal",type:"text",min:I/100,max:Number.isFinite(T)?T/100:void 0,step:"0.01",value:b,onChange:Y=>w(Y.currentTarget.value),onBlur:()=>{Number.isFinite(f)&&w((f/100).toFixed(2))},className:"h-11 rounded-md border border-neutral-300 bg-white px-3 text-neutral-900 dark:border-neutral-700 dark:bg-neutral-950 dark:text-neutral-50"}),!k&&_jsxruntime.jsx.call(void 0, "span",{role:"alert",className:"text-xs text-red-700 dark:text-red-400",children:z?f===0&&t.freeClaimLimit==null?"Free claims are unavailable. Enter a positive amount.":"Enter an amount within the range.":f===0&&t.freeClaimLimit==null?"Darmowy odbi\xF3r jest niedost\u0119pny. Wpisz kwot\u0119 wi\u0119ksz\u0105 od zera.":"Kwota musi mie\u015Bci\u0107 si\u0119 w\xA0podanym zakresie."})]}),t.welcome&&_jsxruntime.jsx.call(void 0, "p",{className:"mt-3 whitespace-pre-wrap text-sm",children:t.welcome}),h&&_jsxruntime.jsx.call(void 0, "p",{role:"alert",className:"mt-2 text-sm text-red-700 dark:text-red-400",children:h})]}),et&&_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunk4Y233NIIjs.g.call(void 0, ue,"shrink-0"),disabled:l||v&&!k||L&&(!B.includes("@")||!M&&s===null||M&&!U),"aria-busy":l||void 0,onClick:async()=>{p(!0),d("");try{L?(await c({...t,...v?{amount:f}:{},email:B,...M?{code:U}:{turnstileToken:s}}),M||($(!0),S(60))):await c({...t,...v?{amount:f}:{}})}catch(Y){d(Tt(Y,r,n.buyError)),M||(o(null),y(tt=>tt+1))}finally{p(!1)}},children:l?n.buying:v?z?"Choose what you pay":"Kup pakiet, p\u0142ac\u0105c, ile chcesz":L?M?z?"Claim for free":"Odbierz za darmo":z?"Send code":"Wy\u015Blij kod":Qe})]})}function yt(e,t,a,n){return t?n.you:a==="thread"?n.creator:e.authorEmail.split("@")[0]||n.creator}function bt({conversation:e,texts:t,locale:a,kind:n,onReport:r,onEdit:c}){let u=_react.useRef.call(void 0, null),l=_react.useRef.call(void 0, !0),p=e.messages.length,h=_optionalChain([e, 'access', _9 => _9.messages, 'access', _10 => _10[p-1], 'optionalAccess', _11 => _11.id]);return _react.useLayoutEffect.call(void 0, ()=>{let d=u.current;d&&l.current&&(d.scrollTop=d.scrollHeight)},[p,h]),_jsxruntime.jsxs.call(void 0, "div",{ref:u,role:"log","aria-live":"polite","aria-relevant":"additions",onScroll:d=>{let b=d.currentTarget;l.current=b.scrollHeight-b.scrollTop-b.clientHeight<80},className:"flex flex-1 flex-col gap-3 overflow-y-auto overscroll-contain px-3 py-4 sm:px-4",children:[e.hasMore&&_jsxruntime.jsx.call(void 0, "button",{type:"button",onClick:()=>{l.current=!1,e.loadOlder()},disabled:e.loadingOlder,className:_chunk4Y233NIIjs.g.call(void 0, G,"self-center text-xs"),children:e.loadingOlder?t.loading:t.loadOlder}),p===0&&_jsxruntime.jsxs.call(void 0, "div",{className:"m-auto max-w-sm text-center","data-testid":"chat-empty",children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm font-medium",children:t.noMessagesYet}),_jsxruntime.jsx.call(void 0, "p",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:n==="channel"?t.emptyChannel:t.emptyThread}),_optionalChain([e, 'access', _12 => _12.channel, 'optionalAccess', _13 => _13.welcome])&&_jsxruntime.jsx.call(void 0, "p",{className:"mt-3 whitespace-pre-wrap text-sm",children:e.channel.welcome})]}),e.messages.map(d=>_jsxruntime.jsx.call(void 0, kt,{message:d,mine:d.authorEmail.toLowerCase()===e.me,kind:n,texts:t,locale:a,onDelete:()=>e.deleteMessage(d.id),onReport:()=>r(d.id),onRetry:()=>void e.retry(d.id),onDiscard:()=>e.discard(d.id),onEdit:()=>c(d)},d.id))]})}function kt({message:e,mine:t,kind:a,texts:n,locale:r,onDelete:c,onReport:u,onRetry:l,onDiscard:p,onEdit:h}){let[d,b]=_react.useState.call(void 0, !1),[w,R]=_react.useState.call(void 0, !1),f=e.local;if(e.system)return _jsxruntime.jsxs.call(void 0, "div",{"data-message-id":e.id,className:"mx-auto max-w-md text-center text-xs text-neutral-600 dark:text-neutral-400",children:[_jsxruntime.jsx.call(void 0, "span",{className:"font-medium",children:n.systemLabel}),e.body&&_jsxruntime.jsx.call(void 0, "p",{className:"mt-0.5 whitespace-pre-wrap",children:e.body})]});let v=_optionalChain([f, 'optionalAccess', _14 => _14.state])==="rejected"||_optionalChain([f, 'optionalAccess', _15 => _15.state])==="failed",I=_optionalChain([f, 'optionalAccess', _16 => _16.state])==="pending"||_optionalChain([f, 'optionalAccess', _17 => _17.state])==="unconfirmed",T=!f&&!e.deleted;return _jsxruntime.jsxs.call(void 0, "div",{"data-message-id":e.id,"data-state":_nullishCoalesce(_optionalChain([f, 'optionalAccess', _18 => _18.state]), () => ((e.deleted?"deleted":"stored"))),className:_chunk4Y233NIIjs.g.call(void 0, "group flex max-w-[85%] flex-col gap-1 sm:max-w-[75%]",t?"items-end self-end":"items-start self-start"),children:[_jsxruntime.jsxs.call(void 0, "div",{className:_chunk4Y233NIIjs.g.call(void 0, "flex items-end gap-1",t&&"flex-row-reverse"),children:[_jsxruntime.jsx.call(void 0, "div",{className:_chunk4Y233NIIjs.g.call(void 0, "min-w-0 rounded-2xl px-3.5 py-2 text-sm leading-relaxed",e.deleted?"border border-dashed border-neutral-300 bg-transparent italic text-neutral-500 dark:border-neutral-700 dark:text-neutral-400":t?"bg-neutral-900 text-white dark:bg-neutral-100 dark:text-neutral-900":"bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50",I&&"opacity-70",v&&"border border-red-600 dark:border-red-400"),children:e.deleted?n.deletedPlaceholder:_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, "p",{className:"whitespace-pre-wrap break-words",children:e.body}),e.attachmentKey&&_jsxruntime.jsxs.call(void 0, "span",{className:"mt-1 inline-flex items-center gap-1 text-xs opacity-80",children:[_jsxruntime.jsx.call(void 0, _lucidereact.Paperclip,{className:"size-3.5","aria-hidden":"true"}),n.attachment]})]})}),T&&_jsxruntime.jsx.call(void 0, "button",{type:"button","aria-label":n.messageActions,"aria-expanded":d,onClick:()=>{b(k=>!k),R(!1)},className:_chunk4Y233NIIjs.g.call(void 0, "inline-flex size-11 shrink-0 items-center justify-center rounded-md text-neutral-500 opacity-100 hover:bg-neutral-100 sm:opacity-0 sm:group-hover:opacity-100 sm:focus-visible:opacity-100 dark:text-neutral-400 dark:hover:bg-neutral-800",d&&"sm:opacity-100",Te),children:_jsxruntime.jsx.call(void 0, _lucidereact.MoreHorizontal,{className:"size-4","aria-hidden":"true"})})]}),_jsxruntime.jsxs.call(void 0, "p",{className:"flex items-center gap-1.5 px-1 text-[11px] text-neutral-500 dark:text-neutral-400",children:[e.pinned&&_jsxruntime.jsxs.call(void 0, "span",{className:"inline-flex items-center gap-0.5",children:[_jsxruntime.jsx.call(void 0, _lucidereact.Pin,{className:"size-3","aria-hidden":"true"}),n.pinned]}),_jsxruntime.jsx.call(void 0, "span",{children:yt(e,t,a,n)}),_jsxruntime.jsx.call(void 0, "span",{"aria-hidden":"true",children:"\xB7"}),I?_jsxruntime.jsxs.call(void 0, "span",{className:"inline-flex items-center gap-1",children:[_jsxruntime.jsx.call(void 0, _lucidereact.Clock,{className:"size-3","aria-hidden":"true"}),_optionalChain([f, 'optionalAccess', _19 => _19.state])==="pending"?n.pending:n.notConfirmed]}):_jsxruntime.jsx.call(void 0, "time",{dateTime:e.createdAt,children:de(e.createdAt,r)})]}),v&&_jsxruntime.jsxs.call(void 0, "div",{role:"alert",className:_chunk4Y233NIIjs.g.call(void 0, "flex flex-col gap-1",t?"items-end":"items-start"),children:[_jsxruntime.jsxs.call(void 0, "p",{className:"flex items-start gap-1 text-xs text-red-700 dark:text-red-400",children:[_jsxruntime.jsx.call(void 0, _lucidereact.AlertCircle,{className:"mt-px size-3.5 shrink-0","aria-hidden":"true"}),De(n,_nullishCoalesce(_optionalChain([f, 'optionalAccess', _20 => _20.reason]), () => ("")),_optionalChain([f, 'optionalAccess', _21 => _21.retryAfter]))]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap gap-1",children:[_optionalChain([f, 'optionalAccess', _22 => _22.state])==="failed"||_optionalChain([f, 'optionalAccess', _23 => _23.reason])==="cooldown"?_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunk4Y233NIIjs.g.call(void 0, G,"text-xs"),onClick:l,children:n.retrySend}):_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunk4Y233NIIjs.g.call(void 0, G,"text-xs"),onClick:h,children:n.editMessage}),_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunk4Y233NIIjs.g.call(void 0, G,"text-xs"),onClick:p,children:n.dismiss})]})]}),d&&T&&_jsxruntime.jsx.call(void 0, "div",{className:"flex flex-wrap gap-1",children:t?_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunk4Y233NIIjs.g.call(void 0, G,"text-xs text-red-700 dark:text-red-400"),onClick:async()=>{if(!w){R(!0);return}b(!1),await c().catch(()=>{})},children:w?n.deleteConfirm:n.deleteMessage}):_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunk4Y233NIIjs.g.call(void 0, G,"text-xs"),onClick:()=>{b(!1),u()},children:n.reportMessage})})]})}function xt(e,t,a){if(t==="thread"&&_optionalChain([e, 'access', _24 => _24.thread, 'optionalAccess', _25 => _25.composerLocked]))return a.composerExpired;if(t==="channel"&&e.channel){if(e.channel.role==="muted")return a.composerMuted;if(e.channel.whoCanPost==="creator"&&e.channel.role!=="creator")return a.composerCreatorOnly}}function Ct({conversation:e,texts:t,kind:a,draft:n,setDraft:r}){let c=_react.useId.call(void 0, ),u=_react.useRef.call(void 0, null),l=xt(e,a,t);if(_react.useLayoutEffect.call(void 0, ()=>{let d=u.current;d&&(d.style.height="auto",d.style.height=`${Math.min(d.scrollHeight,160)}px`)},[n]),l)return _jsxruntime.jsx.call(void 0, "p",{"data-testid":"chat-composer-blocked",className:"border-t border-neutral-200 px-4 py-3 text-sm text-neutral-600 dark:border-neutral-800 dark:text-neutral-400",children:l});let p=d=>{_optionalChain([d, 'optionalAccess', _26 => _26.preventDefault, 'call', _27 => _27()]);let b=n.trim();b&&(r(""),e.send(b))},h=d=>{d.key==="Enter"&&!d.shiftKey&&!d.nativeEvent.isComposing&&(d.preventDefault(),p())};return _jsxruntime.jsxs.call(void 0, "form",{onSubmit:p,className:"border-t border-neutral-200 px-3 pb-3 pt-2 dark:border-neutral-800",children:[e.messages.length===0&&_jsxruntime.jsx.call(void 0, "p",{className:"pb-2 text-xs text-neutral-500 dark:text-neutral-400",children:t.privacyNote}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex items-end gap-2",children:[_jsxruntime.jsx.call(void 0, "label",{htmlFor:c,className:"sr-only",children:t.composerLabel}),_jsxruntime.jsx.call(void 0, "textarea",{id:c,ref:u,rows:1,value:n,onChange:d=>r(d.target.value),onKeyDown:h,placeholder:t.composerPlaceholder,className:"max-h-40 min-h-11 flex-1 resize-none rounded-xl border border-neutral-300 bg-white px-3 py-2.5 text-sm text-neutral-900 placeholder:text-neutral-500 focus-visible:border-neutral-500 focus-visible:outline-none dark:border-neutral-700 dark:bg-neutral-950 dark:text-neutral-50 dark:placeholder:text-neutral-400"}),_jsxruntime.jsx.call(void 0, "button",{type:"submit","aria-label":t.send,disabled:n.trim().length===0,className:_chunk4Y233NIIjs.g.call(void 0, ue,"w-11 px-0"),children:_jsxruntime.jsx.call(void 0, _lucidereact.SendHorizontal,{className:"size-5","aria-hidden":"true"})})]})]})}var wt=["spam","abuse","illegal","other"];function vt({texts:e,messageId:t,onCancel:a,onSubmit:n}){let[r,c]=_react.useState.call(void 0, "spam"),[u,l]=_react.useState.call(void 0, ""),[p,h]=_react.useState.call(void 0, !1),[d,b]=_react.useState.call(void 0, !1),w=_react.useId.call(void 0, ),R={spam:e.reasonSpam,abuse:e.reasonAbuse,illegal:e.reasonIllegal,other:e.reasonOther};return _jsxruntime.jsxs.call(void 0, "form",{"data-testid":"chat-report",className:"flex flex-col gap-3 border-t border-neutral-200 p-4 dark:border-neutral-800",onSubmit:async f=>{f.preventDefault(),h(!0),b(!1);try{await n(r,u.trim())}catch (e6){b(!0)}finally{h(!1)}},children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm font-semibold",children:t?e.reportTitle:e.reportConversationTitle}),_jsxruntime.jsxs.call(void 0, "fieldset",{className:"flex flex-col gap-1",children:[_jsxruntime.jsx.call(void 0, "legend",{className:"mb-1 text-xs text-neutral-600 dark:text-neutral-400",children:e.reportReason}),wt.map(f=>_jsxruntime.jsxs.call(void 0, "label",{className:"flex min-h-9 items-center gap-2 text-sm",children:[_jsxruntime.jsx.call(void 0, "input",{type:"radio",name:"chat-report-reason",value:f,checked:r===f,onChange:()=>c(f),className:"size-4 accent-neutral-900 dark:accent-white"}),R[f]]},f))]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-1",children:[_jsxruntime.jsx.call(void 0, "label",{htmlFor:w,className:"text-xs text-neutral-600 dark:text-neutral-400",children:e.reportNote}),_jsxruntime.jsx.call(void 0, "textarea",{id:w,rows:2,maxLength:1e3,value:u,onChange:f=>l(f.target.value),className:"resize-none rounded-xl border border-neutral-300 bg-white px-3 py-2 text-sm focus-visible:border-neutral-500 focus-visible:outline-none dark:border-neutral-700 dark:bg-neutral-950"})]}),d&&_jsxruntime.jsx.call(void 0, "p",{role:"alert",className:"text-sm text-red-700 dark:text-red-400",children:e.reportError}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap justify-end gap-2",children:[_jsxruntime.jsx.call(void 0, "button",{type:"button",className:G,onClick:a,children:e.reportCancel}),_jsxruntime.jsx.call(void 0, "button",{type:"submit",className:ue,disabled:p,"aria-busy":p||void 0,children:e.reportSend})]})]})}function Tt(e,t,a){let n=e instanceof Error?e.message:"",r=t.toLowerCase().startsWith("en");return_nullishCoalesce(_optionalChain([{"amount-below-minimum":["Kwota jest ni\u017Csza od minimalnej.","The amount is below the minimum."],"amount-above-maximum":["Kwota przekracza maksymaln\u0105.","The amount is above the maximum."],"amount-below-gateway-minimum":["Kwota jest za niska dla dost\u0119pnych p\u0142atno\u015Bci.","The amount is too low for available payment methods."],"amount-invalid":["Podaj prawid\u0142ow\u0105 kwot\u0119.","Enter a valid amount."],"email-verification-required":["Potwierd\u017A adres e-mail, aby odebra\u0107 pakiet.","Verify your email to claim this pack."],"free-claim-exists":["Ten adres e-mail wykorzysta\u0142 ju\u017C limit darmowych odbior\xF3w.","This email has reached the free claim limit."],"free-order-not-supported":["Nie mo\u017Cna zrealizowa\u0107 tego darmowego zam\xF3wienia.","This free order cannot be completed."],"captcha-required":["Potwierd\u017A, \u017Ce nie jeste\u015B robotem.","Complete the security check."],"captcha-invalid":["Weryfikacja wygas\u0142a. Spr\xF3buj ponownie.","The security check expired. Try again."],"rate-limited":["Zbyt wiele pr\xF3b. Spr\xF3buj ponownie za chwil\u0119.","Too many attempts. Try again shortly."],"incorrect-code":["Nieprawid\u0142owy kod. Sprawd\u017A wiadomo\u015B\u0107 i\xA0spr\xF3buj ponownie.","The code is incorrect. Check your email and try again."],"too-many-attempts":["Popro\u015B o\xA0nowy kod za kilka minut.","Request a new code in a few minutes."],unavailable:["Weryfikacja jest chwilowo niedost\u0119pna.","Verification is temporarily unavailable."]}, 'access', _28 => _28[n], 'optionalAccess', _29 => _29[r?1:0]]), () => (a))}var Nt=()=>Promise.resolve().then(() => _interopRequireWildcard(require("@nats-io/nats-core")));function Ie(e){let t=_nullishCoalesce(e.pollIntervalMs, () => (8e3)),a=_nullishCoalesce(e.retryMs, () => (6e4)),n=_nullishCoalesce(e.loadNats, () => (Nt)),r=`.${e.kind}.${e.id}`,c=!1,u,l="",p,h,d,b=()=>{p!=null&&clearInterval(p),p=void 0},w=()=>{c||(e.onMode("polling"),p==null&&(p=setInterval(()=>{e.poll().catch(()=>{})},t)),h==null&&(h=setTimeout(()=>{h=void 0,f()},a)))},R=v=>{d!=null&&clearTimeout(d);let I=Date.parse(v);if(!Number.isFinite(I))return;let T=Math.max(5e3,I-Date.now()-6e4);d=setTimeout(async()=>{if(!c)try{let k=await e.client.realtimeToken({fresh:!0});l=k.jwt,R(k.expiresAt)}catch (e7){}},T)};async function f(){if(!c){if(typeof WebSocket>"u"){w();return}e.onMode("connecting");try{let v=await e.client.realtimeToken(),I=v.subjects.find(j=>j.endsWith(r));if(I||(v=await e.client.realtimeToken({fresh:!0}),I=v.subjects.find(j=>j.endsWith(r))),!I||!v.jwt)throw new Error("subject not granted");l=v.jwt;let T=await n();if(c)return;let k=e.realtimeUrl?[e.realtimeUrl]:v.servers.length>0?v.servers:[xe],L=await T.wsconnect({servers:k,authenticator:T.jwtAuthenticator(()=>l),name:"bitsnap-react/chat",reconnect:!0,maxReconnectAttempts:5});if(c){L.close().catch(()=>{});return}u=L;let B=new TextDecoder;L.subscribe(I,{callback:(j,U)=>{if(!j)try{let m=Ce(JSON.parse(B.decode(U.data)));m&&e.onEvent(m)}catch (e8){}}}),L.closed().then(()=>{u===L&&(u=void 0,w())}),R(v.expiresAt),b(),e.onMode("live"),e.poll().catch(()=>{})}catch (e9){w()}}}return f(),()=>{c=!0,b(),h!=null&&clearTimeout(h),d!=null&&clearTimeout(d);let v=u;u=void 0,v&&v.close().catch(()=>{})}}var je=50,X={status:"loading",messages:[],hasMore:!1,loadingOlder:!1,live:"off"};function It(){let e=globalThis.crypto;if(e&&typeof e.randomUUID=="function")return e.randomUUID();let t=new Uint8Array(16);if(e&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let n=0;n<16;n++)t[n]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let a=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return`${a.slice(0,8)}-${a.slice(8,12)}-${a.slice(12,16)}-${a.slice(16,20)}-${a.slice(20)}`}function oe(e,t){let a=new Map(e.map(n=>[n.id,n]));for(let n of t){let r=a.get(n.id);if(n.status==="pending"){if(r&&!r.local)continue;a.set(n.id,{...n,local:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _30 => _30.local]), () => ({state:"pending"}))});continue}_optionalChain([r, 'optionalAccess', _31 => _31.local])&&r.local.state!=="pending"&&r.local.state!=="unconfirmed"||a.set(n.id,{...n,local:void 0})}return[...a.values()].sort((n,r)=>{let c=Date.parse(n.createdAt)||0,u=Date.parse(r.createdAt)||0;return c-u})}function Me(e){if(e.kind==="pack"){if(e.composerLocked)return{reason:"expired",productId:e.productId};if(e.repliesLeft<=0)return{reason:"replies",productId:e.productId}}}function Ye(e,t,a){let n=Number(e.data.price_cents);return{reason:t,productId:typeof e.data.product_id=="string"&&e.data.product_id?e.data.product_id:a,priceCents:Number.isFinite(n)&&n>0?n:void 0,priceType:e.data.price_type==="free"||e.data.price_type==="pay_what_you_want"?e.data.price_type:"one_time",minimumCents:Number.isFinite(Number(e.data.price_min_cents))?Number(e.data.price_min_cents):void 0,maximumCents:Number.isFinite(Number(e.data.price_max_cents))?Number(e.data.price_max_cents):void 0,freeClaimLimit:Number.isFinite(Number(e.data.free_claim_limit))?Number(e.data.free_claim_limit):void 0,welcome:typeof e.data.welcome=="string"?e.data.welcome:void 0}}function he(e){return e instanceof W?e:new W("internal_error",0)}function ge(e){let{client:t,target:a}=e,[n,r]=_react.useState.call(void 0, X),[c,u]=_react.useState.call(void 0, 0),l=_react.useRef.call(void 0, n);l.current=n;let p=_react.useRef.call(void 0, new Set),h=_react.useRef.call(void 0, void 0),d=_react.useRef.call(void 0, void 0),b=a.kind==="thread"?`t:${_nullishCoalesce(a.threadId, () => (""))}:${_nullishCoalesce(a.productId, () => (""))}`:`c:${a.channelId}:${_nullishCoalesce(a.productId, () => (""))}`;_react.useEffect.call(void 0, ()=>{let s=!1;if(d.current=void 0,r(X),t!==null){if(!t){r({...X,status:"error",error:new W("no_token",401)});return}return(async()=>{try{let o=await t.me(),g=o.email.toLowerCase(),y,P,S;if(a.kind==="thread"){if(y=a.threadId?o.threads.find(_=>_.id===a.threadId):o.threads.find(_=>_.productId===a.productId),!y&&a.productId)try{y=await t.openThread(a.productId)}catch(_){let z=he(_);if(z.code==="locked"||z.status===404){s||r({...X,status:"locked",me:g,lock:Ye(z,"no-pack",a.productId)});return}throw z}if(!y)throw new W("not_found",404);S=y.id}else P=o.channels.find(_=>_.id===a.channelId),S=a.channelId;let K;try{K=await t.messages(S,{limit:je})}catch(_){let z=he(_);if(z.code==="locked"){s||r({...X,status:"locked",me:g,thread:y,channel:P,threadId:S,lock:Ye(z,a.kind==="channel"?"no-access":"no-pack",_nullishCoalesce(_nullishCoalesce(a.productId, () => (_optionalChain([P, 'optionalAccess', _32 => _32.productId]))), () => (_optionalChain([y, 'optionalAccess', _33 => _33.productId]))))});return}throw z}if(s)return;r({...X,status:"ready",me:g,thread:y,channel:P,threadId:S,lock:y?Me(y):void 0,messages:oe([],K.messages),hasMore:K.hasMore})}catch(o){s||r({...X,status:"error",error:he(o)})}})(),()=>{s=!0}}},[t,b,c]);let w=_react.useCallback.call(void 0, ()=>{t&&(h.current&&clearTimeout(h.current),h.current=setTimeout(async()=>{try{let s=await t.me();r(o=>{if(o.status!=="ready")return o;let g=o.thread&&s.threads.find(P=>P.id===o.thread.id),y=o.channel&&s.channels.find(P=>P.id===o.channel.id);return{...o,thread:_nullishCoalesce(g, () => (o.thread)),channel:_nullishCoalesce(y, () => (o.channel)),lock:g?Me(g):o.lock}})}catch (e10){}},1500))},[t]),R=_react.useCallback.call(void 0, async()=>{let{threadId:s}=l.current;if(!t||!s)return;let o=await t.messages(s,{limit:je});r(g=>g.threadId===s?{...g,messages:oe(g.messages,o.messages)}:g)},[t]),f=_react.useCallback.call(void 0, s=>{r(o=>{switch(s.type){case"message.created":return{...o,messages:oe(o.messages,[s.message])};case"message.rejected":return{...o,messages:o.messages.map(g=>g.id===s.id?{...g,local:{state:"rejected",reason:s.reason||"rejected"}}:g)};case"message.deleted":return{...o,messages:o.messages.map(g=>g.id===s.id?{...g,deleted:!0,body:"",attachmentKey:void 0}:g)};case"message.pinned":case"message.unpinned":return{...o,messages:o.messages.map(g=>g.id===s.id?{...g,pinned:s.type==="message.pinned"}:g)}}}),s.type==="message.created"&&!s.message.system&&s.message.authorEmail.toLowerCase()!==l.current.me&&w()},[w]),I=n.status==="ready"?n.threadId:void 0;_react.useEffect.call(void 0, ()=>{if(!t||!I)return;let s=Ie({client:t,kind:a.kind,id:I,onEvent:f,onMode:o=>r(g=>({...g,live:o})),poll:R,pollIntervalMs:e.pollIntervalMs,realtimeUrl:e.realtimeUrl,loadNats:e.loadNats});return()=>{s(),r(o=>({...o,live:"off"}))}},[t,I,f,R]),_react.useEffect.call(void 0, ()=>{if(!t||!n.threadId||n.status!=="ready")return;let s=[...n.messages].reverse().find(o=>!o.local&&o.authorEmail.toLowerCase()!==n.me);!s||d.current===s.id||(d.current=s.id,t.markRead(n.threadId,s.id).catch(()=>{}))},[t,n.threadId,n.status,n.messages,n.me]),_react.useEffect.call(void 0, ()=>()=>{for(let s of p.current)clearTimeout(s);h.current&&clearTimeout(h.current)},[]);let T=(s,o)=>r(g=>({...g,messages:g.messages.map(y=>y.id===s?o(y):y)})),k=_react.useCallback.call(void 0, async(s,o)=>{let g=s.trim(),{threadId:y,me:P}=l.current;if(!t||!y||!g)return;let S=_nullishCoalesce(o, () => (It())),K={id:S,threadId:y,authorEmail:_nullishCoalesce(P, () => ("")),body:g,createdAt:new Date().toISOString(),pinned:!1,deleted:!1,system:!1,status:"pending",local:{state:"pending"}};r(_=>({..._,messages:[..._.messages,K]}));try{let _=await t.send(y,{body:g,clientId:S});r(O=>({...O,messages:oe(O.messages,[{..._.message,id:S}]),thread:O.thread?{...O.thread,..._.thread,id:O.thread.id}:O.thread,lock:O.thread?Me({...O.thread,..._.thread,id:O.thread.id}):O.lock}));let z=setTimeout(()=>{p.current.delete(z),T(S,O=>_optionalChain([O, 'access', _34 => _34.local, 'optionalAccess', _35 => _35.state])==="pending"?{...O,local:{state:"unconfirmed"}}:O)},_nullishCoalesce(e.confirmTimeoutMs, () => (45e3)));p.current.add(z)}catch(_){let z=he(_),O=z.code==="network"||z.code==="unavailable"||z.status>=500;T(S,ye=>({...ye,local:{state:O?"failed":"rejected",reason:z.code,retryAfter:z.retryAfter,keepId:O||o!=null}}))}},[t,e.confirmTimeoutMs]),L=_react.useCallback.call(void 0, s=>{r(o=>({...o,messages:o.messages.filter(g=>g.id!==s)}))},[]),B=_react.useCallback.call(void 0, async s=>{let o=l.current.messages.find(y=>y.id===s);if(!o)return;let g=_optionalChain([o, 'access', _36 => _36.local, 'optionalAccess', _37 => _37.state])!=="rejected"||o.local.keepId===!0;L(s),await k(o.body,g?s:void 0)},[L,k]),j=_react.useCallback.call(void 0, async s=>{let{threadId:o}=l.current,g=l.current.messages.find(y=>y.id===s);if(!(!t||!o||!g)){T(s,y=>({...y,deleted:!0,body:"",attachmentKey:void 0}));try{await t.deleteMessage(o,s)}catch(y){throw T(s,()=>g),y}}},[t]),U=_react.useCallback.call(void 0, async s=>{let{threadId:o}=l.current;!t||!o||await t.report({threadId:o,...s})},[t]),m=_react.useCallback.call(void 0, async s=>{let{threadId:o}=l.current;!t||!o||(await t.mute(o,s),r(g=>g.thread?{...g,thread:{...g.thread,muted:s}}:g))},[t]),M=_react.useCallback.call(void 0, async()=>{let{threadId:s,messages:o,hasMore:g,loadingOlder:y}=l.current,P=o.find(S=>!S.local);if(!(!t||!s||!g||y||!P)){r(S=>({...S,loadingOlder:!0}));try{let S=await t.messages(s,{before:P.id,limit:je});r(K=>({...K,loadingOlder:!1,hasMore:S.hasMore,messages:oe(K.messages,S.messages)}))}catch (e11){r(S=>({...S,loadingOlder:!1}))}}},[t]),$=_react.useCallback.call(void 0, ()=>u(s=>s+1),[]);return{...n,send:k,retry:B,discard:L,deleteMessage:j,report:U,setMuted:m,loadOlder:M,reload:$}}function qe(e){let[t,a]=_react.useState.call(void 0, null),n=_nullishCoalesce(e.host, () => (_chunkMDAFPGPAjs.b.call(void 0, ).host));_react.useEffect.call(void 0, ()=>{e.client||e.token||a(_chunkMDAFPGPAjs.i.call(void 0, e.projectID,n))},[e.client,e.token,e.projectID,n]);let r=_nullishCoalesce(e.token, () => (t)),c=_nullishCoalesce(e.chatProjectID, () => (e.projectID));return _react.useMemo.call(void 0, ()=>{if(e.client)return e.client;if(r===null)return null;if(r)return ne({projectId:c,token:r,baseUrl:e.apiUrl})},[e.client,r,c,e.apiUrl])}function Ge(e){let t=_react.useRef.call(void 0, null);return async a=>{let n=_nullishCoalesce(e.buyProductId, () => (a.productId));if(!n)return;let r={productId:n,reason:a.reason,priceCents:a.priceCents,...a.amount!=null?{amount:a.amount}:{},...a.email?{email:a.email}:{},...a.code?{code:a.code}:{},...a.turnstileToken!=null?{turnstileToken:a.turnstileToken}:{}};if(e.onBuy){await e.onBuy(r);return}let c=(_nullishCoalesce(_nullishCoalesce(e.host, () => (_chunkMDAFPGPAjs.b.call(void 0, ).host)), () => ("https://bitsnap.pl"))).replace(/\/+$/,""),u=a.freeClaimLimit!=null&&(a.priceType==="free"||a.priceType==="pay_what_you_want"&&a.minimumCents===0&&r.amount===0);if(u&&r.email&&r.turnstileToken!=null){t.current=null;let l=await fetch(`${c}/api/integrations/${encodeURIComponent(e.projectID)}/public-commerce/free-claim/request-code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:r.email,turnstileToken:r.turnstileToken})}),p=await l.json();if(!l.ok)throw new Error(_nullishCoalesce(p.code, () => ("internal")));return}if(u&&r.email&&r.code){let l=JSON.stringify([c,e.projectID,n,r.email,r.code]);if(!t.current||t.current.key!==l||t.current.expires<=Date.now()){t.current=null;let d=await fetch(`${c}/api/integrations/${encodeURIComponent(e.projectID)}/public-commerce/free-claim/verify-code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:r.email,code:r.code})}),b=await d.json();if(!d.ok||!b.claimToken)throw new Error(_nullishCoalesce(b.code, () => ("email-verification-required")));t.current={key:l,token:b.claimToken,expires:Date.now()+(_nullishCoalesce(b.expiresIn, () => (600)))*1e3}}let p=await fetch(`${c}/api/integrations/${encodeURIComponent(e.projectID)}/public-commerce/buy`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({items:[{id:n,quantity:1,amount:0}],details:{email:r.email},claimToken:t.current.token})}),h=await p.json();if(!p.ok||!h.url)throw new Error(_nullishCoalesce(h.code, () => ("free-order-not-supported")));window.location.assign(h.url);return}await te({projectID:e.projectID,productId:n,name:e.title,priceCents:a.priceCents,amount:a.amount,host:e.host})}}function ze(e){let t=qe(e),a=_nullishCoalesce(e.locale, () => (_chunkQ337IQNAjs.f.call(void 0, ))),n=_react.useMemo.call(void 0, ()=>ee(e.texts,a),[e.texts,a]),r=ge({client:t,target:{kind:"thread",threadId:e.threadId,productId:e.productId},pollIntervalMs:e.pollIntervalMs,realtimeUrl:e.realtimeUrl,loadNats:e.loadNats}),c=Ge(e);return _jsxruntime.jsx.call(void 0, "div",{className:"bitsnap-react h-full",children:_jsxruntime.jsx.call(void 0, Ne,{host:e.host,conversation:r,texts:n,locale:a,kind:"thread",title:e.title,onBack:e.onBack,onBuy:c,className:e.className})})}function Re(e){let t=qe(e),a=_nullishCoalesce(e.locale, () => (_chunkQ337IQNAjs.f.call(void 0, ))),n=_react.useMemo.call(void 0, ()=>ee(e.texts,a),[e.texts,a]),r=ge({client:t,target:{kind:"channel",channelId:e.channelId,productId:e.productId},pollIntervalMs:e.pollIntervalMs,realtimeUrl:e.realtimeUrl,loadNats:e.loadNats}),c=Ge(e);return _jsxruntime.jsx.call(void 0, "div",{className:"bitsnap-react h-full",children:_jsxruntime.jsx.call(void 0, Ne,{host:e.host,conversation:r,texts:n,locale:a,kind:"channel",title:e.title,onBack:e.onBack,onBuy:c,className:e.className})})}var _t=_react.lazy.call(void 0, ()=>Promise.resolve().then(() => _interopRequireWildcard(require("./BitsnapCart-V4S4EXYV.js")))),Ve=e=>e.productType===5||e.productType===6;function Je(e,t){let a=[...new Set(e.filter(Ve).map(n=>n.projectId).filter(Boolean))];return a.length>0?a:t?[t]:[]}function At(e){let t=new Map;for(let a of e)Ve(a)&&a.projectId&&a.chatProjectId&&t.set(a.projectId,a.chatProjectId);return t}function Xe({accessToken:e,products:t,chatApiUrl:a,projectID:n,host:r,selection:c,onSelect:u,locale:l=_chunkQ337IQNAjs.f.call(void 0, ),texts:p}){let h=_react.useMemo.call(void 0, ()=>ee(p,l),[p,l]),d=_react.useMemo.call(void 0, ()=>Je(t,n),[t,n]),b=_react.useMemo.call(void 0, ()=>At(t),[t]),w=_react.useMemo.call(void 0, ()=>{let s=new Map;for(let o of d)s.set(o,ne({projectId:_nullishCoalesce(b.get(o), () => (o)),token:e,baseUrl:a}));return s},[d,b,e,a]),[R,f]=_react.useState.call(void 0, {}),[v,I]=_react.useState.call(void 0, 0),T=`${_nullishCoalesce(c.chatProject, () => (""))}:${_nullishCoalesce(c.thread, () => (""))}:${_nullishCoalesce(c.channel, () => (""))}`;_react.useEffect.call(void 0, ()=>{let s=!1;for(let[o,g]of w)f(y=>_optionalChain([y, 'access', _38 => _38[o], 'optionalAccess', _39 => _39.status])==="ready"?y:{...y,[o]:{status:"loading"}}),g.me().then(y=>!s&&f(P=>({...P,[o]:{status:"ready",me:y}})),y=>!s&&f(P=>({...P,[o]:{status:"error",error:y instanceof W?y:new W("internal_error",0)}})));return()=>{s=!0}},[w,v,T]);let k=_react.useMemo.call(void 0, ()=>{let s=new Map;for(let o of t)s.set(o.productId,o);return s},[t]),[L,B]=_react.useState.call(void 0, ),j=s=>async o=>{B(s),await te({projectID:s,productId:o.productId,name:_optionalChain([k, 'access', _40 => _40.get, 'call', _41 => _41(o.productId), 'optionalAccess', _42 => _42.productName]),priceCents:o.priceCents,host:r})},U=c.chatProject?w.get(c.chatProject):void 0,m=!!(U&&(c.thread||c.channel)),M=()=>u({}),$=null;if(m&&U&&c.chatProject){let s=c.chatProject,o=R[s],g=_optionalChain([o, 'optionalAccess', _43 => _43.status])==="ready"?o.me:void 0;if(c.thread){let y=_optionalChain([g, 'optionalAccess', _44 => _44.threads, 'access', _45 => _45.find, 'call', _46 => _46(P=>P.id===c.thread)]);$=_jsxruntime.jsx.call(void 0, ze,{projectID:s,client:U,threadId:c.thread,title:_optionalChain([y, 'optionalAccess', _47 => _47.productId])&&_optionalChain([k, 'access', _48 => _48.get, 'call', _49 => _49(y.productId), 'optionalAccess', _50 => _50.productName])||void 0,locale:l,texts:p,onBack:M,onBuy:j(s)},`t:${s}:${c.thread}`)}else if(c.channel){let y=_optionalChain([g, 'optionalAccess', _51 => _51.entitlements, 'access', _52 => _52.channels, 'access', _53 => _53.find, 'call', _54 => _54(P=>P.channelId===c.channel)]);$=_jsxruntime.jsx.call(void 0, Re,{projectID:s,client:U,channelId:c.channel,productId:_optionalChain([y, 'optionalAccess', _55 => _55.productId]),locale:l,texts:p,onBack:M,onBuy:j(s)},`c:${s}:${c.channel}`)}}return _jsxruntime.jsxs.call(void 0, "div",{className:"flex min-h-0 flex-1 flex-col",children:[_jsxruntime.jsxs.call(void 0, "div",{className:_chunk4Y233NIIjs.g.call(void 0, m&&"hidden md:block"),children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-2xl",children:h.inboxHeading}),_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-500 dark:text-neutral-400",children:h.inboxIntro})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"mt-6 grid min-h-0 flex-1 gap-4 md:grid-cols-[minmax(16rem,22rem)_1fr]",children:[_jsxruntime.jsx.call(void 0, "div",{className:_chunk4Y233NIIjs.g.call(void 0, "min-w-0",m&&"hidden md:block"),children:_jsxruntime.jsx.call(void 0, Bt,{projects:d,loads:R,clients:w,products:t,texts:h,locale:l,selection:c,onSelect:u,onRetry:()=>I(s=>s+1)})}),_jsxruntime.jsx.call(void 0, "div",{className:_chunk4Y233NIIjs.g.call(void 0, "min-h-[32rem] min-w-0 md:h-[calc(100dvh-10rem)]",!m&&"hidden md:flex"),children:_nullishCoalesce($, () => (_jsxruntime.jsx.call(void 0, "div",{className:"flex h-full w-full items-center justify-center rounded-xl border border-dashed border-neutral-300 p-6 text-sm text-neutral-600 dark:border-neutral-700 dark:text-neutral-400",children:h.selectConversation})))})]}),L&&_jsxruntime.jsx.call(void 0, _react.Suspense,{fallback:null,children:_jsxruntime.jsx.call(void 0, _t,{projectID:L,locale:l})})]})}var Ze="flex min-h-11 w-full min-w-0 items-start gap-3 rounded-xl p-3 text-left transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-500";function Bt({projects:e,loads:t,clients:a,products:n,texts:r,locale:c,selection:u,onSelect:l,onRetry:p}){let[h,d]=_react.useState.call(void 0, ),[b,w]=_react.useState.call(void 0, ),R=new Map(n.map(k=>[k.productId,k])),f=e.length>1,v=e.map(k=>_nullishCoalesce(t[k], () => ({status:"loading"})));if(v.length>0&&v.every(k=>k.status==="loading"))return _jsxruntime.jsx.call(void 0, "div",{role:"status","aria-busy":"true","aria-label":r.loading,className:"flex flex-col gap-2",children:[0,1,2].map(k=>_jsxruntime.jsx.call(void 0, "div",{"aria-hidden":"true",className:"h-20 rounded-xl bg-white motion-safe:animate-pulse dark:bg-neutral-800"},k))});if(v.length===0||v.every(k=>k.status==="error"))return _jsxruntime.jsxs.call(void 0, "div",{role:"alert",className:"flex flex-col items-start gap-3","data-testid":"chat-inbox-error",children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-700 dark:text-neutral-300",children:r.inboxError}),_jsxruntime.jsx.call(void 0, "button",{type:"button",onClick:p,className:"inline-flex min-h-11 items-center rounded-md bg-neutral-900 px-4 text-sm font-medium text-white hover:bg-neutral-800 focus-visible:outline-2 focus-visible:outline-current dark:bg-white dark:text-neutral-900",children:r.retry})]});let I=[],T=[];for(let k of e){let L=t[k];if(_optionalChain([L, 'optionalAccess', _56 => _56.status])!=="ready")continue;let{me:B}=L,j=f?_optionalChain([n, 'access', _57 => _57.find, 'call', _58 => _58(m=>m.projectId===k), 'optionalAccess', _59 => _59.projectName]):void 0;for(let m of B.threads){let M=m.productId?R.get(m.productId):void 0,$=u.chatProject===k&&u.thread===m.id,s=[ae(r,m.repliesLeft,c)];m.expiresAt&&s.push(H(m.composerLocked?r.expiredOn:r.expiresOn,{date:re(m.expiresAt,c)})),m.responseHours>0&&s.push(H(r.responseHours,{hours:m.responseHours}));let o=m.lastMessage;I.push(_jsxruntime.jsx.call(void 0, "li",{children:_jsxruntime.jsxs.call(void 0, "button",{type:"button","data-thread-id":m.id,"aria-current":$?"true":void 0,onClick:()=>l({chatProject:k,thread:m.id}),className:_chunk4Y233NIIjs.g.call(void 0, Ze,$?"bg-neutral-200 dark:bg-neutral-800":"bg-white hover:bg-neutral-50 dark:bg-neutral-900 dark:hover:bg-neutral-800"),children:[_jsxruntime.jsx.call(void 0, _lucidereact.MessageCircle,{className:"mt-0.5 size-5 shrink-0 text-neutral-500 dark:text-neutral-400","aria-hidden":"true"}),_jsxruntime.jsxs.call(void 0, "span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[_jsxruntime.jsxs.call(void 0, "span",{className:"flex items-baseline gap-2",children:[_jsxruntime.jsx.call(void 0, "span",{className:_chunk4Y233NIIjs.g.call(void 0, "truncate",m.unread>0?"font-semibold":"font-medium"),children:_optionalChain([M, 'optionalAccess', _60 => _60.productName])||r.chatFallbackTitle}),o&&_jsxruntime.jsx.call(void 0, "time",{dateTime:o.createdAt,className:"ml-auto shrink-0 text-xs text-neutral-500 dark:text-neutral-400",children:de(o.createdAt,c)})]}),j&&_jsxruntime.jsx.call(void 0, "span",{className:"truncate text-xs text-neutral-500 dark:text-neutral-400",children:j}),_jsxruntime.jsxs.call(void 0, "span",{className:"flex items-center gap-2",children:[_jsxruntime.jsx.call(void 0, "span",{className:"line-clamp-1 flex-1 text-sm text-neutral-600 dark:text-neutral-300",children:o?o.deleted?r.deletedPlaceholder:o.body:r.noMessagesYet}),m.unread>0&&_jsxruntime.jsx.call(void 0, "span",{"aria-label":H(r.unread,{count:m.unread}),className:"inline-flex min-w-5 shrink-0 items-center justify-center rounded-full bg-neutral-900 px-1.5 text-xs font-semibold text-white tabular-nums dark:bg-white dark:text-neutral-900",children:m.unread})]}),_jsxruntime.jsxs.call(void 0, "span",{className:_chunk4Y233NIIjs.g.call(void 0, "text-xs",m.repliesLeft<=0||m.composerLocked?"text-amber-800 dark:text-amber-300":"text-neutral-500 dark:text-neutral-400"),children:[s.join(" \xB7 "),m.muted&&` \xB7 ${r.mutedBadge}`]})]})]})},`t:${k}:${m.id}`))}for(let m of B.channels){let M=u.chatProject===k&&u.channel===m.id;I.push(_jsxruntime.jsx.call(void 0, "li",{children:_jsxruntime.jsxs.call(void 0, "button",{type:"button","data-channel-id":m.id,"aria-current":M?"true":void 0,onClick:()=>l({chatProject:k,channel:m.id}),className:_chunk4Y233NIIjs.g.call(void 0, Ze,M?"bg-neutral-200 dark:bg-neutral-800":"bg-white hover:bg-neutral-50 dark:bg-neutral-900 dark:hover:bg-neutral-800"),children:[_jsxruntime.jsx.call(void 0, _lucidereact.Hash,{className:"mt-0.5 size-5 shrink-0 text-neutral-500 dark:text-neutral-400","aria-hidden":"true"}),_jsxruntime.jsxs.call(void 0, "span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[_jsxruntime.jsx.call(void 0, "span",{className:"truncate font-medium",children:m.name||r.channelFallbackTitle}),j&&_jsxruntime.jsx.call(void 0, "span",{className:"truncate text-xs text-neutral-500 dark:text-neutral-400",children:j}),_jsxruntime.jsx.call(void 0, "span",{className:"line-clamp-1 text-sm text-neutral-600 dark:text-neutral-300",children:m.topic||r.kindChannel}),m.memberCount>0&&_jsxruntime.jsx.call(void 0, "span",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:H(r.members,{count:m.memberCount})})]})]})},`c:${k}:${m.id}`))}for(let m of B.entitlements.packs){let M=`${k}:${m.productId}`,$=_optionalChain([R, 'access', _61 => _61.get, 'call', _62 => _62(m.productId), 'optionalAccess', _63 => _63.productName])||m.name||r.chatFallbackTitle;T.push(_jsxruntime.jsxs.call(void 0, "li",{className:"flex flex-col gap-2 rounded-xl bg-white p-3 dark:bg-neutral-900 sm:flex-row sm:items-center",children:[_jsxruntime.jsxs.call(void 0, "span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[_jsxruntime.jsx.call(void 0, "span",{className:"truncate font-medium",children:$}),_jsxruntime.jsx.call(void 0, "span",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:[ae(r,m.repliesLeftHint,c),m.expiresAt?H(r.expiresOn,{date:re(m.expiresAt,c)}):""].filter(Boolean).join(" \xB7 ")})]}),_jsxruntime.jsx.call(void 0, "button",{type:"button",disabled:h===M,"aria-busy":h===M||void 0,onClick:async()=>{let s=a.get(k);if(s){d(M),w(void 0);try{let o=await s.openThread(m.productId);l({chatProject:k,thread:o.id})}catch (e12){w(M)}finally{d(void 0)}}},className:"inline-flex min-h-11 shrink-0 items-center justify-center rounded-md bg-neutral-900 px-4 text-sm font-medium text-white hover:bg-neutral-800 disabled:opacity-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-500 dark:bg-white dark:text-neutral-900 dark:hover:bg-neutral-200",children:h===M?r.loading:r.startChat}),b===M&&_jsxruntime.jsx.call(void 0, "p",{role:"alert",className:"text-xs text-red-700 dark:text-red-400 sm:basis-full",children:r.errorGeneric})]},`p:${M}`))}let U=new Set(B.channels.map(m=>m.id));for(let m of B.entitlements.channels){if(m.channelId&&U.has(m.channelId))continue;let M=_optionalChain([R, 'access', _64 => _64.get, 'call', _65 => _65(m.productId), 'optionalAccess', _66 => _66.productName])||r.channelFallbackTitle;T.push(_jsxruntime.jsxs.call(void 0, "li",{className:"flex flex-col gap-2 rounded-xl bg-white p-3 dark:bg-neutral-900 sm:flex-row sm:items-center",children:[_jsxruntime.jsxs.call(void 0, "span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[_jsxruntime.jsx.call(void 0, "span",{className:"truncate font-medium",children:M}),!m.channelId&&_jsxruntime.jsx.call(void 0, "span",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:r.channelNotReady})]}),m.channelId&&_jsxruntime.jsx.call(void 0, "button",{type:"button",onClick:()=>l({chatProject:k,channel:m.channelId}),className:"inline-flex min-h-11 shrink-0 items-center justify-center rounded-md border border-neutral-300 px-4 text-sm font-medium hover:bg-neutral-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-500 dark:border-neutral-700 dark:hover:bg-neutral-800",children:r.openChannel})]},`e:${k}:${m.productId}`))}}return I.length===0&&T.length===0?_jsxruntime.jsx.call(void 0, "p",{"data-testid":"chat-inbox-empty",className:"text-sm text-neutral-600 dark:text-neutral-400",children:r.inboxEmpty}):_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-6","data-testid":"chat-inbox",children:[I.length>0&&_jsxruntime.jsx.call(void 0, "ul",{className:"flex flex-col gap-2",children:I}),T.length>0&&_jsxruntime.jsxs.call(void 0, "section",{className:"flex flex-col gap-2",children:[_jsxruntime.jsx.call(void 0, "h4",{className:"text-sm font-semibold text-neutral-700 dark:text-neutral-300",children:r.startSection}),_jsxruntime.jsx.call(void 0, "ul",{className:"flex flex-col gap-2",children:T})]})]})}exports.CHAT_TEXT_TABLES = Oe; exports.Channel = Re; exports.ChatError = W; exports.ChatThread = ze; exports.DEFAULT_CHAT_API_URL = ke; exports.DEFAULT_CHAT_REALTIME_URL = xe; exports.PanelMessages = Xe; exports.addPackToCart = te; exports.chatProjects = Je; exports.createChatClient = ne; exports.getChatTexts = ee; exports.parseRealtimeEvent = Ce; exports.startLive = Ie; exports.useConversation = ge;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } 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 _chunkZ3YOJ6NZjs = require('./chunk-Z3YOJ6NZ.js');var _chunkTM3E3L57js = require('./chunk-TM3E3L57.js');var _chunkMDAFPGPAjs = require('./chunk-MDAFPGPA.js');require('./chunk-EFN4OW2C.js');var _chunk6DEKVABTjs = require('./chunk-6DEKVABT.js');require('./chunk-EK3D44XW.js');require('./chunk-W3RGQYPD.js');var _chunkQ337IQNAjs = require('./chunk-Q337IQNA.js');require('./chunk-JSDGZ4NY.js');var _react = require('react');async function se(e){await _chunkTM3E3L57js.e.call(void 0, {id:e.productId,name:_nullishCoalesce(e.name, () => ("")),price:_nullishCoalesce(e.priceCents, () => (0)),currency:"",amount:e.amount},{projectID:e.projectID,host:e.host,showCart:!0})}var Ce="https://chat.bitsnap.pl",ve= exports.DEFAULT_CHAT_ATTACHMENTS_URL ="https://bitsnap.pl",Te= exports.DEFAULT_CHAT_REALTIME_URL ="wss://bitsnap-nats-queue-production.up.railway.app";var $=class extends Error{constructor(t,n,a={}){super(`chat: ${t} (${n})`),this.name="ChatError",this.code=t,this.status=n,this.data=a;let r=Number(a.retry_after);Number.isFinite(r)&&r>0&&(this.retryAfter=r)}};function ie(e){let t=(e.baseUrl||Ce).replace(/\/+$/,""),n=typeof window<"u"&&["localhost","127.0.0.1"].includes(window.location.hostname)?window.location.origin:void 0,a=(_nullishCoalesce(_nullishCoalesce(e.attachmentsUrl, () => (n)), () => (ve))).replace(/\/+$/,""),r=_nullishCoalesce(e.fetch, () => (((...u)=>fetch(...u))));async function c(u,i,g){let b;try{b=await r(t+i,{method:u,headers:{Authorization:`Bearer ${e.token}`,"X-Bitsnap-Project":e.projectId,...g===void 0?{}:{"Content-Type":"application/json"}},body:g===void 0?void 0:JSON.stringify(g)})}catch (e2){throw new $("network",0)}let k=null;try{let T=await b.text();k=T?JSON.parse(T):null}catch (e3){k=null}if(!b.ok){let T=K(k)?k:{},f=typeof T.error=="string"?T.error:"internal_error";throw new $(f,b.status,T)}return{status:b.status,json:k}}let v=encodeURIComponent,h;return{baseUrl:t,projectId:e.projectId,async me(){let{json:u}=await c("GET","/v1/me");return lt(u)},async openThread(u){let{json:i}=await c("POST","/v1/threads",{product_id:u});return De(i)},async messages(u,i={}){let g=new URLSearchParams;i.before&&g.set("before",i.before),i.limit&&g.set("limit",String(i.limit));let b=g.toString(),k=b?`?${b}`:"",{json:T}=await c("GET",`/v1/threads/${v(u)}/messages${k}`),f=K(T)?T:{};return{messages:ee(f.messages).map(pe),hasMore:f.has_more===!0}},async send(u,i){let{json:g}=await c("POST",`/v1/threads/${v(u)}/messages`,{body:i.body,...i.clientId?{client_id:i.clientId}:{},...i.attachment?{attachment_key:i.attachment.key,attachment_kind:i.attachment.kind,attachment_name:i.attachment.filename,attachment_size:i.attachment.size,attachment_content_type:i.attachment.contentType}:{}}),b=K(g)?g:{};return{message:pe(b.message),thread:Fe(b.thread)}},async uploadAttachment(u,i,g){let b=async(f,N)=>{let w=await r(`${a}/api/chat/attachments/${f}`,{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"X-Bitsnap-Project":e.projectId,"Content-Type":"application/json"},body:JSON.stringify(N)}),p={};try{p=await w.json()}catch (e4){}if(!w.ok)throw new $(typeof p.error=="string"?p.error:"request_failed",w.status,p);return p},k=await b("upload",{project_id:e.projectId,thread_id:u,filename:i.name,content_type:i.type,size:i.size});await new Promise((f,N)=>{let w=new XMLHttpRequest;w.open("PUT",k.uploadURL),w.setRequestHeader("Content-Type",i.type),w.upload.onprogress=p=>{p.lengthComputable&&g(Math.round(p.loaded/p.total*100))},w.onload=()=>w.status>=200&&w.status<300?f():N(new $("upload_failed",w.status)),w.onerror=()=>N(new $("network",0)),w.send(i)});let T=await b("complete",{project_id:e.projectId,thread_id:u,key:k.key,upload_ticket:k.uploadTicket,filename:i.name,content_type:i.type,size:i.size});return{key:T.key,kind:T.kind,filename:T.filename,size:T.size,contentType:T.content_type}},async attachmentURL(u,i){if(!i.attachmentKey)throw new $("invalid_attachment",400);let g=new URLSearchParams({project_id:e.projectId,thread_id:u,key:i.attachmentKey,filename:_nullishCoalesce(i.attachmentName, () => ("attachment")),size:String(_nullishCoalesce(i.attachmentSize, () => (0)))}),b=await r(`${a}/api/chat/attachments/read?${g}`,{headers:{Authorization:`Bearer ${e.token}`,"X-Bitsnap-Project":e.projectId}}),k={};try{k=await b.json()}catch (e5){}if(!b.ok||typeof k.url!="string")throw new $(typeof k.error=="string"?k.error:"request_failed",b.status,k);return k.url},async deleteMessage(u,i){await c("DELETE",`/v1/threads/${v(u)}/messages/${v(i)}`)},async mute(u,i){await c("POST",`/v1/threads/${v(u)}/mute`,{muted:i})},async report(u){await c("POST","/v1/reports",{thread_id:u.threadId,...u.messageId?{message_id:u.messageId}:{},reason:u.reason,...u.note?{note:u.note}:{}})},async markRead(u,i){await c("POST",`/v1/threads/${v(u)}/receipts`,{state:"read",message_id:i})},async realtimeToken(u={}){if(!u.fresh&&h&&Date.parse(h.expiresAt)-Date.now()>9e4)return h;let{json:i}=await c("POST","/v1/realtime/token"),g=K(i)?i:{};return h={jwt:B(g.jwt),expiresAt:B(g.expires_at),servers:ee(g.servers).filter(b=>typeof b=="string"),subjects:ee(g.subjects).filter(b=>typeof b=="string"),truncated:g.truncated===!0}}}}function Ne(e){if(!K(e)||typeof e.type!="string")return null;let t=B(e.id);switch(e.type){case"message.created":return{type:"message.created",message:pe(e)};case"message.rejected":return{type:"message.rejected",id:t,reason:B(e.reason)};case"message.deleted":case"message.pinned":case"message.unpinned":return{type:e.type,id:t};default:return null}}function K(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}function ee(e){return Array.isArray(e)?e:[]}function B(e){return typeof e=="string"?e:e==null?"":String(e)}function Y(e){let t=Number(e);return Number.isFinite(t)?t:0}function te(e){return typeof e=="string"&&e!==""?e:void 0}function Ie(e){return typeof e=="string"&&e!==""?e:null}function pe(e){let t=K(e)?e:{};return{id:B(t.id),threadId:B(t.thread_id),authorEmail:B(t.author_email),body:B(t.body),attachmentKey:te(t.attachment_key),attachmentKind:te(t.attachment_kind),attachmentName:te(t.attachment_name),attachmentSize:Y(t.attachment_size),attachmentContentType:te(t.attachment_content_type),createdAt:B(t.created_at),pinned:t.pinned===!0,deleted:t.deleted===!0,system:t.system===!0,...t.status==="pending"?{status:"pending"}:{}}}function st(e){let t=K(e)?e:{};return{orderId:B(t.order_id),productId:te(t.product_id),replies:Y(t.replies),used:Y(t.used),left:Y(t.left),expiresAt:Ie(t.expires_at),expired:t.expired===!0}}function Fe(e){let t=K(e)?e:{};return{id:B(t.id),kind:t.kind==="channel"?"channel":"pack",repliesTotal:Y(t.replies_total),repliesUsed:Y(t.replies_used),repliesLeft:Y(t.replies_left),expiresAt:Ie(t.expires_at),composerLocked:t.composer_locked===!0,responseHours:Y(t.response_hours)}}function De(e){let t=K(e)?e:{};return{...Fe(t),channelId:te(t.channel_id),title:B(t.title),lastMessage:K(t.last_message)?pe(t.last_message):void 0,unread:Y(t.unread),productId:te(t.product_id),blocked:t.blocked===!0,packs:ee(t.packs).map(st),muted:t.muted===!0}}function it(e){let t=K(e)?e:{};return{id:B(t.id),name:B(t.name),topic:B(t.topic),welcome:B(t.welcome),whoCanPost:t.who_can_post==="members"?"members":"creator",productId:B(t.product_id),role:B(t.role),memberCount:Y(t.member_count),createdAt:B(t.created_at),blockLinks:t.block_links===!0,blockMedia:t.block_media===!0,cooldownSeconds:Y(t.cooldown_seconds)}}function lt(e){let t=K(e)?e:{},n=K(t.entitlements)?t.entitlements:{};return{email:B(t.email),threads:ee(t.threads).map(De),entitlements:{packs:ee(n.packs).map(a=>{let r=K(a)?a:{};return{productId:B(r.product_id),name:B(r.name),repliesLeftHint:Y(r.replies_left_hint),expiresAt:Ie(r.expires_at)}}),channels:ee(n.channels).map(a=>{let r=K(a)?a:{};return{productId:B(r.product_id),channelId:te(r.channel_id)}})},channels:ee(t.channels).map(it)}}var _lucidereact = require('lucide-react');var $e={pl:{inboxHeading:"Wiadomo\u015Bci",inboxIntro:"Rozmowy z tw\xF3rcami i kana\u0142y, do kt\xF3rych nale\u017Cysz.",inboxEmpty:"Nie masz jeszcze rozm\xF3w. Po zakupie pakietu konsultacji lub dost\u0119pu do spo\u0142eczno\u015Bci rozmowa pojawi si\u0119 tutaj.",inboxError:"Nie uda\u0142o si\u0119 wczyta\u0107 wiadomo\u015Bci.",loading:"Wczytywanie\u2026",retry:"Spr\xF3buj ponownie",back:"Wr\xF3\u0107",selectConversation:"Wybierz rozmow\u0119 z listy.",kindChat:"Czat",kindChannel:"Kana\u0142",startSection:"Do rozpocz\u0119cia",startChat:"Rozpocznij rozmow\u0119",openChannel:"Otw\xF3rz kana\u0142",channelNotReady:"Tw\xF3rca jeszcze nie otworzy\u0142 tego kana\u0142u.",chatFallbackTitle:"Czat z tw\xF3rc\u0105",channelFallbackTitle:"Kana\u0142",repliesLeftOne:"Zosta\u0142a {count} odpowied\u017A",repliesLeftFew:"Zosta\u0142y {count} odpowiedzi",repliesLeftMany:"Zosta\u0142o {count} odpowiedzi",noRepliesLeft:"Brak odpowiedzi w pakiecie",expiresOn:"Wa\u017Cny do {date}",expiredOn:"Wygas\u0142 {date}",responseHours:"Odpowied\u017A w ci\u0105gu {hours} h",unread:"Nieprzeczytane: {count}",members:"Cz\u0142onkowie: {count}",mutedBadge:"Wyciszony",noMessagesYet:"Brak wiadomo\u015Bci",emptyThread:"Napisz pierwsz\u0105 wiadomo\u015B\u0107. Tw\xF3rca odpowie w ramach Twojego pakietu.",emptyChannel:"W kanale nie ma jeszcze wiadomo\u015Bci.",privacyNote:"Wiadomo\u015Bci czyta druga strona rozmowy. Bitsnap przechowuje je przez 90 dni.",loadOlder:"Wcze\u015Bniejsze wiadomo\u015Bci",newMessages:"Nowe wiadomo\u015Bci \u2193",blockedNotice:"Tw\xF3rca zablokowa\u0142 mo\u017Cliwo\u015B\u0107 wysy\u0142ania wiadomo\u015Bci w tej rozmowie.",addAttachment:"Dodaj za\u0142\u0105cznik",photo:"Zdj\u0119cie",file:"Plik",removeAttachment:"Usu\u0144 za\u0142\u0105cznik",uploading:"Wysy\u0142anie pliku",attachmentLoadFailed:"Nie uda\u0142o si\u0119 wczyta\u0107 \u2014 pon\xF3w",you:"Ty",creator:"Tw\xF3rca",systemLabel:"Wiadomo\u015B\u0107 automatyczna",pinned:"Przypi\u0119ta",deletedPlaceholder:"Wiadomo\u015B\u0107 zosta\u0142a usuni\u0119ta",attachment:"Za\u0142\u0105cznik",composerLabel:"Wiadomo\u015B\u0107",composerPlaceholder:"Napisz wiadomo\u015B\u0107\u2026",send:"Wy\u015Blij",composerExpired:"Pakiet wygas\u0142, wi\u0119c nie mo\u017Cesz ju\u017C pisa\u0107 w tej rozmowie.",composerCreatorOnly:"W tym kanale pisze tylko tw\xF3rca.",composerMuted:"Masz wyciszone pisanie w tym kanale.",composerReadOnly:"Ten dost\u0119p pozwala tylko czyta\u0107.",lockRepliesTitle:"Odpowiedzi w pakiecie si\u0119 sko\u0144czy\u0142y",lockRepliesBody:"Mo\u017Cesz dalej pisa\u0107, ale tw\xF3rca odpowie dopiero po zakupie kolejnego pakietu.",lockExpiredTitle:"Pakiet wygas\u0142",lockExpiredBody:"Rozmowa zostaje do wgl\u0105du. Kup nowy pakiet, aby j\u0105 kontynuowa\u0107.",lockThreadTitle:"Nie masz pakietu odpowiedzi",lockThreadBody:"Kup pakiet, aby napisa\u0107 do tw\xF3rcy.",lockChannelTitle:"Kana\u0142 dla cz\u0142onk\xF3w",lockChannelBody:"Kup dost\u0119p, aby czyta\u0107 i pisa\u0107 w tym kanale.",buyPack:"Kup pakiet",buyAccess:"Kup dost\u0119p",buying:"Dodawanie do koszyka\u2026",buyError:"Nie uda\u0142o si\u0119 doda\u0107 do koszyka. Spr\xF3buj ponownie.",pending:"Wysy\u0142anie\u2026",notConfirmed:"Czekamy na potwierdzenie wys\u0142ania",rejectedLink:"Linki s\u0105 w tym kanale zablokowane. Usu\u0144 link i wy\u015Blij ponownie.",rejectedBannedWord:"Wiadomo\u015B\u0107 zawiera s\u0142owo zablokowane w tym kanale. Popraw j\u0105 i wy\u015Blij ponownie.",rejectedMedia:"Za\u0142\u0105czniki s\u0105 w tym kanale zablokowane.",rejectedCooldown:"Piszesz za szybko. Spr\xF3buj ponownie za {seconds} s.",rejectedBlocked:"Tw\xF3rca zablokowa\u0142 Ci mo\u017Cliwo\u015B\u0107 pisania w tym sklepie.",rejectedMuted:"Masz wyciszone pisanie w tym kanale.",rejectedReadOnly:"Ten dost\u0119p pozwala tylko czyta\u0107.",rejectedPackEmpty:"Pakiet nie ma ju\u017C odpowiedzi.",rejectedForbidden:"Nie mo\u017Cesz pisa\u0107 w tej rozmowie.",rejectedGeneric:"Nie uda\u0142o si\u0119 wys\u0142a\u0107 wiadomo\u015Bci.",failedNetwork:"Brak po\u0142\u0105czenia. Wiadomo\u015B\u0107 nie zosta\u0142a wys\u0142ana.",editMessage:"Popraw",retrySend:"Wy\u015Blij ponownie",dismiss:"Odrzu\u0107",messageActions:"Opcje wiadomo\u015Bci",deleteMessage:"Usu\u0144 wiadomo\u015B\u0107",deleteConfirm:"Na pewno usun\u0105\u0107?",reportMessage:"Zg\u0142o\u015B wiadomo\u015B\u0107",conversationActions:"Opcje rozmowy",muteThread:"Wycisz powiadomienia",unmuteThread:"W\u0142\u0105cz powiadomienia",muteError:"Nie uda\u0142o si\u0119 zmieni\u0107 powiadomie\u0144.",reportConversation:"Zg\u0142o\u015B rozmow\u0119",reportTitle:"Zg\u0142o\u015B wiadomo\u015B\u0107",reportConversationTitle:"Zg\u0142o\u015B rozmow\u0119",reportReason:"Pow\xF3d zg\u0142oszenia",reasonSpam:"Spam",reasonAbuse:"N\u0119kanie lub obra\u017Aliwe tre\u015Bci",reasonIllegal:"Tre\u015Bci niezgodne z prawem",reasonOther:"Inny pow\xF3d",reportNote:"Opis (opcjonalnie)",reportSend:"Wy\u015Blij zg\u0142oszenie",reportCancel:"Anuluj",reportSent:"Dzi\u0119kujemy. Zg\u0142oszenie trafi\u0142o do moderacji.",reportError:"Nie uda\u0142o si\u0119 wys\u0142a\u0107 zg\u0142oszenia. Spr\xF3buj ponownie.",liveLabel:"Nowe wiadomo\u015Bci pojawiaj\u0105 si\u0119 na bie\u017C\u0105co",pollingLabel:"Nowe wiadomo\u015Bci od\u015Bwie\u017Caj\u0105 si\u0119 co kilka sekund",errorNoToken:"Zaloguj si\u0119 w panelu klienta, aby zobaczy\u0107 rozmow\u0119.",errorUnauthorized:"Sesja wygas\u0142a. Zaloguj si\u0119 ponownie.",errorPlan:"Czat nie jest dost\u0119pny w tym sklepie.",errorNotFound:"Nie znaleziono tej rozmowy.",errorUnavailable:"Czat jest chwilowo niedost\u0119pny. Spr\xF3buj za chwil\u0119.",errorGeneric:"Nie uda\u0142o si\u0119 wczyta\u0107 rozmowy."},en:{inboxHeading:"Messages",inboxIntro:"Your conversations with creators and the channels you belong to.",inboxEmpty:"No conversations yet. When you buy a consultation pack or community access, it shows up here.",inboxError:"Your messages could not be loaded.",loading:"Loading\u2026",retry:"Try again",back:"Back",selectConversation:"Pick a conversation from the list.",kindChat:"Chat",kindChannel:"Channel",startSection:"Ready to start",startChat:"Start the conversation",openChannel:"Open the channel",channelNotReady:"The creator has not opened this channel yet.",chatFallbackTitle:"Chat with the creator",channelFallbackTitle:"Channel",repliesLeftOne:"{count} reply left",repliesLeftFew:"{count} replies left",repliesLeftMany:"{count} replies left",noRepliesLeft:"No replies left in your pack",expiresOn:"Valid until {date}",expiredOn:"Expired on {date}",responseHours:"Replies within {hours} h",unread:"Unread: {count}",members:"Members: {count}",mutedBadge:"Muted",noMessagesYet:"No messages yet",emptyThread:"Write the first message. The creator replies within your pack.",emptyChannel:"There are no messages in this channel yet.",privacyNote:"The other side of the conversation reads your messages. Bitsnap keeps them for 90 days.",loadOlder:"Earlier messages",newMessages:"New messages \u2193",blockedNotice:"The creator has blocked you from sending messages in this conversation.",addAttachment:"Add attachment",photo:"Photo",file:"File",removeAttachment:"Remove attachment",uploading:"Uploading file",attachmentLoadFailed:"Could not load \u2014 retry",you:"You",creator:"Creator",systemLabel:"Automatic message",pinned:"Pinned",deletedPlaceholder:"This message was deleted",attachment:"Attachment",composerLabel:"Message",composerPlaceholder:"Write a message\u2026",send:"Send",composerExpired:"Your pack has expired, so you can no longer write here.",composerCreatorOnly:"Only the creator posts in this channel.",composerMuted:"You are muted in this channel.",composerReadOnly:"This access is read only.",lockRepliesTitle:"Your pack has no replies left",lockRepliesBody:"You can keep writing, but the creator can reply only after you buy another pack.",lockExpiredTitle:"Your pack has expired",lockExpiredBody:"You can still read the conversation. Buy a new pack to continue it.",lockThreadTitle:"You have no reply pack",lockThreadBody:"Buy a pack to write to the creator.",lockChannelTitle:"Members-only channel",lockChannelBody:"Buy access to read and post in this channel.",buyPack:"Buy a pack",buyAccess:"Buy access",buying:"Adding to cart\u2026",buyError:"Could not add it to the cart. Try again.",pending:"Sending\u2026",notConfirmed:"Waiting for the send to be confirmed",rejectedLink:"Links are blocked in this channel. Remove the link and send again.",rejectedBannedWord:"Your message contains a word blocked in this channel. Edit it and send again.",rejectedMedia:"Attachments are blocked in this channel.",rejectedCooldown:"You are posting too fast. Try again in {seconds} s.",rejectedBlocked:"The creator has blocked you from posting in this shop.",rejectedMuted:"You are muted in this channel.",rejectedReadOnly:"This access is read only.",rejectedPackEmpty:"The pack has no replies left.",rejectedForbidden:"You cannot post in this conversation.",rejectedGeneric:"Your message could not be sent.",failedNetwork:"No connection. Your message was not sent.",editMessage:"Edit",retrySend:"Send again",dismiss:"Discard",messageActions:"Message options",deleteMessage:"Delete message",deleteConfirm:"Delete for sure?",reportMessage:"Report message",conversationActions:"Conversation options",muteThread:"Mute notifications",unmuteThread:"Unmute notifications",muteError:"Notifications could not be changed.",reportConversation:"Report conversation",reportTitle:"Report message",reportConversationTitle:"Report conversation",reportReason:"Reason",reasonSpam:"Spam",reasonAbuse:"Harassment or abusive content",reasonIllegal:"Illegal content",reasonOther:"Something else",reportNote:"Details (optional)",reportSend:"Send report",reportCancel:"Cancel",reportSent:"Thank you. Your report went to moderation.",reportError:"Your report could not be sent. Try again.",liveLabel:"New messages appear live",pollingLabel:"New messages refresh every few seconds",errorNoToken:"Log in to the customer panel to see this conversation.",errorUnauthorized:"Your session has expired. Log in again.",errorPlan:"Chat is not available in this shop.",errorNotFound:"This conversation was not found.",errorUnavailable:"Chat is unavailable right now. Try again in a moment.",errorGeneric:"The conversation could not be loaded."}};function re(e,t=_chunkQ337IQNAjs.f.call(void 0, )){return _chunkQ337IQNAjs.b.call(void 0, $e,t,e)}function G(e,t){return e.replace(/\{(\w+)\}/g,(n,a)=>a in t?String(t[a]):n)}function le(e,t,n=_chunkQ337IQNAjs.f.call(void 0, )){if(t<=0)return e.noRepliesLeft;let a="other";try{a=new Intl.PluralRules(n).select(t)}catch (e6){}let r=a==="one"?e.repliesLeftOne:a==="few"?e.repliesLeftFew:e.repliesLeftMany;return G(r,{count:t})}function de(e,t=_chunkQ337IQNAjs.f.call(void 0, )){let n=new Date(e);return Number.isNaN(n.getTime())?"":new Intl.DateTimeFormat(t,{day:"numeric",month:"numeric",year:"numeric"}).format(n)}function he(e,t=_chunkQ337IQNAjs.f.call(void 0, ),n=new Date){let a=new Date(e);if(Number.isNaN(a.getTime()))return"";let r=a.toDateString()===n.toDateString();return new Intl.DateTimeFormat(t,r?{hour:"2-digit",minute:"2-digit"}:{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}).format(a)}function He(e,t,n){switch(t){case"moderation_link":return e.rejectedLink;case"moderation_banned_word":return e.rejectedBannedWord;case"moderation_media":return e.rejectedMedia;case"cooldown":return G(e.rejectedCooldown,{seconds:_nullishCoalesce(n, () => (30))});case"blocked":return e.rejectedBlocked;case"muted":return e.rejectedMuted;case"read_only":return e.rejectedReadOnly;case"pack_empty":case"replies_exhausted":return e.rejectedPackEmpty;case"forbidden":case"locked":return e.rejectedForbidden;case"network":case"unavailable":return e.failedNetwork;default:return e.rejectedGeneric}}var _jsxruntime = require('react/jsx-runtime');var Me="focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-500";function We(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Ze(e=0){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function je(e,t){typeof e.scrollTo=="function"?e.scrollTo({top:e.scrollHeight,behavior:t?"smooth":"auto"}):e.scrollTop=e.scrollHeight}var Z=_chunk6DEKVABTjs.g.call(void 0, "inline-flex min-h-11 items-center gap-2 rounded-md px-3 text-sm text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800",Me),ge=_chunk6DEKVABTjs.g.call(void 0, "inline-flex min-h-11 items-center justify-center gap-2 rounded-md bg-neutral-900 px-4 text-sm font-medium text-white hover:bg-neutral-800 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white dark:text-neutral-900 dark:hover:bg-neutral-200",Me);function Pe({host:e,conversation:t,texts:n,locale:a,kind:r,title:c,onBack:v,onBuy:h,className:u}){let[i,g]=_react.useState.call(void 0, !1),[b,k]=_react.useState.call(void 0, null),[T,f]=_react.useState.call(void 0, ),[N,w]=_react.useState.call(void 0, ""),[p,y]=_react.useState.call(void 0, !1);_react.useEffect.call(void 0, ()=>{if(!p)return;let j=setTimeout(()=>y(!1),6e3);return()=>clearTimeout(j)},[p]);let L=c||_optionalChain([t, 'access', _2 => _2.channel, 'optionalAccess', _3 => _3.name])||(r==="channel"?n.channelFallbackTitle:n.chatFallbackTitle),A=bt(t,n,a);return _jsxruntime.jsxs.call(void 0, "section",{"data-bitsnap-chat":r,"aria-label":L,className:_chunk6DEKVABTjs.g.call(void 0, "flex h-full min-h-[28rem] w-full min-w-0 flex-col overflow-hidden rounded-xl border border-neutral-200 bg-white text-neutral-900 dark:border-neutral-800 dark:bg-neutral-900 dark:text-neutral-50",u),children:[_jsxruntime.jsxs.call(void 0, "header",{className:"flex items-start gap-2 border-b border-neutral-200 px-3 py-2 dark:border-neutral-800",children:[v&&_jsxruntime.jsx.call(void 0, "button",{type:"button",onClick:v,"aria-label":n.back,className:_chunk6DEKVABTjs.g.call(void 0, Z,"w-11 justify-center px-0"),children:_jsxruntime.jsx.call(void 0, _lucidereact.ArrowLeft,{className:"size-5","aria-hidden":"true"})}),_jsxruntime.jsxs.call(void 0, "div",{className:"min-w-0 flex-1 py-1.5",children:[_jsxruntime.jsxs.call(void 0, "h2",{className:"flex items-center gap-2 text-base font-semibold",children:[_jsxruntime.jsx.call(void 0, "span",{className:"truncate",children:L}),_jsxruntime.jsx.call(void 0, kt,{live:t.live,texts:n})]}),A.length>0&&_jsxruntime.jsx.call(void 0, "p",{className:"mt-0.5 flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-neutral-600 dark:text-neutral-400",children:A.map(j=>_jsxruntime.jsx.call(void 0, "span",{children:j},j))})]}),t.status==="ready"&&_jsxruntime.jsx.call(void 0, "button",{type:"button","aria-label":n.conversationActions,"aria-expanded":i,onClick:()=>g(j=>!j),className:_chunk6DEKVABTjs.g.call(void 0, Z,"w-11 justify-center px-0"),children:_jsxruntime.jsx.call(void 0, _lucidereact.MoreHorizontal,{className:"size-5","aria-hidden":"true"})})]}),i&&t.status==="ready"&&_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap gap-1 border-b border-neutral-200 bg-neutral-50 px-3 py-1 dark:border-neutral-800 dark:bg-neutral-950",children:[r==="thread"&&t.thread&&_jsxruntime.jsx.call(void 0, "button",{type:"button",className:Z,onClick:async()=>{g(!1);try{await t.setMuted(!t.thread.muted),f(void 0)}catch (e7){f(n.muteError)}},children:t.thread.muted?n.unmuteThread:n.muteThread}),_jsxruntime.jsx.call(void 0, "button",{type:"button",className:Z,onClick:()=>{g(!1),k({})},children:n.reportConversation})]}),t.status==="loading"&&_jsxruntime.jsx.call(void 0, wt,{texts:n}),t.status==="error"&&_jsxruntime.jsx.call(void 0, Ct,{conversation:t,texts:n}),t.status==="locked"&&t.lock&&_jsxruntime.jsx.call(void 0, "div",{className:"flex flex-1 flex-col justify-center overflow-y-auto p-4",children:_jsxruntime.jsx.call(void 0, Ke,{host:e,lock:t.lock,kind:r,texts:n,locale:a,onBuy:h,prominent:!0})}),t.status==="ready"&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, Tt,{conversation:t,texts:n,locale:a,kind:r,onReport:j=>k({messageId:j}),onEdit:j=>{w(j.body),t.discard(j.id)}}),T&&_jsxruntime.jsx.call(void 0, "p",{role:"status",className:"px-4 pb-2 text-xs text-red-700 dark:text-red-400",children:T}),t.lock&&_jsxruntime.jsx.call(void 0, "div",{className:"border-t border-neutral-200 p-3 dark:border-neutral-800",children:_jsxruntime.jsx.call(void 0, Ke,{host:e,lock:t.lock,kind:r,texts:n,locale:a,onBuy:h})}),b?_jsxruntime.jsx.call(void 0, Pt,{texts:n,messageId:b.messageId,onCancel:()=>k(null),onSubmit:async(j,x)=>{await t.report({messageId:b.messageId,reason:j,note:x}),k(null),f(void 0),y(!0)}}):_jsxruntime.jsx.call(void 0, jt,{conversation:t,texts:n,kind:r,draft:N,setDraft:w})]}),p&&_jsxruntime.jsx.call(void 0, "p",{role:"status",className:"border-t border-neutral-200 px-4 py-2 text-xs text-neutral-700 dark:border-neutral-800 dark:text-neutral-300",children:n.reportSent})]})}function bt(e,t,n){let a=[];if(e.thread&&e.thread.kind==="pack"){if(a.push(le(t,e.thread.repliesLeft,n)),e.thread.expiresAt){let r=de(e.thread.expiresAt,n);a.push(G(e.thread.composerLocked?t.expiredOn:t.expiresOn,{date:r}))}e.thread.responseHours>0&&a.push(G(t.responseHours,{hours:e.thread.responseHours})),e.thread.muted&&a.push(t.mutedBadge)}return e.channel&&(e.channel.topic&&a.push(e.channel.topic),e.channel.memberCount>0&&a.push(G(t.members,{count:e.channel.memberCount}))),a}function kt({live:e,texts:t}){if(e!=="live"&&e!=="polling")return null;let n=e==="live"?t.liveLabel:t.pollingLabel;return _jsxruntime.jsx.call(void 0, "span",{title:n,"data-live":e,className:_chunk6DEKVABTjs.g.call(void 0, "inline-block size-2 shrink-0 rounded-full",e==="live"?"bg-emerald-500":"bg-neutral-400 dark:bg-neutral-500"),children:_jsxruntime.jsx.call(void 0, "span",{className:"sr-only",children:n})})}function wt({texts:e}){return _jsxruntime.jsx.call(void 0, "div",{role:"status","aria-busy":"true","aria-label":e.loading,className:"flex flex-1 flex-col gap-3 p-4",children:[60,40,70].map((t,n)=>_jsxruntime.jsx.call(void 0, "div",{"aria-hidden":"true",style:{width:`${t}%`},className:_chunk6DEKVABTjs.g.call(void 0, "h-10 rounded-2xl bg-neutral-100 motion-safe:animate-pulse dark:bg-neutral-800",n===1&&"self-end")},n))})}function xt(e,t){switch(e){case"no_token":return t.errorNoToken;case"unauthorized":return t.errorUnauthorized;case"plan_required":return t.errorPlan;case"not_found":return t.errorNotFound;case"unavailable":case"network":return t.errorUnavailable;default:return t.errorGeneric}}function Ct({conversation:e,texts:t}){let n=_nullishCoalesce(_optionalChain([e, 'access', _4 => _4.error, 'optionalAccess', _5 => _5.code]), () => ("")),a=n!=="no_token"&&n!=="plan_required"&&n!=="unauthorized";return _jsxruntime.jsxs.call(void 0, "div",{role:"alert",className:"flex flex-1 flex-col items-start justify-center gap-3 p-4",children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-700 dark:text-neutral-300",children:xt(n,t)}),a&&_jsxruntime.jsx.call(void 0, "button",{type:"button",className:ge,onClick:e.reload,children:t.retry})]})}function Ke({host:e,lock:t,kind:n,texts:a,locale:r,onBuy:c,prominent:v}){let[h,u]=_react.useState.call(void 0, !1),[i,g]=_react.useState.call(void 0, ""),[b,k]=_react.useState.call(void 0, String((_nullishCoalesce(t.priceCents, () => (0)))/100)),T=b.trim().replace(",","."),f=/^\d+(\.\d{0,2})?$/.test(T)?Math.round(Number(T)*100):NaN,N=t.priceType==="pay_what_you_want",w=_nullishCoalesce(t.minimumCents, () => (0)),p=_nullishCoalesce(t.maximumCents, () => (Number.MAX_SAFE_INTEGER)),y=Number.isInteger(f)&&f>=w&&f<=p&&(f>0||t.freeClaimLimit!=null),L=t.freeClaimLimit!=null&&(t.priceType==="free"||N&&w===0&&f===0),[A,j]=_react.useState.call(void 0, ""),[x,d]=_react.useState.call(void 0, ""),[R,_]=_react.useState.call(void 0, !1),[P,s]=_react.useState.call(void 0, null),[l,m]=_react.useState.call(void 0, 0),[C,O]=_react.useState.call(void 0, 0),D=_react.useRef.call(void 0, null);_react.useEffect.call(void 0, ()=>{R&&_optionalChain([D, 'access', _6 => _6.current, 'optionalAccess', _7 => _7.focus, 'call', _8 => _8()])},[R]),_react.useEffect.call(void 0, ()=>{if(C<=0)return;let q=window.setTimeout(()=>O(C-1),1e3);return()=>window.clearTimeout(q)},[C]);let H=()=>{_(!1),d(""),s(null),m(q=>q+1),g("")},F=r.toLowerCase().startsWith("en"),[E,J]=t.reason==="replies"?[a.lockRepliesTitle,a.lockRepliesBody]:t.reason==="expired"?[a.lockExpiredTitle,a.lockExpiredBody]:n==="channel"?[a.lockChannelTitle,a.lockChannelBody]:[a.lockThreadTitle,a.lockThreadBody],ne=n==="channel"?a.buyAccess:a.buyPack,U=c!=null&&t.productId!=null;return _jsxruntime.jsxs.call(void 0, "div",{"data-testid":"chat-lock","data-lock":t.reason,className:_chunk6DEKVABTjs.g.call(void 0, "flex gap-3 rounded-xl bg-neutral-100 p-3 dark:bg-neutral-800",v?"flex-col items-start p-5":"flex-col sm:flex-row sm:items-center"),children:[_jsxruntime.jsx.call(void 0, _lucidereact.Lock,{className:_chunk6DEKVABTjs.g.call(void 0, "shrink-0 text-neutral-500 dark:text-neutral-400",v?"size-6":"hidden size-5 sm:block"),"aria-hidden":"true"}),_jsxruntime.jsxs.call(void 0, "div",{className:"min-w-0 flex-1",children:[_jsxruntime.jsx.call(void 0, "p",{className:_chunk6DEKVABTjs.g.call(void 0, "font-semibold",v?"text-lg":"text-sm"),children:E}),_jsxruntime.jsx.call(void 0, "p",{className:"mt-0.5 text-sm text-neutral-600 dark:text-neutral-300",children:J}),L&&_jsxruntime.jsxs.call(void 0, "div",{className:"mt-3 grid max-w-sm gap-2",children:[_jsxruntime.jsxs.call(void 0, "label",{className:"grid gap-1 text-sm",children:[_jsxruntime.jsx.call(void 0, "span",{children:F?"Email":"E-mail"}),_jsxruntime.jsx.call(void 0, "input",{type:"email",autoComplete:"email",value:A,onChange:q=>{j(q.currentTarget.value),H()},disabled:h,className:"h-11 rounded-md border border-neutral-300 bg-white px-3 text-neutral-900 dark:border-neutral-700 dark:bg-neutral-950 dark:text-neutral-50"})]}),R?_jsxruntime.jsxs.call(void 0, "label",{className:"grid gap-1 text-sm",children:[_jsxruntime.jsx.call(void 0, "span",{children:F?"Email code":"Kod z\xA0e-maila"}),_jsxruntime.jsx.call(void 0, "input",{ref:D,inputMode:"numeric",autoComplete:"one-time-code",value:x,onChange:q=>d(q.currentTarget.value),className:"h-11 rounded-md border border-neutral-300 bg-white px-3 text-neutral-900 dark:border-neutral-700 dark:bg-neutral-950 dark:text-neutral-50"})]}):A.includes("@")?_jsxruntime.jsx.call(void 0, _chunkZ3YOJ6NZjs.a,{host:e,action:"free_chat_claim",locale:r,onToken:s,onFailure:()=>s(null)},l):null,R&&_jsxruntime.jsxs.call(void 0, "button",{type:"button",disabled:h||C>0,className:"min-h-11 text-sm underline disabled:opacity-50",onClick:H,children:[F?"Request a new code":"Popro\u015B o\xA0nowy kod",C>0?` (${C}s)`:""]})]}),N&&_jsxruntime.jsxs.call(void 0, "label",{className:"mt-3 grid max-w-xs gap-1 text-sm",children:[_jsxruntime.jsx.call(void 0, "span",{children:F?`Amount (${(w/100).toFixed(2)}\u2013${Number.isFinite(p)?(p/100).toFixed(2):"\u221E"} PLN)`:`Kwota (${(w/100).toFixed(2)}\u2013${Number.isFinite(p)?(p/100).toFixed(2):"\u221E"} z\u0142)`}),_jsxruntime.jsx.call(void 0, "input",{"aria-label":F?"Amount":"Kwota",inputMode:"decimal",type:"text",min:w/100,max:Number.isFinite(p)?p/100:void 0,step:"0.01",value:b,onChange:q=>k(q.currentTarget.value),onBlur:()=>{Number.isFinite(f)&&k((f/100).toFixed(2))},className:"h-11 rounded-md border border-neutral-300 bg-white px-3 text-neutral-900 dark:border-neutral-700 dark:bg-neutral-950 dark:text-neutral-50"}),!y&&_jsxruntime.jsx.call(void 0, "span",{role:"alert",className:"text-xs text-red-700 dark:text-red-400",children:F?f===0&&t.freeClaimLimit==null?"Free claims are unavailable. Enter a positive amount.":"Enter an amount within the range.":f===0&&t.freeClaimLimit==null?"Darmowy odbi\xF3r jest niedost\u0119pny. Wpisz kwot\u0119 wi\u0119ksz\u0105 od zera.":"Kwota musi mie\u015Bci\u0107 si\u0119 w\xA0podanym zakresie."})]}),t.welcome&&_jsxruntime.jsx.call(void 0, "p",{className:"mt-3 whitespace-pre-wrap text-sm",children:t.welcome}),i&&_jsxruntime.jsx.call(void 0, "p",{role:"alert",className:"mt-2 text-sm text-red-700 dark:text-red-400",children:i})]}),U&&_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunk6DEKVABTjs.g.call(void 0, ge,"shrink-0"),disabled:h||N&&!y||L&&(!A.includes("@")||!R&&P===null||R&&!x),"aria-busy":h||void 0,onClick:async()=>{u(!0),g("");try{L?(await c({...t,...N?{amount:f}:{},email:A,...R?{code:x}:{turnstileToken:P}}),R||(_(!0),O(60))):await c({...t,...N?{amount:f}:{}})}catch(q){g(zt(q,r,a.buyError)),R||(s(null),m(ot=>ot+1))}finally{u(!1)}},children:h?a.buying:N?F?"Choose what you pay":"Kup pakiet, p\u0142ac\u0105c, ile chcesz":L?R?F?"Claim for free":"Odbierz za darmo":F?"Send code":"Wy\u015Blij kod":ne})]})}function vt(e,t,n,a){return t?a.you:n==="thread"?a.creator:e.authorEmail.split("@")[0]||a.creator}function Tt({conversation:e,texts:t,locale:n,kind:a,onReport:r,onEdit:c}){let v=_react.useRef.call(void 0, null),h=_react.useRef.call(void 0, !0),u=_react.useRef.call(void 0, !1),i=_react.useRef.call(void 0, null),g=_react.useRef.call(void 0, null),[b,k]=_react.useState.call(void 0, ()=>new Set),[T,f]=_react.useState.call(void 0, !1),N=e.messages.length,w=_optionalChain([e, 'access', _9 => _9.messages, 'access', _10 => _10[N-1], 'optionalAccess', _11 => _11.id]);return _react.useEffect.call(void 0, ()=>{if(e.status!=="ready")return;let p=new Set(e.messages.map(x=>x.id)),y=i.current;i.current=p;let L=e.messages.reduce((x,d)=>x==null||d.createdAt<x?d.createdAt:x,null),A=g.current;if(g.current=L,!y)return;let j=e.messages.filter(x=>!y.has(x.id)&&(A==null||x.createdAt>=A));!j.length||e.loadingOlder||(k(x=>new Set([...x,...j.map(d=>d.id)])),h.current?f(!1):f(!0))},[e.messages,e.loadingOlder]),_react.useLayoutEffect.call(void 0, ()=>{let p=v.current;if(p){if(h.current){let y=We();je(p,!y&&u.current)}u.current=!0}},[N,w]),_jsxruntime.jsxs.call(void 0, "div",{className:"relative flex min-h-0 flex-1 flex-col",children:[T&&_jsxruntime.jsx.call(void 0, "button",{type:"button",onClick:()=>{let p=v.current;p&&je(p,!We()),h.current=!0,f(!1)},className:"absolute bottom-3 left-1/2 z-10 -translate-x-1/2 rounded-full bg-neutral-900 px-3 py-1.5 text-xs font-medium text-white shadow-md dark:bg-neutral-100 dark:text-neutral-900",children:_nullishCoalesce(t.newMessages, () => ("Nowe wiadomo\u015Bci \u2193"))}),_jsxruntime.jsxs.call(void 0, "div",{ref:v,role:"log","aria-live":"polite","aria-relevant":"additions",onLoadCapture:()=>{let p=v.current;p&&h.current&&je(p,!1)},onScroll:p=>{let y=p.currentTarget;h.current=y.scrollHeight-y.scrollTop-y.clientHeight<80},className:"flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto overscroll-contain px-3 py-4 sm:px-4",children:[e.hasMore&&_jsxruntime.jsx.call(void 0, "button",{type:"button",onClick:()=>{h.current=!1,e.loadOlder()},disabled:e.loadingOlder,className:_chunk6DEKVABTjs.g.call(void 0, Z,"self-center text-xs"),children:e.loadingOlder?t.loading:t.loadOlder}),N===0&&_jsxruntime.jsxs.call(void 0, "div",{className:"m-auto max-w-sm text-center","data-testid":"chat-empty",children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm font-medium",children:t.noMessagesYet}),_jsxruntime.jsx.call(void 0, "p",{className:"mt-1 text-sm text-neutral-600 dark:text-neutral-400",children:a==="channel"?t.emptyChannel:t.emptyThread}),_optionalChain([e, 'access', _12 => _12.channel, 'optionalAccess', _13 => _13.welcome])&&_jsxruntime.jsx.call(void 0, "p",{className:"mt-3 whitespace-pre-wrap text-sm",children:e.channel.welcome})]}),e.messages.map(p=>_jsxruntime.jsx.call(void 0, Nt,{message:p,mine:p.authorEmail.toLowerCase()===e.me,kind:a,texts:t,locale:n,getAttachmentURL:e.getAttachmentURL,animateEntry:b.has(p.id),onDelete:()=>e.deleteMessage(p.id),onReport:()=>r(p.id),onRetry:()=>void e.retry(p.id),onDiscard:()=>e.discard(p.id),onEdit:()=>c(p)},p.id))]})]})}function Nt({message:e,mine:t,kind:n,texts:a,locale:r,getAttachmentURL:c,animateEntry:v=!1,onDelete:h,onReport:u,onRetry:i,onDiscard:g,onEdit:b}){let[k,T]=_react.useState.call(void 0, !1),[f,N]=_react.useState.call(void 0, !1),[w,p]=_react.useState.call(void 0, ),[y,L]=_react.useState.call(void 0, !1),[A,j]=_react.useState.call(void 0, 0),x=_react.useRef.call(void 0, 0),d=()=>{p(void 0),L(!1),j(m=>m+1)},R=async m=>{if(w&&Date.now()<x.current)return;m.preventDefault();let C=window.open("about:blank","_blank");C&&(C.opener=null);try{let O=await c(e);x.current=Date.now()+5e4,p(O),C&&(C.location.href=O)}catch (e8){_optionalChain([C, 'optionalAccess', _14 => _14.close, 'call', _15 => _15()]),L(!0)}},_=e.local;if(_react.useEffect.call(void 0, ()=>{if(!e.attachmentKey||e.deleted||e.local)return;let m=!1;return L(!1),c(e).then(C=>{m||(x.current=Date.now()+5e4,p(C))}).catch(()=>{m||L(!0)}),()=>{m=!0}},[e.attachmentKey,e.deleted,!!e.local,c,A]),e.system)return _jsxruntime.jsxs.call(void 0, "div",{"data-message-id":e.id,className:"mx-auto max-w-md text-center text-xs text-neutral-600 dark:text-neutral-400",children:[_jsxruntime.jsx.call(void 0, "span",{className:"font-medium",children:a.systemLabel}),e.body&&_jsxruntime.jsx.call(void 0, "p",{className:"mt-0.5 whitespace-pre-wrap",children:e.body})]});let P=_optionalChain([_, 'optionalAccess', _16 => _16.state])==="rejected"||_optionalChain([_, 'optionalAccess', _17 => _17.state])==="failed",s=_optionalChain([_, 'optionalAccess', _18 => _18.state])==="pending"||_optionalChain([_, 'optionalAccess', _19 => _19.state])==="unconfirmed",l=!_&&!e.deleted;return _jsxruntime.jsxs.call(void 0, "div",{"data-message-id":e.id,"data-state":_nullishCoalesce(_optionalChain([_, 'optionalAccess', _20 => _20.state]), () => ((e.deleted?"deleted":"stored"))),className:_chunk6DEKVABTjs.g.call(void 0, "group flex max-w-[85%] flex-col gap-1 sm:max-w-[75%]",v&&"motion-safe:animate-[bitsnap-chat-message-enter_190ms_ease-out]",t?"items-end self-end":"items-start self-start"),children:[_jsxruntime.jsxs.call(void 0, "div",{className:_chunk6DEKVABTjs.g.call(void 0, "flex items-end gap-1",t&&"flex-row-reverse"),children:[_jsxruntime.jsx.call(void 0, "div",{className:_chunk6DEKVABTjs.g.call(void 0, "min-w-0 rounded-2xl px-3.5 py-2 text-sm leading-relaxed transition-opacity duration-200 ease-out motion-reduce:transition-none",e.deleted?"border border-dashed border-neutral-300 bg-transparent italic text-neutral-500 dark:border-neutral-700 dark:text-neutral-400":t?"bg-neutral-900 text-white dark:bg-neutral-100 dark:text-neutral-900":"bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50",s&&"opacity-70",P&&"border border-red-600 dark:border-red-400"),children:e.deleted?a.deletedPlaceholder:_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, "p",{className:"whitespace-pre-wrap break-words",children:e.body}),!e.deleted&&e.attachmentName&&(e.attachmentKind==="image"?y?_jsxruntime.jsx.call(void 0, "button",{type:"button",onClick:d,className:"mt-2 text-xs underline",children:a.attachmentLoadFailed}):w?_jsxruntime.jsx.call(void 0, "a",{href:w,onClick:R,target:"_blank",rel:"noreferrer",children:_jsxruntime.jsx.call(void 0, "img",{src:w,onError:()=>{Date.now()>=x.current?d():(p(void 0),L(!0))},alt:e.attachmentName,className:"mt-2 max-h-48 rounded-lg object-cover"})}):_jsxruntime.jsx.call(void 0, "div",{role:"status","aria-label":a.loading,className:"mt-2 h-32 w-48 animate-pulse rounded-lg bg-current/10 motion-reduce:animate-none"}):_jsxruntime.jsxs.call(void 0, "a",{href:_nullishCoalesce(w, () => ("#")),onClick:R,download:e.attachmentName,className:"mt-2 flex max-w-56 items-center gap-2 rounded-lg border border-neutral-300/60 px-2 py-1.5 text-xs dark:border-neutral-700",children:[_jsxruntime.jsx.call(void 0, _lucidereact.Paperclip,{className:"size-3.5 shrink-0","aria-hidden":"true"}),_jsxruntime.jsx.call(void 0, "span",{className:"min-w-0 flex-1 truncate",children:e.attachmentName}),_jsxruntime.jsx.call(void 0, "span",{children:Ze(e.attachmentSize)})]})),y&&e.attachmentKind!=="image"&&_jsxruntime.jsx.call(void 0, "button",{type:"button",onClick:d,className:"mt-1 text-xs underline",children:a.attachmentLoadFailed}),e.attachmentName&&_optionalChain([_, 'optionalAccess', _21 => _21.state])==="pending"&&_.uploadProgress!=null&&_jsxruntime.jsxs.call(void 0, "p",{className:"mt-1 text-[11px] opacity-75",children:[a.uploading," ",_.uploadProgress,"%"]})]})}),l&&_jsxruntime.jsx.call(void 0, "button",{type:"button","aria-label":a.messageActions,"aria-expanded":k,onClick:()=>{T(m=>!m),N(!1)},className:_chunk6DEKVABTjs.g.call(void 0, "inline-flex size-11 shrink-0 items-center justify-center rounded-md text-neutral-500 opacity-100 hover:bg-neutral-100 sm:opacity-0 sm:group-hover:opacity-100 sm:focus-visible:opacity-100 dark:text-neutral-400 dark:hover:bg-neutral-800",k&&"sm:opacity-100",Me),children:_jsxruntime.jsx.call(void 0, _lucidereact.MoreHorizontal,{className:"size-4","aria-hidden":"true"})})]}),_jsxruntime.jsxs.call(void 0, "p",{className:"flex items-center gap-1.5 px-1 text-[11px] text-neutral-500 dark:text-neutral-400",children:[e.pinned&&_jsxruntime.jsxs.call(void 0, "span",{className:"inline-flex items-center gap-0.5",children:[_jsxruntime.jsx.call(void 0, _lucidereact.Pin,{className:"size-3","aria-hidden":"true"}),a.pinned]}),_jsxruntime.jsx.call(void 0, "span",{children:vt(e,t,n,a)}),_jsxruntime.jsx.call(void 0, "span",{"aria-hidden":"true",children:"\xB7"}),s?_jsxruntime.jsxs.call(void 0, "span",{className:"inline-flex items-center gap-1",children:[_jsxruntime.jsx.call(void 0, _lucidereact.Clock,{className:"size-3","aria-hidden":"true"}),_optionalChain([_, 'optionalAccess', _22 => _22.state])==="pending"?a.pending:a.notConfirmed]}):_jsxruntime.jsx.call(void 0, "time",{dateTime:e.createdAt,children:he(e.createdAt,r)})]}),P&&_jsxruntime.jsxs.call(void 0, "div",{role:"alert",className:_chunk6DEKVABTjs.g.call(void 0, "flex flex-col gap-1",t?"items-end":"items-start"),children:[_jsxruntime.jsxs.call(void 0, "p",{className:"flex items-start gap-1 text-xs text-red-700 dark:text-red-400",children:[_jsxruntime.jsx.call(void 0, _lucidereact.AlertCircle,{className:"mt-px size-3.5 shrink-0","aria-hidden":"true"}),He(a,_nullishCoalesce(_optionalChain([_, 'optionalAccess', _23 => _23.reason]), () => ("")),_optionalChain([_, 'optionalAccess', _24 => _24.retryAfter]))]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap gap-1",children:[_optionalChain([_, 'optionalAccess', _25 => _25.state])==="failed"||_optionalChain([_, 'optionalAccess', _26 => _26.reason])==="cooldown"?_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunk6DEKVABTjs.g.call(void 0, Z,"text-xs"),onClick:i,children:a.retrySend}):_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunk6DEKVABTjs.g.call(void 0, Z,"text-xs"),onClick:b,children:a.editMessage}),_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunk6DEKVABTjs.g.call(void 0, Z,"text-xs"),onClick:g,children:a.dismiss})]})]}),k&&l&&_jsxruntime.jsx.call(void 0, "div",{className:"flex flex-wrap gap-1",children:t?_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunk6DEKVABTjs.g.call(void 0, Z,"text-xs text-red-700 dark:text-red-400"),onClick:async()=>{if(!f){N(!0);return}T(!1),await h().catch(()=>{})},children:f?a.deleteConfirm:a.deleteMessage}):_jsxruntime.jsx.call(void 0, "button",{type:"button",className:_chunk6DEKVABTjs.g.call(void 0, Z,"text-xs"),onClick:()=>{T(!1),u()},children:a.reportMessage})})]})}function It(e,t,n){if(t==="thread"&&_optionalChain([e, 'access', _27 => _27.thread, 'optionalAccess', _28 => _28.blocked]))return n.blockedNotice;if(t==="thread"&&_optionalChain([e, 'access', _29 => _29.thread, 'optionalAccess', _30 => _30.composerLocked]))return n.composerExpired;if(t==="channel"&&e.channel){if(e.channel.role==="muted")return n.composerMuted;if(e.channel.whoCanPost==="creator"&&e.channel.role!=="creator")return n.composerCreatorOnly}}function jt({conversation:e,texts:t,kind:n,draft:a,setDraft:r}){let c=_react.useId.call(void 0, ),v=_react.useRef.call(void 0, null),h=_react.useRef.call(void 0, null),u=_react.useRef.call(void 0, null),[i,g]=_react.useState.call(void 0, ),[b,k]=_react.useState.call(void 0, !1),[T,f]=_react.useState.call(void 0, !1),[N,w]=_react.useState.call(void 0, ".pdf,.zip,.txt,.docx,.xlsx"),p=It(e,n,t);_react.useEffect.call(void 0, ()=>()=>{u.current&&clearTimeout(u.current)},[]);let y=x=>{u.current&&clearTimeout(u.current),u.current=null,k(!1),g(x)},L=()=>{!i||b||(k(!0),u.current=setTimeout(()=>{g(void 0),k(!1),u.current=null},140))};if(_react.useLayoutEffect.call(void 0, ()=>{let x=v.current;x&&(x.style.height="auto",x.style.height=`${Math.min(x.scrollHeight,160)}px`)},[a]),p)return _jsxruntime.jsx.call(void 0, "p",{"data-testid":"chat-composer-blocked",className:"border-t border-neutral-200 px-4 py-3 text-sm text-neutral-600 dark:border-neutral-800 dark:text-neutral-400",children:p});let A=x=>{_optionalChain([x, 'optionalAccess', _31 => _31.preventDefault, 'call', _32 => _32()]);let d=a.trim();!d&&!i||(r(""),g(void 0),e.send(d,i),requestAnimationFrame(()=>_optionalChain([v, 'access', _33 => _33.current, 'optionalAccess', _34 => _34.focus, 'call', _35 => _35()])))},j=x=>{x.key==="Enter"&&!x.shiftKey&&!x.nativeEvent.isComposing&&(x.preventDefault(),A())};return _jsxruntime.jsxs.call(void 0, "form",{onSubmit:A,className:"border-t border-neutral-200 px-3 pb-3 pt-2 dark:border-neutral-800",children:[e.messages.length===0&&_jsxruntime.jsx.call(void 0, "p",{className:"pb-2 text-xs text-neutral-500 dark:text-neutral-400",children:t.privacyNote}),i&&_jsxruntime.jsxs.call(void 0, "div",{className:_chunk6DEKVABTjs.g.call(void 0, "mb-2 flex max-w-sm items-center gap-2 rounded-lg border border-neutral-300 bg-neutral-50 px-3 py-2 text-xs text-neutral-800 dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-100",b?"chat-preview-exit":"chat-preview-enter"),children:[_jsxruntime.jsx.call(void 0, "span",{className:"min-w-0 flex-1 truncate",children:i.name}),_jsxruntime.jsx.call(void 0, "span",{className:"text-neutral-500 dark:text-neutral-400",children:Ze(i.size)}),_jsxruntime.jsx.call(void 0, "button",{type:"button","aria-label":t.removeAttachment,onClick:L,disabled:b,className:"rounded p-1 hover:bg-neutral-200 disabled:cursor-default dark:hover:bg-neutral-800",children:_jsxruntime.jsx.call(void 0, _lucidereact.X,{className:"size-3.5"})})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex items-end gap-2",children:[_jsxruntime.jsxs.call(void 0, "div",{className:"relative",children:[_jsxruntime.jsx.call(void 0, "button",{type:"button","aria-label":t.addAttachment,"aria-expanded":T,onClick:()=>f(x=>!x),className:_chunk6DEKVABTjs.g.call(void 0, Z,"h-11 w-11 justify-center px-0 transition-transform duration-150 motion-safe:active:scale-95 motion-reduce:transition-none"),children:_jsxruntime.jsx.call(void 0, _lucidereact.Plus,{className:"size-5","aria-hidden":"true"})}),T&&_jsxruntime.jsxs.call(void 0, "div",{role:"menu",className:"absolute bottom-full left-0 z-20 mb-2 min-w-36 rounded-lg border border-neutral-200 bg-white p-1 shadow-lg dark:border-neutral-700 dark:bg-neutral-900",children:[_jsxruntime.jsx.call(void 0, "button",{type:"button",role:"menuitem",className:"block w-full rounded px-3 py-2 text-left text-sm hover:bg-neutral-100 dark:hover:bg-neutral-800",onClick:()=>{w("image/jpeg,image/png,image/webp,image/gif"),h.current&&(h.current.accept="image/jpeg,image/png,image/webp,image/gif",h.current.click()),f(!1)},children:t.photo}),_jsxruntime.jsx.call(void 0, "button",{type:"button",role:"menuitem",className:"block w-full rounded px-3 py-2 text-left text-sm hover:bg-neutral-100 dark:hover:bg-neutral-800",onClick:()=>{w(".pdf,.zip,.txt,.docx,.xlsx"),h.current&&(h.current.accept=".pdf,.zip,.txt,.docx,.xlsx",h.current.click()),f(!1)},children:t.file})]}),_jsxruntime.jsx.call(void 0, "input",{ref:h,hidden:!0,type:"file",accept:N,onChange:x=>{let d=_optionalChain([x, 'access', _36 => _36.target, 'access', _37 => _37.files, 'optionalAccess', _38 => _38[0]]);d&&y(d),x.currentTarget.value=""}})]}),_jsxruntime.jsx.call(void 0, "label",{htmlFor:c,className:"sr-only",children:t.composerLabel}),_jsxruntime.jsx.call(void 0, "textarea",{id:c,ref:v,rows:1,value:a,onChange:x=>r(x.target.value),onKeyDown:j,placeholder:t.composerPlaceholder,className:"max-h-40 min-h-11 flex-1 resize-none rounded-xl border border-neutral-300 bg-white px-3 py-2.5 text-sm text-neutral-900 placeholder:text-neutral-500 focus-visible:border-neutral-500 focus-visible:outline-none dark:border-neutral-700 dark:bg-neutral-950 dark:text-neutral-50 dark:placeholder:text-neutral-400"}),_jsxruntime.jsx.call(void 0, "button",{type:"submit","aria-label":t.send,disabled:a.trim().length===0&&!i,className:_chunk6DEKVABTjs.g.call(void 0, ge,"w-11 px-0 transition-[transform,opacity] duration-150 ease-out motion-safe:active:scale-95 disabled:scale-100 motion-reduce:transition-none"),children:_jsxruntime.jsx.call(void 0, _lucidereact.SendHorizontal,{className:"size-5","aria-hidden":"true"})})]})]})}var Mt=["spam","abuse","illegal","other"];function Pt({texts:e,messageId:t,onCancel:n,onSubmit:a}){let[r,c]=_react.useState.call(void 0, "spam"),[v,h]=_react.useState.call(void 0, ""),[u,i]=_react.useState.call(void 0, !1),[g,b]=_react.useState.call(void 0, !1),k=_react.useId.call(void 0, ),T={spam:e.reasonSpam,abuse:e.reasonAbuse,illegal:e.reasonIllegal,other:e.reasonOther};return _jsxruntime.jsxs.call(void 0, "form",{"data-testid":"chat-report",className:"flex flex-col gap-3 border-t border-neutral-200 p-4 dark:border-neutral-800",onSubmit:async f=>{f.preventDefault(),i(!0),b(!1);try{await a(r,v.trim())}catch (e9){b(!0)}finally{i(!1)}},children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm font-semibold",children:t?e.reportTitle:e.reportConversationTitle}),_jsxruntime.jsxs.call(void 0, "fieldset",{className:"flex flex-col gap-1",children:[_jsxruntime.jsx.call(void 0, "legend",{className:"mb-1 text-xs text-neutral-600 dark:text-neutral-400",children:e.reportReason}),Mt.map(f=>_jsxruntime.jsxs.call(void 0, "label",{className:"flex min-h-9 items-center gap-2 text-sm",children:[_jsxruntime.jsx.call(void 0, "input",{type:"radio",name:"chat-report-reason",value:f,checked:r===f,onChange:()=>c(f),className:"size-4 accent-neutral-900 dark:accent-white"}),T[f]]},f))]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-1",children:[_jsxruntime.jsx.call(void 0, "label",{htmlFor:k,className:"text-xs text-neutral-600 dark:text-neutral-400",children:e.reportNote}),_jsxruntime.jsx.call(void 0, "textarea",{id:k,rows:2,maxLength:1e3,value:v,onChange:f=>h(f.target.value),className:"resize-none rounded-xl border border-neutral-300 bg-white px-3 py-2 text-sm focus-visible:border-neutral-500 focus-visible:outline-none dark:border-neutral-700 dark:bg-neutral-950"})]}),g&&_jsxruntime.jsx.call(void 0, "p",{role:"alert",className:"text-sm text-red-700 dark:text-red-400",children:e.reportError}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap justify-end gap-2",children:[_jsxruntime.jsx.call(void 0, "button",{type:"button",className:Z,onClick:n,children:e.reportCancel}),_jsxruntime.jsx.call(void 0, "button",{type:"submit",className:ge,disabled:u,"aria-busy":u||void 0,children:e.reportSend})]})]})}function zt(e,t,n){let a=e instanceof Error?e.message:"",r=t.toLowerCase().startsWith("en");return_nullishCoalesce(_optionalChain([{"amount-below-minimum":["Kwota jest ni\u017Csza od minimalnej.","The amount is below the minimum."],"amount-above-maximum":["Kwota przekracza maksymaln\u0105.","The amount is above the maximum."],"amount-below-gateway-minimum":["Kwota jest za niska dla dost\u0119pnych p\u0142atno\u015Bci.","The amount is too low for available payment methods."],"amount-invalid":["Podaj prawid\u0142ow\u0105 kwot\u0119.","Enter a valid amount."],"email-verification-required":["Potwierd\u017A adres e-mail, aby odebra\u0107 pakiet.","Verify your email to claim this pack."],"free-claim-exists":["Ten adres e-mail wykorzysta\u0142 ju\u017C limit darmowych odbior\xF3w.","This email has reached the free claim limit."],"free-order-not-supported":["Nie mo\u017Cna zrealizowa\u0107 tego darmowego zam\xF3wienia.","This free order cannot be completed."],"captcha-required":["Potwierd\u017A, \u017Ce nie jeste\u015B robotem.","Complete the security check."],"captcha-invalid":["Weryfikacja wygas\u0142a. Spr\xF3buj ponownie.","The security check expired. Try again."],"rate-limited":["Zbyt wiele pr\xF3b. Spr\xF3buj ponownie za chwil\u0119.","Too many attempts. Try again shortly."],"incorrect-code":["Nieprawid\u0142owy kod. Sprawd\u017A wiadomo\u015B\u0107 i\xA0spr\xF3buj ponownie.","The code is incorrect. Check your email and try again."],"too-many-attempts":["Popro\u015B o\xA0nowy kod za kilka minut.","Request a new code in a few minutes."],unavailable:["Weryfikacja jest chwilowo niedost\u0119pna.","Verification is temporarily unavailable."]}, 'access', _39 => _39[a], 'optionalAccess', _40 => _40[r?1:0]]), () => (n))}var Lt=()=>Promise.resolve().then(() => _interopRequireWildcard(require("@nats-io/nats-core")));function ze(e){let t=_nullishCoalesce(e.pollIntervalMs, () => (8e3)),n=_nullishCoalesce(e.retryMs, () => (6e4)),a=_nullishCoalesce(e.loadNats, () => (Lt)),r=`.${e.kind}.${e.id}`,c=!1,v,h="",u,i,g,b=()=>{u!=null&&clearInterval(u),u=void 0},k=()=>{c||(e.onMode("polling"),u==null&&(u=setInterval(()=>{e.poll().catch(()=>{})},t)),i==null&&(i=setTimeout(()=>{i=void 0,f()},n)))},T=N=>{g!=null&&clearTimeout(g);let w=Date.parse(N);if(!Number.isFinite(w))return;let p=Math.max(5e3,w-Date.now()-6e4);g=setTimeout(async()=>{if(!c)try{let y=await e.client.realtimeToken({fresh:!0});h=y.jwt,T(y.expiresAt)}catch (e10){}},p)};async function f(){if(!c){if(typeof WebSocket>"u"){k();return}e.onMode("connecting");try{let N=await e.client.realtimeToken(),w=N.subjects.find(j=>j.endsWith(r));if(w||(N=await e.client.realtimeToken({fresh:!0}),w=N.subjects.find(j=>j.endsWith(r))),!w||!N.jwt)throw new Error("subject not granted");h=N.jwt;let p=await a();if(c)return;let y=e.realtimeUrl?[e.realtimeUrl]:N.servers.length>0?N.servers:[Te],L=await p.wsconnect({servers:y,authenticator:p.jwtAuthenticator(()=>h),name:"bitsnap-react/chat",reconnect:!0,maxReconnectAttempts:5});if(c){L.close().catch(()=>{});return}v=L;let A=new TextDecoder;L.subscribe(w,{callback:(j,x)=>{if(!j)try{let d=Ne(JSON.parse(A.decode(x.data)));d&&e.onEvent(d)}catch (e11){}}}),L.closed().then(()=>{v===L&&(v=void 0,k())}),T(N.expiresAt),b(),e.onMode("live"),e.poll().catch(()=>{})}catch (e12){k()}}}return f(),()=>{c=!0,b(),i!=null&&clearTimeout(i),g!=null&&clearTimeout(g);let N=v;v=void 0,N&&N.close().catch(()=>{})}}var Le=50,ae={status:"loading",messages:[],hasMore:!1,loadingOlder:!1,live:"off"};function Rt(){let e=globalThis.crypto;if(e&&typeof e.randomUUID=="function")return e.randomUUID();let t=new Uint8Array(16);if(e&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let a=0;a<16;a++)t[a]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=Array.from(t,a=>a.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function ce(e,t){let n=new Map(e.map(a=>[a.id,a]));for(let a of t){let r=n.get(a.id);if(a.status==="pending"){if(r&&!r.local)continue;n.set(a.id,{...a,retryFile:_optionalChain([r, 'optionalAccess', _41 => _41.retryFile]),local:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _42 => _42.local]), () => ({state:"pending"}))});continue}_optionalChain([r, 'optionalAccess', _43 => _43.local])&&r.local.state!=="pending"&&r.local.state!=="unconfirmed"||n.set(a.id,{...a,local:void 0})}return[...n.values()].sort((a,r)=>{let c=Date.parse(a.createdAt)||0,v=Date.parse(r.createdAt)||0;return c-v})}function Re(e){if(e.kind==="pack"){if(e.composerLocked)return{reason:"expired",productId:e.productId};if(e.repliesLeft<=0)return{reason:"replies",productId:e.productId}}}function Xe(e,t,n){let a=Number(e.data.price_cents);return{reason:t,productId:typeof e.data.product_id=="string"&&e.data.product_id?e.data.product_id:n,priceCents:Number.isFinite(a)&&a>0?a:void 0,priceType:e.data.price_type==="free"||e.data.price_type==="pay_what_you_want"?e.data.price_type:"one_time",minimumCents:Number.isFinite(Number(e.data.price_min_cents))?Number(e.data.price_min_cents):void 0,maximumCents:Number.isFinite(Number(e.data.price_max_cents))?Number(e.data.price_max_cents):void 0,freeClaimLimit:Number.isFinite(Number(e.data.free_claim_limit))?Number(e.data.free_claim_limit):void 0,welcome:typeof e.data.welcome=="string"?e.data.welcome:void 0}}function be(e){return e instanceof $?e:new $("internal_error",0)}function ke(e){let{client:t,target:n}=e,[a,r]=_react.useState.call(void 0, ae),[c,v]=_react.useState.call(void 0, 0),h=_react.useRef.call(void 0, a);h.current=a;let u=_react.useRef.call(void 0, new Set),i=_react.useRef.call(void 0, void 0),g=_react.useRef.call(void 0, void 0),b=n.kind==="thread"?`t:${_nullishCoalesce(n.threadId, () => (""))}:${_nullishCoalesce(n.productId, () => (""))}`:`c:${n.channelId}:${_nullishCoalesce(n.productId, () => (""))}`;_react.useEffect.call(void 0, ()=>{let s=!1;if(g.current=void 0,r(ae),t!==null){if(!t){r({...ae,status:"error",error:new $("no_token",401)});return}return(async()=>{try{let l=await t.me(),m=l.email.toLowerCase(),C,O,D;if(n.kind==="thread"){if(C=n.threadId?l.threads.find(F=>F.id===n.threadId):l.threads.find(F=>F.productId===n.productId),!C&&n.productId)try{C=await t.openThread(n.productId)}catch(F){let E=be(F);if(E.code==="locked"||E.status===404){s||r({...ae,status:"locked",me:m,lock:Xe(E,"no-pack",n.productId)});return}throw E}if(!C)throw new $("not_found",404);D=C.id}else O=l.channels.find(F=>F.id===n.channelId),D=n.channelId;let H;try{H=await t.messages(D,{limit:Le})}catch(F){let E=be(F);if(E.code==="locked"){s||r({...ae,status:"locked",me:m,thread:C,channel:O,threadId:D,lock:Xe(E,n.kind==="channel"?"no-access":"no-pack",_nullishCoalesce(_nullishCoalesce(n.productId, () => (_optionalChain([O, 'optionalAccess', _44 => _44.productId]))), () => (_optionalChain([C, 'optionalAccess', _45 => _45.productId]))))});return}throw E}if(s)return;r({...ae,status:"ready",me:m,thread:C,channel:O,threadId:D,lock:C?Re(C):void 0,messages:ce([],H.messages),hasMore:H.hasMore})}catch(l){s||r({...ae,status:"error",error:be(l)})}})(),()=>{s=!0}}},[t,b,c]);let k=_react.useCallback.call(void 0, ()=>{t&&(i.current&&clearTimeout(i.current),i.current=setTimeout(async()=>{try{let s=await t.me();r(l=>{if(l.status!=="ready")return l;let m=l.thread&&s.threads.find(O=>O.id===l.thread.id),C=l.channel&&s.channels.find(O=>O.id===l.channel.id);return{...l,thread:_nullishCoalesce(m, () => (l.thread)),channel:_nullishCoalesce(C, () => (l.channel)),lock:m?Re(m):l.lock}})}catch (e13){}},1500))},[t]),T=_react.useCallback.call(void 0, async()=>{let{threadId:s}=h.current;if(!t||!s)return;let l=await t.messages(s,{limit:Le});r(m=>m.threadId===s?{...m,messages:ce(m.messages,l.messages)}:m)},[t]),f=_react.useCallback.call(void 0, s=>{r(l=>{switch(s.type){case"message.created":return{...l,messages:ce(l.messages,[s.message])};case"message.rejected":return{...l,messages:l.messages.map(m=>m.id===s.id?{...m,local:{state:"rejected",reason:s.reason||"rejected"}}:m)};case"message.deleted":return{...l,messages:l.messages.map(m=>m.id===s.id?{...m,deleted:!0,body:"",attachmentKey:void 0}:m)};case"message.pinned":case"message.unpinned":return{...l,messages:l.messages.map(m=>m.id===s.id?{...m,pinned:s.type==="message.pinned"}:m)}}}),s.type==="message.created"&&!s.message.system&&s.message.authorEmail.toLowerCase()!==h.current.me&&k()},[k]),w=a.status==="ready"?a.threadId:void 0;_react.useEffect.call(void 0, ()=>{if(!t||!w)return;let s=ze({client:t,kind:n.kind,id:w,onEvent:f,onMode:l=>r(m=>({...m,live:l})),poll:T,pollIntervalMs:e.pollIntervalMs,realtimeUrl:e.realtimeUrl,loadNats:e.loadNats});return()=>{s(),r(l=>({...l,live:"off"}))}},[t,w,f,T]),_react.useEffect.call(void 0, ()=>{if(!t||!a.threadId||a.status!=="ready")return;let s=[...a.messages].reverse().find(l=>!l.local&&l.authorEmail.toLowerCase()!==a.me);!s||g.current===s.id||(g.current=s.id,t.markRead(a.threadId,s.id).catch(()=>{}))},[t,a.threadId,a.status,a.messages,a.me]),_react.useEffect.call(void 0, ()=>()=>{for(let s of u.current)clearTimeout(s);i.current&&clearTimeout(i.current)},[]);let p=(s,l)=>r(m=>({...m,messages:m.messages.map(C=>C.id===s?l(C):C)})),y=_react.useCallback.call(void 0, async(s,l,m)=>{let C=s.trim(),{threadId:O,me:D}=h.current;if(!t||!O||!C&&!l)return;let H=_nullishCoalesce(m, () => (Rt())),F={id:H,threadId:O,authorEmail:_nullishCoalesce(D, () => ("")),body:C,retryFile:l,...l?{attachmentName:l.name,attachmentSize:l.size,attachmentContentType:l.type,attachmentKind:l.type.startsWith("image/")?"image":"file"}:{},createdAt:new Date().toISOString(),pinned:!1,deleted:!1,system:!1,status:"pending",local:{state:"pending"}};r(E=>({...E,messages:[...E.messages,F]}));try{let E=l?await t.uploadAttachment(O,l,U=>p(H,q=>({...q,local:{...q.local,state:"pending",uploadProgress:U}}))):void 0;E&&p(H,U=>({...U,attachmentKey:E.key,attachmentKind:E.kind,attachmentName:E.filename,attachmentSize:E.size,attachmentContentType:E.contentType,local:{state:"pending"}}));let J=await t.send(O,{body:C,clientId:H,...E?{attachment:E}:{}});r(U=>({...U,messages:ce(U.messages,[{...J.message,id:H}]),thread:U.thread?{...U.thread,...J.thread,id:U.thread.id}:U.thread,lock:U.thread?Re({...U.thread,...J.thread,id:U.thread.id}):U.lock}));let ne=setTimeout(()=>{u.current.delete(ne),p(H,U=>_optionalChain([U, 'access', _46 => _46.local, 'optionalAccess', _47 => _47.state])==="pending"?{...U,local:{state:"unconfirmed"}}:U)},_nullishCoalesce(e.confirmTimeoutMs, () => (45e3)));u.current.add(ne)}catch(E){let J=be(E),ne=J.code==="network"||J.code==="unavailable"||J.status>=500;p(H,U=>({...U,local:{state:ne?"failed":"rejected",reason:J.code,retryAfter:J.retryAfter,keepId:ne||m!=null}}))}},[t,e.confirmTimeoutMs]),L=_react.useCallback.call(void 0, s=>{r(l=>({...l,messages:l.messages.filter(m=>m.id!==s)}))},[]),A=_react.useCallback.call(void 0, async s=>{let l=h.current.messages.find(C=>C.id===s);if(!l)return;let m=_optionalChain([l, 'access', _48 => _48.local, 'optionalAccess', _49 => _49.state])!=="rejected"||l.local.keepId===!0;L(s),await y(l.body,l.retryFile,m?s:void 0)},[L,y]),j=_react.useCallback.call(void 0, async s=>{let{threadId:l}=h.current,m=h.current.messages.find(C=>C.id===s);if(!(!t||!l||!m)){p(s,C=>({...C,deleted:!0,body:"",attachmentKey:void 0}));try{await t.deleteMessage(l,s)}catch(C){throw p(s,()=>m),C}}},[t]),x=_react.useCallback.call(void 0, async s=>{let l=h.current.threadId;if(!t||!l)throw new $("not_found",404);return t.attachmentURL(l,s)},[t]),d=_react.useCallback.call(void 0, async s=>{let{threadId:l}=h.current;!t||!l||await t.report({threadId:l,...s})},[t]),R=_react.useCallback.call(void 0, async s=>{let{threadId:l}=h.current;!t||!l||(await t.mute(l,s),r(m=>m.thread?{...m,thread:{...m.thread,muted:s}}:m))},[t]),_=_react.useCallback.call(void 0, async()=>{let{threadId:s,messages:l,hasMore:m,loadingOlder:C}=h.current,O=l.find(D=>!D.local);if(!(!t||!s||!m||C||!O)){r(D=>({...D,loadingOlder:!0}));try{let D=await t.messages(s,{before:O.id,limit:Le});r(H=>({...H,loadingOlder:!1,hasMore:D.hasMore,messages:ce(H.messages,D.messages)}))}catch (e14){r(D=>({...D,loadingOlder:!1}))}}},[t]),P=_react.useCallback.call(void 0, ()=>v(s=>s+1),[]);return{...a,send:y,retry:A,getAttachmentURL:x,discard:L,deleteMessage:j,report:d,setMuted:R,loadOlder:_,reload:P}}function Qe(e){let[t,n]=_react.useState.call(void 0, null),a=_nullishCoalesce(e.host, () => (_chunkMDAFPGPAjs.b.call(void 0, ).host));_react.useEffect.call(void 0, ()=>{e.client||e.token||n(_chunkMDAFPGPAjs.i.call(void 0, e.projectID,a))},[e.client,e.token,e.projectID,a]);let r=_nullishCoalesce(e.token, () => (t)),c=_nullishCoalesce(e.chatProjectID, () => (e.projectID));return _react.useMemo.call(void 0, ()=>{if(e.client)return e.client;if(r===null)return null;if(r)return ie({projectId:c,token:r,baseUrl:e.apiUrl,attachmentsUrl:e.attachmentsUrl})},[e.client,r,c,e.apiUrl,e.attachmentsUrl])}function et(e){let t=_react.useRef.call(void 0, null);return async n=>{let a=_nullishCoalesce(e.buyProductId, () => (n.productId));if(!a)return;let r={productId:a,reason:n.reason,priceCents:n.priceCents,...n.amount!=null?{amount:n.amount}:{},...n.email?{email:n.email}:{},...n.code?{code:n.code}:{},...n.turnstileToken!=null?{turnstileToken:n.turnstileToken}:{}};if(e.onBuy){await e.onBuy(r);return}let c=(_nullishCoalesce(_nullishCoalesce(e.host, () => (_chunkMDAFPGPAjs.b.call(void 0, ).host)), () => ("https://bitsnap.pl"))).replace(/\/+$/,""),v=n.freeClaimLimit!=null&&(n.priceType==="free"||n.priceType==="pay_what_you_want"&&n.minimumCents===0&&r.amount===0);if(v&&r.email&&r.turnstileToken!=null){t.current=null;let h=await fetch(`${c}/api/integrations/${encodeURIComponent(e.projectID)}/public-commerce/free-claim/request-code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:r.email,turnstileToken:r.turnstileToken})}),u=await h.json();if(!h.ok)throw new Error(_nullishCoalesce(u.code, () => ("internal")));return}if(v&&r.email&&r.code){let h=JSON.stringify([c,e.projectID,a,r.email,r.code]);if(!t.current||t.current.key!==h||t.current.expires<=Date.now()){t.current=null;let g=await fetch(`${c}/api/integrations/${encodeURIComponent(e.projectID)}/public-commerce/free-claim/verify-code`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:r.email,code:r.code})}),b=await g.json();if(!g.ok||!b.claimToken)throw new Error(_nullishCoalesce(b.code, () => ("email-verification-required")));t.current={key:h,token:b.claimToken,expires:Date.now()+(_nullishCoalesce(b.expiresIn, () => (600)))*1e3}}let u=await fetch(`${c}/api/integrations/${encodeURIComponent(e.projectID)}/public-commerce/buy`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({items:[{id:a,quantity:1,amount:0}],details:{email:r.email},claimToken:t.current.token})}),i=await u.json();if(!u.ok||!i.url)throw new Error(_nullishCoalesce(i.code, () => ("free-order-not-supported")));window.location.assign(i.url);return}await se({projectID:e.projectID,productId:a,name:e.title,priceCents:n.priceCents,amount:n.amount,host:e.host})}}function _e(e){let t=Qe(e),n=_nullishCoalesce(e.locale, () => (_chunkQ337IQNAjs.f.call(void 0, ))),a=_react.useMemo.call(void 0, ()=>re(e.texts,n),[e.texts,n]),r=ke({client:t,target:{kind:"thread",threadId:e.threadId,productId:e.productId},pollIntervalMs:e.pollIntervalMs,realtimeUrl:e.realtimeUrl,loadNats:e.loadNats}),c=et(e);return _jsxruntime.jsx.call(void 0, "div",{className:"bitsnap-react h-full",children:_jsxruntime.jsx.call(void 0, Pe,{host:e.host,conversation:r,texts:a,locale:n,kind:"thread",title:e.title,onBack:e.onBack,onBuy:c,className:e.className})})}function Ae(e){let t=Qe(e),n=_nullishCoalesce(e.locale, () => (_chunkQ337IQNAjs.f.call(void 0, ))),a=_react.useMemo.call(void 0, ()=>re(e.texts,n),[e.texts,n]),r=ke({client:t,target:{kind:"channel",channelId:e.channelId,productId:e.productId},pollIntervalMs:e.pollIntervalMs,realtimeUrl:e.realtimeUrl,loadNats:e.loadNats}),c=et(e);return _jsxruntime.jsx.call(void 0, "div",{className:"bitsnap-react h-full",children:_jsxruntime.jsx.call(void 0, Pe,{host:e.host,conversation:r,texts:a,locale:n,kind:"channel",title:e.title,onBack:e.onBack,onBuy:c,className:e.className})})}var Dt=_react.lazy.call(void 0, ()=>Promise.resolve().then(() => _interopRequireWildcard(require("./BitsnapCart-TWT7LVGJ.js")))),nt=e=>e.productType===5||e.productType===6;function at(e,t){let n=[...new Set(e.filter(nt).map(a=>a.projectId).filter(Boolean))];return n.length>0?n:t?[t]:[]}function $t(e){let t=new Map;for(let n of e)nt(n)&&n.projectId&&n.chatProjectId&&t.set(n.projectId,n.chatProjectId);return t}function rt({accessToken:e,products:t,chatApiUrl:n,projectID:a,host:r,selection:c,onSelect:v,locale:h=_chunkQ337IQNAjs.f.call(void 0, ),texts:u}){let i=_react.useMemo.call(void 0, ()=>re(u,h),[u,h]),g=_react.useMemo.call(void 0, ()=>at(t,a),[t,a]),b=_react.useMemo.call(void 0, ()=>$t(t),[t]),k=_react.useMemo.call(void 0, ()=>{let P=new Map;for(let s of g)P.set(s,ie({projectId:_nullishCoalesce(b.get(s), () => (s)),token:e,baseUrl:n}));return P},[g,b,e,n]),[T,f]=_react.useState.call(void 0, {}),[N,w]=_react.useState.call(void 0, 0),p=`${_nullishCoalesce(c.chatProject, () => (""))}:${_nullishCoalesce(c.thread, () => (""))}:${_nullishCoalesce(c.channel, () => (""))}`;_react.useEffect.call(void 0, ()=>{let P=!1;for(let[s,l]of k)f(m=>_optionalChain([m, 'access', _50 => _50[s], 'optionalAccess', _51 => _51.status])==="ready"?m:{...m,[s]:{status:"loading"}}),l.me().then(m=>!P&&f(C=>({...C,[s]:{status:"ready",me:m}})),m=>!P&&f(C=>({...C,[s]:{status:"error",error:m instanceof $?m:new $("internal_error",0)}})));return()=>{P=!0}},[k,N,p]);let y=_react.useMemo.call(void 0, ()=>{let P=new Map;for(let s of t)P.set(s.productId,s);return P},[t]),[L,A]=_react.useState.call(void 0, ),j=P=>async s=>{A(P),await se({projectID:P,productId:s.productId,name:_optionalChain([y, 'access', _52 => _52.get, 'call', _53 => _53(s.productId), 'optionalAccess', _54 => _54.productName]),priceCents:s.priceCents,host:r})},x=c.chatProject?k.get(c.chatProject):void 0,d=!!(x&&(c.thread||c.channel)),R=()=>v({}),_=null;if(d&&x&&c.chatProject){let P=c.chatProject,s=T[P],l=_optionalChain([s, 'optionalAccess', _55 => _55.status])==="ready"?s.me:void 0;if(c.thread){let m=_optionalChain([l, 'optionalAccess', _56 => _56.threads, 'access', _57 => _57.find, 'call', _58 => _58(C=>C.id===c.thread)]);_=_jsxruntime.jsx.call(void 0, _e,{projectID:P,client:x,threadId:c.thread,title:_optionalChain([m, 'optionalAccess', _59 => _59.productId])&&_optionalChain([y, 'access', _60 => _60.get, 'call', _61 => _61(m.productId), 'optionalAccess', _62 => _62.productName])||void 0,locale:h,texts:u,onBack:R,onBuy:j(P)},`t:${P}:${c.thread}`)}else if(c.channel){let m=_optionalChain([l, 'optionalAccess', _63 => _63.entitlements, 'access', _64 => _64.channels, 'access', _65 => _65.find, 'call', _66 => _66(C=>C.channelId===c.channel)]);_=_jsxruntime.jsx.call(void 0, Ae,{projectID:P,client:x,channelId:c.channel,productId:_optionalChain([m, 'optionalAccess', _67 => _67.productId]),locale:h,texts:u,onBack:R,onBuy:j(P)},`c:${P}:${c.channel}`)}}return _jsxruntime.jsxs.call(void 0, "div",{className:"flex min-h-0 flex-1 flex-col",children:[_jsxruntime.jsxs.call(void 0, "div",{className:_chunk6DEKVABTjs.g.call(void 0, d&&"hidden md:block"),children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-2xl",children:i.inboxHeading}),_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-500 dark:text-neutral-400",children:i.inboxIntro})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"mt-6 grid min-h-0 flex-1 gap-4 md:grid-cols-[minmax(16rem,22rem)_1fr]",children:[_jsxruntime.jsx.call(void 0, "div",{className:_chunk6DEKVABTjs.g.call(void 0, "min-w-0",d&&"hidden md:block"),children:_jsxruntime.jsx.call(void 0, Ht,{projects:g,loads:T,clients:k,products:t,texts:i,locale:h,selection:c,onSelect:v,onRetry:()=>w(P=>P+1)})}),_jsxruntime.jsx.call(void 0, "div",{className:_chunk6DEKVABTjs.g.call(void 0, "min-h-[32rem] min-w-0 md:h-[calc(100dvh-10rem)]",!d&&"hidden md:flex"),children:_nullishCoalesce(_, () => (_jsxruntime.jsx.call(void 0, "div",{className:"flex h-full w-full items-center justify-center rounded-xl border border-dashed border-neutral-300 p-6 text-sm text-neutral-600 dark:border-neutral-700 dark:text-neutral-400",children:i.selectConversation})))})]}),L&&_jsxruntime.jsx.call(void 0, _react.Suspense,{fallback:null,children:_jsxruntime.jsx.call(void 0, Dt,{projectID:L,locale:h})})]})}var tt="flex min-h-11 w-full min-w-0 items-start gap-3 rounded-xl p-3 text-left transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-500";function Ht({projects:e,loads:t,clients:n,products:a,texts:r,locale:c,selection:v,onSelect:h,onRetry:u}){let[i,g]=_react.useState.call(void 0, ),[b,k]=_react.useState.call(void 0, ),T=new Map(a.map(y=>[y.productId,y])),f=e.length>1,N=e.map(y=>_nullishCoalesce(t[y], () => ({status:"loading"})));if(N.length>0&&N.every(y=>y.status==="loading"))return _jsxruntime.jsx.call(void 0, "div",{role:"status","aria-busy":"true","aria-label":r.loading,className:"flex flex-col gap-2",children:[0,1,2].map(y=>_jsxruntime.jsx.call(void 0, "div",{"aria-hidden":"true",className:"h-20 rounded-xl bg-white motion-safe:animate-pulse dark:bg-neutral-800"},y))});if(N.length===0||N.every(y=>y.status==="error"))return _jsxruntime.jsxs.call(void 0, "div",{role:"alert",className:"flex flex-col items-start gap-3","data-testid":"chat-inbox-error",children:[_jsxruntime.jsx.call(void 0, "p",{className:"text-sm text-neutral-700 dark:text-neutral-300",children:r.inboxError}),_jsxruntime.jsx.call(void 0, "button",{type:"button",onClick:u,className:"inline-flex min-h-11 items-center rounded-md bg-neutral-900 px-4 text-sm font-medium text-white hover:bg-neutral-800 focus-visible:outline-2 focus-visible:outline-current dark:bg-white dark:text-neutral-900",children:r.retry})]});let w=[],p=[];for(let y of e){let L=t[y];if(_optionalChain([L, 'optionalAccess', _68 => _68.status])!=="ready")continue;let{me:A}=L,j=f?_optionalChain([a, 'access', _69 => _69.find, 'call', _70 => _70(d=>d.projectId===y), 'optionalAccess', _71 => _71.projectName]):void 0;for(let d of A.threads){let R=d.productId?T.get(d.productId):void 0,_=v.chatProject===y&&v.thread===d.id,P=[le(r,d.repliesLeft,c)];d.expiresAt&&P.push(G(d.composerLocked?r.expiredOn:r.expiresOn,{date:de(d.expiresAt,c)})),d.responseHours>0&&P.push(G(r.responseHours,{hours:d.responseHours}));let s=d.lastMessage;w.push(_jsxruntime.jsx.call(void 0, "li",{children:_jsxruntime.jsxs.call(void 0, "button",{type:"button","data-thread-id":d.id,"aria-current":_?"true":void 0,onClick:()=>h({chatProject:y,thread:d.id}),className:_chunk6DEKVABTjs.g.call(void 0, tt,_?"bg-neutral-200 dark:bg-neutral-800":"bg-white hover:bg-neutral-50 dark:bg-neutral-900 dark:hover:bg-neutral-800"),children:[_jsxruntime.jsx.call(void 0, _lucidereact.MessageCircle,{className:"mt-0.5 size-5 shrink-0 text-neutral-500 dark:text-neutral-400","aria-hidden":"true"}),_jsxruntime.jsxs.call(void 0, "span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[_jsxruntime.jsxs.call(void 0, "span",{className:"flex items-baseline gap-2",children:[_jsxruntime.jsx.call(void 0, "span",{className:_chunk6DEKVABTjs.g.call(void 0, "truncate",d.unread>0?"font-semibold":"font-medium"),children:_optionalChain([R, 'optionalAccess', _72 => _72.productName])||r.chatFallbackTitle}),s&&_jsxruntime.jsx.call(void 0, "time",{dateTime:s.createdAt,className:"ml-auto shrink-0 text-xs text-neutral-500 dark:text-neutral-400",children:he(s.createdAt,c)})]}),j&&_jsxruntime.jsx.call(void 0, "span",{className:"truncate text-xs text-neutral-500 dark:text-neutral-400",children:j}),_jsxruntime.jsxs.call(void 0, "span",{className:"flex items-center gap-2",children:[_jsxruntime.jsx.call(void 0, "span",{className:"line-clamp-1 flex-1 text-sm text-neutral-600 dark:text-neutral-300",children:s?s.deleted?r.deletedPlaceholder:s.body:r.noMessagesYet}),d.unread>0&&_jsxruntime.jsx.call(void 0, "span",{"aria-label":G(r.unread,{count:d.unread}),className:"inline-flex min-w-5 shrink-0 items-center justify-center rounded-full bg-neutral-900 px-1.5 text-xs font-semibold text-white tabular-nums dark:bg-white dark:text-neutral-900",children:d.unread})]}),_jsxruntime.jsxs.call(void 0, "span",{className:_chunk6DEKVABTjs.g.call(void 0, "text-xs",d.repliesLeft<=0||d.composerLocked?"text-amber-800 dark:text-amber-300":"text-neutral-500 dark:text-neutral-400"),children:[P.join(" \xB7 "),d.muted&&` \xB7 ${r.mutedBadge}`]})]})]})},`t:${y}:${d.id}`))}for(let d of A.channels){let R=v.chatProject===y&&v.channel===d.id;w.push(_jsxruntime.jsx.call(void 0, "li",{children:_jsxruntime.jsxs.call(void 0, "button",{type:"button","data-channel-id":d.id,"aria-current":R?"true":void 0,onClick:()=>h({chatProject:y,channel:d.id}),className:_chunk6DEKVABTjs.g.call(void 0, tt,R?"bg-neutral-200 dark:bg-neutral-800":"bg-white hover:bg-neutral-50 dark:bg-neutral-900 dark:hover:bg-neutral-800"),children:[_jsxruntime.jsx.call(void 0, _lucidereact.Hash,{className:"mt-0.5 size-5 shrink-0 text-neutral-500 dark:text-neutral-400","aria-hidden":"true"}),_jsxruntime.jsxs.call(void 0, "span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[_jsxruntime.jsx.call(void 0, "span",{className:"truncate font-medium",children:d.name||r.channelFallbackTitle}),j&&_jsxruntime.jsx.call(void 0, "span",{className:"truncate text-xs text-neutral-500 dark:text-neutral-400",children:j}),_jsxruntime.jsx.call(void 0, "span",{className:"line-clamp-1 text-sm text-neutral-600 dark:text-neutral-300",children:d.topic||r.kindChannel}),d.memberCount>0&&_jsxruntime.jsx.call(void 0, "span",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:G(r.members,{count:d.memberCount})})]})]})},`c:${y}:${d.id}`))}for(let d of A.entitlements.packs){let R=`${y}:${d.productId}`,_=_optionalChain([T, 'access', _73 => _73.get, 'call', _74 => _74(d.productId), 'optionalAccess', _75 => _75.productName])||d.name||r.chatFallbackTitle;p.push(_jsxruntime.jsxs.call(void 0, "li",{className:"flex flex-col gap-2 rounded-xl bg-white p-3 dark:bg-neutral-900 sm:flex-row sm:items-center",children:[_jsxruntime.jsxs.call(void 0, "span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[_jsxruntime.jsx.call(void 0, "span",{className:"truncate font-medium",children:_}),_jsxruntime.jsx.call(void 0, "span",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:[le(r,d.repliesLeftHint,c),d.expiresAt?G(r.expiresOn,{date:de(d.expiresAt,c)}):""].filter(Boolean).join(" \xB7 ")})]}),_jsxruntime.jsx.call(void 0, "button",{type:"button",disabled:i===R,"aria-busy":i===R||void 0,onClick:async()=>{let P=n.get(y);if(P){g(R),k(void 0);try{let s=await P.openThread(d.productId);h({chatProject:y,thread:s.id})}catch (e15){k(R)}finally{g(void 0)}}},className:"inline-flex min-h-11 shrink-0 items-center justify-center rounded-md bg-neutral-900 px-4 text-sm font-medium text-white hover:bg-neutral-800 disabled:opacity-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-500 dark:bg-white dark:text-neutral-900 dark:hover:bg-neutral-200",children:i===R?r.loading:r.startChat}),b===R&&_jsxruntime.jsx.call(void 0, "p",{role:"alert",className:"text-xs text-red-700 dark:text-red-400 sm:basis-full",children:r.errorGeneric})]},`p:${R}`))}let x=new Set(A.channels.map(d=>d.id));for(let d of A.entitlements.channels){if(d.channelId&&x.has(d.channelId))continue;let R=_optionalChain([T, 'access', _76 => _76.get, 'call', _77 => _77(d.productId), 'optionalAccess', _78 => _78.productName])||r.channelFallbackTitle;p.push(_jsxruntime.jsxs.call(void 0, "li",{className:"flex flex-col gap-2 rounded-xl bg-white p-3 dark:bg-neutral-900 sm:flex-row sm:items-center",children:[_jsxruntime.jsxs.call(void 0, "span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[_jsxruntime.jsx.call(void 0, "span",{className:"truncate font-medium",children:R}),!d.channelId&&_jsxruntime.jsx.call(void 0, "span",{className:"text-xs text-neutral-500 dark:text-neutral-400",children:r.channelNotReady})]}),d.channelId&&_jsxruntime.jsx.call(void 0, "button",{type:"button",onClick:()=>h({chatProject:y,channel:d.channelId}),className:"inline-flex min-h-11 shrink-0 items-center justify-center rounded-md border border-neutral-300 px-4 text-sm font-medium hover:bg-neutral-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-500 dark:border-neutral-700 dark:hover:bg-neutral-800",children:r.openChannel})]},`e:${y}:${d.productId}`))}}return w.length===0&&p.length===0?_jsxruntime.jsx.call(void 0, "p",{"data-testid":"chat-inbox-empty",className:"text-sm text-neutral-600 dark:text-neutral-400",children:r.inboxEmpty}):_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-6","data-testid":"chat-inbox",children:[w.length>0&&_jsxruntime.jsx.call(void 0, "ul",{className:"flex flex-col gap-2",children:w}),p.length>0&&_jsxruntime.jsxs.call(void 0, "section",{className:"flex flex-col gap-2",children:[_jsxruntime.jsx.call(void 0, "h4",{className:"text-sm font-semibold text-neutral-700 dark:text-neutral-300",children:r.startSection}),_jsxruntime.jsx.call(void 0, "ul",{className:"flex flex-col gap-2",children:p})]})]})}exports.CHAT_TEXT_TABLES = $e; exports.Channel = Ae; exports.ChatError = $; exports.ChatThread = _e; exports.DEFAULT_CHAT_API_URL = Ce; exports.DEFAULT_CHAT_ATTACHMENTS_URL = ve; exports.DEFAULT_CHAT_REALTIME_URL = Te; exports.PanelMessages = rt; exports.addPackToCart = se; exports.chatProjects = at; exports.createChatClient = ie; exports.getChatTexts = re; exports.parseRealtimeEvent = Ne; exports.startLive = ze; exports.useConversation = ke;
2
2
  //# sourceMappingURL=chat.js.map
package/dist/chat.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chat.js","../src/chat/widgets.tsx","../src/chat/buy.ts","../src/chat/types.ts","../src/chat/client.ts"],"names":["addPackToCart","input","addProductToCart","DEFAULT_CHAT_API_URL","DEFAULT_CHAT_REALTIME_URL","ChatError","code","status","data","retry","createChatClient","options","baseUrl","doFetch","args","call","method","path","body","response"],"mappings":"AAAA,y/BAAwC,sDAAyC,sDAAiD,+BAA4B,sDAAwC,+BAA4B,+BAA4B,sDAAgD,+BAA4B,8BCArR,MCqBrD,SAAsBA,EAAAA,CAAcC,CAAAA,CAAoC,CACtE,MAAMC,gCAAAA,CAEF,EAAA,CAAID,CAAAA,CAAM,SAAA,CACV,IAAA,kBAAMA,CAAAA,CAAM,IAAA,SAAQ,IAAA,CACpB,KAAA,kBAAOA,CAAAA,CAAM,UAAA,SAAc,GAAA,CAC3B,QAAA,CAAU,EAAA,CACV,MAAA,CAAQA,CAAAA,CAAM,MAChB,CAAA,CACA,CAAE,SAAA,CAAWA,CAAAA,CAAM,SAAA,CAAW,IAAA,CAAMA,CAAAA,CAAM,IAAA,CAAM,QAAA,CAAU,CAAA,CAAK,CACjE,CACF,CCzBO,IAAME,EAAAA,CAAuB,yBAAA,CAGvBC,EAAAA,qCACX,oDAAA,CCcK,IAAMC,CAAAA,CAAN,MAAA,QAAwB,KAAM,CAC1B,WAOT,CACEC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAgC,CAAC,CAAA,CACjC,CACA,KAAA,CAAM,CAAA,MAAA,EAASF,CAAI,CAAA,EAAA,EAAKC,CAAM,CAAA,CAAA,CAAG,CAAA,CACjC,IAAA,CAAK,IAAA,CAAO,WAAA,CACZ,IAAA,CAAK,IAAA,CAAOD,CAAAA,CACZ,IAAA,CAAK,MAAA,CAASC,CAAAA,CACd,IAAA,CAAK,IAAA,CAAOC,CAAAA,CACZ,IAAMC,CAAAA,CAAQ,MAAA,CAAOD,CAAAA,CAAK,WAAW,CAAA,CACjC,MAAA,CAAO,QAAA,CAASC,CAAK,CAAA,EAAKA,CAAAA,CAAQ,CAAA,EAAA,CAAG,IAAA,CAAK,UAAA,CAAaA,CAAAA,CAC7D,CACF,CAAA,CA+CO,SAASC,EAAAA,CAAiBC,CAAAA,CAAwC,CACvE,IAAMC,CAAAA,CAAAA,CAAWD,CAAAA,CAAQ,OAAA,EAAWR,EAAAA,CAAAA,CAAsB,OAAA,CAAQ,MAAA,CAAQ,EAAE,CAAA,CACtEU,CAAAA,kBAAUF,CAAAA,CAAQ,KAAA,SAAA,CAAU,CAAA,GAAIG,CAAAA,CAAAA,EAAS,KAAA,CAAM,GAAGA,CAAI,CAAA,GAAA,CAE5D,MAAA,SAAeC,CAAAA,CACbC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAC4C,CAC5C,IAAIC,CAAAA,CACJ,GAAI,CACFA,CAAAA,CAAW,MAAMN,CAAAA,CAAQD,CAAAA,CAAUK,CAAAA,CAAM,CACvC,MAAA,CAAAD,CAAAA,CACA,OAAA,CAAS,CACP,aAAA,CAAe,CAAA,OAAA,EAAUL,CAAAA,CAAQ,KAAK,CAAA,CAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chat.js","sourcesContent":[null,"import { useEffect, useMemo, useRef, useState } from \"react\";\nimport { getLocale } from \"../components/checkout/locale\";\nimport { getPanelConfig } from \"../panel/config\";\nimport { getPanelSession } from \"../panel/session-storage\";\nimport { addPackToCart } from \"./buy\";\nimport { createChatClient, type ChatClient } from \"./client\";\nimport { ConversationView } from \"./Conversation\";\nimport type { NatsModule } from \"./realtime\";\nimport { getChatTexts, type ChatTexts } from \"./texts\";\nimport { useConversation, type ConversationLock } from \"./useConversation\";\n\n/** What the lock's buy action gets. */\nexport type ChatBuyRequest = {\n /** The product (or variant) to sell: `buyProductId`, else the locked product. */\n productId: string;\n /** `replies`, `expired`, `no-pack` or `no-access`. */\n reason: ConversationLock[\"reason\"];\n /** Known for a locked channel (from the chat service). */\n priceCents?: number;\n amount?: number;\n email?: string;\n code?: string;\n turnstileToken?: string;\n};\n\n/** Props shared by `ChatThread` and `Channel`. */\nexport type ChatWidgetBaseProps = {\n /**\n * Public Bitsnap project id of the shop. The cart uses it, the panel\n * session is looked up with it, and it is the `X-Bitsnap-Project` of the\n * chat service unless `chatProjectID` is given.\n */\n projectID: string;\n /** Project id for the chat service, when it differs from `projectID`. */\n chatProjectID?: string;\n /**\n * Bearer for the chat service: a `bcht_` buyer token from your server\n * (`POST /api/v1/chat/buyer-token`). Defaults to the customer panel session\n * of this browser (after `PanelLogin`).\n */\n token?: string;\n /** Chat service base URL. Defaults to `https://chat.bitsnap.pl`. */\n apiUrl?: string;\n /** NATS WebSocket URL overriding the one of the realtime token. */\n realtimeUrl?: string;\n /** Bitsnap host of the panel session (`setHost`), when not the default. */\n host?: string;\n /** Polling interval in ms while the live connection is down. Default 8000. */\n pollIntervalMs?: number;\n /** Language of the default texts; defaults to the library locale. */\n locale?: string;\n /** Text overrides, whatever the locale. */\n texts?: Partial<ChatTexts>;\n /** Heading of the conversation. */\n title?: string;\n /** Shows a back button in the header. */\n onBack?: () => void;\n /**\n * The lock's \"Kup pakiet\" / \"Kup dostęp\". Default: add the product to the\n * page cart and open it (mount `BitsnapCheckout` on the page). Throw to\n * show the error line.\n */\n onBuy?: (request: ChatBuyRequest) => Promise<void> | void;\n /** The product or variant the buy action sells (e.g. the pack variant). */\n buyProductId?: string;\n className?: string;\n /** A ready client (tests, custom transport). Replaces token and URLs. */\n client?: ChatClient;\n /** @internal Replaces the NATS loader (tests). */\n loadNats?: () => Promise<NatsModule>;\n};\n\nexport type ChatThreadProps = ChatWidgetBaseProps & {\n /** The service product of the pack: opens its thread, creating it if needed. */\n productId?: string;\n /** An existing thread. Give this or `productId`. */\n threadId?: string;\n};\n\nexport type ChannelProps = ChatWidgetBaseProps & {\n /** The channel (its id is also the id of its conversation). */\n channelId: string;\n /** The community product sold by the lock; defaults to the channel's own. */\n productId?: string;\n};\n\n/**\n * The chat client of a widget. The panel session lives in localStorage, so\n * it is read after mounting (`null` until then: the widget stays loading and\n * the server HTML has no session-dependent content).\n */\nfunction useWidgetClient(props: ChatWidgetBaseProps): ChatClient | null | undefined {\n const [stored, setStored] = useState<string | undefined | null>(null);\n const host = props.host ?? getPanelConfig().host;\n useEffect(() => {\n if (props.client || props.token) return;\n setStored(getPanelSession(props.projectID, host));\n }, [props.client, props.token, props.projectID, host]);\n const token = props.token ?? stored;\n const projectId = props.chatProjectID ?? props.projectID;\n return useMemo(() => {\n if (props.client) return props.client;\n if (token === null) return null;\n if (!token) return undefined;\n return createChatClient({ projectId, token, baseUrl: props.apiUrl });\n }, [props.client, token, projectId, props.apiUrl]);\n}\n\nfunction useBuy(props: ChatWidgetBaseProps) {\n const claim = useRef<{ key: string; token: string; expires: number } | null>(null);\n return async (lock: ConversationLock & { email?: string; code?: string; turnstileToken?: string }) => {\n const productId = props.buyProductId ?? lock.productId;\n if (!productId) return;\n const request: ChatBuyRequest = { productId, reason: lock.reason, priceCents: lock.priceCents, ...(lock.amount != null ? { amount: lock.amount } : {}), ...(lock.email ? { email: lock.email } : {}), ...(lock.code ? { code: lock.code } : {}), ...(lock.turnstileToken != null ? { turnstileToken: lock.turnstileToken } : {}) };\n if (props.onBuy) {\n await props.onBuy(request);\n return;\n }\n const commerceBase = (props.host ?? getPanelConfig().host ?? \"https://bitsnap.pl\").replace(/\\/+$/, \"\");\n const isFreeClaim = lock.freeClaimLimit != null && (lock.priceType === \"free\" || (lock.priceType === \"pay_what_you_want\" && lock.minimumCents === 0 && request.amount === 0));\n if (isFreeClaim && request.email && request.turnstileToken != null) {\n claim.current = null;\n const response = await fetch(`${commerceBase}/api/integrations/${encodeURIComponent(props.projectID)}/public-commerce/free-claim/request-code`, {\n method: \"POST\", headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email: request.email, turnstileToken: request.turnstileToken }),\n });\n const result = await response.json() as { code?: string };\n if (!response.ok) throw new Error(result.code ?? \"internal\");\n return;\n }\n if (isFreeClaim && request.email && request.code) {\n const key = JSON.stringify([commerceBase, props.projectID, productId, request.email, request.code]);\n if (!claim.current || claim.current.key !== key || claim.current.expires <= Date.now()) {\n claim.current = null;\n const verify = await fetch(`${commerceBase}/api/integrations/${encodeURIComponent(props.projectID)}/public-commerce/free-claim/verify-code`, {\n method: \"POST\", headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email: request.email, code: request.code }),\n });\n const verified = await verify.json() as { claimToken?: string; code?: string; expiresIn?: number };\n if (!verify.ok || !verified.claimToken) throw new Error(verified.code ?? \"email-verification-required\");\n claim.current = { key, token: verified.claimToken, expires: Date.now() + (verified.expiresIn ?? 600) * 1000 };\n }\n const bought = await fetch(`${commerceBase}/api/integrations/${encodeURIComponent(props.projectID)}/public-commerce/buy`, {\n method: \"POST\", headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ items: [{ id: productId, quantity: 1, amount: 0 }], details: { email: request.email }, claimToken: claim.current.token }),\n });\n const result = await bought.json() as { success?: boolean; url?: string; code?: string };\n if (!bought.ok || !result.url) throw new Error(result.code ?? \"free-order-not-supported\");\n window.location.assign(result.url);\n return;\n }\n await addPackToCart({\n projectID: props.projectID,\n productId,\n name: props.title,\n priceCents: lock.priceCents,\n amount: lock.amount,\n host: props.host,\n });\n };\n}\n\n/**\n * A buyer's pack thread for one service product: history, live updates,\n * sending with pending and refused states, report and mute, and the lock\n * with \"Kup pakiet\" when the replies are used up or the pack expired.\n * Load `bitsnap-react/dist/index.css` once.\n */\nexport function ChatThread(props: ChatThreadProps) {\n const client = useWidgetClient(props);\n const locale = props.locale ?? getLocale();\n const texts = useMemo(() => getChatTexts(props.texts, locale), [props.texts, locale]);\n const conversation = useConversation({\n client,\n target: { kind: \"thread\", threadId: props.threadId, productId: props.productId },\n pollIntervalMs: props.pollIntervalMs,\n realtimeUrl: props.realtimeUrl,\n loadNats: props.loadNats,\n });\n const buy = useBuy(props);\n return (\n <div className=\"bitsnap-react h-full\">\n <ConversationView\n host={props.host}\n conversation={conversation}\n texts={texts}\n locale={locale}\n kind=\"thread\"\n title={props.title}\n onBack={props.onBack}\n onBuy={buy}\n className={props.className}\n />\n </div>\n );\n}\n\n/**\n * A community channel: messages, live updates, posting when the channel\n * allows it (with the channel's moderation refusals shown on the message),\n * report, and the lock with \"Kup dostęp\" for a buyer without a grant.\n * Load `bitsnap-react/dist/index.css` once.\n */\nexport function Channel(props: ChannelProps) {\n const client = useWidgetClient(props);\n const locale = props.locale ?? getLocale();\n const texts = useMemo(() => getChatTexts(props.texts, locale), [props.texts, locale]);\n const conversation = useConversation({\n client,\n target: { kind: \"channel\", channelId: props.channelId, productId: props.productId },\n pollIntervalMs: props.pollIntervalMs,\n realtimeUrl: props.realtimeUrl,\n loadNats: props.loadNats,\n });\n const buy = useBuy(props);\n return (\n <div className=\"bitsnap-react h-full\">\n <ConversationView\n host={props.host}\n conversation={conversation}\n texts={texts}\n locale={locale}\n kind=\"channel\"\n title={props.title}\n onBack={props.onBack}\n onBuy={buy}\n className={props.className}\n />\n </div>\n );\n}\n","import { addProductToCart } from \"../components/products/add-to-cart\";\n\nexport type BuyPackInput = {\n /** Public project id of the shop (the cart's project). */\n projectID: string;\n /** The product (or variant) to add: the pack's service or community product. */\n productId: string;\n name?: string;\n priceCents?: number;\n amount?: number;\n /** Backend origin of the cart, when not the default. */\n host?: string;\n};\n\n/**\n * Default \"Kup pakiet\" / \"Kup dostęp\" action: adds the product to the page\n * cart (`Bitsnap.addProductToCart`) and opens the cart drawer. The page needs\n * a mounted `BitsnapCheckout`. When the page cart belongs to another project\n * or host nothing changes and the promise rejects; pass `onBuy` to the widget\n * to use your own checkout instead.\n */\nexport async function addPackToCart(input: BuyPackInput): Promise<void> {\n await addProductToCart(\n {\n id: input.productId,\n name: input.name ?? \"\",\n price: input.priceCents ?? 0,\n currency: \"\",\n amount: input.amount,\n },\n { projectID: input.projectID, host: input.host, showCart: true },\n );\n}\n","/**\n * Buyer side of the Bitsnap chat service (`bitsnap-messaging`): the shapes\n * the library works with. The wire is snake_case JSON; `client.ts` maps it to\n * these camelCase types. Times are ISO 8601 strings, `null` when absent.\n */\n\n/** Default base URL of the chat service. */\nexport const DEFAULT_CHAT_API_URL = \"https://chat.bitsnap.pl\";\n\n/** Default NATS WebSocket URL, used when the realtime token lists no server. */\nexport const DEFAULT_CHAT_REALTIME_URL =\n \"wss://bitsnap-nats-queue-production.up.railway.app\";\n\n/** One paid order that gives a pack thread creator replies. */\nexport type ChatPack = {\n orderId: string;\n productId?: string;\n replies: number;\n used: number;\n left: number;\n expiresAt: string | null;\n expired: boolean;\n};\n\n/** A stored message, or the pending answer of a send. */\nexport type ChatMessage = {\n id: string;\n threadId: string;\n authorEmail: string;\n body: string;\n attachmentKey?: string;\n attachmentKind?: string;\n createdAt: string;\n pinned: boolean;\n /** Soft deleted: the body is empty. */\n deleted: boolean;\n /** A message of the service, such as the creator's away notice. */\n system: boolean;\n /** `\"pending\"` in the answer of a send: queued, not stored yet. */\n status?: \"pending\";\n};\n\n/** The state of a conversation for the caller (`ThreadView` on the wire). */\nexport type ChatThreadSummary = {\n id: string;\n kind: \"pack\" | \"channel\";\n channelId?: string;\n /** For a buyer, the creator's e-mail (pack) or the channel name. */\n title: string;\n lastMessage?: ChatMessage;\n unread: number;\n repliesTotal: number;\n repliesUsed: number;\n repliesLeft: number;\n expiresAt: string | null;\n /** The caller cannot write: every pack has expired. */\n composerLocked: boolean;\n productId?: string;\n /** The creator's promise in hours (\"odpowiedź w ciągu 48 h\"), 0 for none. */\n responseHours: number;\n packs: ChatPack[];\n muted: boolean;\n};\n\n/** A channel the caller may read. */\nexport type ChatChannelSummary = {\n id: string;\n name: string;\n topic: string;\n welcome: string;\n whoCanPost: \"creator\" | \"members\";\n productId: string;\n /** `creator`, `member` or `muted`. */\n role: string;\n memberCount: number;\n createdAt: string;\n blockLinks: boolean;\n blockMedia: boolean;\n cooldownSeconds: number;\n};\n\n/** A pack the buyer holds and has not opened a thread for yet. */\nexport type ChatPackEntitlement = {\n productId: string;\n name: string;\n repliesLeftHint: number;\n expiresAt: string | null;\n};\n\n/** A community product the buyer holds; `channelId` once a channel is bound. */\nexport type ChatChannelEntitlement = {\n productId: string;\n channelId?: string;\n};\n\n/** `GET /v1/me`: the buyer's chat in one project. */\nexport type ChatMe = {\n email: string;\n threads: ChatThreadSummary[];\n entitlements: {\n packs: ChatPackEntitlement[];\n channels: ChatChannelEntitlement[];\n };\n channels: ChatChannelSummary[];\n};\n\n/** One page of history, newest first as the service answers it. */\nexport type ChatMessagePage = {\n messages: ChatMessage[];\n hasMore: boolean;\n};\n\n/** The thread part of a send answer. */\nexport type ChatThreadState = Pick<\n ChatThreadSummary,\n | \"id\"\n | \"kind\"\n | \"repliesTotal\"\n | \"repliesUsed\"\n | \"repliesLeft\"\n | \"expiresAt\"\n | \"composerLocked\"\n | \"responseHours\"\n>;\n\n/** `POST /v1/threads/{id}/messages` answers 202 with the queued message. */\nexport type ChatSendResult = {\n message: ChatMessage;\n thread: ChatThreadState;\n};\n\nexport type ChatReportReason = \"spam\" | \"abuse\" | \"illegal\" | \"other\";\n\n/** `POST /v1/realtime/token`. */\nexport type ChatRealtimeToken = {\n jwt: string;\n expiresAt: string;\n servers: string[];\n subjects: string[];\n truncated: boolean;\n};\n\n/** Live events on the thread or channel subject. */\nexport type ChatRealtimeEvent =\n | { type: \"message.created\"; message: ChatMessage }\n | { type: \"message.rejected\"; id: string; reason: string }\n | { type: \"message.deleted\"; id: string }\n | { type: \"message.pinned\"; id: string }\n | { type: \"message.unpinned\"; id: string };\n\n/** How a conversation hears about new messages. */\nexport type ChatLiveMode = \"connecting\" | \"live\" | \"polling\" | \"off\";\n","import {\n DEFAULT_CHAT_API_URL,\n type ChatChannelSummary,\n type ChatMe,\n type ChatMessage,\n type ChatMessagePage,\n type ChatPack,\n type ChatRealtimeEvent,\n type ChatRealtimeToken,\n type ChatReportReason,\n type ChatSendResult,\n type ChatThreadState,\n type ChatThreadSummary,\n} from \"./types\";\n\n/**\n * An error answer of the chat service (`{\"error\":\"<code>\"}`), or `network`\n * (status 0) when the request did not get an answer.\n *\n * Codes the buyer UI handles: `unauthorized` (401), `plan_required`,\n * `locked`, `muted`, `blocked`, `forbidden`, `read_only` (403), `not_found`\n * (404), `moderation_link`, `moderation_banned_word`, `moderation_media`\n * (422), `cooldown` (429, with `retryAfter`), `unavailable` (503),\n * `invalid_project` (400).\n */\nexport class ChatError extends Error {\n readonly code: string;\n readonly status: number;\n /** `cooldown`: seconds to wait before the next post. */\n readonly retryAfter?: number;\n /** Extra fields of the answer (`locked`: product, price type and bounds). */\n readonly data: Record<string, unknown>;\n\n constructor(\n code: string,\n status: number,\n data: Record<string, unknown> = {},\n ) {\n super(`chat: ${code} (${status})`);\n this.name = \"ChatError\";\n this.code = code;\n this.status = status;\n this.data = data;\n const retry = Number(data.retry_after);\n if (Number.isFinite(retry) && retry > 0) this.retryAfter = retry;\n }\n}\n\nexport type ChatClientOptions = {\n /** Project id sent as `X-Bitsnap-Project`. */\n projectId: string;\n /** Bearer credential: the panel session token or a `bcht_` buyer token. */\n token: string;\n /** Base URL of the chat service. Defaults to `https://chat.bitsnap.pl`. */\n baseUrl?: string;\n /** Replaces `fetch` (tests, server rendering). */\n fetch?: typeof fetch;\n};\n\n/** The buyer calls of the chat service HTTP API. */\nexport type ChatClient = {\n readonly baseUrl: string;\n readonly projectId: string;\n me(): Promise<ChatMe>;\n /** Opens or returns the pack thread of a service product. */\n openThread(productId: string): Promise<ChatThreadSummary>;\n /** Newest first; `before` is a message id. */\n messages(\n threadId: string,\n options?: { before?: string; limit?: number },\n ): Promise<ChatMessagePage>;\n /** Queues a message. The service answers 202 with `status: \"pending\"`. */\n send(\n threadId: string,\n input: { body: string; clientId?: string },\n ): Promise<ChatSendResult>;\n deleteMessage(threadId: string, messageId: string): Promise<void>;\n mute(threadId: string, muted: boolean): Promise<void>;\n report(input: {\n threadId: string;\n messageId?: string;\n reason: ChatReportReason;\n note?: string;\n }): Promise<void>;\n markRead(threadId: string, messageId: string): Promise<void>;\n /**\n * A NATS token for every conversation the caller may read. The answer is\n * kept until a minute and a half before it expires (the service mints one\n * per caller every 10 s); `fresh` asks for a new one.\n */\n realtimeToken(options?: { fresh?: boolean }): Promise<ChatRealtimeToken>;\n};\n\nexport function createChatClient(options: ChatClientOptions): ChatClient {\n const baseUrl = (options.baseUrl || DEFAULT_CHAT_API_URL).replace(/\\/+$/, \"\");\n const doFetch = options.fetch ?? ((...args) => fetch(...args));\n\n async function call(\n method: string,\n path: string,\n body?: unknown,\n ): Promise<{ status: number; json: unknown }> {\n let response: Response;\n try {\n response = await doFetch(baseUrl + path, {\n method,\n headers: {\n Authorization: `Bearer ${options.token}`,\n \"X-Bitsnap-Project\": options.projectId,\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch {\n throw new ChatError(\"network\", 0);\n }\n let json: unknown = null;\n try {\n const text = await response.text();\n json = text ? JSON.parse(text) : null;\n } catch {\n json = null;\n }\n if (!response.ok) {\n const data = isRecord(json) ? json : {};\n const code = typeof data.error === \"string\" ? data.error : \"internal_error\";\n throw new ChatError(code, response.status, data);\n }\n return { status: response.status, json };\n }\n\n const id = encodeURIComponent;\n let cachedToken: ChatRealtimeToken | undefined;\n\n return {\n baseUrl,\n projectId: options.projectId,\n async me() {\n const { json } = await call(\"GET\", \"/v1/me\");\n return mapMe(json);\n },\n async openThread(productId) {\n const { json } = await call(\"POST\", \"/v1/threads\", {\n product_id: productId,\n });\n return mapThread(json);\n },\n async messages(threadId, opts = {}) {\n const query = new URLSearchParams();\n if (opts.before) query.set(\"before\", opts.before);\n if (opts.limit) query.set(\"limit\", String(opts.limit));\n const qs = query.toString();\n const suffix = qs ? `?${qs}` : \"\";\n const { json } = await call(\n \"GET\",\n `/v1/threads/${id(threadId)}/messages${suffix}`,\n );\n const page = isRecord(json) ? json : {};\n return {\n messages: arr(page.messages).map(mapMessage),\n hasMore: page.has_more === true,\n };\n },\n async send(threadId, input) {\n const { json } = await call(\n \"POST\",\n `/v1/threads/${id(threadId)}/messages`,\n {\n body: input.body,\n ...(input.clientId ? { client_id: input.clientId } : {}),\n },\n );\n const res = isRecord(json) ? json : {};\n return {\n message: mapMessage(res.message),\n thread: mapThreadState(res.thread),\n };\n },\n async deleteMessage(threadId, messageId) {\n await call(\n \"DELETE\",\n `/v1/threads/${id(threadId)}/messages/${id(messageId)}`,\n );\n },\n async mute(threadId, muted) {\n await call(\"POST\", `/v1/threads/${id(threadId)}/mute`, { muted });\n },\n async report(input) {\n await call(\"POST\", \"/v1/reports\", {\n thread_id: input.threadId,\n ...(input.messageId ? { message_id: input.messageId } : {}),\n reason: input.reason,\n ...(input.note ? { note: input.note } : {}),\n });\n },\n async markRead(threadId, messageId) {\n await call(\"POST\", `/v1/threads/${id(threadId)}/receipts`, {\n state: \"read\",\n message_id: messageId,\n });\n },\n async realtimeToken(opts = {}) {\n if (\n !opts.fresh &&\n cachedToken &&\n Date.parse(cachedToken.expiresAt) - Date.now() > 90_000\n ) {\n return cachedToken;\n }\n const { json } = await call(\"POST\", \"/v1/realtime/token\");\n const res = isRecord(json) ? json : {};\n return (cachedToken = {\n jwt: str(res.jwt),\n expiresAt: str(res.expires_at),\n servers: arr(res.servers).filter((s): s is string => typeof s === \"string\"),\n subjects: arr(res.subjects).filter((s): s is string => typeof s === \"string\"),\n truncated: res.truncated === true,\n });\n },\n };\n}\n\n/** Parses one live event of the thread or channel subject. */\nexport function parseRealtimeEvent(raw: unknown): ChatRealtimeEvent | null {\n if (!isRecord(raw) || typeof raw.type !== \"string\") return null;\n const eventId = str(raw.id);\n switch (raw.type) {\n case \"message.created\":\n return { type: \"message.created\", message: mapMessage(raw) };\n case \"message.rejected\":\n return { type: \"message.rejected\", id: eventId, reason: str(raw.reason) };\n case \"message.deleted\":\n case \"message.pinned\":\n case \"message.unpinned\":\n return { type: raw.type, id: eventId };\n default:\n return null;\n }\n}\n\n// --- wire mapping -------------------------------------------------------\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value != null && !Array.isArray(value);\n}\n\nfunction arr(value: unknown): unknown[] {\n return Array.isArray(value) ? value : [];\n}\n\nfunction str(value: unknown): string {\n return typeof value === \"string\" ? value : value == null ? \"\" : String(value);\n}\n\nfunction num(value: unknown): number {\n const n = Number(value);\n return Number.isFinite(n) ? n : 0;\n}\n\nfunction optStr(value: unknown): string | undefined {\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\nfunction time(value: unknown): string | null {\n return typeof value === \"string\" && value !== \"\" ? value : null;\n}\n\nexport function mapMessage(raw: unknown): ChatMessage {\n const m = isRecord(raw) ? raw : {};\n return {\n id: str(m.id),\n threadId: str(m.thread_id),\n authorEmail: str(m.author_email),\n body: str(m.body),\n attachmentKey: optStr(m.attachment_key),\n attachmentKind: optStr(m.attachment_kind),\n createdAt: str(m.created_at),\n pinned: m.pinned === true,\n deleted: m.deleted === true,\n system: m.system === true,\n ...(m.status === \"pending\" ? { status: \"pending\" as const } : {}),\n };\n}\n\nfunction mapPack(raw: unknown): ChatPack {\n const p = isRecord(raw) ? raw : {};\n return {\n orderId: str(p.order_id),\n productId: optStr(p.product_id),\n replies: num(p.replies),\n used: num(p.used),\n left: num(p.left),\n expiresAt: time(p.expires_at),\n expired: p.expired === true,\n };\n}\n\nfunction mapThreadState(raw: unknown): ChatThreadState {\n const t = isRecord(raw) ? raw : {};\n return {\n id: str(t.id),\n kind: t.kind === \"channel\" ? \"channel\" : \"pack\",\n repliesTotal: num(t.replies_total),\n repliesUsed: num(t.replies_used),\n repliesLeft: num(t.replies_left),\n expiresAt: time(t.expires_at),\n composerLocked: t.composer_locked === true,\n responseHours: num(t.response_hours),\n };\n}\n\nexport function mapThread(raw: unknown): ChatThreadSummary {\n const t = isRecord(raw) ? raw : {};\n return {\n ...mapThreadState(t),\n channelId: optStr(t.channel_id),\n title: str(t.title),\n lastMessage: isRecord(t.last_message) ? mapMessage(t.last_message) : undefined,\n unread: num(t.unread),\n productId: optStr(t.product_id),\n packs: arr(t.packs).map(mapPack),\n muted: t.muted === true,\n };\n}\n\nfunction mapChannel(raw: unknown): ChatChannelSummary {\n const c = isRecord(raw) ? raw : {};\n return {\n id: str(c.id),\n name: str(c.name),\n topic: str(c.topic),\n welcome: str(c.welcome),\n whoCanPost: c.who_can_post === \"members\" ? \"members\" : \"creator\",\n productId: str(c.product_id),\n role: str(c.role),\n memberCount: num(c.member_count),\n createdAt: str(c.created_at),\n blockLinks: c.block_links === true,\n blockMedia: c.block_media === true,\n cooldownSeconds: num(c.cooldown_seconds),\n };\n}\n\nfunction mapMe(raw: unknown): ChatMe {\n const m = isRecord(raw) ? raw : {};\n const ent = isRecord(m.entitlements) ? m.entitlements : {};\n return {\n email: str(m.email),\n threads: arr(m.threads).map(mapThread),\n entitlements: {\n packs: arr(ent.packs).map((raw) => {\n const p = isRecord(raw) ? raw : {};\n return {\n productId: str(p.product_id),\n name: str(p.name),\n repliesLeftHint: num(p.replies_left_hint),\n expiresAt: time(p.expires_at),\n };\n }),\n channels: arr(ent.channels).map((raw) => {\n const c = isRecord(raw) ? raw : {};\n return { productId: str(c.product_id), channelId: optStr(c.channel_id) };\n }),\n },\n channels: arr(m.channels).map(mapChannel),\n };\n}\n"]}
1
+ {"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/chat-attachments/dist/chat.js","../src/chat/widgets.tsx","../src/chat/buy.ts","../src/chat/types.ts","../src/chat/client.ts"],"names":["addPackToCart","input","addProductToCart","DEFAULT_CHAT_API_URL","DEFAULT_CHAT_ATTACHMENTS_URL","DEFAULT_CHAT_REALTIME_URL","ChatError","code","status","data","retry","createChatClient","options","baseUrl","localOrigin","attachmentBase","doFetch","args","call","method","path","body","response"],"mappings":"AAAA,y/BAAwC,sDAAyC,sDAAiD,+BAA4B,sDAAwC,+BAA4B,+BAA4B,sDAAgD,+BAA4B,8BCArR,MCqBrD,SAAsBA,EAAAA,CAAcC,CAAAA,CAAoC,CACtE,MAAMC,gCAAAA,CAEF,EAAA,CAAID,CAAAA,CAAM,SAAA,CACV,IAAA,kBAAMA,CAAAA,CAAM,IAAA,SAAQ,IAAA,CACpB,KAAA,kBAAOA,CAAAA,CAAM,UAAA,SAAc,GAAA,CAC3B,QAAA,CAAU,EAAA,CACV,MAAA,CAAQA,CAAAA,CAAM,MAChB,CAAA,CACA,CAAE,SAAA,CAAWA,CAAAA,CAAM,SAAA,CAAW,IAAA,CAAMA,CAAAA,CAAM,IAAA,CAAM,QAAA,CAAU,CAAA,CAAK,CACjE,CACF,CCzBO,IAAME,EAAAA,CAAuB,yBAAA,CAEvBC,EAAAA,wCAA+B,oBAAA,CAG/BC,EAAAA,qCACX,oDAAA,CCcK,IAAMC,CAAAA,CAAN,MAAA,QAAwB,KAAM,CAC1B,WAOT,CACEC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAgC,CAAC,CAAA,CACjC,CACA,KAAA,CAAM,CAAA,MAAA,EAASF,CAAI,CAAA,EAAA,EAAKC,CAAM,CAAA,CAAA,CAAG,CAAA,CACjC,IAAA,CAAK,IAAA,CAAO,WAAA,CACZ,IAAA,CAAK,IAAA,CAAOD,CAAAA,CACZ,IAAA,CAAK,MAAA,CAASC,CAAAA,CACd,IAAA,CAAK,IAAA,CAAOC,CAAAA,CACZ,IAAMC,CAAAA,CAAQ,MAAA,CAAOD,CAAAA,CAAK,WAAW,CAAA,CACjC,MAAA,CAAO,QAAA,CAASC,CAAK,CAAA,EAAKA,CAAAA,CAAQ,CAAA,EAAA,CAAG,IAAA,CAAK,UAAA,CAAaA,CAAAA,CAC7D,CACF,CAAA,CAmDO,SAASC,EAAAA,CAAiBC,CAAAA,CAAwC,CACvE,IAAMC,CAAAA,CAAAA,CAAWD,CAAAA,CAAQ,OAAA,EAAWT,EAAAA,CAAAA,CAAsB,OAAA,CAAQ,MAAA,CAAQ,EAAE,CAAA,CACtEW,CAAAA,CAAc,OAAO,MAAA,CAAW,GAAA,EAAe,CAAC,WAAA,CAAa,WAAW,CAAA,CAAE,QAAA,CAAS,MAAA,CAAO,QAAA,CAAS,QAAQ,CAAA,CAAI,MAAA,CAAO,QAAA,CAAS,MAAA,CAAS,KAAA,CAAA,CACxIC,CAAAA,CAAAA,mCAAkBH,CAAAA,CAAQ,cAAA,SAAkBE,GAAAA,SAAeV,IAAAA,CAAAA,CAA8B,OAAA,CAAQ,MAAA,CAAQ,EAAE,CAAA,CAC3GY,CAAAA,kBAAUJ,CAAAA,CAAQ,KAAA,SAAA,CAAU,CAAA,GAAIK,CAAAA,CAAAA,EAAS,KAAA,CAAM,GAAGA,CAAI,CAAA,GAAA,CAE5D,MAAA,SAAeC,CAAAA,CACbC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAC4C,CAC5C,IAAIC,CAAAA,CACJ,GAAI,CACFA,CAAAA,CAAW,MAAMN,CAAAA,CAAQH,CAAAA,CAAUO,CAAAA,CAAM,CACvC,MAAA,CAAAD,CAAAA,CACA,OAAA,CAAS,CACP,aAAA,CAAe,CAAA,OAAA,EAAUP,CAAAA,CAAQ,KAAK,CAAA,CAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/chat-attachments/dist/chat.js","sourcesContent":[null,"import { useEffect, useMemo, useRef, useState } from \"react\";\nimport { getLocale } from \"../components/checkout/locale\";\nimport { getPanelConfig } from \"../panel/config\";\nimport { getPanelSession } from \"../panel/session-storage\";\nimport { addPackToCart } from \"./buy\";\nimport { createChatClient, type ChatClient } from \"./client\";\nimport { ConversationView } from \"./Conversation\";\nimport type { NatsModule } from \"./realtime\";\nimport { getChatTexts, type ChatTexts } from \"./texts\";\nimport { useConversation, type ConversationLock } from \"./useConversation\";\n\n/** What the lock's buy action gets. */\nexport type ChatBuyRequest = {\n /** The product (or variant) to sell: `buyProductId`, else the locked product. */\n productId: string;\n /** `replies`, `expired`, `no-pack` or `no-access`. */\n reason: ConversationLock[\"reason\"];\n /** Known for a locked channel (from the chat service). */\n priceCents?: number;\n amount?: number;\n email?: string;\n code?: string;\n turnstileToken?: string;\n};\n\n/** Props shared by `ChatThread` and `Channel`. */\nexport type ChatWidgetBaseProps = {\n /**\n * Public Bitsnap project id of the shop. The cart uses it, the panel\n * session is looked up with it, and it is the `X-Bitsnap-Project` of the\n * chat service unless `chatProjectID` is given.\n */\n projectID: string;\n /** Project id for the chat service, when it differs from `projectID`. */\n chatProjectID?: string;\n /**\n * Bearer for the chat service: a `bcht_` buyer token from your server\n * (`POST /api/v1/chat/buyer-token`). Defaults to the customer panel session\n * of this browser (after `PanelLogin`).\n */\n token?: string;\n /** Chat service base URL. Defaults to `https://chat.bitsnap.pl`. */\n apiUrl?: string;\n /** Bitsnap app host serving private chat attachment APIs (defaults to the page origin). */\n attachmentsUrl?: string;\n /** NATS WebSocket URL overriding the one of the realtime token. */\n realtimeUrl?: string;\n /** Bitsnap host of the panel session (`setHost`), when not the default. */\n host?: string;\n /** Polling interval in ms while the live connection is down. Default 8000. */\n pollIntervalMs?: number;\n /** Language of the default texts; defaults to the library locale. */\n locale?: string;\n /** Text overrides, whatever the locale. */\n texts?: Partial<ChatTexts>;\n /** Heading of the conversation. */\n title?: string;\n /** Shows a back button in the header. */\n onBack?: () => void;\n /**\n * The lock's \"Kup pakiet\" / \"Kup dostęp\". Default: add the product to the\n * page cart and open it (mount `BitsnapCheckout` on the page). Throw to\n * show the error line.\n */\n onBuy?: (request: ChatBuyRequest) => Promise<void> | void;\n /** The product or variant the buy action sells (e.g. the pack variant). */\n buyProductId?: string;\n className?: string;\n /** A ready client (tests, custom transport). Replaces token and URLs. */\n client?: ChatClient;\n /** @internal Replaces the NATS loader (tests). */\n loadNats?: () => Promise<NatsModule>;\n};\n\nexport type ChatThreadProps = ChatWidgetBaseProps & {\n /** The service product of the pack: opens its thread, creating it if needed. */\n productId?: string;\n /** An existing thread. Give this or `productId`. */\n threadId?: string;\n};\n\nexport type ChannelProps = ChatWidgetBaseProps & {\n /** The channel (its id is also the id of its conversation). */\n channelId: string;\n /** The community product sold by the lock; defaults to the channel's own. */\n productId?: string;\n};\n\n/**\n * The chat client of a widget. The panel session lives in localStorage, so\n * it is read after mounting (`null` until then: the widget stays loading and\n * the server HTML has no session-dependent content).\n */\nfunction useWidgetClient(props: ChatWidgetBaseProps): ChatClient | null | undefined {\n const [stored, setStored] = useState<string | undefined | null>(null);\n const host = props.host ?? getPanelConfig().host;\n useEffect(() => {\n if (props.client || props.token) return;\n setStored(getPanelSession(props.projectID, host));\n }, [props.client, props.token, props.projectID, host]);\n const token = props.token ?? stored;\n const projectId = props.chatProjectID ?? props.projectID;\n return useMemo(() => {\n if (props.client) return props.client;\n if (token === null) return null;\n if (!token) return undefined;\n return createChatClient({ projectId, token, baseUrl: props.apiUrl, attachmentsUrl: props.attachmentsUrl });\n }, [props.client, token, projectId, props.apiUrl, props.attachmentsUrl]);\n}\n\nfunction useBuy(props: ChatWidgetBaseProps) {\n const claim = useRef<{ key: string; token: string; expires: number } | null>(null);\n return async (lock: ConversationLock & { email?: string; code?: string; turnstileToken?: string }) => {\n const productId = props.buyProductId ?? lock.productId;\n if (!productId) return;\n const request: ChatBuyRequest = { productId, reason: lock.reason, priceCents: lock.priceCents, ...(lock.amount != null ? { amount: lock.amount } : {}), ...(lock.email ? { email: lock.email } : {}), ...(lock.code ? { code: lock.code } : {}), ...(lock.turnstileToken != null ? { turnstileToken: lock.turnstileToken } : {}) };\n if (props.onBuy) {\n await props.onBuy(request);\n return;\n }\n const commerceBase = (props.host ?? getPanelConfig().host ?? \"https://bitsnap.pl\").replace(/\\/+$/, \"\");\n const isFreeClaim = lock.freeClaimLimit != null && (lock.priceType === \"free\" || (lock.priceType === \"pay_what_you_want\" && lock.minimumCents === 0 && request.amount === 0));\n if (isFreeClaim && request.email && request.turnstileToken != null) {\n claim.current = null;\n const response = await fetch(`${commerceBase}/api/integrations/${encodeURIComponent(props.projectID)}/public-commerce/free-claim/request-code`, {\n method: \"POST\", headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email: request.email, turnstileToken: request.turnstileToken }),\n });\n const result = await response.json() as { code?: string };\n if (!response.ok) throw new Error(result.code ?? \"internal\");\n return;\n }\n if (isFreeClaim && request.email && request.code) {\n const key = JSON.stringify([commerceBase, props.projectID, productId, request.email, request.code]);\n if (!claim.current || claim.current.key !== key || claim.current.expires <= Date.now()) {\n claim.current = null;\n const verify = await fetch(`${commerceBase}/api/integrations/${encodeURIComponent(props.projectID)}/public-commerce/free-claim/verify-code`, {\n method: \"POST\", headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email: request.email, code: request.code }),\n });\n const verified = await verify.json() as { claimToken?: string; code?: string; expiresIn?: number };\n if (!verify.ok || !verified.claimToken) throw new Error(verified.code ?? \"email-verification-required\");\n claim.current = { key, token: verified.claimToken, expires: Date.now() + (verified.expiresIn ?? 600) * 1000 };\n }\n const bought = await fetch(`${commerceBase}/api/integrations/${encodeURIComponent(props.projectID)}/public-commerce/buy`, {\n method: \"POST\", headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ items: [{ id: productId, quantity: 1, amount: 0 }], details: { email: request.email }, claimToken: claim.current.token }),\n });\n const result = await bought.json() as { success?: boolean; url?: string; code?: string };\n if (!bought.ok || !result.url) throw new Error(result.code ?? \"free-order-not-supported\");\n window.location.assign(result.url);\n return;\n }\n await addPackToCart({\n projectID: props.projectID,\n productId,\n name: props.title,\n priceCents: lock.priceCents,\n amount: lock.amount,\n host: props.host,\n });\n };\n}\n\n/**\n * A buyer's pack thread for one service product: history, live updates,\n * sending with pending and refused states, report and mute, and the lock\n * with \"Kup pakiet\" when the replies are used up or the pack expired.\n * Load `bitsnap-react/dist/index.css` once.\n */\nexport function ChatThread(props: ChatThreadProps) {\n const client = useWidgetClient(props);\n const locale = props.locale ?? getLocale();\n const texts = useMemo(() => getChatTexts(props.texts, locale), [props.texts, locale]);\n const conversation = useConversation({\n client,\n target: { kind: \"thread\", threadId: props.threadId, productId: props.productId },\n pollIntervalMs: props.pollIntervalMs,\n realtimeUrl: props.realtimeUrl,\n loadNats: props.loadNats,\n });\n const buy = useBuy(props);\n return (\n <div className=\"bitsnap-react h-full\">\n <ConversationView\n host={props.host}\n conversation={conversation}\n texts={texts}\n locale={locale}\n kind=\"thread\"\n title={props.title}\n onBack={props.onBack}\n onBuy={buy}\n className={props.className}\n />\n </div>\n );\n}\n\n/**\n * A community channel: messages, live updates, posting when the channel\n * allows it (with the channel's moderation refusals shown on the message),\n * report, and the lock with \"Kup dostęp\" for a buyer without a grant.\n * Load `bitsnap-react/dist/index.css` once.\n */\nexport function Channel(props: ChannelProps) {\n const client = useWidgetClient(props);\n const locale = props.locale ?? getLocale();\n const texts = useMemo(() => getChatTexts(props.texts, locale), [props.texts, locale]);\n const conversation = useConversation({\n client,\n target: { kind: \"channel\", channelId: props.channelId, productId: props.productId },\n pollIntervalMs: props.pollIntervalMs,\n realtimeUrl: props.realtimeUrl,\n loadNats: props.loadNats,\n });\n const buy = useBuy(props);\n return (\n <div className=\"bitsnap-react h-full\">\n <ConversationView\n host={props.host}\n conversation={conversation}\n texts={texts}\n locale={locale}\n kind=\"channel\"\n title={props.title}\n onBack={props.onBack}\n onBuy={buy}\n className={props.className}\n />\n </div>\n );\n}\n","import { addProductToCart } from \"../components/products/add-to-cart\";\n\nexport type BuyPackInput = {\n /** Public project id of the shop (the cart's project). */\n projectID: string;\n /** The product (or variant) to add: the pack's service or community product. */\n productId: string;\n name?: string;\n priceCents?: number;\n amount?: number;\n /** Backend origin of the cart, when not the default. */\n host?: string;\n};\n\n/**\n * Default \"Kup pakiet\" / \"Kup dostęp\" action: adds the product to the page\n * cart (`Bitsnap.addProductToCart`) and opens the cart drawer. The page needs\n * a mounted `BitsnapCheckout`. When the page cart belongs to another project\n * or host nothing changes and the promise rejects; pass `onBuy` to the widget\n * to use your own checkout instead.\n */\nexport async function addPackToCart(input: BuyPackInput): Promise<void> {\n await addProductToCart(\n {\n id: input.productId,\n name: input.name ?? \"\",\n price: input.priceCents ?? 0,\n currency: \"\",\n amount: input.amount,\n },\n { projectID: input.projectID, host: input.host, showCart: true },\n );\n}\n","/**\n * Buyer side of the Bitsnap chat service (`bitsnap-messaging`): the shapes\n * the library works with. The wire is snake_case JSON; `client.ts` maps it to\n * these camelCase types. Times are ISO 8601 strings, `null` when absent.\n */\n\n/** Default base URL of the chat service. */\nexport const DEFAULT_CHAT_API_URL = \"https://chat.bitsnap.pl\";\n/** Bitsnap API that authenticates callers before signing private attachment URLs. */\nexport const DEFAULT_CHAT_ATTACHMENTS_URL = \"https://bitsnap.pl\";\n\n/** Default NATS WebSocket URL, used when the realtime token lists no server. */\nexport const DEFAULT_CHAT_REALTIME_URL =\n \"wss://bitsnap-nats-queue-production.up.railway.app\";\n\n/** One paid order that gives a pack thread creator replies. */\nexport type ChatPack = {\n orderId: string;\n productId?: string;\n replies: number;\n used: number;\n left: number;\n expiresAt: string | null;\n expired: boolean;\n};\n\n/** A stored message, or the pending answer of a send. */\nexport type ChatMessage = {\n id: string;\n threadId: string;\n authorEmail: string;\n body: string;\n attachmentKey?: string;\n attachmentKind?: string;\n attachmentName?: string;\n attachmentSize?: number;\n attachmentContentType?: string;\n createdAt: string;\n pinned: boolean;\n /** Soft deleted: the body is empty. */\n deleted: boolean;\n /** A message of the service, such as the creator's away notice. */\n system: boolean;\n /** `\"pending\"` in the answer of a send: queued, not stored yet. */\n status?: \"pending\";\n};\n\nexport type ChatAttachment = {\n key: string;\n kind: \"image\" | \"file\";\n filename: string;\n size: number;\n contentType: string;\n};\n\n/** The state of a conversation for the caller (`ThreadView` on the wire). */\nexport type ChatThreadSummary = {\n id: string;\n kind: \"pack\" | \"channel\";\n channelId?: string;\n /** For a buyer, the creator's e-mail (pack) or the channel name. */\n title: string;\n lastMessage?: ChatMessage;\n unread: number;\n repliesTotal: number;\n repliesUsed: number;\n repliesLeft: number;\n expiresAt: string | null;\n /** The caller cannot write: every pack has expired. */\n composerLocked: boolean;\n /** The creator blocked this buyer from posting. */\n blocked?: boolean;\n productId?: string;\n /** The creator's promise in hours (\"odpowiedź w ciągu 48 h\"), 0 for none. */\n responseHours: number;\n packs: ChatPack[];\n muted: boolean;\n};\n\n/** A channel the caller may read. */\nexport type ChatChannelSummary = {\n id: string;\n name: string;\n topic: string;\n welcome: string;\n whoCanPost: \"creator\" | \"members\";\n productId: string;\n /** `creator`, `member` or `muted`. */\n role: string;\n memberCount: number;\n createdAt: string;\n blockLinks: boolean;\n blockMedia: boolean;\n cooldownSeconds: number;\n};\n\n/** A pack the buyer holds and has not opened a thread for yet. */\nexport type ChatPackEntitlement = {\n productId: string;\n name: string;\n repliesLeftHint: number;\n expiresAt: string | null;\n};\n\n/** A community product the buyer holds; `channelId` once a channel is bound. */\nexport type ChatChannelEntitlement = {\n productId: string;\n channelId?: string;\n};\n\n/** `GET /v1/me`: the buyer's chat in one project. */\nexport type ChatMe = {\n email: string;\n threads: ChatThreadSummary[];\n entitlements: {\n packs: ChatPackEntitlement[];\n channels: ChatChannelEntitlement[];\n };\n channels: ChatChannelSummary[];\n};\n\n/** One page of history, newest first as the service answers it. */\nexport type ChatMessagePage = {\n messages: ChatMessage[];\n hasMore: boolean;\n};\n\n/** The thread part of a send answer. */\nexport type ChatThreadState = Pick<\n ChatThreadSummary,\n | \"id\"\n | \"kind\"\n | \"repliesTotal\"\n | \"repliesUsed\"\n | \"repliesLeft\"\n | \"expiresAt\"\n | \"composerLocked\"\n | \"responseHours\"\n>;\n\n/** `POST /v1/threads/{id}/messages` answers 202 with the queued message. */\nexport type ChatSendResult = {\n message: ChatMessage;\n thread: ChatThreadState;\n};\n\nexport type ChatReportReason = \"spam\" | \"abuse\" | \"illegal\" | \"other\";\n\n/** `POST /v1/realtime/token`. */\nexport type ChatRealtimeToken = {\n jwt: string;\n expiresAt: string;\n servers: string[];\n subjects: string[];\n truncated: boolean;\n};\n\n/** Live events on the thread or channel subject. */\nexport type ChatRealtimeEvent =\n | { type: \"message.created\"; message: ChatMessage }\n | { type: \"message.rejected\"; id: string; reason: string }\n | { type: \"message.deleted\"; id: string }\n | { type: \"message.pinned\"; id: string }\n | { type: \"message.unpinned\"; id: string };\n\n/** How a conversation hears about new messages. */\nexport type ChatLiveMode = \"connecting\" | \"live\" | \"polling\" | \"off\";\n","import {\n DEFAULT_CHAT_API_URL,\n DEFAULT_CHAT_ATTACHMENTS_URL,\n type ChatChannelSummary,\n type ChatAttachment,\n type ChatMe,\n type ChatMessage,\n type ChatMessagePage,\n type ChatPack,\n type ChatRealtimeEvent,\n type ChatRealtimeToken,\n type ChatReportReason,\n type ChatSendResult,\n type ChatThreadState,\n type ChatThreadSummary,\n} from \"./types\";\n\n/**\n * An error answer of the chat service (`{\"error\":\"<code>\"}`), or `network`\n * (status 0) when the request did not get an answer.\n *\n * Codes the buyer UI handles: `unauthorized` (401), `plan_required`,\n * `locked`, `muted`, `blocked`, `forbidden`, `read_only` (403), `not_found`\n * (404), `moderation_link`, `moderation_banned_word`, `moderation_media`\n * (422), `cooldown` (429, with `retryAfter`), `unavailable` (503),\n * `invalid_project` (400).\n */\nexport class ChatError extends Error {\n readonly code: string;\n readonly status: number;\n /** `cooldown`: seconds to wait before the next post. */\n readonly retryAfter?: number;\n /** Extra fields of the answer (`locked`: product, price type and bounds). */\n readonly data: Record<string, unknown>;\n\n constructor(\n code: string,\n status: number,\n data: Record<string, unknown> = {},\n ) {\n super(`chat: ${code} (${status})`);\n this.name = \"ChatError\";\n this.code = code;\n this.status = status;\n this.data = data;\n const retry = Number(data.retry_after);\n if (Number.isFinite(retry) && retry > 0) this.retryAfter = retry;\n }\n}\n\nexport type ChatClientOptions = {\n /** Project id sent as `X-Bitsnap-Project`. */\n projectId: string;\n /** Bearer credential: the panel session token or a `bcht_` buyer token. */\n token: string;\n /** Base URL of the chat service. Defaults to `https://chat.bitsnap.pl`. */\n baseUrl?: string;\n /** Bitsnap app host for private attachment upload and read endpoints. */\n attachmentsUrl?: string;\n /** Replaces `fetch` (tests, server rendering). */\n fetch?: typeof fetch;\n};\n\n/** The buyer calls of the chat service HTTP API. */\nexport type ChatClient = {\n readonly baseUrl: string;\n readonly projectId: string;\n me(): Promise<ChatMe>;\n /** Opens or returns the pack thread of a service product. */\n openThread(productId: string): Promise<ChatThreadSummary>;\n /** Newest first; `before` is a message id. */\n messages(\n threadId: string,\n options?: { before?: string; limit?: number },\n ): Promise<ChatMessagePage>;\n /** Queues a message. The service answers 202 with `status: \"pending\"`. */\n send(\n threadId: string,\n input: { body: string; clientId?: string; attachment?: ChatAttachment },\n ): Promise<ChatSendResult>;\n uploadAttachment(threadId: string, file: File, progress: (value: number) => void): Promise<ChatAttachment>;\n attachmentURL(threadId: string, message: ChatMessage): Promise<string>;\n deleteMessage(threadId: string, messageId: string): Promise<void>;\n mute(threadId: string, muted: boolean): Promise<void>;\n report(input: {\n threadId: string;\n messageId?: string;\n reason: ChatReportReason;\n note?: string;\n }): Promise<void>;\n markRead(threadId: string, messageId: string): Promise<void>;\n /**\n * A NATS token for every conversation the caller may read. The answer is\n * kept until a minute and a half before it expires (the service mints one\n * per caller every 10 s); `fresh` asks for a new one.\n */\n realtimeToken(options?: { fresh?: boolean }): Promise<ChatRealtimeToken>;\n};\n\nexport function createChatClient(options: ChatClientOptions): ChatClient {\n const baseUrl = (options.baseUrl || DEFAULT_CHAT_API_URL).replace(/\\/+$/, \"\");\n const localOrigin = typeof window !== \"undefined\" && [\"localhost\", \"127.0.0.1\"].includes(window.location.hostname) ? window.location.origin : undefined;\n const attachmentBase = (options.attachmentsUrl ?? localOrigin ?? DEFAULT_CHAT_ATTACHMENTS_URL).replace(/\\/+$/, \"\");\n const doFetch = options.fetch ?? ((...args) => fetch(...args));\n\n async function call(\n method: string,\n path: string,\n body?: unknown,\n ): Promise<{ status: number; json: unknown }> {\n let response: Response;\n try {\n response = await doFetch(baseUrl + path, {\n method,\n headers: {\n Authorization: `Bearer ${options.token}`,\n \"X-Bitsnap-Project\": options.projectId,\n ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch {\n throw new ChatError(\"network\", 0);\n }\n let json: unknown = null;\n try {\n const text = await response.text();\n json = text ? JSON.parse(text) : null;\n } catch {\n json = null;\n }\n if (!response.ok) {\n const data = isRecord(json) ? json : {};\n const code = typeof data.error === \"string\" ? data.error : \"internal_error\";\n throw new ChatError(code, response.status, data);\n }\n return { status: response.status, json };\n }\n\n const id = encodeURIComponent;\n let cachedToken: ChatRealtimeToken | undefined;\n\n return {\n baseUrl,\n projectId: options.projectId,\n async me() {\n const { json } = await call(\"GET\", \"/v1/me\");\n return mapMe(json);\n },\n async openThread(productId) {\n const { json } = await call(\"POST\", \"/v1/threads\", {\n product_id: productId,\n });\n return mapThread(json);\n },\n async messages(threadId, opts = {}) {\n const query = new URLSearchParams();\n if (opts.before) query.set(\"before\", opts.before);\n if (opts.limit) query.set(\"limit\", String(opts.limit));\n const qs = query.toString();\n const suffix = qs ? `?${qs}` : \"\";\n const { json } = await call(\n \"GET\",\n `/v1/threads/${id(threadId)}/messages${suffix}`,\n );\n const page = isRecord(json) ? json : {};\n return {\n messages: arr(page.messages).map(mapMessage),\n hasMore: page.has_more === true,\n };\n },\n async send(threadId, input) {\n const { json } = await call(\n \"POST\",\n `/v1/threads/${id(threadId)}/messages`,\n {\n body: input.body,\n ...(input.clientId ? { client_id: input.clientId } : {}),\n ...(input.attachment ? {\n attachment_key: input.attachment.key,\n attachment_kind: input.attachment.kind,\n attachment_name: input.attachment.filename,\n attachment_size: input.attachment.size,\n attachment_content_type: input.attachment.contentType,\n } : {}),\n },\n );\n const res = isRecord(json) ? json : {};\n return {\n message: mapMessage(res.message),\n thread: mapThreadState(res.thread),\n };\n },\n async uploadAttachment(threadId, file, progress) {\n const requestAttachment = async <T,>(path: string, body: unknown): Promise<T> => {\n const response = await doFetch(`${attachmentBase}/api/chat/attachments/${path}`, {\n method: \"POST\",\n headers: { Authorization: `Bearer ${options.token}`, \"X-Bitsnap-Project\": options.projectId, \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n let data: Record<string, unknown> = {};\n try { data = await response.json() as Record<string, unknown>; } catch { /* parsed as request error below */ }\n if (!response.ok) throw new ChatError(typeof data.error === \"string\" ? data.error : \"request_failed\", response.status, data);\n return data as T;\n };\n const ticket = await requestAttachment<{ key: string; uploadURL: string; uploadTicket: string }>(\"upload\", {\n project_id: options.projectId, thread_id: threadId, filename: file.name, content_type: file.type, size: file.size,\n });\n await new Promise<void>((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(\"PUT\", ticket.uploadURL);\n xhr.setRequestHeader(\"Content-Type\", file.type);\n xhr.upload.onprogress = (event) => { if (event.lengthComputable) progress(Math.round(event.loaded / event.total * 100)); };\n xhr.onload = () => xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new ChatError(\"upload_failed\", xhr.status));\n xhr.onerror = () => reject(new ChatError(\"network\", 0));\n xhr.send(file);\n });\n const done = await requestAttachment<{ key: string; kind: \"image\" | \"file\"; filename: string; size: number; content_type: string }>(\"complete\", {\n project_id: options.projectId, thread_id: threadId, key: ticket.key, upload_ticket: ticket.uploadTicket, filename: file.name, content_type: file.type, size: file.size,\n });\n return { key: done.key, kind: done.kind, filename: done.filename, size: done.size, contentType: done.content_type };\n },\n async attachmentURL(threadId, message) {\n if (!message.attachmentKey) throw new ChatError(\"invalid_attachment\", 400);\n const query = new URLSearchParams({ project_id: options.projectId, thread_id: threadId, key: message.attachmentKey, filename: message.attachmentName ?? \"attachment\", size: String(message.attachmentSize ?? 0) });\n const response = await doFetch(`${attachmentBase}/api/chat/attachments/read?${query}`, { headers: { Authorization: `Bearer ${options.token}`, \"X-Bitsnap-Project\": options.projectId } });\n let data: Record<string, unknown> = {};\n try { data = await response.json() as Record<string, unknown>; } catch { /* parsed as request error below */ }\n if (!response.ok || typeof data.url !== \"string\") throw new ChatError(typeof data.error === \"string\" ? data.error : \"request_failed\", response.status, data);\n return data.url;\n },\n async deleteMessage(threadId, messageId) {\n await call(\n \"DELETE\",\n `/v1/threads/${id(threadId)}/messages/${id(messageId)}`,\n );\n },\n async mute(threadId, muted) {\n await call(\"POST\", `/v1/threads/${id(threadId)}/mute`, { muted });\n },\n async report(input) {\n await call(\"POST\", \"/v1/reports\", {\n thread_id: input.threadId,\n ...(input.messageId ? { message_id: input.messageId } : {}),\n reason: input.reason,\n ...(input.note ? { note: input.note } : {}),\n });\n },\n async markRead(threadId, messageId) {\n await call(\"POST\", `/v1/threads/${id(threadId)}/receipts`, {\n state: \"read\",\n message_id: messageId,\n });\n },\n async realtimeToken(opts = {}) {\n if (\n !opts.fresh &&\n cachedToken &&\n Date.parse(cachedToken.expiresAt) - Date.now() > 90_000\n ) {\n return cachedToken;\n }\n const { json } = await call(\"POST\", \"/v1/realtime/token\");\n const res = isRecord(json) ? json : {};\n return (cachedToken = {\n jwt: str(res.jwt),\n expiresAt: str(res.expires_at),\n servers: arr(res.servers).filter((s): s is string => typeof s === \"string\"),\n subjects: arr(res.subjects).filter((s): s is string => typeof s === \"string\"),\n truncated: res.truncated === true,\n });\n },\n };\n}\n\n/** Parses one live event of the thread or channel subject. */\nexport function parseRealtimeEvent(raw: unknown): ChatRealtimeEvent | null {\n if (!isRecord(raw) || typeof raw.type !== \"string\") return null;\n const eventId = str(raw.id);\n switch (raw.type) {\n case \"message.created\":\n return { type: \"message.created\", message: mapMessage(raw) };\n case \"message.rejected\":\n return { type: \"message.rejected\", id: eventId, reason: str(raw.reason) };\n case \"message.deleted\":\n case \"message.pinned\":\n case \"message.unpinned\":\n return { type: raw.type, id: eventId };\n default:\n return null;\n }\n}\n\n// --- wire mapping -------------------------------------------------------\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value != null && !Array.isArray(value);\n}\n\nfunction arr(value: unknown): unknown[] {\n return Array.isArray(value) ? value : [];\n}\n\nfunction str(value: unknown): string {\n return typeof value === \"string\" ? value : value == null ? \"\" : String(value);\n}\n\nfunction num(value: unknown): number {\n const n = Number(value);\n return Number.isFinite(n) ? n : 0;\n}\n\nfunction optStr(value: unknown): string | undefined {\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\nfunction time(value: unknown): string | null {\n return typeof value === \"string\" && value !== \"\" ? value : null;\n}\n\nexport function mapMessage(raw: unknown): ChatMessage {\n const m = isRecord(raw) ? raw : {};\n return {\n id: str(m.id),\n threadId: str(m.thread_id),\n authorEmail: str(m.author_email),\n body: str(m.body),\n attachmentKey: optStr(m.attachment_key),\n attachmentKind: optStr(m.attachment_kind),\n attachmentName: optStr(m.attachment_name),\n attachmentSize: num(m.attachment_size),\n attachmentContentType: optStr(m.attachment_content_type),\n createdAt: str(m.created_at),\n pinned: m.pinned === true,\n deleted: m.deleted === true,\n system: m.system === true,\n ...(m.status === \"pending\" ? { status: \"pending\" as const } : {}),\n };\n}\n\nfunction mapPack(raw: unknown): ChatPack {\n const p = isRecord(raw) ? raw : {};\n return {\n orderId: str(p.order_id),\n productId: optStr(p.product_id),\n replies: num(p.replies),\n used: num(p.used),\n left: num(p.left),\n expiresAt: time(p.expires_at),\n expired: p.expired === true,\n };\n}\n\nfunction mapThreadState(raw: unknown): ChatThreadState {\n const t = isRecord(raw) ? raw : {};\n return {\n id: str(t.id),\n kind: t.kind === \"channel\" ? \"channel\" : \"pack\",\n repliesTotal: num(t.replies_total),\n repliesUsed: num(t.replies_used),\n repliesLeft: num(t.replies_left),\n expiresAt: time(t.expires_at),\n composerLocked: t.composer_locked === true,\n responseHours: num(t.response_hours),\n };\n}\n\nexport function mapThread(raw: unknown): ChatThreadSummary {\n const t = isRecord(raw) ? raw : {};\n return {\n ...mapThreadState(t),\n channelId: optStr(t.channel_id),\n title: str(t.title),\n lastMessage: isRecord(t.last_message) ? mapMessage(t.last_message) : undefined,\n unread: num(t.unread),\n productId: optStr(t.product_id),\n blocked: t.blocked === true,\n packs: arr(t.packs).map(mapPack),\n muted: t.muted === true,\n };\n}\n\nfunction mapChannel(raw: unknown): ChatChannelSummary {\n const c = isRecord(raw) ? raw : {};\n return {\n id: str(c.id),\n name: str(c.name),\n topic: str(c.topic),\n welcome: str(c.welcome),\n whoCanPost: c.who_can_post === \"members\" ? \"members\" : \"creator\",\n productId: str(c.product_id),\n role: str(c.role),\n memberCount: num(c.member_count),\n createdAt: str(c.created_at),\n blockLinks: c.block_links === true,\n blockMedia: c.block_media === true,\n cooldownSeconds: num(c.cooldown_seconds),\n };\n}\n\nfunction mapMe(raw: unknown): ChatMe {\n const m = isRecord(raw) ? raw : {};\n const ent = isRecord(m.entitlements) ? m.entitlements : {};\n return {\n email: str(m.email),\n threads: arr(m.threads).map(mapThread),\n entitlements: {\n packs: arr(ent.packs).map((raw) => {\n const p = isRecord(raw) ? raw : {};\n return {\n productId: str(p.product_id),\n name: str(p.name),\n repliesLeftHint: num(p.replies_left_hint),\n expiresAt: time(p.expires_at),\n };\n }),\n channels: arr(ent.channels).map((raw) => {\n const c = isRecord(raw) ? raw : {};\n return { productId: str(c.product_id), channelId: optStr(c.channel_id) };\n }),\n },\n channels: arr(m.channels).map(mapChannel),\n };\n}\n"]}