@linktr.ee/messaging-react 4.2.0-rc-1787255254 → 4.2.0-rc-1787325521

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 (53) hide show
  1. package/dist/Card-BYJyA83X.js +701 -0
  2. package/dist/Card-BYJyA83X.js.map +1 -0
  3. package/dist/Card-Be81K6su.cjs +2 -0
  4. package/dist/Card-Be81K6su.cjs.map +1 -0
  5. package/dist/Card-BplJtZao.cjs +2 -0
  6. package/dist/Card-BplJtZao.cjs.map +1 -0
  7. package/dist/Card-BzvDr-pU.js +112 -0
  8. package/dist/Card-BzvDr-pU.js.map +1 -0
  9. package/dist/PurchaseStatusBadge-BmqAQEV9.cjs +2 -0
  10. package/dist/PurchaseStatusBadge-BmqAQEV9.cjs.map +1 -0
  11. package/dist/PurchaseStatusBadge-D1RRsubZ.js +59 -0
  12. package/dist/PurchaseStatusBadge-D1RRsubZ.js.map +1 -0
  13. package/dist/assets/index.css +1 -2
  14. package/dist/index-BUC9vqhJ.js +5916 -0
  15. package/dist/index-BUC9vqhJ.js.map +1 -0
  16. package/dist/index-BkqyKPJP.cjs +3 -0
  17. package/dist/index-BkqyKPJP.cjs.map +1 -0
  18. package/dist/index.cjs +2 -3
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.ts +26 -0
  21. package/dist/index.js +41 -4071
  22. package/dist/index.js.map +1 -1
  23. package/dist/testing.cjs +2 -2
  24. package/dist/testing.cjs.map +1 -1
  25. package/dist/testing.js +118 -106
  26. package/dist/testing.js.map +1 -1
  27. package/package.json +5 -5
  28. package/src/components/ChannelView.stories.tsx +4 -0
  29. package/src/components/CustomMessageInput/index.tsx +1 -1
  30. package/src/index.ts +3 -0
  31. package/src/logging/index.test.tsx +136 -0
  32. package/src/logging/index.tsx +48 -0
  33. package/src/providers/MessagingProvider.test.tsx +127 -1
  34. package/src/providers/MessagingProvider.tsx +26 -15
  35. package/src/styles.css +46 -89
  36. package/src/types.ts +8 -0
  37. package/dist/AttachmentCard-C-X0jLZ2.cjs +0 -2
  38. package/dist/AttachmentCard-C-X0jLZ2.cjs.map +0 -1
  39. package/dist/AttachmentCard-D2IoHdcv.js +0 -410
  40. package/dist/AttachmentCard-D2IoHdcv.js.map +0 -1
  41. package/dist/Card-C7uLQbYz.js +0 -105
  42. package/dist/Card-C7uLQbYz.js.map +0 -1
  43. package/dist/Card-DENHpLIC.cjs +0 -2
  44. package/dist/Card-DENHpLIC.cjs.map +0 -1
  45. package/dist/Card-Ds1FMcUj.cjs +0 -2
  46. package/dist/Card-Ds1FMcUj.cjs.map +0 -1
  47. package/dist/Card-EKD9NkTa.js +0 -498
  48. package/dist/Card-EKD9NkTa.js.map +0 -1
  49. package/dist/LoadingDots-BSk_UeS0.cjs +0 -2
  50. package/dist/LoadingDots-BSk_UeS0.cjs.map +0 -1
  51. package/dist/LoadingDots-B_WiXBeQ.js +0 -73
  52. package/dist/LoadingDots-B_WiXBeQ.js.map +0 -1
  53. package/dist/rolldown-runtime-BocRIvOZ.cjs +0 -1
