@fayz-ai/plugin-conversations 0.34.1 → 0.35.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.
@@ -1,102 +0,0 @@
1
- import React from 'react';
2
- import { useStore } from 'zustand';
3
- import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
4
- import { getSupabaseClientOptional, useTranslation } from '@fayz-ai/core';
5
- import { CircleHelp, User, MapPin, Sticker, FileText, Video, Camera, Mic } from 'lucide-react';
6
-
7
- // src/types.ts
8
- var CHANNEL_LABELS = {
9
- sms: "SMS",
10
- whatsapp: "WhatsApp",
11
- instagram: "Instagram",
12
- email: "Email",
13
- webchat: "Web Chat",
14
- support: "Suporte"
15
- };
16
- function isWaitingOnUs(conversation) {
17
- if (conversation.status !== "open") return false;
18
- if (conversation.acknowledgedAt && conversation.lastMessageAt && conversation.acknowledgedAt >= conversation.lastMessageAt) return false;
19
- if (conversation.lastMessageDirection) return conversation.lastMessageDirection === "inbound";
20
- return conversation.unreadCount > 0;
21
- }
22
- var DEFAULT_CONVERSATIONS_CONFIG = {
23
- contactKind: "contact"
24
- };
25
- var StoreContext = React.createContext(null);
26
- var ConfigContext = React.createContext(DEFAULT_CONVERSATIONS_CONFIG);
27
- function ConversationsContextProvider({
28
- store,
29
- config = DEFAULT_CONVERSATIONS_CONFIG,
30
- children
31
- }) {
32
- return /* @__PURE__ */ jsx(StoreContext.Provider, { value: store, children: /* @__PURE__ */ jsx(ConfigContext.Provider, { value: config, children }) });
33
- }
34
- function useConversationsStore(selector) {
35
- const store = React.useContext(StoreContext);
36
- if (!store) throw new Error("useConversationsStore must be used within ConversationsPage");
37
- return useStore(store, selector);
38
- }
39
- function useConversationsConfig() {
40
- return React.useContext(ConfigContext);
41
- }
42
- var porConta = /* @__PURE__ */ new Map();
43
- function assinarChegada(tenantId, ouvinte) {
44
- const supabase = getSupabaseClientOptional();
45
- if (!supabase?.channel || !tenantId) return () => {
46
- };
47
- let assinatura = porConta.get(tenantId);
48
- if (!assinatura) {
49
- const ouvintes = /* @__PURE__ */ new Set();
50
- const canal = supabase.channel(`conversas:${tenantId}`).on("broadcast", { event: "inbound" }, (msg) => {
51
- const carga = { conversationId: msg?.payload?.conversationId };
52
- for (const f of [...ouvintes]) {
53
- try {
54
- f(carga);
55
- } catch {
56
- }
57
- }
58
- }).subscribe();
59
- assinatura = { canal, ouvintes };
60
- porConta.set(tenantId, assinatura);
61
- }
62
- assinatura.ouvintes.add(ouvinte);
63
- return () => {
64
- const a = porConta.get(tenantId);
65
- if (!a) return;
66
- a.ouvintes.delete(ouvinte);
67
- if (a.ouvintes.size === 0) {
68
- porConta.delete(tenantId);
69
- void getSupabaseClientOptional()?.removeChannel?.(a.canal);
70
- }
71
- };
72
- }
73
- var KINDS = {
74
- "[\xE1udio]": { icon: Mic, key: "conversations.preview.audio" },
75
- "[imagem]": { icon: Camera, key: "conversations.preview.image" },
76
- "[v\xEDdeo]": { icon: Video, key: "conversations.preview.video" },
77
- "[documento]": { icon: FileText, key: "conversations.preview.document" },
78
- "[figurinha]": { icon: Sticker, key: "conversations.preview.sticker" },
79
- "[localiza\xE7\xE3o]": { icon: MapPin, key: "conversations.preview.location" },
80
- "[contato]": { icon: User, key: "conversations.preview.contact" },
81
- "[mensagem n\xE3o suportada]": { icon: CircleHelp, key: "conversations.preview.unsupported" }
82
- };
83
- function mediaPreviewKind(text) {
84
- return KINDS[String(text ?? "").trim()] ?? null;
85
- }
86
- function MessagePreview({ text, suffix, className }) {
87
- const t = useTranslation();
88
- const kind = mediaPreviewKind(text);
89
- if (!kind) return /* @__PURE__ */ jsx(Fragment, { children: text });
90
- const Icon = kind.icon;
91
- return /* @__PURE__ */ jsxs("span", { className: `inline-flex min-w-0 items-center gap-1 ${className ?? ""}`, children: [
92
- /* @__PURE__ */ jsx(Icon, { className: "h-3.5 w-3.5 shrink-0" }),
93
- /* @__PURE__ */ jsxs("span", { className: "truncate", children: [
94
- t(kind.key),
95
- suffix ? ` (${suffix})` : ""
96
- ] })
97
- ] });
98
- }
99
-
100
- export { CHANNEL_LABELS, ConversationsContextProvider, MessagePreview, assinarChegada, isWaitingOnUs, mediaPreviewKind, useConversationsConfig, useConversationsStore };
101
- //# sourceMappingURL=chunk-OJ3Q4S5Y.js.map
102
- //# sourceMappingURL=chunk-OJ3Q4S5Y.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/types.ts","../src/context.tsx","../src/lib/campainha.ts","../src/components/MessagePreview.tsx"],"names":["jsx"],"mappings":";;;;;;;AA8KO,IAAM,cAAA,GAA0C;AAAA,EACrD,GAAA,EAAK,KAAA;AAAA,EACL,QAAA,EAAU,UAAA;AAAA,EACV,SAAA,EAAW,WAAA;AAAA,EACX,KAAA,EAAO,OAAA;AAAA,EACP,OAAA,EAAS,UAAA;AAAA,EACT,OAAA,EAAS;AACX;AAeO,SAAS,cAAc,YAAA,EAAqC;AACjE,EAAA,IAAI,YAAA,CAAa,MAAA,KAAW,MAAA,EAAQ,OAAO,KAAA;AAO3C,EAAA,IAAI,YAAA,CAAa,kBAAkB,YAAA,CAAa,aAAA,IACzC,aAAa,cAAA,IAAkB,YAAA,CAAa,eAAe,OAAO,KAAA;AACzE,EAAA,IAAI,YAAA,CAAa,oBAAA,EAAsB,OAAO,YAAA,CAAa,oBAAA,KAAyB,SAAA;AACpF,EAAA,OAAO,aAAa,WAAA,GAAc,CAAA;AACpC;AC5LO,IAAM,4BAAA,GAA4D;AAAA,EACvE,WAAA,EAAa;AACf,CAAA;AAEA,IAAM,YAAA,GAAe,KAAA,CAAM,aAAA,CAAqD,IAAI,CAAA;AACpF,IAAM,aAAA,GAAgB,KAAA,CAAM,aAAA,CAA2C,4BAA4B,CAAA;AAE5F,SAAS,4BAAA,CAA6B;AAAA,EAC3C,KAAA;AAAA,EACA,MAAA,GAAS,4BAAA;AAAA,EACT;AACF,CAAA,EAIG;AACD,EAAA,uBACE,GAAA,CAAC,YAAA,CAAa,QAAA,EAAb,EAAsB,KA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AAY,KAAK,mCAAA;AACvD,CAAA;AAGO,SAAS,iBAAiB,IAAA,EAA2E;AAC1G,EAAA,OAAO,MAAM,MAAA,CAAO,IAAA,IAAQ,EAAE,CAAA,CAAE,IAAA,EAAM,CAAA,IAAK,IAAA;AAC7C;AAGO,SAAS,cAAA,CAAe,EAAE,IAAA,EAAM,MAAA,EAAQ,WAAU,EAA6E;AACpI,EAAA,MAAM,IAAI,cAAA,EAAe;AACzB,EAAA,MAAM,IAAA,GAAO,iBAAiB,IAAI,CAAA;AAClC,EAAA,IAAI,CAAC,IAAA,EAAM,uBAAOA,GAAAA,CAAA,YAAG,QAAA,EAAA,IAAA,EAAK,CAAA;AAC1B,EAAA,MAAM,OAAO,IAAA,CAAK,IAAA;AAClB,EAAA,4BACG,MAAA,EAAA,EAAK,SAAA,EAAW,CAAA,uCAAA,EAA0C,SAAA,IAAa,EAAE,CAAA,CAAA,EACxE,QAAA,EAAA;AAAA,oBAAAA,GAAAA,CAAC,IAAA,EAAA,EAAK,SAAA,EAAU,sBAAA,EAAuB,CAAA;AAAA,oBACvC,IAAA,CAAC,MAAA,EAAA,EAAK,SAAA,EAAU,UAAA,EAAY,QAAA,EAAA;AAAA,MAAA,CAAA,CAAE,KAAK,GAAG,CAAA;AAAA,MAAG,MAAA,GAAS,CAAA,EAAA,EAAK,MAAM,CAAA,CAAA,CAAA,GAAM;AAAA,KAAA,EAAG;AAAA,GAAA,EACxE,CAAA;AAEJ","file":"chunk-OJ3Q4S5Y.js","sourcesContent":["// ---------------------------------------------------------------------------\n// @fayz-ai/plugin-conversations — domain types for the unified omni-channel\n// inbox (the GoHighLevel \"Conversations\" equivalent). Provider-agnostic.\n// ---------------------------------------------------------------------------\n\n// `support` threads are help-desk tickets written into the same inbox.\nexport type Channel = 'sms' | 'whatsapp' | 'instagram' | 'email' | 'webchat' | 'support'\n\nexport type ConversationStatus = 'open' | 'snoozed' | 'closed'\n\nexport type MessageDirection = 'inbound' | 'outbound'\n\nexport interface Conversation {\n id: string\n contactName: string\n /** The WhatsApp number (provider) the thread lives on — replies leave from\n * it (019). `evolution` = the everyday number, `tyxter` = the official one. */\n provider?: string\n /**\n * `public.people` id when the thread is tied to a real contact record (the\n * compose modal resolves one via the shared ContactPicker). Absent for legacy\n * threads and for inbound messages from an unknown handle.\n */\n contactPersonId?: string\n /** Phone, @handle, or email depending on channel */\n contactHandle: string\n channel: Channel\n lastMessagePreview: string\n lastMessageAt: string\n /**\n * Who spoke last: `inbound` = the customer, `outbound` = the house.\n *\n * The field the queue is built on — \"waiting on us\" is `status === 'open'`\n * plus this being `inbound`. `unreadCount` is the older approximation and\n * gets the painful case wrong: a thread somebody opened, read, meant to\n * answer later and forgot has zero unread and a customer still waiting.\n *\n * Optional because a thread predating the column's backfill (or a provider\n * that does not report direction) genuinely does not know — see\n * `isWaitingOnUs`, which falls back rather than guessing.\n */\n lastMessageDirection?: MessageDirection\n unreadCount: number\n /** Quando alguém deu a conversa por vista.\n *\n * Vale enquanto for POSTERIOR a `lastMessageAt`: mensagem nova devolve a\n * conversa à fila sozinha, sem ninguém ter de lembrar de apagar nada. */\n acknowledgedAt?: string | null\n status: ConversationStatus\n /** Quem ATENDE esta conversa. */\n assignedTo?: string\n /** Quem é dono do LEAD — outra pergunta, e a que decide o follow-up.\n * Derivado de `v_leads` pela view `v_conversations`: copiar aqui faria uma\n * segunda verdade que envelhece quando alguém clica \"Assumir\" no funil. */\n leadOwnerId?: string\n leadOwnerName?: string\n /** Which team's inbox the thread is in (024): help-desk threads are\n * `support`, everything else `commercial`. The database only returns the\n * inboxes the reader may see. */\n inbox?: 'commercial' | 'support'\n /** Tailwind-ish accent for the avatar bubble */\n accent: string\n tags: string[]\n // Optional context shown in the contact panel.\n location?: string\n note?: string\n}\n\nexport interface Message {\n id: string\n conversationId: string\n channel: Channel\n direction: MessageDirection\n body: string\n at: string\n author: string\n /** O que aconteceu com ela depois que saiu. Nulo na entrada — ela chegou,\n * não foi entregue por nós. `failed` é o caso que a tela precisa gritar:\n * uma mensagem que nunca saiu não pode parecer uma mensagem enviada. */\n deliveryStatus?: string | null\n /** O id no provedor. Sem ele, não saiu — e é a chave para buscar o JSON cru. */\n providerMessageId?: string | null\n /**\n * What the provider sent, when it was not plain text. Absent on every row\n * written before migration 012 — absent is \"unknown\", never \"text\", because\n * the rows this exists for are exactly the ones that stored as empty text.\n */\n messageType?: MessageType | null\n /**\n * The part `body` cannot hold: parsed vCards, media metadata, coordinates.\n * Shape follows `messageType`; see functions/_shared/evolution-runtime.js.\n */\n payload?: MessagePayload | null\n /**\n * Where the bytes are, in the private `attachments` bucket — or null, which\n * means one of three ordinary things: the message is text, the row predates\n * 013, or the upload did not happen. Never a URL: the bucket is private and\n * a link has to be signed per view, which `media_url` does against the row\n * rather than against a path the client supplies.\n */\n mediaPath?: string | null\n}\n\nexport type MessageType =\n | 'text' | 'contact' | 'image' | 'video' | 'audio'\n | 'document' | 'sticker' | 'location' | 'reaction' | 'poll' | 'unknown'\n\n/** A contact card someone forwarded into the thread. The number in it is\n * routinely the reason the conversation is happening. */\nexport interface SharedContact {\n name: string\n /** `display` is what a human reads back; `digits` is what dials. */\n phones: Array<{ display: string; digits: string }>\n}\n\nexport interface MessagePayload {\n contacts?: SharedContact[]\n mimetype?: string | null\n fileName?: string | null\n fileLength?: number | null\n seconds?: number | null\n ptt?: boolean | null\n caption?: string | null\n latitude?: number | null\n longitude?: number | null\n name?: string | null\n address?: string | null\n /** Only on `unknown`: the provider keys nobody has mapped yet. */\n keys?: string[]\n /** Business templates and interactive cards: the buttons under the text. */\n kind?: 'template' | 'interactive' | 'buttons' | 'button_reply'\n buttons?: Array<{ text?: string | null; url?: string | null; phone?: string | null }>\n /** The message this one answers (WhatsApp's quoted block). */\n quoted?: { id: string; type?: string; body?: string }\n /** \"Encaminhada\" / \"Encaminhada com frequência\". */\n forwarded?: boolean | 'many'\n /** The preview card the sender's phone built for a link. */\n link?: { url?: string | null; title?: string | null; description?: string | null; thumbnail?: string | null }\n /** Poll options. */\n options?: string[]\n /** Reactions by side: what the contact and what we reacted with. */\n reactions?: { contact?: string; me?: string }\n edited?: boolean\n deleted?: boolean\n}\n\nexport interface ListConversationsQuery {\n channel?: Channel | 'all'\n status?: ConversationStatus | 'all'\n search?: string\n /** Recorta pelo DONO DO LEAD. `'none'` traz quem ainda não é lead de\n * ninguém — a fila que precisa de dono, e a pergunta que a caixa sozinha\n * não respondia. */\n leadOwnerId?: string | 'none'\n}\n\nexport interface SendMessageInput {\n conversationId: string\n body: string\n}\n\nexport interface CreateConversationInput {\n contactName: string\n /** `public.people` id, when the contact was resolved/created by the picker. */\n contactPersonId?: string\n /** Phone, @handle, or email depending on channel. */\n contactHandle?: string\n channel: Channel\n /** Optional first outbound message; stamps preview + last_message_at. */\n firstMessage?: string\n /** Optional free-text note surfaced in the contact panel. */\n note?: string\n}\n\nexport const CHANNEL_LABELS: Record<Channel, string> = {\n sms: 'SMS',\n whatsapp: 'WhatsApp',\n instagram: 'Instagram',\n email: 'Email',\n webchat: 'Web Chat',\n support: 'Suporte',\n}\n\n/**\n * Is this thread waiting on US?\n *\n * One definition, in one place, because the KPI, the queue table and anything\n * that later filters the inbox have to agree — a dashboard that says three and\n * a list that shows one is worse than neither.\n *\n * `lastMessageDirection` is the real answer. `unreadCount` is the fallback for\n * a thread that genuinely does not know its direction (older than migration\n * 001, or a provider that does not report one) — it under-reports rather than\n * over-reports, which is the right way round: a queue that invents work loses\n * trust faster than one that misses an old row.\n */\nexport function isWaitingOnUs(conversation: Conversation): boolean {\n if (conversation.status !== 'open') return false\n // DAR POR VISTA vence a direção — e só enquanto for mais recente que a\n // última mensagem. Alguém leu, decidiu que não cabe resposta, e tirou da\n // fila; se chegar mensagem depois disso, a comparação se inverte sozinha e a\n // conversa volta. É por isso que é um instante e não um booleano: um\n // booleano precisaria de alguém para apagá-lo, e o dia do esquecimento é o\n // dia em que um cliente fica esperando sem aparecer para ninguém.\n if (conversation.acknowledgedAt && conversation.lastMessageAt\n && conversation.acknowledgedAt >= conversation.lastMessageAt) return false\n if (conversation.lastMessageDirection) return conversation.lastMessageDirection === 'inbound'\n return conversation.unreadCount > 0\n}\n","import React from 'react'\nimport { useStore, type StoreApi } from 'zustand'\nimport type { EntityLookup } from '@fayz-ai/admin'\nimport type { EntityDef } from '@fayz-ai/core'\nimport type { ConversationsUIState } from './store'\n\n/**\n * App-tunable knobs the inbox UI reads. Kept tiny on purpose: everything here\n * describes the APP's data shape (which people are \"contacts\" in this vertical),\n * never product policy.\n */\nexport interface ResolvedConversationsConfig {\n /** `people.kind` the picker searches. */\n contactKind: string\n /** Search source for the contact picker. Defaults to the person archetype. */\n contactLookup?: EntityLookup\n /** The app's own contact entity — \"Create\" opens ITS form. Agenda's twin is `clientEntityDef`. */\n contactEntityDef?: EntityDef\n}\n\nexport const DEFAULT_CONVERSATIONS_CONFIG: ResolvedConversationsConfig = {\n contactKind: 'contact',\n}\n\nconst StoreContext = React.createContext<StoreApi<ConversationsUIState> | null>(null)\nconst ConfigContext = React.createContext<ResolvedConversationsConfig>(DEFAULT_CONVERSATIONS_CONFIG)\n\nexport function ConversationsContextProvider({\n store,\n config = DEFAULT_CONVERSATIONS_CONFIG,\n children,\n}: {\n store: StoreApi<ConversationsUIState>\n config?: ResolvedConversationsConfig\n children?: React.ReactNode\n}) {\n return (\n <StoreContext.Provider value={store}>\n <ConfigContext.Provider value={config}>{children}</ConfigContext.Provider>\n </StoreContext.Provider>\n )\n}\n\nexport function useConversationsStore<T>(selector: (state: ConversationsUIState) => T): T {\n const store = React.useContext(StoreContext)\n if (!store) throw new Error('useConversationsStore must be used within ConversationsPage')\n return useStore(store, selector)\n}\n\nexport function useConversationsConfig(): ResolvedConversationsConfig {\n return React.useContext(ConfigContext)\n}\n","import { getSupabaseClientOptional } from '@fayz-ai/core'\n\n/**\n * UMA assinatura do tópico da conta, partilhada por quem precisar.\n *\n * ── por que não cada um a sua ───────────────────────────────────────────\n *\n * Dois consumidores querem o mesmo sinal: o vigia global (som, contagem,\n * notificação do sistema) e a caixa aberta (lista e thread ao vivo). O jeito\n * óbvio é cada um chamar `supabase.channel('conversas:<tenant>')` — e é o que\n * eu fiz, e está errado.\n *\n * Dois canais com o MESMO tópico no mesmo cliente não recebem os dois: um\n * vence. Testados em separado, ambos funcionam; juntos, um emudece. Em\n * produção quem venceu foi a tela — a mensagem aparecia sozinha e a notificação\n * do sistema não saía, sem erro nenhum para explicar.\n *\n * É o tipo de defeito que só aparece com as duas peças no ar ao mesmo tempo, e\n * por isso passou por dois testes verdes.\n *\n * ── o desenho ───────────────────────────────────────────────────────────\n *\n * Um canal por conta, contado por referências. O primeiro a chegar abre, o\n * último a sair fecha, e todos recebem a mesma campainha.\n */\n\nexport interface Chegada {\n conversationId?: string\n}\n\ntype Ouvinte = (c: Chegada) => void\n\ninterface Assinatura {\n canal: unknown\n ouvintes: Set<Ouvinte>\n}\n\nconst porConta = new Map<string, Assinatura>()\n\n/** Escuta a chegada de mensagem nesta conta. Devolve como deixar de escutar. */\nexport function assinarChegada(tenantId: string, ouvinte: Ouvinte): () => void {\n const supabase = getSupabaseClientOptional() as any\n if (!supabase?.channel || !tenantId) return () => {}\n\n let assinatura = porConta.get(tenantId)\n if (!assinatura) {\n const ouvintes = new Set<Ouvinte>()\n const canal = supabase\n .channel(`conversas:${tenantId}`)\n .on('broadcast', { event: 'inbound' }, (msg: any) => {\n const carga: Chegada = { conversationId: msg?.payload?.conversationId }\n // Cópia antes de percorrer: um ouvinte que se desinscreve ao receber\n // (a tela fechando no mesmo tique) mutaria o Set durante a iteração.\n for (const f of [...ouvintes]) {\n try { f(carga) } catch { /* um ouvinte que falha não cala os outros */ }\n }\n })\n .subscribe()\n assinatura = { canal, ouvintes }\n porConta.set(tenantId, assinatura)\n }\n\n assinatura.ouvintes.add(ouvinte)\n return () => {\n const a = porConta.get(tenantId)\n if (!a) return\n a.ouvintes.delete(ouvinte)\n // O último a sair fecha a porta. Deixar o canal aberto sem ouvintes seria\n // pagar uma conexão por conta que a pessoa visitou e abandonou.\n if (a.ouvintes.size === 0) {\n porConta.delete(tenantId)\n void (getSupabaseClientOptional() as any)?.removeChannel?.(a.canal)\n }\n }\n}\n","import * as React from 'react'\nimport { Camera, CircleHelp, FileText, MapPin, Mic, Sticker, User, Video, type LucideIcon } from 'lucide-react'\nimport { useTranslation } from '@fayz-ai/core'\n\n// ---------------------------------------------------------------------------\n// A message with no text of its own, the way WhatsApp shows it: an icon and a\n// word (\"🎤 Mensagem de voz\"), not \"[áudio]\".\n//\n// The bracketed labels are what the backend stores in `body` and in\n// `last_message_preview` for media without a caption (MEDIA_LABELS in the\n// integration service's evolution-runtime). They stay the stored value — a\n// notification or an export still reads as something — and the screen swaps\n// them for an icon here.\n// ---------------------------------------------------------------------------\n\nconst KINDS: Record<string, { icon: LucideIcon; key: string }> = {\n '[áudio]': { icon: Mic, key: 'conversations.preview.audio' },\n '[imagem]': { icon: Camera, key: 'conversations.preview.image' },\n '[vídeo]': { icon: Video, key: 'conversations.preview.video' },\n '[documento]': { icon: FileText, key: 'conversations.preview.document' },\n '[figurinha]': { icon: Sticker, key: 'conversations.preview.sticker' },\n '[localização]': { icon: MapPin, key: 'conversations.preview.location' },\n '[contato]': { icon: User, key: 'conversations.preview.contact' },\n '[mensagem não suportada]': { icon: CircleHelp, key: 'conversations.preview.unsupported' },\n}\n\n/** The icon and translation key for a stored media label, or null for text. */\nexport function mediaPreviewKind(text: string | null | undefined): { icon: LucideIcon; key: string } | null {\n return KINDS[String(text ?? '').trim()] ?? null\n}\n\n/** One line: the icon and its word for a media label, the text otherwise. */\nexport function MessagePreview({ text, suffix, className }: { text: string | null | undefined; suffix?: string; className?: string }) {\n const t = useTranslation()\n const kind = mediaPreviewKind(text)\n if (!kind) return <>{text}</>\n const Icon = kind.icon\n return (\n <span className={`inline-flex min-w-0 items-center gap-1 ${className ?? ''}`}>\n <Icon className=\"h-3.5 w-3.5 shrink-0\" />\n <span className=\"truncate\">{t(kind.key)}{suffix ? ` (${suffix})` : ''}</span>\n </span>\n )\n}\n"]}