package/dist/testing.cjs CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("stream-chat");function t(t,{stubConnection:n=!1}={}){let r=new e.StreamChat(`mock-api-key`,{allowServerSideConnect:!0});return r.userID=t.id,r.user=t,n&&(r.connectUser=async()=>({me:t}),r.disconnectUser=async()=>void 0,r.userMuteStatus=(()=>!1)),r}var n=600;function r({currentUser:e,participant:r,messages:i=[],channelId:a=`mock-dm`,onSend:o}){let s=t(e,{stubConnection:!0}),c=`messaging:${a}`,l=(t,n)=>{let a=t.from===`me`?e:r,o=new Date(Date.now()-(i.length-n)*6e4);return{id:t.id??`mock-msg-${n}`,text:t.text??``,type:`regular`,html:t.text?`<p>${t.text}</p>`:``,user:a,attachments:t.attachments??[],latest_reactions:[],own_reactions:[],reaction_counts:{},reaction_scores:{},reply_count:0,status:`received`,cid:c,created_at:o,updated_at:o,mentioned_users:[],...t.metadata?{metadata:t.metadata}:{}}},u=i.map(l),d={[e.id]:{user:{...e,is_account:!1},user_id:e.id,role:`owner`,is_account:!1},[r.id]:{user:{...r,is_account:!0},user_id:r.id,role:`member`,is_account:!0}},f=s.channel(`messaging`,a,{members:[e.id,r.id]});f.muteStatus=()=>({muted:!1,createdAt:null,expiresAt:null}),f.markRead=(async()=>({})),f.keystroke=(async()=>void 0),f.stopTyping=(async()=>void 0),f.sendReaction=(async()=>({})),f.deleteReaction=(async()=>({})),f.countUnread=(()=>0),f.query=(async()=>({messages:[]})),f.hide=(async()=>({}));let p=!1;f.watch=async()=>(p||=(f.state.messages=u,!0),f.state.members=d,{channel:{members:[e.id,r.id]},members:[],messages:f.state.messages,watchers:[],pinned_messages:[],duration:`0ms`});let m=e=>{f.state.addMessageSorted(e),s.dispatchEvent({type:`message.new`,cid:c,message:e,user:e.user??void 0})},h=0,g=0;return f.sendMessage=async t=>{let r=typeof t==`string`?t:t?.text??``,i={...l({text:r,from:`me`,id:`mock-sent-${h++}`},u.length),...typeof t==`object`?t:{},user:e,cid:c};m(i);let a=o?.(r);if(a){let e=typeof a==`string`?a:a.text,t=typeof a==`string`?void 0:a.attachments,r=`mock-reply-${g++}`;setTimeout(()=>{m(l({text:e,from:`them`,attachments:t,id:r},u.length))},n)}return{message:i}},s.queryChannels=async()=>[f],f.watch(),{client:s,channel:f,participantFilterId:r.id}}exports.createMockMessagingClient=r;
2
- //# sourceMappingURL=testing.cjs.map
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("stream-chat");function v(s,{stubConnection:n=!1}={}){const a=new b.StreamChat("mock-api-key",{allowServerSideConnect:!0});return a.userID=s.id,a.user=s,n&&(a.connectUser=async()=>({me:s}),a.disconnectUser=async()=>{},a.userMuteStatus=(()=>!1)),a}const w=600;function x({currentUser:s,participant:n,messages:a=[],channelId:y="mock-dm",onSend:d}){const r=v(s,{stubConnection:!0}),u=`messaging:${y}`,l=(t,c)=>{const i=t.from==="me"?s:n,o=new Date(Date.now()-(a.length-c)*6e4);return{id:t.id??`mock-msg-${c}`,text:t.text??"",type:"regular",html:t.text?`<p>${t.text}</p>`:"",user:i,attachments:t.attachments??[],latest_reactions:[],own_reactions:[],reaction_counts:{},reaction_scores:{},reply_count:0,status:"received",cid:u,created_at:o,updated_at:o,mentioned_users:[],...t.metadata?{metadata:t.metadata}:{}}},m=a.map(l),_={[s.id]:{user:{...s,is_account:!1},user_id:s.id,role:"owner",is_account:!1},[n.id]:{user:{...n,is_account:!0},user_id:n.id,role:"member",is_account:!0}},e=r.channel("messaging",y,{members:[s.id,n.id]});e.muteStatus=()=>({muted:!1,createdAt:null,expiresAt:null}),e.markRead=(async()=>({})),e.keystroke=(async()=>{}),e.stopTyping=(async()=>{}),e.sendReaction=(async()=>({})),e.deleteReaction=(async()=>({})),e.countUnread=(()=>0),e.query=(async()=>({messages:[]})),e.hide=(async()=>({}));let h=!1;e.watch=async()=>(h||(e.state.messages=m,h=!0),e.state.members=_,{channel:{members:[s.id,n.id]},members:[],messages:e.state.messages,watchers:[],pinned_messages:[],duration:"0ms"});const f=t=>{e.state.addMessageSorted(t),r.dispatchEvent({type:"message.new",cid:u,message:t,user:t.user??void 0})};let p=0,g=0;return e.sendMessage=async t=>{const c=typeof t=="string"?t:(t==null?void 0:t.text)??"",i={...l({text:c,from:"me",id:`mock-sent-${p++}`},m.length),...typeof t=="object"?t:{},user:s,cid:u};f(i);const o=d==null?void 0:d(c);if(o){const M=typeof o=="string"?o:o.text,k=typeof o=="string"?void 0:o.attachments,C=`mock-reply-${g++}`;setTimeout(()=>{f(l({text:M,from:"them",attachments:k,id:C},m.length))},w)}return{message:i}},r.queryChannels=async()=>[e],e.watch(),{client:r,channel:e,participantFilterId:n.id}}exports.createMockMessagingClient=x;
2
+ //# sourceMappingURL=testing.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"testing.cjs","names":[],"sources":["../src/testing/createMockStreamChatClient.ts","../src/testing/createMockMessagingClient.ts"],"sourcesContent":["import { StreamChat } from 'stream-chat'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** A participant in the mock conversation. */\nexport interface MockMessagingUser {\n id: string\n name?: string\n image?: string\n}\n\nexport interface CreateMockStreamChatClientOptions {\n /**\n * Also replace the connection-dependent client methods (`connectUser`,\n * `disconnectUser`, `userMuteStatus`) with offline no-ops. Needed when the\n * client drives a flow that would otherwise open a WebSocket or throw\n * \"Make sure to await connectUser() first.\" offline. Direct `<Chat client>`\n * rendering (e.g. component stories) does not need this.\n */\n stubConnection?: boolean\n}\n\n/**\n * Builds an offline `StreamChat` for mocks and stories: a real client on a\n * throwaway api key with `userID`/`user` set so `<Chat>` treats it as\n * connected without a backend. The single place that knows how to construct a\n * connectionless Stream client, so a stream-chat version bump only needs\n * updating here rather than in each mock surface.\n */\nexport function createMockStreamChatClient(\n user: MockMessagingUser,\n { stubConnection = false }: CreateMockStreamChatClientOptions = {}\n): StreamChat {\n const client = new StreamChat('mock-api-key', {\n allowServerSideConnect: true,\n })\n client.userID = user.id\n client.user = user as any\n\n if (stubConnection) {\n client.connectUser = async () => ({ me: user }) as any\n client.disconnectUser = async () => undefined\n client.userMuteStatus = (() => false) as any\n }\n\n return client\n}\n\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","import type {\n Channel,\n MessageResponse,\n QueryChannelAPIResponse,\n SendMessageAPIResponse,\n} from 'stream-chat'\nimport { StreamChat } from 'stream-chat'\n\nimport {\n createMockStreamChatClient,\n type MockMessagingUser,\n} from './createMockStreamChatClient'\n\n/**\n * A seed message, authored from the viewer's perspective. `from: 'me'` is the\n * connected user (the viewer); `from: 'them'` is the other participant.\n */\nexport interface MockMessage {\n id?: string\n text?: string\n from: 'me' | 'them'\n /** Stream attachment payloads, rendered by the toolkit's attachment gate. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments?: any[]\n /** e.g. `{ custom_type: 'MESSAGE_WELCOME' }`. */\n metadata?: Record<string, unknown>\n}\n\nexport interface CreateMockMessagingClientOptions {\n /** The connected/viewing user. */\n currentUser: MockMessagingUser\n /** The other party in the direct conversation (e.g. the creator/linker). */\n participant: MockMessagingUser\n /** Seed conversation, oldest-first. */\n messages?: MockMessage[]\n /** Channel id; defaults to `mock-dm`. */\n channelId?: string\n /**\n * Optional canned reply. Called after the viewer sends a message; return the\n * reply text (or a partial message) to have `participant` echo a response, or\n * a falsy value for no reply. Drives the \"send echo\" in `dev:mock-messaging`.\n */\n onSend?: (\n text: string\n ) => string | { text?: string; attachments?: unknown[] } | null | undefined\n}\n\nexport interface MockMessagingClient {\n /** Pass to `<MessagingProvider client={...}>`. */\n client: StreamChat\n /** The seeded direct-conversation channel. */\n channel: Channel\n /** Pass to `<MessagingShell initialParticipantFilter={...}>`. */\n participantFilterId: string\n}\n\nconst REPLY_DELAY_MS = 600\n\n/**\n * Builds an offline Stream client seeded with a single direct conversation, so\n * consumers can render the **real** messaging UI (MessagingProvider →\n * MessagingShell → ChannelView) without a Stream backend — for `dev:mock-*`\n * surfaces and Storybook. It is a real `StreamChat` whose network calls\n * (`connectUser`, `queryChannels`, `channel.watch`, `channel.sendMessage`) are\n * replaced with in-memory behaviour driven by Stream's own channel-state\n * machinery, so rendering fidelity matches production.\n *\n * Ships from `@linktr.ee/messaging-react/testing` and must never be imported by\n * production code.\n */\nexport function createMockMessagingClient({\n currentUser,\n participant,\n messages = [],\n channelId = 'mock-dm',\n onSend,\n}: CreateMockMessagingClientOptions): MockMessagingClient {\n // Offline client marked connected without a WebSocket. `stubConnection` also\n // no-ops connectUser/disconnectUser/userMuteStatus: `MessagingProvider`\n // renders `<Chat client={client}>` directly so it never calls connectUser,\n // and handling the `message.new` events dispatched on send + echo below runs\n // Channel._countMessageAsUnread → client.userMuteStatus, which throws offline.\n const client = createMockStreamChatClient(currentUser, {\n stubConnection: true,\n })\n\n const cid = `messaging:${channelId}`\n\n const toStreamMessage = (\n message: MockMessage,\n index: number\n ): MessageResponse => {\n const author = message.from === 'me' ? currentUser : participant\n // Stagger timestamps oldest-first so the list orders naturally. Must be a\n // Date, not an ISO string: we seed `channel.state.messages` directly\n // (bypassing Stream's wire→Date parsing), and stream-chat-react calls\n // `.getTime()` on `created_at` (e.g. useCooldownTimer / addToMessageList).\n const createdAt = new Date(Date.now() - (messages.length - index) * 60_000)\n return {\n id: message.id ?? `mock-msg-${index}`,\n text: message.text ?? '',\n type: 'regular',\n html: message.text ? `<p>${message.text}</p>` : '',\n user: author,\n attachments: message.attachments ?? [],\n latest_reactions: [],\n own_reactions: [],\n reaction_counts: {},\n reaction_scores: {},\n reply_count: 0,\n status: 'received',\n cid,\n created_at: createdAt,\n updated_at: createdAt,\n mentioned_users: [],\n ...(message.metadata ? { metadata: message.metadata } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n const seededMessages = messages.map(toStreamMessage)\n\n const memberState = {\n [currentUser.id]: {\n user: { ...currentUser, is_account: false },\n user_id: currentUser.id,\n role: 'owner',\n is_account: false,\n },\n [participant.id]: {\n user: { ...participant, is_account: true },\n user_id: participant.id,\n role: 'member',\n is_account: true,\n },\n }\n\n const channel = client.channel('messaging', channelId, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: [currentUser.id, participant.id] as any,\n })\n // Read/unread bookkeeping consults channel mute status; without a live\n // connection the real method throws, so report \"not muted\".\n channel.muteStatus = () => ({\n muted: false,\n createdAt: null,\n expiresAt: null,\n })\n\n // Neutralise the rest of the connection-dependent channel API that\n // stream-chat-react calls during the chat lifecycle. Each of these POSTs to\n // Stream or checks for a live WebSocket and would otherwise throw\n // \"Make sure to await connectUser() first.\" offline. They are fire-and-forget\n // (read receipts, typing) or read-only (pagination, unread) so no-ops are safe.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n channel.markRead = (async () => ({}) as any) as any\n channel.keystroke = (async () => undefined) as any\n channel.stopTyping = (async () => undefined) as any\n channel.sendReaction = (async () => ({}) as any) as any\n channel.deleteReaction = (async () => ({}) as any) as any\n channel.countUnread = (() => 0) as any\n // Pagination: report no older pages so \"load more\" resolves to a no-op.\n channel.query = (async () => ({ messages: [] }) as any) as any\n // Leave/Delete Conversation calls channel.hide(); the real method POSTs to\n // Stream, so no-op it to keep the action working offline.\n channel.hide = (async () => ({}) as any) as any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n // Seed state locally instead of fetching. Mirrors the proven ChannelView\n // story mock: override `watch` to populate `state` and return a canned\n // QueryChannelAPIResponse. `stream-chat-react` may call `watch()` again on\n // remount/navigation, so seed only once — otherwise a re-watch would wipe\n // messages added via `sendMessage` + the send-echo reply, resetting the chat.\n let hasSeeded = false\n channel.watch = async () => {\n if (!hasSeeded) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.messages = seededMessages as unknown as any[]\n hasSeeded = true\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.members = memberState as unknown as any\n return {\n channel: { members: [currentUser.id, participant.id] },\n members: [],\n messages: channel.state.messages,\n watchers: [],\n pinned_messages: [],\n duration: '0ms',\n } as unknown as QueryChannelAPIResponse\n }\n\n const appendMessage = (message: MessageResponse) => {\n // addMessageSorted is Stream's own state mutation (dedupes by id), so the\n // toolkit re-renders through the real channel-state path.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.addMessageSorted(message as any)\n client.dispatchEvent({\n type: 'message.new',\n cid,\n message,\n user: message.user ?? undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n }\n\n let sentCount = 0\n let replyCount = 0\n channel.sendMessage = async (message) => {\n const text =\n typeof message === 'string'\n ? message\n : ((message as { text?: string })?.text ?? '')\n const sent = {\n ...toStreamMessage(\n { text, from: 'me', id: `mock-sent-${sentCount++}` },\n seededMessages.length\n ),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...(typeof message === 'object' ? (message as any) : {}),\n user: currentUser,\n cid,\n } as MessageResponse\n\n // stream-chat-react adds the outgoing message optimistically; addMessageSorted\n // dedupes by id, so confirming here is safe and idempotent.\n appendMessage(sent)\n\n const reply = onSend?.(text)\n if (reply) {\n const replyText = typeof reply === 'string' ? reply : reply.text\n const replyAttachments =\n typeof reply === 'string' ? undefined : reply.attachments\n // Capture a unique id before scheduling: two sends within REPLY_DELAY_MS\n // would otherwise both read the same later `sentCount` at fire time and\n // emit colliding reply ids, so Stream's id-based dedupe drops one echo.\n const replyId = `mock-reply-${replyCount++}`\n setTimeout(() => {\n appendMessage(\n toStreamMessage(\n {\n text: replyText,\n from: 'them',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments: replyAttachments as any,\n id: replyId,\n },\n seededMessages.length\n )\n )\n }, REPLY_DELAY_MS)\n }\n\n return { message: sent } as unknown as SendMessageAPIResponse\n }\n\n // MessagingShell finds the direct conversation via queryChannels; always\n // return the one seeded channel regardless of the filter.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client.queryChannels = async () => [channel] as any\n\n // Initialise state up-front so first render already has the conversation.\n void channel.watch()\n\n return { client, channel, participantFilterId: participant.id }\n}\n"],"mappings":"gGA6BA,SAAgB,EACd,EACA,CAAE,iBAAiB,IAA6C,CAAC,EACrD,CACZ,IAAM,EAAS,IAAI,EAAA,WAAW,eAAgB,CAC5C,uBAAwB,EAC1B,CAAC,EAUD,MATA,GAAO,OAAS,EAAK,GACrB,EAAO,KAAO,EAEV,IACF,EAAO,YAAc,UAAa,CAAE,GAAI,CAAK,GAC7C,EAAO,eAAiB,SAAY,IAAA,GACpC,EAAO,oBAAwB,KAG1B,CACT,CCUA,IAAM,EAAiB,IAcvB,SAAgB,EAA0B,CACxC,cACA,cACA,WAAW,CAAC,EACZ,YAAY,UACZ,UACwD,CAMxD,IAAM,EAAS,EAA2B,EAAa,CACrD,eAAgB,EAClB,CAAC,EAEK,EAAM,aAAa,IAEnB,GACJ,EACA,IACoB,CACpB,IAAM,EAAS,EAAQ,OAAS,KAAO,EAAc,EAK/C,EAAY,IAAI,KAAK,KAAK,I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L,QAAS,CAAE,QAAS,CAAC,EAAY,GAAI,EAAY,EAAE,CAAE,EACrD,QAAS,CAAC,EACV,SAAU,EAAQ,MAAM,SACxB,SAAU,CAAC,EACX,gBAAiB,CAAC,EAClB,SAAU,KACZ,GAGF,IAAM,EAAiB,GAA6B,CAIlD,EAAQ,MAAM,iBAAiB,CAAc,EAC7C,EAAO,cAAc,CACnB,KAAM,cACN,MACA,UACA,KAAM,EAAQ,MAAQ,IAAA,EAExB,CAAQ,CACV,EAEI,EAAY,EACZ,EAAa,EAyDjB,MAxDA,GAAQ,YAAc,KAAO,IAAY,CACvC,IAAM,EACJ,OAAO,GAAY,SACf,EACE,GAA+B,MAAQ,GACzC,EAAO,CACX,GAAG,EACD,CAAE,OAAM,KAAM,KAAM,GAAI,aAAa,KAAc,EACnD,EAAe,MACjB,EAEA,GAAI,OAAO,GAAY,SAAY,EAAkB,CAAC,EACtD,KAAM,EACN,KACF,EAIA,EAAc,CAAI,EAElB,IAAM,EAAQ,IAAS,CAAI,EAC3B,GAAI,EAAO,CACT,IAAM,EAAY,OAAO,GAAU,SAAW,EAAQ,EAAM,KACtD,EACJ,OAAO,GAAU,SAAW,IAAA,GAAY,EAAM,YAI1C,EAAU,cAAc,MAC9B,eAAiB,CACf,EACE,EACE,CACE,KAAM,EACN,KAAM,OAEN,YAAa,EACb,GAAI,CACN,EACA,EAAe,MACjB,CACF,CACF,EAAG,CAAc,CACnB,CAEA,MAAO,CAAE,QAAS,CAAK,CACzB,EAKA,EAAO,cAAgB,SAAY,CAAC,CAAO,EAG3C,EAAa,MAAM,EAEZ,CAAE,SAAQ,UAAS,oBAAqB,EAAY,EAAG,CAChE"}
1
+ {"version":3,"file":"testing.cjs","sources":["../src/testing/createMockStreamChatClient.ts","../src/testing/createMockMessagingClient.ts"],"sourcesContent":["import { StreamChat } from 'stream-chat'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** A participant in the mock conversation. */\nexport interface MockMessagingUser {\n id: string\n name?: string\n image?: string\n}\n\nexport interface CreateMockStreamChatClientOptions {\n /**\n * Also replace the connection-dependent client methods (`connectUser`,\n * `disconnectUser`, `userMuteStatus`) with offline no-ops. Needed when the\n * client drives a flow that would otherwise open a WebSocket or throw\n * \"Make sure to await connectUser() first.\" offline. Direct `<Chat client>`\n * rendering (e.g. component stories) does not need this.\n */\n stubConnection?: boolean\n}\n\n/**\n * Builds an offline `StreamChat` for mocks and stories: a real client on a\n * throwaway api key with `userID`/`user` set so `<Chat>` treats it as\n * connected without a backend. The single place that knows how to construct a\n * connectionless Stream client, so a stream-chat version bump only needs\n * updating here rather than in each mock surface.\n */\nexport function createMockStreamChatClient(\n user: MockMessagingUser,\n { stubConnection = false }: CreateMockStreamChatClientOptions = {}\n): StreamChat {\n const client = new StreamChat('mock-api-key', {\n allowServerSideConnect: true,\n })\n client.userID = user.id\n client.user = user as any\n\n if (stubConnection) {\n client.connectUser = async () => ({ me: user }) as any\n client.disconnectUser = async () => undefined\n client.userMuteStatus = (() => false) as any\n }\n\n return client\n}\n\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","import type {\n Channel,\n MessageResponse,\n QueryChannelAPIResponse,\n SendMessageAPIResponse,\n} from 'stream-chat'\nimport { StreamChat } from 'stream-chat'\n\nimport {\n createMockStreamChatClient,\n type MockMessagingUser,\n} from './createMockStreamChatClient'\n\n/**\n * A seed message, authored from the viewer's perspective. `from: 'me'` is the\n * connected user (the viewer); `from: 'them'` is the other participant.\n */\nexport interface MockMessage {\n id?: string\n text?: string\n from: 'me' | 'them'\n /** Stream attachment payloads, rendered by the toolkit's attachment gate. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments?: any[]\n /** e.g. `{ custom_type: 'MESSAGE_WELCOME' }`. */\n metadata?: Record<string, unknown>\n}\n\nexport interface CreateMockMessagingClientOptions {\n /** The connected/viewing user. */\n currentUser: MockMessagingUser\n /** The other party in the direct conversation (e.g. the creator/linker). */\n participant: MockMessagingUser\n /** Seed conversation, oldest-first. */\n messages?: MockMessage[]\n /** Channel id; defaults to `mock-dm`. */\n channelId?: string\n /**\n * Optional canned reply. Called after the viewer sends a message; return the\n * reply text (or a partial message) to have `participant` echo a response, or\n * a falsy value for no reply. Drives the \"send echo\" in `dev:mock-messaging`.\n */\n onSend?: (\n text: string\n ) => string | { text?: string; attachments?: unknown[] } | null | undefined\n}\n\nexport interface MockMessagingClient {\n /** Pass to `<MessagingProvider client={...}>`. */\n client: StreamChat\n /** The seeded direct-conversation channel. */\n channel: Channel\n /** Pass to `<MessagingShell initialParticipantFilter={...}>`. */\n participantFilterId: string\n}\n\nconst REPLY_DELAY_MS = 600\n\n/**\n * Builds an offline Stream client seeded with a single direct conversation, so\n * consumers can render the **real** messaging UI (MessagingProvider →\n * MessagingShell → ChannelView) without a Stream backend — for `dev:mock-*`\n * surfaces and Storybook. It is a real `StreamChat` whose network calls\n * (`connectUser`, `queryChannels`, `channel.watch`, `channel.sendMessage`) are\n * replaced with in-memory behaviour driven by Stream's own channel-state\n * machinery, so rendering fidelity matches production.\n *\n * Ships from `@linktr.ee/messaging-react/testing` and must never be imported by\n * production code.\n */\nexport function createMockMessagingClient({\n currentUser,\n participant,\n messages = [],\n channelId = 'mock-dm',\n onSend,\n}: CreateMockMessagingClientOptions): MockMessagingClient {\n // Offline client marked connected without a WebSocket. `stubConnection` also\n // no-ops connectUser/disconnectUser/userMuteStatus: `MessagingProvider`\n // renders `<Chat client={client}>` directly so it never calls connectUser,\n // and handling the `message.new` events dispatched on send + echo below runs\n // Channel._countMessageAsUnread → client.userMuteStatus, which throws offline.\n const client = createMockStreamChatClient(currentUser, {\n stubConnection: true,\n })\n\n const cid = `messaging:${channelId}`\n\n const toStreamMessage = (\n message: MockMessage,\n index: number\n ): MessageResponse => {\n const author = message.from === 'me' ? currentUser : participant\n // Stagger timestamps oldest-first so the list orders naturally. Must be a\n // Date, not an ISO string: we seed `channel.state.messages` directly\n // (bypassing Stream's wire→Date parsing), and stream-chat-react calls\n // `.getTime()` on `created_at` (e.g. useCooldownTimer / addToMessageList).\n const createdAt = new Date(Date.now() - (messages.length - index) * 60_000)\n return {\n id: message.id ?? `mock-msg-${index}`,\n text: message.text ?? '',\n type: 'regular',\n html: message.text ? `<p>${message.text}</p>` : '',\n user: author,\n attachments: message.attachments ?? [],\n latest_reactions: [],\n own_reactions: [],\n reaction_counts: {},\n reaction_scores: {},\n reply_count: 0,\n status: 'received',\n cid,\n created_at: createdAt,\n updated_at: createdAt,\n mentioned_users: [],\n ...(message.metadata ? { metadata: message.metadata } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n const seededMessages = messages.map(toStreamMessage)\n\n const memberState = {\n [currentUser.id]: {\n user: { ...currentUser, is_account: false },\n user_id: currentUser.id,\n role: 'owner',\n is_account: false,\n },\n [participant.id]: {\n user: { ...participant, is_account: true },\n user_id: participant.id,\n role: 'member',\n is_account: true,\n },\n }\n\n const channel = client.channel('messaging', channelId, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: [currentUser.id, participant.id] as any,\n })\n // Read/unread bookkeeping consults channel mute status; without a live\n // connection the real method throws, so report \"not muted\".\n channel.muteStatus = () => ({\n muted: false,\n createdAt: null,\n expiresAt: null,\n })\n\n // Neutralise the rest of the connection-dependent channel API that\n // stream-chat-react calls during the chat lifecycle. Each of these POSTs to\n // Stream or checks for a live WebSocket and would otherwise throw\n // \"Make sure to await connectUser() first.\" offline. They are fire-and-forget\n // (read receipts, typing) or read-only (pagination, unread) so no-ops are safe.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n channel.markRead = (async () => ({}) as any) as any\n channel.keystroke = (async () => undefined) as any\n channel.stopTyping = (async () => undefined) as any\n channel.sendReaction = (async () => ({}) as any) as any\n channel.deleteReaction = (async () => ({}) as any) as any\n channel.countUnread = (() => 0) as any\n // Pagination: report no older pages so \"load more\" resolves to a no-op.\n channel.query = (async () => ({ messages: [] }) as any) as any\n // Leave/Delete Conversation calls channel.hide(); the real method POSTs to\n // Stream, so no-op it to keep the action working offline.\n channel.hide = (async () => ({}) as any) as any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n // Seed state locally instead of fetching. Mirrors the proven ChannelView\n // story mock: override `watch` to populate `state` and return a canned\n // QueryChannelAPIResponse. `stream-chat-react` may call `watch()` again on\n // remount/navigation, so seed only once — otherwise a re-watch would wipe\n // messages added via `sendMessage` + the send-echo reply, resetting the chat.\n let hasSeeded = false\n channel.watch = async () => {\n if (!hasSeeded) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.messages = seededMessages as unknown as any[]\n hasSeeded = true\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.members = memberState as unknown as any\n return {\n channel: { members: [currentUser.id, participant.id] },\n members: [],\n messages: channel.state.messages,\n watchers: [],\n pinned_messages: [],\n duration: '0ms',\n } as unknown as QueryChannelAPIResponse\n }\n\n const appendMessage = (message: MessageResponse) => {\n // addMessageSorted is Stream's own state mutation (dedupes by id), so the\n // toolkit re-renders through the real channel-state path.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.addMessageSorted(message as any)\n client.dispatchEvent({\n type: 'message.new',\n cid,\n message,\n user: message.user ?? undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n }\n\n let sentCount = 0\n let replyCount = 0\n channel.sendMessage = async (message) => {\n const text =\n typeof message === 'string'\n ? message\n : ((message as { text?: string })?.text ?? '')\n const sent = {\n ...toStreamMessage(\n { text, from: 'me', id: `mock-sent-${sentCount++}` },\n seededMessages.length\n ),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...(typeof message === 'object' ? (message as any) : {}),\n user: currentUser,\n cid,\n } as MessageResponse\n\n // stream-chat-react adds the outgoing message optimistically; addMessageSorted\n // dedupes by id, so confirming here is safe and idempotent.\n appendMessage(sent)\n\n const reply = onSend?.(text)\n if (reply) {\n const replyText = typeof reply === 'string' ? reply : reply.text\n const replyAttachments =\n typeof reply === 'string' ? undefined : reply.attachments\n // Capture a unique id before scheduling: two sends within REPLY_DELAY_MS\n // would otherwise both read the same later `sentCount` at fire time and\n // emit colliding reply ids, so Stream's id-based dedupe drops one echo.\n const replyId = `mock-reply-${replyCount++}`\n setTimeout(() => {\n appendMessage(\n toStreamMessage(\n {\n text: replyText,\n from: 'them',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments: replyAttachments as any,\n id: replyId,\n },\n seededMessages.length\n )\n )\n }, REPLY_DELAY_MS)\n }\n\n return { message: sent } as unknown as SendMessageAPIResponse\n }\n\n // MessagingShell finds the direct conversation via queryChannels; always\n // return the one seeded channel regardless of the filter.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client.queryChannels = async () => [channel] as any\n\n // Initialise state up-front so first render already has the conversation.\n void channel.watch()\n\n return { client, channel, participantFilterId: participant.id }\n}\n"],"names":["createMockStreamChatClient","user","stubConnection","client","StreamChat","REPLY_DELAY_MS","createMockMessagingClient","currentUser","participant","messages","channelId","onSend","cid","toStreamMessage","message","index","author","createdAt","seededMessages","memberState","channel","hasSeeded","appendMessage","sentCount","replyCount","text","sent","reply","replyText","replyAttachments","replyId"],"mappings":"+GA6BO,SAASA,EACdC,EACA,CAAE,eAAAC,EAAiB,EAAA,EAA6C,CAAA,EACpD,CACZ,MAAMC,EAAS,IAAIC,EAAAA,WAAW,eAAgB,CAC5C,uBAAwB,EAAA,CACzB,EACD,OAAAD,EAAO,OAASF,EAAK,GACrBE,EAAO,KAAOF,EAEVC,IACFC,EAAO,YAAc,UAAa,CAAE,GAAIF,CAAA,GACxCE,EAAO,eAAiB,YACxBA,EAAO,gBAAkB,IAAM,KAG1BA,CACT,CCUA,MAAME,EAAiB,IAchB,SAASC,EAA0B,CACxC,YAAAC,EACA,YAAAC,EACA,SAAAC,EAAW,CAAA,EACX,UAAAC,EAAY,UACZ,OAAAC,CACF,EAA0D,CAMxD,MAAMR,EAASH,EAA2BO,EAAa,CACrD,eAAgB,EAAA,CACjB,EAEK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CAAA,CACpB,EAKAvB,EAAO,cAAgB,SAAY,CAACiB,CAAO,EAGtCA,EAAQ,MAAA,EAEN,CAAE,OAAAjB,EAAQ,QAAAiB,EAAS,oBAAqBZ,EAAY,EAAA,CAC7D"}
package/dist/testing.js CHANGED
@@ -1,108 +1,120 @@
1
- import { StreamChat as e } from "stream-chat";
2
- //#region src/testing/createMockStreamChatClient.ts
3
- function t(t, { stubConnection: n = !1 } = {}) {
4
- let r = new e("mock-api-key", { allowServerSideConnect: !0 });
5
- return r.userID = t.id, r.user = t, n && (r.connectUser = async () => ({ me: t }), r.disconnectUser = async () => void 0, r.userMuteStatus = (() => !1)), r;
1
+ import { StreamChat as g } from "stream-chat";
2
+ function v(s, { stubConnection: n = !1 } = {}) {
3
+ const a = new g("mock-api-key", {
4
+ allowServerSideConnect: !0
5
+ });
6
+ return a.userID = s.id, a.user = s, n && (a.connectUser = async () => ({ me: s }), a.disconnectUser = async () => {
7
+ }, a.userMuteStatus = (() => !1)), a;
6
8
  }
7
- //#endregion
8
- //#region src/testing/createMockMessagingClient.ts
9
- var n = 600;
10
- function r({ currentUser: e, participant: r, messages: i = [], channelId: a = "mock-dm", onSend: o }) {
11
- let s = t(e, { stubConnection: !0 }), c = `messaging:${a}`, l = (t, n) => {
12
- let a = t.from === "me" ? e : r, o = /* @__PURE__ */ new Date(Date.now() - (i.length - n) * 6e4);
13
- return {
14
- id: t.id ?? `mock-msg-${n}`,
15
- text: t.text ?? "",
16
- type: "regular",
17
- html: t.text ? `<p>${t.text}</p>` : "",
18
- user: a,
19
- attachments: t.attachments ?? [],
20
- latest_reactions: [],
21
- own_reactions: [],
22
- reaction_counts: {},
23
- reaction_scores: {},
24
- reply_count: 0,
25
- status: "received",
26
- cid: c,
27
- created_at: o,
28
- updated_at: o,
29
- mentioned_users: [],
30
- ...t.metadata ? { metadata: t.metadata } : {}
31
- };
32
- }, u = i.map(l), d = {
33
- [e.id]: {
34
- user: {
35
- ...e,
36
- is_account: !1
37
- },
38
- user_id: e.id,
39
- role: "owner",
40
- is_account: !1
41
- },
42
- [r.id]: {
43
- user: {
44
- ...r,
45
- is_account: !0
46
- },
47
- user_id: r.id,
48
- role: "member",
49
- is_account: !0
50
- }
51
- }, f = s.channel("messaging", a, { members: [e.id, r.id] });
52
- f.muteStatus = () => ({
53
- muted: !1,
54
- createdAt: null,
55
- expiresAt: null
56
- }), f.markRead = (async () => ({})), f.keystroke = (async () => void 0), f.stopTyping = (async () => void 0), f.sendReaction = (async () => ({})), f.deleteReaction = (async () => ({})), f.countUnread = (() => 0), f.query = (async () => ({ messages: [] })), f.hide = (async () => ({}));
57
- let p = !1;
58
- f.watch = async () => (p ||= (f.state.messages = u, !0), f.state.members = d, {
59
- channel: { members: [e.id, r.id] },
60
- members: [],
61
- messages: f.state.messages,
62
- watchers: [],
63
- pinned_messages: [],
64
- duration: "0ms"
65
- });
66
- let m = (e) => {
67
- f.state.addMessageSorted(e), s.dispatchEvent({
68
- type: "message.new",
69
- cid: c,
70
- message: e,
71
- user: e.user ?? void 0
72
- });
73
- }, h = 0, g = 0;
74
- return f.sendMessage = async (t) => {
75
- let r = typeof t == "string" ? t : t?.text ?? "", i = {
76
- ...l({
77
- text: r,
78
- from: "me",
79
- id: `mock-sent-${h++}`
80
- }, u.length),
81
- ...typeof t == "object" ? t : {},
82
- user: e,
83
- cid: c
84
- };
85
- m(i);
86
- let a = o?.(r);
87
- if (a) {
88
- let e = typeof a == "string" ? a : a.text, t = typeof a == "string" ? void 0 : a.attachments, r = `mock-reply-${g++}`;
89
- setTimeout(() => {
90
- m(l({
91
- text: e,
92
- from: "them",
93
- attachments: t,
94
- id: r
95
- }, u.length));
96
- }, n);
97
- }
98
- return { message: i };
99
- }, s.queryChannels = async () => [f], f.watch(), {
100
- client: s,
101
- channel: f,
102
- participantFilterId: r.id
103
- };
9
+ const C = 600;
10
+ function S({
11
+ currentUser: s,
12
+ participant: n,
13
+ messages: a = [],
14
+ channelId: y = "mock-dm",
15
+ onSend: d
16
+ }) {
17
+ const r = v(s, {
18
+ stubConnection: !0
19
+ }), u = `messaging:${y}`, l = (t, c) => {
20
+ const i = t.from === "me" ? s : n, o = new Date(Date.now() - (a.length - c) * 6e4);
21
+ return {
22
+ id: t.id ?? `mock-msg-${c}`,
23
+ text: t.text ?? "",
24
+ type: "regular",
25
+ html: t.text ? `<p>${t.text}</p>` : "",
26
+ user: i,
27
+ attachments: t.attachments ?? [],
28
+ latest_reactions: [],
29
+ own_reactions: [],
30
+ reaction_counts: {},
31
+ reaction_scores: {},
32
+ reply_count: 0,
33
+ status: "received",
34
+ cid: u,
35
+ created_at: o,
36
+ updated_at: o,
37
+ mentioned_users: [],
38
+ ...t.metadata ? { metadata: t.metadata } : {}
39
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
40
+ };
41
+ }, m = a.map(l), p = {
42
+ [s.id]: {
43
+ user: { ...s, is_account: !1 },
44
+ user_id: s.id,
45
+ role: "owner",
46
+ is_account: !1
47
+ },
48
+ [n.id]: {
49
+ user: { ...n, is_account: !0 },
50
+ user_id: n.id,
51
+ role: "member",
52
+ is_account: !0
53
+ }
54
+ }, e = r.channel("messaging", y, {
55
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
56
+ members: [s.id, n.id]
57
+ });
58
+ e.muteStatus = () => ({
59
+ muted: !1,
60
+ createdAt: null,
61
+ expiresAt: null
62
+ }), e.markRead = (async () => ({})), e.keystroke = (async () => {
63
+ }), e.stopTyping = (async () => {
64
+ }), e.sendReaction = (async () => ({})), e.deleteReaction = (async () => ({})), e.countUnread = (() => 0), e.query = (async () => ({ messages: [] })), e.hide = (async () => ({}));
65
+ let h = !1;
66
+ e.watch = async () => (h || (e.state.messages = m, h = !0), e.state.members = p, {
67
+ channel: { members: [s.id, n.id] },
68
+ members: [],
69
+ messages: e.state.messages,
70
+ watchers: [],
71
+ pinned_messages: [],
72
+ duration: "0ms"
73
+ });
74
+ const f = (t) => {
75
+ e.state.addMessageSorted(t), r.dispatchEvent({
76
+ type: "message.new",
77
+ cid: u,
78
+ message: t,
79
+ user: t.user ?? void 0
80
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
81
+ });
82
+ };
83
+ let _ = 0, k = 0;
84
+ return e.sendMessage = async (t) => {
85
+ const c = typeof t == "string" ? t : (t == null ? void 0 : t.text) ?? "", i = {
86
+ ...l(
87
+ { text: c, from: "me", id: `mock-sent-${_++}` },
88
+ m.length
89
+ ),
90
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
91
+ ...typeof t == "object" ? t : {},
92
+ user: s,
93
+ cid: u
94
+ };
95
+ f(i);
96
+ const o = d == null ? void 0 : d(c);
97
+ if (o) {
98
+ const w = typeof o == "string" ? o : o.text, x = typeof o == "string" ? void 0 : o.attachments, M = `mock-reply-${k++}`;
99
+ setTimeout(() => {
100
+ f(
101
+ l(
102
+ {
103
+ text: w,
104
+ from: "them",
105
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
106
+ attachments: x,
107
+ id: M
108
+ },
109
+ m.length
110
+ )
111
+ );
112
+ }, C);
113
+ }
114
+ return { message: i };
115
+ }, r.queryChannels = async () => [e], e.watch(), { client: r, channel: e, participantFilterId: n.id };
104
116
  }
105
- //#endregion
106
- export { r as createMockMessagingClient };
107
-
108
- //# sourceMappingURL=testing.js.map
117
+ export {
118
+ S as createMockMessagingClient
119
+ };
120
+ //# sourceMappingURL=testing.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"testing.js","names":[],"sources":["../src/testing/createMockStreamChatClient.ts","../src/testing/createMockMessagingClient.ts"],"sourcesContent":["import { StreamChat } from 'stream-chat'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** A participant in the mock conversation. */\nexport interface MockMessagingUser {\n id: string\n name?: string\n image?: string\n}\n\nexport interface CreateMockStreamChatClientOptions {\n /**\n * Also replace the connection-dependent client methods (`connectUser`,\n * `disconnectUser`, `userMuteStatus`) with offline no-ops. Needed when the\n * client drives a flow that would otherwise open a WebSocket or throw\n * \"Make sure to await connectUser() first.\" offline. Direct `<Chat client>`\n * rendering (e.g. component stories) does not need this.\n */\n stubConnection?: boolean\n}\n\n/**\n * Builds an offline `StreamChat` for mocks and stories: a real client on a\n * throwaway api key with `userID`/`user` set so `<Chat>` treats it as\n * connected without a backend. The single place that knows how to construct a\n * connectionless Stream client, so a stream-chat version bump only needs\n * updating here rather than in each mock surface.\n */\nexport function createMockStreamChatClient(\n user: MockMessagingUser,\n { stubConnection = false }: CreateMockStreamChatClientOptions = {}\n): StreamChat {\n const client = new StreamChat('mock-api-key', {\n allowServerSideConnect: true,\n })\n client.userID = user.id\n client.user = user as any\n\n if (stubConnection) {\n client.connectUser = async () => ({ me: user }) as any\n client.disconnectUser = async () => undefined\n client.userMuteStatus = (() => false) as any\n }\n\n return client\n}\n\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","import type {\n Channel,\n MessageResponse,\n QueryChannelAPIResponse,\n SendMessageAPIResponse,\n} from 'stream-chat'\nimport { StreamChat } from 'stream-chat'\n\nimport {\n createMockStreamChatClient,\n type MockMessagingUser,\n} from './createMockStreamChatClient'\n\n/**\n * A seed message, authored from the viewer's perspective. `from: 'me'` is the\n * connected user (the viewer); `from: 'them'` is the other participant.\n */\nexport interface MockMessage {\n id?: string\n text?: string\n from: 'me' | 'them'\n /** Stream attachment payloads, rendered by the toolkit's attachment gate. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments?: any[]\n /** e.g. `{ custom_type: 'MESSAGE_WELCOME' }`. */\n metadata?: Record<string, unknown>\n}\n\nexport interface CreateMockMessagingClientOptions {\n /** The connected/viewing user. */\n currentUser: MockMessagingUser\n /** The other party in the direct conversation (e.g. the creator/linker). */\n participant: MockMessagingUser\n /** Seed conversation, oldest-first. */\n messages?: MockMessage[]\n /** Channel id; defaults to `mock-dm`. */\n channelId?: string\n /**\n * Optional canned reply. Called after the viewer sends a message; return the\n * reply text (or a partial message) to have `participant` echo a response, or\n * a falsy value for no reply. Drives the \"send echo\" in `dev:mock-messaging`.\n */\n onSend?: (\n text: string\n ) => string | { text?: string; attachments?: unknown[] } | null | undefined\n}\n\nexport interface MockMessagingClient {\n /** Pass to `<MessagingProvider client={...}>`. */\n client: StreamChat\n /** The seeded direct-conversation channel. */\n channel: Channel\n /** Pass to `<MessagingShell initialParticipantFilter={...}>`. */\n participantFilterId: string\n}\n\nconst REPLY_DELAY_MS = 600\n\n/**\n * Builds an offline Stream client seeded with a single direct conversation, so\n * consumers can render the **real** messaging UI (MessagingProvider →\n * MessagingShell → ChannelView) without a Stream backend — for `dev:mock-*`\n * surfaces and Storybook. It is a real `StreamChat` whose network calls\n * (`connectUser`, `queryChannels`, `channel.watch`, `channel.sendMessage`) are\n * replaced with in-memory behaviour driven by Stream's own channel-state\n * machinery, so rendering fidelity matches production.\n *\n * Ships from `@linktr.ee/messaging-react/testing` and must never be imported by\n * production code.\n */\nexport function createMockMessagingClient({\n currentUser,\n participant,\n messages = [],\n channelId = 'mock-dm',\n onSend,\n}: CreateMockMessagingClientOptions): MockMessagingClient {\n // Offline client marked connected without a WebSocket. `stubConnection` also\n // no-ops connectUser/disconnectUser/userMuteStatus: `MessagingProvider`\n // renders `<Chat client={client}>` directly so it never calls connectUser,\n // and handling the `message.new` events dispatched on send + echo below runs\n // Channel._countMessageAsUnread → client.userMuteStatus, which throws offline.\n const client = createMockStreamChatClient(currentUser, {\n stubConnection: true,\n })\n\n const cid = `messaging:${channelId}`\n\n const toStreamMessage = (\n message: MockMessage,\n index: number\n ): MessageResponse => {\n const author = message.from === 'me' ? currentUser : participant\n // Stagger timestamps oldest-first so the list orders naturally. Must be a\n // Date, not an ISO string: we seed `channel.state.messages` directly\n // (bypassing Stream's wire→Date parsing), and stream-chat-react calls\n // `.getTime()` on `created_at` (e.g. useCooldownTimer / addToMessageList).\n const createdAt = new Date(Date.now() - (messages.length - index) * 60_000)\n return {\n id: message.id ?? `mock-msg-${index}`,\n text: message.text ?? '',\n type: 'regular',\n html: message.text ? `<p>${message.text}</p>` : '',\n user: author,\n attachments: message.attachments ?? [],\n latest_reactions: [],\n own_reactions: [],\n reaction_counts: {},\n reaction_scores: {},\n reply_count: 0,\n status: 'received',\n cid,\n created_at: createdAt,\n updated_at: createdAt,\n mentioned_users: [],\n ...(message.metadata ? { metadata: message.metadata } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n const seededMessages = messages.map(toStreamMessage)\n\n const memberState = {\n [currentUser.id]: {\n user: { ...currentUser, is_account: false },\n user_id: currentUser.id,\n role: 'owner',\n is_account: false,\n },\n [participant.id]: {\n user: { ...participant, is_account: true },\n user_id: participant.id,\n role: 'member',\n is_account: true,\n },\n }\n\n const channel = client.channel('messaging', channelId, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: [currentUser.id, participant.id] as any,\n })\n // Read/unread bookkeeping consults channel mute status; without a live\n // connection the real method throws, so report \"not muted\".\n channel.muteStatus = () => ({\n muted: false,\n createdAt: null,\n expiresAt: null,\n })\n\n // Neutralise the rest of the connection-dependent channel API that\n // stream-chat-react calls during the chat lifecycle. Each of these POSTs to\n // Stream or checks for a live WebSocket and would otherwise throw\n // \"Make sure to await connectUser() first.\" offline. They are fire-and-forget\n // (read receipts, typing) or read-only (pagination, unread) so no-ops are safe.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n channel.markRead = (async () => ({}) as any) as any\n channel.keystroke = (async () => undefined) as any\n channel.stopTyping = (async () => undefined) as any\n channel.sendReaction = (async () => ({}) as any) as any\n channel.deleteReaction = (async () => ({}) as any) as any\n channel.countUnread = (() => 0) as any\n // Pagination: report no older pages so \"load more\" resolves to a no-op.\n channel.query = (async () => ({ messages: [] }) as any) as any\n // Leave/Delete Conversation calls channel.hide(); the real method POSTs to\n // Stream, so no-op it to keep the action working offline.\n channel.hide = (async () => ({}) as any) as any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n // Seed state locally instead of fetching. Mirrors the proven ChannelView\n // story mock: override `watch` to populate `state` and return a canned\n // QueryChannelAPIResponse. `stream-chat-react` may call `watch()` again on\n // remount/navigation, so seed only once — otherwise a re-watch would wipe\n // messages added via `sendMessage` + the send-echo reply, resetting the chat.\n let hasSeeded = false\n channel.watch = async () => {\n if (!hasSeeded) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.messages = seededMessages as unknown as any[]\n hasSeeded = true\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.members = memberState as unknown as any\n return {\n channel: { members: [currentUser.id, participant.id] },\n members: [],\n messages: channel.state.messages,\n watchers: [],\n pinned_messages: [],\n duration: '0ms',\n } as unknown as QueryChannelAPIResponse\n }\n\n const appendMessage = (message: MessageResponse) => {\n // addMessageSorted is Stream's own state mutation (dedupes by id), so the\n // toolkit re-renders through the real channel-state path.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.addMessageSorted(message as any)\n client.dispatchEvent({\n type: 'message.new',\n cid,\n message,\n user: message.user ?? undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n }\n\n let sentCount = 0\n let replyCount = 0\n channel.sendMessage = async (message) => {\n const text =\n typeof message === 'string'\n ? message\n : ((message as { text?: string })?.text ?? '')\n const sent = {\n ...toStreamMessage(\n { text, from: 'me', id: `mock-sent-${sentCount++}` },\n seededMessages.length\n ),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...(typeof message === 'object' ? (message as any) : {}),\n user: currentUser,\n cid,\n } as MessageResponse\n\n // stream-chat-react adds the outgoing message optimistically; addMessageSorted\n // dedupes by id, so confirming here is safe and idempotent.\n appendMessage(sent)\n\n const reply = onSend?.(text)\n if (reply) {\n const replyText = typeof reply === 'string' ? reply : reply.text\n const replyAttachments =\n typeof reply === 'string' ? undefined : reply.attachments\n // Capture a unique id before scheduling: two sends within REPLY_DELAY_MS\n // would otherwise both read the same later `sentCount` at fire time and\n // emit colliding reply ids, so Stream's id-based dedupe drops one echo.\n const replyId = `mock-reply-${replyCount++}`\n setTimeout(() => {\n appendMessage(\n toStreamMessage(\n {\n text: replyText,\n from: 'them',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments: replyAttachments as any,\n id: replyId,\n },\n seededMessages.length\n )\n )\n }, REPLY_DELAY_MS)\n }\n\n return { message: sent } as unknown as SendMessageAPIResponse\n }\n\n // MessagingShell finds the direct conversation via queryChannels; always\n // return the one seeded channel regardless of the filter.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client.queryChannels = async () => [channel] as any\n\n // Initialise state up-front so first render already has the conversation.\n void channel.watch()\n\n return { client, channel, participantFilterId: participant.id }\n}\n"],"mappings":";;AA6BA,SAAgB,EACd,GACA,EAAE,oBAAiB,OAA6C,CAAC,GACrD;CACZ,IAAM,IAAS,IAAI,EAAW,gBAAgB,EAC5C,wBAAwB,GAC1B,CAAC;CAUD,OATA,EAAO,SAAS,EAAK,IACrB,EAAO,OAAO,GAEV,MACF,EAAO,cAAc,aAAa,EAAE,IAAI,EAAK,IAC7C,EAAO,iBAAiB,YAAY,KAAA,GACpC,EAAO,wBAAwB,MAG1B;AACT;;;ACUA,IAAM,IAAiB;AAcvB,SAAgB,EAA0B,EACxC,gBACA,gBACA,cAAW,CAAC,GACZ,eAAY,WACZ,aACwD;CAMxD,IAAM,IAAS,EAA2B,GAAa,EACrD,gBAAgB,GAClB,CAAC,GAEK,IAAM,aAAa,KAEnB,KACJ,GACA,MACoB;EACpB,IAAM,IAAS,EAAQ,SAAS,OAAO,IAAc,GAK/C,oBAAY,IAAI,KAAK,KAAK,IAAI,KAAK,EAAS,SAAS,KAAS,GAAM;EAC1E,OAAO;GACL,IAAI,EAAQ,MAAM,YAAY;GAC9B,MAAM,EAAQ,QAAQ;GACtB,MAAM;GACN,MAAM,EAAQ,OAAO,MAAM,EAAQ,KAAK,QAAQ;GAChD,MAAM;GACN,aAAa,EAAQ,eAAe,CAAC;GACrC,kBAAkB,CAAC;GACnB,eAAe,CAAC;GAChB,iBAAiB,CAAC;GAClB,iBAAiB,C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Q,QAAQ,KAAA;EAExB,CAAQ;CACV,GAEI,IAAY,GACZ,IAAa;CAyDjB,OAxDA,EAAQ,cAAc,OAAO,MAAY;EACvC,IAAM,IACJ,OAAO,KAAY,WACf,IACE,GAA+B,QAAQ,IACzC,IAAO;GACX,GAAG,EACD;IAAE;IAAM,MAAM;IAAM,IAAI,aAAa;GAAc,GACnD,EAAe,MACjB;GAEA,GAAI,OAAO,KAAY,WAAY,IAAkB,CAAC;GACtD,MAAM;GACN;EACF;EAIA,EAAc,CAAI;EAElB,IAAM,IAAQ,IAAS,CAAI;EAC3B,IAAI,GAAO;GACT,IAAM,IAAY,OAAO,KAAU,WAAW,IAAQ,EAAM,MACtD,IACJ,OAAO,KAAU,WAAW,KAAA,IAAY,EAAM,aAI1C,IAAU,cAAc;GAC9B,iBAAiB;IACf,EACE,EACE;KACE,MAAM;KACN,MAAM;KAEN,aAAa;KACb,IAAI;IACN,GACA,EAAe,MACjB,CACF;GACF,GAAG,CAAc;EACnB;EAEA,OAAO,EAAE,SAAS,EAAK;CACzB,GAKA,EAAO,gBAAgB,YAAY,CAAC,CAAO,GAG3C,EAAa,MAAM,GAEZ;EAAE;EAAQ;EAAS,qBAAqB,EAAY;CAAG;AAChE"}
1
+ {"version":3,"file":"testing.js","sources":["../src/testing/createMockStreamChatClient.ts","../src/testing/createMockMessagingClient.ts"],"sourcesContent":["import { StreamChat } from 'stream-chat'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** A participant in the mock conversation. */\nexport interface MockMessagingUser {\n id: string\n name?: string\n image?: string\n}\n\nexport interface CreateMockStreamChatClientOptions {\n /**\n * Also replace the connection-dependent client methods (`connectUser`,\n * `disconnectUser`, `userMuteStatus`) with offline no-ops. Needed when the\n * client drives a flow that would otherwise open a WebSocket or throw\n * \"Make sure to await connectUser() first.\" offline. Direct `<Chat client>`\n * rendering (e.g. component stories) does not need this.\n */\n stubConnection?: boolean\n}\n\n/**\n * Builds an offline `StreamChat` for mocks and stories: a real client on a\n * throwaway api key with `userID`/`user` set so `<Chat>` treats it as\n * connected without a backend. The single place that knows how to construct a\n * connectionless Stream client, so a stream-chat version bump only needs\n * updating here rather than in each mock surface.\n */\nexport function createMockStreamChatClient(\n user: MockMessagingUser,\n { stubConnection = false }: CreateMockStreamChatClientOptions = {}\n): StreamChat {\n const client = new StreamChat('mock-api-key', {\n allowServerSideConnect: true,\n })\n client.userID = user.id\n client.user = user as any\n\n if (stubConnection) {\n client.connectUser = async () => ({ me: user }) as any\n client.disconnectUser = async () => undefined\n client.userMuteStatus = (() => false) as any\n }\n\n return client\n}\n\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","import type {\n Channel,\n MessageResponse,\n QueryChannelAPIResponse,\n SendMessageAPIResponse,\n} from 'stream-chat'\nimport { StreamChat } from 'stream-chat'\n\nimport {\n createMockStreamChatClient,\n type MockMessagingUser,\n} from './createMockStreamChatClient'\n\n/**\n * A seed message, authored from the viewer's perspective. `from: 'me'` is the\n * connected user (the viewer); `from: 'them'` is the other participant.\n */\nexport interface MockMessage {\n id?: string\n text?: string\n from: 'me' | 'them'\n /** Stream attachment payloads, rendered by the toolkit's attachment gate. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments?: any[]\n /** e.g. `{ custom_type: 'MESSAGE_WELCOME' }`. */\n metadata?: Record<string, unknown>\n}\n\nexport interface CreateMockMessagingClientOptions {\n /** The connected/viewing user. */\n currentUser: MockMessagingUser\n /** The other party in the direct conversation (e.g. the creator/linker). */\n participant: MockMessagingUser\n /** Seed conversation, oldest-first. */\n messages?: MockMessage[]\n /** Channel id; defaults to `mock-dm`. */\n channelId?: string\n /**\n * Optional canned reply. Called after the viewer sends a message; return the\n * reply text (or a partial message) to have `participant` echo a response, or\n * a falsy value for no reply. Drives the \"send echo\" in `dev:mock-messaging`.\n */\n onSend?: (\n text: string\n ) => string | { text?: string; attachments?: unknown[] } | null | undefined\n}\n\nexport interface MockMessagingClient {\n /** Pass to `<MessagingProvider client={...}>`. */\n client: StreamChat\n /** The seeded direct-conversation channel. */\n channel: Channel\n /** Pass to `<MessagingShell initialParticipantFilter={...}>`. */\n participantFilterId: string\n}\n\nconst REPLY_DELAY_MS = 600\n\n/**\n * Builds an offline Stream client seeded with a single direct conversation, so\n * consumers can render the **real** messaging UI (MessagingProvider →\n * MessagingShell → ChannelView) without a Stream backend — for `dev:mock-*`\n * surfaces and Storybook. It is a real `StreamChat` whose network calls\n * (`connectUser`, `queryChannels`, `channel.watch`, `channel.sendMessage`) are\n * replaced with in-memory behaviour driven by Stream's own channel-state\n * machinery, so rendering fidelity matches production.\n *\n * Ships from `@linktr.ee/messaging-react/testing` and must never be imported by\n * production code.\n */\nexport function createMockMessagingClient({\n currentUser,\n participant,\n messages = [],\n channelId = 'mock-dm',\n onSend,\n}: CreateMockMessagingClientOptions): MockMessagingClient {\n // Offline client marked connected without a WebSocket. `stubConnection` also\n // no-ops connectUser/disconnectUser/userMuteStatus: `MessagingProvider`\n // renders `<Chat client={client}>` directly so it never calls connectUser,\n // and handling the `message.new` events dispatched on send + echo below runs\n // Channel._countMessageAsUnread → client.userMuteStatus, which throws offline.\n const client = createMockStreamChatClient(currentUser, {\n stubConnection: true,\n })\n\n const cid = `messaging:${channelId}`\n\n const toStreamMessage = (\n message: MockMessage,\n index: number\n ): MessageResponse => {\n const author = message.from === 'me' ? currentUser : participant\n // Stagger timestamps oldest-first so the list orders naturally. Must be a\n // Date, not an ISO string: we seed `channel.state.messages` directly\n // (bypassing Stream's wire→Date parsing), and stream-chat-react calls\n // `.getTime()` on `created_at` (e.g. useCooldownTimer / addToMessageList).\n const createdAt = new Date(Date.now() - (messages.length - index) * 60_000)\n return {\n id: message.id ?? `mock-msg-${index}`,\n text: message.text ?? '',\n type: 'regular',\n html: message.text ? `<p>${message.text}</p>` : '',\n user: author,\n attachments: message.attachments ?? [],\n latest_reactions: [],\n own_reactions: [],\n reaction_counts: {},\n reaction_scores: {},\n reply_count: 0,\n status: 'received',\n cid,\n created_at: createdAt,\n updated_at: createdAt,\n mentioned_users: [],\n ...(message.metadata ? { metadata: message.metadata } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n const seededMessages = messages.map(toStreamMessage)\n\n const memberState = {\n [currentUser.id]: {\n user: { ...currentUser, is_account: false },\n user_id: currentUser.id,\n role: 'owner',\n is_account: false,\n },\n [participant.id]: {\n user: { ...participant, is_account: true },\n user_id: participant.id,\n role: 'member',\n is_account: true,\n },\n }\n\n const channel = client.channel('messaging', channelId, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: [currentUser.id, participant.id] as any,\n })\n // Read/unread bookkeeping consults channel mute status; without a live\n // connection the real method throws, so report \"not muted\".\n channel.muteStatus = () => ({\n muted: false,\n createdAt: null,\n expiresAt: null,\n })\n\n // Neutralise the rest of the connection-dependent channel API that\n // stream-chat-react calls during the chat lifecycle. Each of these POSTs to\n // Stream or checks for a live WebSocket and would otherwise throw\n // \"Make sure to await connectUser() first.\" offline. They are fire-and-forget\n // (read receipts, typing) or read-only (pagination, unread) so no-ops are safe.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n channel.markRead = (async () => ({}) as any) as any\n channel.keystroke = (async () => undefined) as any\n channel.stopTyping = (async () => undefined) as any\n channel.sendReaction = (async () => ({}) as any) as any\n channel.deleteReaction = (async () => ({}) as any) as any\n channel.countUnread = (() => 0) as any\n // Pagination: report no older pages so \"load more\" resolves to a no-op.\n channel.query = (async () => ({ messages: [] }) as any) as any\n // Leave/Delete Conversation calls channel.hide(); the real method POSTs to\n // Stream, so no-op it to keep the action working offline.\n channel.hide = (async () => ({}) as any) as any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n // Seed state locally instead of fetching. Mirrors the proven ChannelView\n // story mock: override `watch` to populate `state` and return a canned\n // QueryChannelAPIResponse. `stream-chat-react` may call `watch()` again on\n // remount/navigation, so seed only once — otherwise a re-watch would wipe\n // messages added via `sendMessage` + the send-echo reply, resetting the chat.\n let hasSeeded = false\n channel.watch = async () => {\n if (!hasSeeded) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.messages = seededMessages as unknown as any[]\n hasSeeded = true\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.members = memberState as unknown as any\n return {\n channel: { members: [currentUser.id, participant.id] },\n members: [],\n messages: channel.state.messages,\n watchers: [],\n pinned_messages: [],\n duration: '0ms',\n } as unknown as QueryChannelAPIResponse\n }\n\n const appendMessage = (message: MessageResponse) => {\n // addMessageSorted is Stream's own state mutation (dedupes by id), so the\n // toolkit re-renders through the real channel-state path.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.addMessageSorted(message as any)\n client.dispatchEvent({\n type: 'message.new',\n cid,\n message,\n user: message.user ?? undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n }\n\n let sentCount = 0\n let replyCount = 0\n channel.sendMessage = async (message) => {\n const text =\n typeof message === 'string'\n ? message\n : ((message as { text?: string })?.text ?? '')\n const sent = {\n ...toStreamMessage(\n { text, from: 'me', id: `mock-sent-${sentCount++}` },\n seededMessages.length\n ),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...(typeof message === 'object' ? (message as any) : {}),\n user: currentUser,\n cid,\n } as MessageResponse\n\n // stream-chat-react adds the outgoing message optimistically; addMessageSorted\n // dedupes by id, so confirming here is safe and idempotent.\n appendMessage(sent)\n\n const reply = onSend?.(text)\n if (reply) {\n const replyText = typeof reply === 'string' ? reply : reply.text\n const replyAttachments =\n typeof reply === 'string' ? undefined : reply.attachments\n // Capture a unique id before scheduling: two sends within REPLY_DELAY_MS\n // would otherwise both read the same later `sentCount` at fire time and\n // emit colliding reply ids, so Stream's id-based dedupe drops one echo.\n const replyId = `mock-reply-${replyCount++}`\n setTimeout(() => {\n appendMessage(\n toStreamMessage(\n {\n text: replyText,\n from: 'them',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments: replyAttachments as any,\n id: replyId,\n },\n seededMessages.length\n )\n )\n }, REPLY_DELAY_MS)\n }\n\n return { message: sent } as unknown as SendMessageAPIResponse\n }\n\n // MessagingShell finds the direct conversation via queryChannels; always\n // return the one seeded channel regardless of the filter.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client.queryChannels = async () => [channel] as any\n\n // Initialise state up-front so first render already has the conversation.\n void channel.watch()\n\n return { client, channel, participantFilterId: participant.id }\n}\n"],"names":["createMockStreamChatClient","user","stubConnection","client","StreamChat","REPLY_DELAY_MS","createMockMessagingClient","currentUser","participant","messages","channelId","onSend","cid","toStreamMessage","message","index","author","createdAt","seededMessages","memberState","channel","hasSeeded","appendMessage","sentCount","replyCount","text","sent","reply","replyText","replyAttachments","replyId"],"mappings":";AA6BO,SAASA,EACdC,GACA,EAAE,gBAAAC,IAAiB,GAAA,IAA6C,CAAA,GACpD;AACZ,QAAMC,IAAS,IAAIC,EAAW,gBAAgB;AAAA,IAC5C,wBAAwB;AAAA,EAAA,CACzB;AACD,SAAAD,EAAO,SAASF,EAAK,IACrBE,EAAO,OAAOF,GAEVC,MACFC,EAAO,cAAc,aAAa,EAAE,IAAIF,EAAA,IACxCE,EAAO,iBAAiB;KACxBA,EAAO,kBAAkB,MAAM,MAG1BA;AACT;ACUA,MAAME,IAAiB;AAchB,SAASC,EAA0B;AAAA,EACxC,aAAAC;AAAA,EACA,aAAAC;AAAA,EACA,UAAAC,IAAW,CAAA;AAAA,EACX,WAAAC,IAAY;AAAA,EACZ,QAAAC;AACF,GAA0D;AAMxD,QAAMR,IAASH,EAA2BO,GAAa;AAAA,IACrD,gBAAgB;AAAA,EAAA,CACjB,GAEKK,IAAM,aAAaF,CAAS,IAE5BG,IAAkB,CACtBC,GACAC,MACoB;AACpB,UAAMC,IAASF,EAAQ,SAAS,OAAOP,IAAcC,GAK/CS,IAAY,IAAI,KAAK,KAAK,SAASR,EAAS,SAASM,KAAS,GAAM;AAC1E,WAAO;AAAA,MACL,IAAID,EAAQ,MAAM,YAAYC,CAA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YA,EAAM,aAI1CG,IAAU,cAAcN,GAAY;AAC1C,iBAAW,MAAM;AACf,QAAAF;AAAA,UACET;AAAA,YACE;AAAA,cACE,MAAMe;AAAA,cACN,MAAM;AAAA;AAAA,cAEN,aAAaC;AAAA,cACb,IAAIC;AAAA,YAAA;AAAA,YAENZ,EAAe;AAAA,UAAA;AAAA,QACjB;AAAA,MAEJ,GAAGb,CAAc;AAAA,IACnB;AAEA,WAAO,EAAE,SAASqB,EAAA;AAAA,EACpB,GAKAvB,EAAO,gBAAgB,YAAY,CAACiB,CAAO,GAGtCA,EAAQ,MAAA,GAEN,EAAE,QAAAjB,GAAQ,SAAAiB,GAAS,qBAAqBZ,EAAY,GAAA;AAC7D;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@linktr.ee/messaging-react",
3
- "version": "4.2.0-rc-1787255254",
3
+ "version": "4.2.0-rc-1787325521",
4
4
  "description": "React messaging components built on messaging-core for web applications",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -50,8 +50,8 @@
50
50
  "chromatic:local": "yarn storybook:build && chromatic"
51
51
  },
52
52
  "dependencies": {
53
- "@linktr.ee/messaging-core": "2.6.0-rc-1787255254",
54
- "@linktr.ee/messaging-taxonomy": "^0.11.0",
53
+ "@linktr.ee/messaging-core": "2.5.0-rc-1787325521",
54
+ "@linktr.ee/messaging-taxonomy": "^0.10.0",
55
55
  "@phosphor-icons/react": "^2.1.10"
56
56
  },
57
57
  "devDependencies": {
@@ -68,7 +68,7 @@
68
68
  "@testing-library/user-event": "^14.5.1",
69
69
  "@types/react": "^18.3.24",
70
70
  "@types/react-dom": "^18.3.7",
71
- "@vitejs/plugin-react": "^5.2.0",
71
+ "@vitejs/plugin-react": "^4.2.1",
72
72
  "@vitest/ui": "^4.1.10",
73
73
  "autoprefixer": "^10.4.20",
74
74
  "chromatic": "^17.4.0",
@@ -83,7 +83,7 @@
83
83
  "tailwindcss": "^3.4.17",
84
84
  "tailwindcss-animate": "^1.0.7",
85
85
  "typescript": "5.9.2",
86
- "vite": "^8.2.1",
86
+ "vite": "^6.0.7",
87
87
  "vite-plugin-dts": "^3.7.0",
88
88
  "vitest": "^4.1.10"
89
89
  },
@@ -682,6 +682,10 @@ WithTypingIndicator.args = {
682
682
  },
683
683
  }
684
684
  WithTypingIndicator.parameters = {
685
+ // The typing indicator is animation-dominant, so a snapshot mostly captures
686
+ // whichever frame the animation happened to pause at — a false-positive
687
+ // source. Skip it in Chromatic; the story stays browsable in Storybook.
688
+ chromatic: { disableSnapshot: true },
685
689
  docs: {
686
690
  description: {
687
691
  story:
@@ -496,7 +496,7 @@ export const CustomMessageInput: React.FC<CustomMessageInputProps> = ({
496
496
 
497
497
  <div className="relative z-10 flex min-h-0 flex-col">
498
498
  {renderHeader?.()}
499
- <div className="flex min-h-0 flex-col gap-4 p-4">
499
+ <div className="flex min-h-0 flex-col gap-4 p-3 pb-5 md:p-5">
500
500
  <div
501
501
  // @ts-expect-error Only React 19 onwards has `inert` in its types.
502
502
  inert={isFrozen ? '' : undefined}
package/src/index.ts CHANGED
@@ -29,11 +29,13 @@ export type {
29
29
 
30
30
  // Providers
31
31
  export { MessagingProvider } from './providers/MessagingProvider'
32
+ export { MessagingLoggerProvider } from './logging'
32
33
  export { CustomMessageProvider } from './components/CustomMessage/context'
33
34
 
34
35
  // Hooks
35
36
  export { useComposerLocked } from './components/CustomMessageInput'
36
37
  export { useMessaging } from './hooks/useMessaging'
38
+ export { useMessagingLogger } from './logging'
37
39
  export { useCustomMessage } from './components/CustomMessage/context'
38
40
 
39
41
  // Utils
@@ -136,3 +138,4 @@ export type { CustomMessageRegistry } from './components/CustomMessage/context'
136
138
  export type { AttachmentSourceType } from './components/AttachmentCard/utils/mimeType'
137
139
  export type { Faq, FaqListProps } from './components/FaqList'
138
140
  export type { FaqListItemProps } from './components/FaqList/FaqListItem'
141
+ export type { Logger } from '@linktr.ee/messaging-core'
@@ -0,0 +1,136 @@
1
+ import type { Logger } from '@linktr.ee/messaging-core'
2
+ import { render } from '@testing-library/react'
3
+ import React from 'react'
4
+ import { describe, it, expect, vi, afterEach } from 'vitest'
5
+
6
+ import {
7
+ MessagingLoggerProvider,
8
+ consoleLogger,
9
+ resolveLogger,
10
+ useMessagingLogger,
11
+ } from './index'
12
+
13
+ const ERROR_MESSAGE = '[MessagingShell] Failed to load channels:'
14
+
15
+ /** Logs one error through the seam the way a call site would. */
16
+ const ErrorEmitter: React.FC<{ error: Error }> = ({ error }) => {
17
+ const logger = useMessagingLogger()
18
+ logger.error(ERROR_MESSAGE, error)
19
+ return null
20
+ }
21
+
22
+ /** Emits one line at every level so partial-sink fallback is observable. */
23
+ const AllLevelsEmitter: React.FC = () => {
24
+ const logger = useMessagingLogger()
25
+ logger.debug('debug line', 1)
26
+ logger.info('info line', 2)
27
+ logger.warn('warn line', 3)
28
+ logger.error('error line', 4)
29
+ return null
30
+ }
31
+
32
+ afterEach(() => {
33
+ vi.restoreAllMocks()
34
+ })
35
+
36
+ describe('logger seam', () => {
37
+ it('routes error to an injected sink with the exact message and raw error object', () => {
38
+ const error = new Error('boom')
39
+ const sink = { error: vi.fn() }
40
+
41
+ render(
42
+ <MessagingLoggerProvider logger={sink}>
43
+ <ErrorEmitter error={error} />
44
+ </MessagingLoggerProvider>
45
+ )
46
+
47
+ expect(sink.error).toHaveBeenCalledTimes(1)
48
+ expect(sink.error).toHaveBeenCalledWith(ERROR_MESSAGE, error)
49
+ // The raw Error instance, not a serialized copy.
50
+ expect(sink.error.mock.calls[0][1]).toBe(error)
51
+ })
52
+
53
+ it('passes identical arguments to console.error when no sink is injected', () => {
54
+ const error = new Error('boom')
55
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
56
+ const sink = { error: vi.fn() }
57
+
58
+ render(
59
+ <MessagingLoggerProvider logger={sink}>
60
+ <ErrorEmitter error={error} />
61
+ </MessagingLoggerProvider>
62
+ )
63
+ const injectedArgs = sink.error.mock.calls[0]
64
+
65
+ // No provider at all, and a provider with no logger prop: both must produce
66
+ // byte-identical console output to what the injected sink received.
67
+ render(<ErrorEmitter error={error} />)
68
+ render(
69
+ <MessagingLoggerProvider>
70
+ <ErrorEmitter error={error} />
71
+ </MessagingLoggerProvider>
72
+ )
73
+
74
+ expect(consoleError).toHaveBeenCalledTimes(2)
75
+ expect(consoleError.mock.calls[0]).toEqual(injectedArgs)
76
+ expect(consoleError.mock.calls[1]).toEqual(injectedArgs)
77
+ expect(consoleError.mock.calls[0][1]).toBe(error)
78
+ })
79
+
80
+ it('falls back to console for the levels a partial sink omits', () => {
81
+ const consoleLog = vi.spyOn(console, 'log').mockImplementation(() => {})
82
+ const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {})
83
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
84
+ const sink: Logger = { warn: vi.fn(), error: vi.fn() }
85
+
86
+ render(
87
+ <MessagingLoggerProvider logger={sink}>
88
+ <AllLevelsEmitter />
89
+ </MessagingLoggerProvider>
90
+ )
91
+
92
+ expect(sink.warn).toHaveBeenCalledWith('warn line', 3)
93
+ expect(sink.error).toHaveBeenCalledWith('error line', 4)
94
+ expect(consoleWarn).not.toHaveBeenCalled()
95
+ expect(consoleError).not.toHaveBeenCalled()
96
+ // debug and info are unset on the sink, so both land on console.log.
97
+ expect(consoleLog.mock.calls).toEqual([
98
+ ['debug line', 1],
99
+ ['info line', 2],
100
+ ])
101
+ })
102
+
103
+ it('defaults every level to console when the hook is used with no provider', () => {
104
+ const consoleLog = vi.spyOn(console, 'log').mockImplementation(() => {})
105
+ const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {})
106
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
107
+
108
+ render(<AllLevelsEmitter />)
109
+
110
+ expect(consoleLog.mock.calls).toEqual([
111
+ ['debug line', 1],
112
+ ['info line', 2],
113
+ ])
114
+ expect(consoleWarn).toHaveBeenCalledWith('warn line', 3)
115
+ expect(consoleError).toHaveBeenCalledWith('error line', 4)
116
+ })
117
+
118
+ it('resolveLogger keeps provided levels and fills the rest from console', () => {
119
+ const warn = vi.fn()
120
+ const resolved = resolveLogger({ warn })
121
+
122
+ expect(resolved.warn).toBe(warn)
123
+ expect(resolved.debug).toBe(consoleLogger.debug)
124
+ expect(resolved.info).toBe(consoleLogger.info)
125
+ expect(resolved.error).toBe(consoleLogger.error)
126
+ expect(resolveLogger()).toEqual(consoleLogger)
127
+ })
128
+
129
+ it('consoleLogger dispatches through console at call time, not bind time', () => {
130
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
131
+
132
+ consoleLogger.error('late spy', 'arg')
133
+
134
+ expect(consoleError).toHaveBeenCalledWith('late spy', 'arg')
135
+ })
136
+ })