isometrik-plugin-chat-sdk 2.0.19 → 2.0.20

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 (138) hide show
  1. package/dist/cjs/{app-globals-170f9e71.js → app-globals-2824b330.js} +3 -3
  2. package/dist/cjs/{app-globals-170f9e71.js.map → app-globals-2824b330.js.map} +1 -1
  3. package/dist/cjs/attachment-preview_22.cjs.entry.js +114 -141
  4. package/dist/cjs/attachment-preview_22.cjs.entry.js.map +1 -1
  5. package/dist/cjs/audio-bubble_4.cjs.entry.js +1 -1
  6. package/dist/cjs/{chat-assets-686620e7.js → chat-assets-8c4dc04f.js} +22 -3
  7. package/dist/cjs/chat-assets-8c4dc04f.js.map +1 -0
  8. package/dist/cjs/chat-tile_3.cjs.entry.js +1 -1
  9. package/dist/cjs/forward-memebers.cjs.entry.js +1 -1
  10. package/dist/cjs/{groupcast-4239cbfc.js → groupcast-8441b4df.js} +2 -2
  11. package/dist/cjs/{groupcast-4239cbfc.js.map → groupcast-8441b4df.js.map} +1 -1
  12. package/dist/cjs/{groupcast-3cb44a25.js → groupcast-f24da720.js} +14 -4
  13. package/dist/cjs/groupcast-f24da720.js.map +1 -0
  14. package/dist/cjs/index.cjs.js +4 -4
  15. package/dist/cjs/isometrik-webchat.cjs.js +6 -6
  16. package/dist/cjs/loader.cjs.js +6 -6
  17. package/dist/cjs/login-page_3.cjs.entry.js +7 -7
  18. package/dist/cjs/login-page_3.cjs.entry.js.map +1 -1
  19. package/dist/cjs/member-add.cjs.entry.js +2 -2
  20. package/dist/cjs/new-chat-sidebar.cjs.entry.js +1 -1
  21. package/dist/cjs/{runtime-controls-99f378d4.js → runtime-controls-cfc8fc31.js} +3 -3
  22. package/dist/cjs/{runtime-controls-99f378d4.js.map → runtime-controls-cfc8fc31.js.map} +1 -1
  23. package/dist/cjs/send-media-4ee967d4.js +1194 -0
  24. package/dist/cjs/send-media-4ee967d4.js.map +1 -0
  25. package/dist/collection/api/groupcast.js +13 -3
  26. package/dist/collection/components/ChatUIComponent/ChatSidebar/ChatSidebar.js +102 -100
  27. package/dist/collection/components/ChatUIComponent/ChatSidebar/ChatSidebar.js.map +1 -1
  28. package/dist/collection/components/ChatUIComponent/Footer/ChatFooter.js +25 -47
  29. package/dist/collection/components/ChatUIComponent/Footer/ChatFooter.js.map +1 -1
  30. package/dist/collection/components/ChatUIComponent/shared/GroupCast/GroupCast.js +3 -16
  31. package/dist/collection/components/ChatUIComponent/shared/GroupCast/GroupCast.js.map +1 -1
  32. package/dist/collection/components/ChatUIComponent/shared/message-info/message-info.js +10 -4
  33. package/dist/collection/components/ChatUIComponent/shared/message-info/message-info.js.map +1 -1
  34. package/dist/collection/components/my-component/web-chat/public-send.js +4 -4
  35. package/dist/collection/components/my-component/web-chat/public-send.js.map +1 -1
  36. package/dist/collection/constants/chat-assets.js +21 -2
  37. package/dist/collection/lib/chat/document-thumbnail.js +433 -0
  38. package/dist/collection/lib/chat/document-thumbnail.js.map +1 -0
  39. package/dist/collection/lib/chat/index.js +1 -1
  40. package/dist/collection/lib/chat/index.js.map +1 -1
  41. package/dist/collection/lib/chat/send-media.js +348 -25
  42. package/dist/collection/lib/chat/send-media.js.map +1 -1
  43. package/dist/components/ChatFooter.js +25 -47
  44. package/dist/components/ChatFooter.js.map +1 -1
  45. package/dist/components/ChatSidebar.js +78 -73
  46. package/dist/components/ChatSidebar.js.map +1 -1
  47. package/dist/components/GroupCast2.js +3 -16
  48. package/dist/components/GroupCast2.js.map +1 -1
  49. package/dist/components/WebChat.js +4 -4
  50. package/dist/components/WebChat.js.map +1 -1
  51. package/dist/components/WebChatBody.js +1 -1
  52. package/dist/components/chat-assets.js +21 -2
  53. package/dist/components/chat-assets.js.map +1 -1
  54. package/dist/components/groupcast.js +13 -3
  55. package/dist/components/groupcast.js.map +1 -1
  56. package/dist/components/message-info2.js +10 -4
  57. package/dist/components/message-info2.js.map +1 -1
  58. package/dist/components/send-media.js +780 -26
  59. package/dist/components/send-media.js.map +1 -1
  60. package/dist/esm/{app-globals-15a6ef50.js → app-globals-e3f4717b.js} +3 -3
  61. package/dist/esm/{app-globals-15a6ef50.js.map → app-globals-e3f4717b.js.map} +1 -1
  62. package/dist/esm/attachment-preview_22.entry.js +114 -141
  63. package/dist/esm/attachment-preview_22.entry.js.map +1 -1
  64. package/dist/esm/audio-bubble_4.entry.js +1 -1
  65. package/dist/esm/{chat-assets-bb056958.js → chat-assets-27beb552.js} +22 -3
  66. package/dist/esm/chat-assets-27beb552.js.map +1 -0
  67. package/dist/esm/chat-tile_3.entry.js +1 -1
  68. package/dist/esm/forward-memebers.entry.js +1 -1
  69. package/dist/esm/{groupcast-ea2466c8.js → groupcast-5fb19ec3.js} +2 -2
  70. package/dist/esm/{groupcast-ea2466c8.js.map → groupcast-5fb19ec3.js.map} +1 -1
  71. package/dist/esm/{groupcast-cc10c6a4.js → groupcast-f96c1d9e.js} +14 -4
  72. package/dist/esm/groupcast-f96c1d9e.js.map +1 -0
  73. package/dist/esm/index.js +5 -5
  74. package/dist/esm/isometrik-webchat.js +6 -6
  75. package/dist/esm/loader.js +6 -6
  76. package/dist/esm/login-page_3.entry.js +7 -7
  77. package/dist/esm/login-page_3.entry.js.map +1 -1
  78. package/dist/esm/member-add.entry.js +2 -2
  79. package/dist/esm/new-chat-sidebar.entry.js +1 -1
  80. package/dist/esm/{runtime-controls-8a22625e.js → runtime-controls-ff81e90a.js} +3 -3
  81. package/dist/esm/{runtime-controls-8a22625e.js.map → runtime-controls-ff81e90a.js.map} +1 -1
  82. package/dist/esm/send-media-58e7145b.js +1166 -0
  83. package/dist/esm/send-media-58e7145b.js.map +1 -0
  84. package/dist/isometrik-webchat/index.esm.js +1 -1
  85. package/dist/isometrik-webchat/isometrik-webchat.esm.js +1 -1
  86. package/dist/isometrik-webchat/isometrik-webchat.esm.js.map +1 -1
  87. package/dist/isometrik-webchat/{p-fd6ce589.entry.js → p-09980c53.entry.js} +2 -2
  88. package/dist/isometrik-webchat/p-352b589e.entry.js +2 -0
  89. package/dist/isometrik-webchat/p-352b589e.entry.js.map +1 -0
  90. package/dist/isometrik-webchat/p-3b3dc33e.js +2 -0
  91. package/dist/isometrik-webchat/p-3b3dc33e.js.map +1 -0
  92. package/dist/isometrik-webchat/{p-ffbbe278.entry.js → p-44da28d3.entry.js} +2 -2
  93. package/dist/isometrik-webchat/p-6f5037b2.js +2 -0
  94. package/dist/isometrik-webchat/p-6f5037b2.js.map +1 -0
  95. package/dist/isometrik-webchat/{p-6fc95e0e.js → p-78fb47c4.js} +2 -2
  96. package/dist/isometrik-webchat/{p-3120b9d3.entry.js → p-a9efcf1c.entry.js} +2 -2
  97. package/dist/isometrik-webchat/p-b0baa9ad.entry.js +2 -0
  98. package/dist/isometrik-webchat/p-b0baa9ad.entry.js.map +1 -0
  99. package/dist/isometrik-webchat/{p-c08055fe.js → p-b385ac4b.js} +2 -2
  100. package/dist/isometrik-webchat/p-c06ad586.js +2 -0
  101. package/dist/isometrik-webchat/p-c06ad586.js.map +1 -0
  102. package/dist/isometrik-webchat/p-d758e431.js +2 -0
  103. package/dist/isometrik-webchat/{p-c49de274.entry.js → p-d864bb9f.entry.js} +2 -2
  104. package/dist/isometrik-webchat/{p-39b626ed.entry.js → p-f7d05551.entry.js} +2 -2
  105. package/dist/types/components/ChatUIComponent/ChatSidebar/ChatSidebar.d.ts +3 -2
  106. package/dist/types/components.d.ts +17 -17
  107. package/dist/types/js.d.ts +3 -0
  108. package/dist/types/lib/chat/document-thumbnail.d.ts +38 -0
  109. package/dist/types/lib/chat/index.d.ts +1 -1
  110. package/dist/types/lib/chat/send-media.d.ts +58 -1
  111. package/package.json +1 -1
  112. package/dist/cjs/chat-assets-686620e7.js.map +0 -1
  113. package/dist/cjs/groupcast-3cb44a25.js.map +0 -1
  114. package/dist/cjs/send-media-7c865c19.js +0 -438
  115. package/dist/cjs/send-media-7c865c19.js.map +0 -1
  116. package/dist/esm/chat-assets-bb056958.js.map +0 -1
  117. package/dist/esm/groupcast-cc10c6a4.js.map +0 -1
  118. package/dist/esm/send-media-5527ee9f.js +0 -412
  119. package/dist/esm/send-media-5527ee9f.js.map +0 -1
  120. package/dist/isometrik-webchat/p-1db79cfb.js +0 -2
  121. package/dist/isometrik-webchat/p-4671fe73.js +0 -2
  122. package/dist/isometrik-webchat/p-4671fe73.js.map +0 -1
  123. package/dist/isometrik-webchat/p-643457b8.js +0 -2
  124. package/dist/isometrik-webchat/p-643457b8.js.map +0 -1
  125. package/dist/isometrik-webchat/p-a5707f12.js +0 -2
  126. package/dist/isometrik-webchat/p-a5707f12.js.map +0 -1
  127. package/dist/isometrik-webchat/p-a9380fb3.entry.js +0 -2
  128. package/dist/isometrik-webchat/p-a9380fb3.entry.js.map +0 -1
  129. package/dist/isometrik-webchat/p-fc3fd090.entry.js +0 -2
  130. package/dist/isometrik-webchat/p-fc3fd090.entry.js.map +0 -1
  131. /package/dist/isometrik-webchat/{p-fd6ce589.entry.js.map → p-09980c53.entry.js.map} +0 -0
  132. /package/dist/isometrik-webchat/{p-ffbbe278.entry.js.map → p-44da28d3.entry.js.map} +0 -0
  133. /package/dist/isometrik-webchat/{p-6fc95e0e.js.map → p-78fb47c4.js.map} +0 -0
  134. /package/dist/isometrik-webchat/{p-3120b9d3.entry.js.map → p-a9efcf1c.entry.js.map} +0 -0
  135. /package/dist/isometrik-webchat/{p-c08055fe.js.map → p-b385ac4b.js.map} +0 -0
  136. /package/dist/isometrik-webchat/{p-1db79cfb.js.map → p-d758e431.js.map} +0 -0
  137. /package/dist/isometrik-webchat/{p-c49de274.entry.js.map → p-d864bb9f.entry.js.map} +0 -0
  138. /package/dist/isometrik-webchat/{p-39b626ed.entry.js.map → p-f7d05551.entry.js.map} +0 -0
@@ -2,12 +2,445 @@ import { M } from './index.m.js';
2
2
  import { t as takeMediaFiles } from './media-limits.js';
3
3
  import { w as withHostMessagePushFields } from './local-notification.js';
4
4
 
5
+ const WORD_EXTENSIONS = new Set(['doc', 'docx', 'docm']);
6
+ const EXCEL_EXTENSIONS = new Set(['xls', 'xlsx', 'xlsm']);
7
+ const OOXML_EXTENSIONS = new Set(['docx', 'docm', 'xlsx', 'xlsm']);
8
+ /** Skip parsing huge workbooks; those still get a typed card thumbnail. */
9
+ const MAX_PREVIEW_BYTES = 12 * 1024 * 1024;
10
+ const MAX_XML_BYTES = 8 * 1024 * 1024;
11
+ const WORD_LINES = 12;
12
+ const EXCEL_ROWS = 8;
13
+ const EXCEL_COLS = 6;
14
+ const WORD_COLOR = '#2b579a';
15
+ const EXCEL_COLOR = '#217346';
16
+ /** True when this URL is the document itself, which Image.network cannot draw. */
17
+ function looksLikeDocumentFileUrl(url) {
18
+ const path = String(url || '')
19
+ .split('?')[0]
20
+ .split('#')[0]
21
+ .toLowerCase();
22
+ return /\.(pdf|docx?|docm|xlsx?|xlsm|pptx?|csv|txt|rtf)$/.test(path);
23
+ }
24
+ function officePreviewKind(file) {
25
+ const mime = String((file === null || file === void 0 ? void 0 : file.mimeType) || '').toLowerCase();
26
+ const name = String((file === null || file === void 0 ? void 0 : file.nameWithExtension) || (file === null || file === void 0 ? void 0 : file.name) || '');
27
+ const ext = extensionOf(name);
28
+ const word = WORD_EXTENSIONS.has(ext) ||
29
+ mime === 'application/msword' ||
30
+ mime.includes('wordprocessingml') ||
31
+ mime.includes('ms-word') ||
32
+ mime.includes('msword');
33
+ if (word)
34
+ return 'word';
35
+ const excel = EXCEL_EXTENSIONS.has(ext) ||
36
+ mime === 'application/vnd.ms-excel' ||
37
+ mime.includes('spreadsheetml') ||
38
+ mime.includes('ms-excel');
39
+ if (excel)
40
+ return 'excel';
41
+ return null;
42
+ }
43
+ /**
44
+ * First-page text (Word) or first-sheet grid (Excel) from an OOXML zip.
45
+ * Returns null when the zip cannot be read; callers then paint a file card.
46
+ */
47
+ async function extractOfficePreview(data, kind) {
48
+ const entries = listZipEntries(data);
49
+ if (!entries.length)
50
+ return null;
51
+ if (kind === 'word') {
52
+ const entry = findEntry(entries, 'word/document.xml');
53
+ if (!entry)
54
+ return null;
55
+ const xml = await readZipXml(data, entry);
56
+ if (!xml)
57
+ return null;
58
+ return { lines: docxLines(xml), rows: [] };
59
+ }
60
+ const sheet = firstSheetEntry(entries);
61
+ if (!sheet)
62
+ return null;
63
+ const shared = findEntry(entries, 'xl/sharedStrings.xml');
64
+ const [sheetXml, sharedXml] = await Promise.all([
65
+ readZipXml(data, sheet),
66
+ shared ? readZipXml(data, shared) : Promise.resolve(''),
67
+ ]);
68
+ if (!sheetXml)
69
+ return null;
70
+ return { lines: [], rows: xlsxRows(sheetXml, sharedXml || '') };
71
+ }
72
+ /**
73
+ * JPEG the send pipeline uploads as `thumbnailUrl`.
74
+ * Null for any file that is not Word or Excel, and when canvas is unavailable.
75
+ */
76
+ async function captureOfficeThumbnailBlob(file) {
77
+ if (typeof document === 'undefined')
78
+ return null;
79
+ const kind = officePreviewKind({ mimeType: file === null || file === void 0 ? void 0 : file.type, name: file === null || file === void 0 ? void 0 : file.name });
80
+ if (!kind)
81
+ return null;
82
+ // A failed preview must not block the file upload. Callers send the document either way.
83
+ try {
84
+ const label = (file === null || file === void 0 ? void 0 : file.name) || (kind === 'excel' ? 'Spreadsheet.xlsx' : 'Document.docx');
85
+ let content = null;
86
+ if (file.size > 0 && file.size <= MAX_PREVIEW_BYTES && OOXML_EXTENSIONS.has(extensionOf(label))) {
87
+ content = await extractOfficePreview(new Uint8Array(await file.arrayBuffer()), kind);
88
+ }
89
+ const hasWord = !!(content === null || content === void 0 ? void 0 : content.lines.some(line => line.trim()));
90
+ const hasExcel = !!(content === null || content === void 0 ? void 0 : content.rows.some(row => row.some(cell => cell.trim())));
91
+ if (kind === 'word' && hasWord && content)
92
+ return await paintWordPage(content.lines, label);
93
+ if (kind === 'excel' && hasExcel && content)
94
+ return await paintExcelSheet(content.rows, label);
95
+ return await paintFileCard(kind, label);
96
+ }
97
+ catch (_a) {
98
+ return null;
99
+ }
100
+ }
101
+ function extensionOf(name) {
102
+ const base = (name || '').split(/[/\\]/).pop() || '';
103
+ const idx = base.lastIndexOf('.');
104
+ if (idx <= 0)
105
+ return '';
106
+ return base.slice(idx + 1).toLowerCase();
107
+ }
108
+ function decodeXml(value) {
109
+ return value
110
+ .replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))
111
+ .replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec)))
112
+ .replace(/&lt;/g, '<')
113
+ .replace(/&gt;/g, '>')
114
+ .replace(/&quot;/g, '"')
115
+ .replace(/&apos;/g, "'")
116
+ .replace(/&amp;/g, '&');
117
+ }
118
+ /** Paragraph text from word/document.xml, in reading order. */
119
+ function docxLines(xml) {
120
+ const lines = [];
121
+ const paragraphs = xml.match(/<w:p\b[\s\S]*?<\/w:p>/g) || [];
122
+ for (const paragraph of paragraphs) {
123
+ const normalized = paragraph.replace(/<w:tab\/>/g, ' ').replace(/<w:br\/>/g, '\n');
124
+ const parts = [...normalized.matchAll(/<w:t\b[^>]*>([\s\S]*?)<\/w:t>/g)].map(match => decodeXml(match[1]));
125
+ const text = parts.join('').replace(/\s+/g, ' ').trim();
126
+ if (!text)
127
+ continue;
128
+ lines.push(text.slice(0, 180));
129
+ if (lines.length >= WORD_LINES)
130
+ break;
131
+ }
132
+ return lines;
133
+ }
134
+ /** First rows and columns of a worksheet. Shared strings are optional. */
135
+ function xlsxRows(sheetXml, sharedStringsXml) {
136
+ const strings = sharedStrings(sharedStringsXml);
137
+ const cells = [];
138
+ const cellRe = /<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g;
139
+ let match;
140
+ while ((match = cellRe.exec(sheetXml))) {
141
+ const attrs = match[1] || '';
142
+ const ref = attr(attrs, 'r');
143
+ const parsed = parseCellRef(ref);
144
+ if (!parsed || parsed.row >= 40 || parsed.col >= 20)
145
+ continue;
146
+ const value = cellText(match[2] || '', attr(attrs, 't'), strings);
147
+ if (!value)
148
+ continue;
149
+ cells.push({ row: parsed.row, col: parsed.col, value: value.slice(0, 40) });
150
+ }
151
+ return denseGrid(cells);
152
+ }
153
+ function sharedStrings(xml) {
154
+ if (!xml)
155
+ return [];
156
+ const items = xml.match(/<si\b[\s\S]*?<\/si>/g) || [];
157
+ return items.map(item => {
158
+ const withoutPhonetic = item.replace(/<rPh\b[\s\S]*?<\/rPh>/g, '');
159
+ return [...withoutPhonetic.matchAll(/<t\b[^>]*>([\s\S]*?)<\/t>/g)].map(match => decodeXml(match[1])).join('');
160
+ });
161
+ }
162
+ function attr(attrs, name) {
163
+ const match = new RegExp(`\\b${name}="([^"]*)"`).exec(attrs);
164
+ return match ? match[1] : '';
165
+ }
166
+ function parseCellRef(ref) {
167
+ const match = /^([A-Z]+)(\d+)$/i.exec(ref || '');
168
+ if (!match)
169
+ return null;
170
+ let col = 0;
171
+ for (const ch of match[1].toUpperCase())
172
+ col = col * 26 + (ch.charCodeAt(0) - 64);
173
+ return { col: col - 1, row: Number(match[2]) - 1 };
174
+ }
175
+ function cellText(inner, type, strings) {
176
+ if (type === 'inlineStr') {
177
+ return [...inner.matchAll(/<t\b[^>]*>([\s\S]*?)<\/t>/g)].map(match => decodeXml(match[1])).join('').trim();
178
+ }
179
+ const value = /<v\b[^>]*>([\s\S]*?)<\/v>/.exec(inner);
180
+ if (!value)
181
+ return '';
182
+ const raw = decodeXml(value[1]).trim();
183
+ if (type === 's')
184
+ return strings[Number(raw)] || '';
185
+ return raw;
186
+ }
187
+ function denseGrid(cells) {
188
+ if (!cells.length)
189
+ return [];
190
+ const rowIds = [...new Set(cells.map(cell => cell.row))].sort((a, b) => a - b).slice(0, EXCEL_ROWS);
191
+ const colIds = [...new Set(cells.map(cell => cell.col))].sort((a, b) => a - b).slice(0, EXCEL_COLS);
192
+ const rowPos = new Map(rowIds.map((row, index) => [row, index]));
193
+ const colPos = new Map(colIds.map((col, index) => [col, index]));
194
+ const grid = rowIds.map(() => colIds.map(() => ''));
195
+ for (const cell of cells) {
196
+ const row = rowPos.get(cell.row);
197
+ const col = colPos.get(cell.col);
198
+ if (row == null || col == null)
199
+ continue;
200
+ grid[row][col] = cell.value;
201
+ }
202
+ return grid;
203
+ }
204
+ function listZipEntries(data) {
205
+ if (data.length < 22)
206
+ return [];
207
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
208
+ const eocd = findEocd(data);
209
+ if (eocd < 0)
210
+ return [];
211
+ const count = view.getUint16(eocd + 10, true);
212
+ const cdOffset = view.getUint32(eocd + 16, true);
213
+ if (cdOffset === 0xffffffff || cdOffset >= data.length)
214
+ return [];
215
+ const entries = [];
216
+ let cursor = cdOffset;
217
+ for (let i = 0; i < count && cursor + 46 <= data.length; i++) {
218
+ if (view.getUint32(cursor, true) !== 0x02014b50)
219
+ break;
220
+ const method = view.getUint16(cursor + 10, true);
221
+ const compressedSize = view.getUint32(cursor + 20, true);
222
+ const uncompressedSize = view.getUint32(cursor + 24, true);
223
+ const nameLen = view.getUint16(cursor + 28, true);
224
+ const extraLen = view.getUint16(cursor + 30, true);
225
+ const commentLen = view.getUint16(cursor + 32, true);
226
+ const localOffset = view.getUint32(cursor + 42, true);
227
+ const name = new TextDecoder().decode(data.subarray(cursor + 46, cursor + 46 + nameLen));
228
+ entries.push({ name, method, compressedSize, uncompressedSize, localOffset });
229
+ cursor += 46 + nameLen + extraLen + commentLen;
230
+ }
231
+ return entries;
232
+ }
233
+ function findEocd(data) {
234
+ const start = Math.max(0, data.length - (22 + 0xffff));
235
+ for (let i = data.length - 22; i >= start; i--) {
236
+ if (data[i] === 0x50 && data[i + 1] === 0x4b && data[i + 2] === 0x05 && data[i + 3] === 0x06)
237
+ return i;
238
+ }
239
+ return -1;
240
+ }
241
+ function findEntry(entries, name) {
242
+ const want = name.toLowerCase();
243
+ return entries.find(entry => entry.name.replace(/\\/g, '/').toLowerCase() === want);
244
+ }
245
+ function firstSheetEntry(entries) {
246
+ const sheets = entries.filter(entry => /^xl\/worksheets\/sheet\d+\.xml$/i.test(entry.name.replace(/\\/g, '/')));
247
+ sheets.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }));
248
+ return sheets[0];
249
+ }
250
+ async function readZipXml(data, entry) {
251
+ if (entry.uncompressedSize > MAX_XML_BYTES)
252
+ return null;
253
+ const bytes = await unzipEntry(data, entry);
254
+ if (!bytes)
255
+ return null;
256
+ return new TextDecoder().decode(bytes);
257
+ }
258
+ async function unzipEntry(data, entry) {
259
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
260
+ const local = entry.localOffset;
261
+ if (local < 0 || local + 30 > data.length)
262
+ return null;
263
+ if (view.getUint32(local, true) !== 0x04034b50)
264
+ return null;
265
+ const nameLen = view.getUint16(local + 26, true);
266
+ const extraLen = view.getUint16(local + 28, true);
267
+ const start = local + 30 + nameLen + extraLen;
268
+ const end = start + entry.compressedSize;
269
+ if (end > data.length)
270
+ return null;
271
+ const compressed = data.subarray(start, end);
272
+ if (entry.method === 0)
273
+ return compressed;
274
+ if (entry.method === 8)
275
+ return inflateRaw(compressed);
276
+ return null;
277
+ }
278
+ async function inflateRaw(compressed) {
279
+ var _a, _b;
280
+ const DecompressionStreamCtor = globalThis.DecompressionStream;
281
+ if (typeof DecompressionStreamCtor !== 'function')
282
+ return null;
283
+ try {
284
+ const copy = compressed.buffer.slice(compressed.byteOffset, compressed.byteOffset + compressed.byteLength);
285
+ const blob = new Blob([copy]);
286
+ const source = (_b = (_a = blob).stream) === null || _b === void 0 ? void 0 : _b.call(_a);
287
+ if (!source)
288
+ return null;
289
+ const stream = source.pipeThrough(new DecompressionStreamCtor('deflate-raw'));
290
+ const buffer = await new Response(stream).arrayBuffer();
291
+ return new Uint8Array(buffer);
292
+ }
293
+ catch (_c) {
294
+ return null;
295
+ }
296
+ }
297
+ function renderJpeg(width, height, draw) {
298
+ const canvas = document.createElement('canvas');
299
+ canvas.width = width;
300
+ canvas.height = height;
301
+ const ctx = canvas.getContext('2d');
302
+ if (!ctx || typeof canvas.toBlob !== 'function')
303
+ return Promise.resolve(null);
304
+ draw(ctx);
305
+ return new Promise(resolve => canvas.toBlob(blob => resolve(blob), 'image/jpeg', 0.85));
306
+ }
307
+ function paintWordPage(lines, fileName) {
308
+ return renderJpeg(640, 840, ctx => {
309
+ ctx.fillStyle = '#ffffff';
310
+ ctx.fillRect(0, 0, 640, 840);
311
+ ctx.fillStyle = WORD_COLOR;
312
+ ctx.fillRect(0, 0, 640, 10);
313
+ ctx.fillStyle = WORD_COLOR;
314
+ ctx.font = '700 12px sans-serif';
315
+ ctx.fillText(badge(fileName, 'word'), 36, 40);
316
+ ctx.fillStyle = '#1f2937';
317
+ ctx.font = '16px sans-serif';
318
+ let y = 72;
319
+ for (const line of lines) {
320
+ const wrapped = wrapText(ctx, line, 568, 3);
321
+ for (const row of wrapped) {
322
+ ctx.fillText(row, 36, y);
323
+ y += 26;
324
+ if (y > 760)
325
+ return;
326
+ }
327
+ y += 8;
328
+ }
329
+ paintFileName(ctx, fileName, 800);
330
+ });
331
+ }
332
+ function paintExcelSheet(rows, fileName) {
333
+ return renderJpeg(800, 560, ctx => {
334
+ ctx.fillStyle = '#ffffff';
335
+ ctx.fillRect(0, 0, 800, 560);
336
+ ctx.fillStyle = EXCEL_COLOR;
337
+ ctx.fillRect(0, 0, 800, 48);
338
+ ctx.fillStyle = '#ffffff';
339
+ ctx.font = '600 16px sans-serif';
340
+ ctx.fillText(fitText(ctx, baseName(fileName), 740), 20, 30);
341
+ const cols = Math.max(1, ...rows.map(row => row.length));
342
+ const bodyTop = 48;
343
+ const rowHeight = Math.min(56, Math.floor((560 - bodyTop) / Math.max(rows.length, 1)));
344
+ const colWidth = Math.floor(800 / cols);
345
+ rows.forEach((row, rowIndex) => {
346
+ const y = bodyTop + rowIndex * rowHeight;
347
+ for (let col = 0; col < cols; col++) {
348
+ const x = col * colWidth;
349
+ ctx.fillStyle = rowIndex === 0 ? '#e7f4ec' : rowIndex % 2 ? '#f8faf9' : '#ffffff';
350
+ ctx.fillRect(x, y, colWidth, rowHeight);
351
+ ctx.strokeStyle = '#d1d5db';
352
+ ctx.strokeRect(x + 0.5, y + 0.5, colWidth - 1, rowHeight - 1);
353
+ ctx.fillStyle = '#111827';
354
+ ctx.font = rowIndex === 0 ? '700 14px sans-serif' : '14px sans-serif';
355
+ const text = fitText(ctx, row[col] || '', colWidth - 16);
356
+ ctx.fillText(text, x + 8, y + Math.min(28, rowHeight - 14));
357
+ }
358
+ });
359
+ });
360
+ }
361
+ function paintFileCard(kind, fileName) {
362
+ const color = kind === 'excel' ? EXCEL_COLOR : WORD_COLOR;
363
+ const title = kind === 'excel' ? 'Excel spreadsheet' : 'Word document';
364
+ return renderJpeg(640, 800, ctx => {
365
+ ctx.fillStyle = '#f8fafc';
366
+ ctx.fillRect(0, 0, 640, 800);
367
+ ctx.fillStyle = '#ffffff';
368
+ roundRect(ctx, 70, 150, 500, 460, 20);
369
+ ctx.fill();
370
+ ctx.fillStyle = color;
371
+ roundRect(ctx, 230, 230, 180, 140, 16);
372
+ ctx.fill();
373
+ ctx.fillStyle = '#ffffff';
374
+ ctx.font = '700 36px sans-serif';
375
+ const label = badge(fileName, kind);
376
+ ctx.fillText(label, 320 - ctx.measureText(label).width / 2, 312);
377
+ ctx.fillStyle = '#111827';
378
+ ctx.font = '600 22px sans-serif';
379
+ const name = fitText(ctx, baseName(fileName), 420);
380
+ ctx.fillText(name, 320 - ctx.measureText(name).width / 2, 440);
381
+ ctx.fillStyle = '#6b7280';
382
+ ctx.font = '16px sans-serif';
383
+ ctx.fillText(title, 320 - ctx.measureText(title).width / 2, 478);
384
+ });
385
+ }
386
+ function paintFileName(ctx, fileName, y) {
387
+ ctx.fillStyle = '#6b7280';
388
+ ctx.font = '13px sans-serif';
389
+ ctx.fillText(fitText(ctx, baseName(fileName), 560), 36, y);
390
+ }
391
+ function badge(fileName, kind) {
392
+ const ext = extensionOf(fileName);
393
+ if (ext)
394
+ return ext.toUpperCase();
395
+ return kind === 'excel' ? 'XLS' : 'DOC';
396
+ }
397
+ function baseName(fileName) {
398
+ return (fileName || 'Document').split(/[/\\]/).pop() || 'Document';
399
+ }
400
+ function fitText(ctx, text, maxWidth) {
401
+ if (ctx.measureText(text).width <= maxWidth)
402
+ return text;
403
+ let trimmed = text;
404
+ while (trimmed.length > 1 && ctx.measureText(`${trimmed}…`).width > maxWidth)
405
+ trimmed = trimmed.slice(0, -1);
406
+ return `${trimmed}…`;
407
+ }
408
+ function wrapText(ctx, text, maxWidth, maxLines) {
409
+ const words = text.split(/\s+/).filter(Boolean);
410
+ const lines = [];
411
+ let current = '';
412
+ for (const word of words) {
413
+ const next = current ? `${current} ${word}` : word;
414
+ if (current && ctx.measureText(next).width > maxWidth) {
415
+ lines.push(current);
416
+ current = word;
417
+ if (lines.length >= maxLines)
418
+ return lines;
419
+ }
420
+ else {
421
+ current = next;
422
+ }
423
+ }
424
+ if (current && lines.length < maxLines)
425
+ lines.push(fitText(ctx, current, maxWidth));
426
+ return lines;
427
+ }
428
+ function roundRect(ctx, x, y, width, height, radius) {
429
+ ctx.beginPath();
430
+ ctx.moveTo(x + radius, y);
431
+ ctx.arcTo(x + width, y, x + width, y + height, radius);
432
+ ctx.arcTo(x + width, y + height, x, y + height, radius);
433
+ ctx.arcTo(x, y + height, x, y, radius);
434
+ ctx.arcTo(x, y, x + width, y, radius);
435
+ ctx.closePath();
436
+ }
437
+
5
438
  /**
6
439
  * Shared media-send helpers for ChatFooter + public web-chat.sendMedia.
7
440
  * Conversation path only (groupcast keeps using ChatFooter).
8
441
  *
9
442
  * Attachment body contract (Flutter / Swift / web):
10
- * - API rejects empty body → use caption text, or 'AttachmentMessage:Multiple' when none
443
+ * - API rejects empty body → caption, filename (single doc), or 'AttachmentMessage:Multiple'
11
444
  * - Real caption for UI lives in metaData.caption (read captionMessage for older web sends)
12
445
  */
13
446
  const ATTACHMENT_BODY_PLACEHOLDER = 'AttachmentMessage:Multiple';
@@ -31,7 +464,7 @@ function customTypeFromMime(mime) {
31
464
  return 'AttachmentMessage:Video';
32
465
  if (mime.startsWith('audio/'))
33
466
  return 'AttachmentMessage:Audio';
34
- if (mime.startsWith('application/'))
467
+ if (mime.startsWith('application/') || mime.startsWith('text/'))
35
468
  return 'AttachmentMessage:Doc';
36
469
  return ATTACHMENT_BODY_PLACEHOLDER;
37
470
  }
@@ -41,19 +474,137 @@ function isAttachmentBodyPlaceholder(body) {
41
474
  }
42
475
  /** Caption for UI — never treat AttachmentMessage:* body placeholders as caption. */
43
476
  function attachmentCaption(message) {
44
- var _a, _b, _c;
477
+ var _a, _b, _c, _d;
45
478
  const meta = message === null || message === void 0 ? void 0 : message.metaData;
46
479
  const fromMeta = String((_b = (_a = meta === null || meta === void 0 ? void 0 : meta.caption) !== null && _a !== void 0 ? _a : meta === null || meta === void 0 ? void 0 : meta.captionMessage) !== null && _b !== void 0 ? _b : '').trim();
47
480
  if (fromMeta)
48
481
  return fromMeta;
49
482
  const body = String((_c = message === null || message === void 0 ? void 0 : message.body) !== null && _c !== void 0 ? _c : '').trim();
483
+ const customType = String((_d = message === null || message === void 0 ? void 0 : message.customType) !== null && _d !== void 0 ? _d : '').trim();
484
+ // Multiple attachments: real caption lives in metaData only (Flutter/Swift/web); never use body text
485
+ if (body === ATTACHMENT_BODY_PLACEHOLDER || customType === ATTACHMENT_BODY_PLACEHOLDER)
486
+ return '';
50
487
  if (isAttachmentBodyPlaceholder(body))
51
488
  return '';
52
489
  return body;
53
490
  }
491
+ /** @deprecated Prefer attachmentBodyForOutgoing — kept for callers that only pass caption. */
54
492
  function attachmentBodyForApi(caption) {
55
493
  return (caption === null || caption === void 0 ? void 0 : caption.trim()) || ATTACHMENT_BODY_PLACEHOLDER;
56
494
  }
495
+ /** File extension without dot (e.g. "report.pdf" → "pdf"). */
496
+ function extensionFromFileName(name) {
497
+ const base = (name || '').split(/[/\\]/).pop() || '';
498
+ const idx = base.lastIndexOf('.');
499
+ if (idx <= 0)
500
+ return '';
501
+ return base.slice(idx + 1).toLowerCase();
502
+ }
503
+ /**
504
+ * MIME stored on each attachment. Flutter parity: `mimeTypeForAttachmentExtension`
505
+ * in Flutter_Chat_Sdk send_message_media.dart (mediaType 0 image, 1 video, 2 audio, 3 doc).
506
+ */
507
+ function mimeTypeForAttachmentExtension(extension, mediaType) {
508
+ const ext = (extension !== null && extension !== void 0 ? extension : '').toLowerCase().replace(/^\./, '');
509
+ switch (ext) {
510
+ case 'jpg':
511
+ case 'jpeg':
512
+ return 'image/jpeg';
513
+ case 'png':
514
+ return 'image/png';
515
+ case 'gif':
516
+ return 'image/gif';
517
+ case 'webp':
518
+ return 'image/webp';
519
+ case 'heic':
520
+ case 'heif':
521
+ return 'image/heic';
522
+ case 'mp4':
523
+ return mediaType === 2 ? 'audio/mp4' : 'video/mp4';
524
+ case 'mov':
525
+ return 'video/quicktime';
526
+ case 'webm':
527
+ return mediaType === 2 ? 'audio/webm' : 'video/webm';
528
+ case 'mkv':
529
+ return 'video/x-matroska';
530
+ case 'mp3':
531
+ return 'audio/mpeg';
532
+ case 'm4a':
533
+ case 'aac':
534
+ return 'audio/mp4';
535
+ case 'wav':
536
+ return 'audio/wav';
537
+ case 'pdf':
538
+ return 'application/pdf';
539
+ case 'doc':
540
+ return 'application/msword';
541
+ case 'docx':
542
+ return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
543
+ case 'docm':
544
+ return 'application/vnd.ms-word.document.macroEnabled.12';
545
+ case 'xls':
546
+ return 'application/vnd.ms-excel';
547
+ case 'xlsx':
548
+ return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
549
+ case 'xlsm':
550
+ return 'application/vnd.ms-excel.sheet.macroEnabled.12';
551
+ case 'txt':
552
+ return 'text/plain';
553
+ case 'csv':
554
+ return 'text/csv';
555
+ case 'rtf':
556
+ return 'application/rtf';
557
+ default:
558
+ switch (mediaType) {
559
+ case 1:
560
+ return 'video/mp4';
561
+ case 2:
562
+ return 'audio/mpeg';
563
+ case 3:
564
+ return 'application/pdf';
565
+ default:
566
+ return 'image/jpeg';
567
+ }
568
+ }
569
+ }
570
+ function inferMediaTypeFromExtension(ext) {
571
+ const e = (ext || '').toLowerCase();
572
+ if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'heic', 'heif', 'bmp'].includes(e))
573
+ return 0;
574
+ if (['mp4', 'mov', 'webm', 'mkv'].includes(e))
575
+ return 1;
576
+ if (['mp3', 'wav', 'm4a', 'aac', 'ogg'].includes(e))
577
+ return 2;
578
+ return 3;
579
+ }
580
+ /** Prefer browser File.type; infer from extension when empty (common for PDF picks). */
581
+ function resolveMimeType(file) {
582
+ const trimmed = (file.type || '').trim();
583
+ if (trimmed)
584
+ return trimmed;
585
+ const ext = extensionFromFileName(file.name);
586
+ const mediaType = inferMediaTypeFromExtension(ext);
587
+ return mimeTypeForAttachmentExtension(ext, mediaType);
588
+ }
589
+ /** Flutter single-document send uses filename as body when there is no caption. */
590
+ function attachmentBodyForOutgoing(caption, files) {
591
+ const cap = caption === null || caption === void 0 ? void 0 : caption.trim();
592
+ if (cap)
593
+ return cap;
594
+ if (files.length === 1) {
595
+ const f = files[0];
596
+ const name = 'nameWithExtension' in f ? f.nameWithExtension : f.name;
597
+ const mime = 'mimeType' in f ? f.mimeType : resolveMimeType(f);
598
+ if (mediaTypeFromMime(mime) === 3)
599
+ return name;
600
+ }
601
+ return ATTACHMENT_BODY_PLACEHOLDER;
602
+ }
603
+ function resolveCustomTypeForUpload(attachments) {
604
+ if (!(attachments === null || attachments === void 0 ? void 0 : attachments.length) || attachments.length !== 1)
605
+ return ATTACHMENT_BODY_PLACEHOLDER;
606
+ return customTypeFromMime(attachments[0].mimeType);
607
+ }
57
608
  function buildReplyMetaData(replyMessage, caption) {
58
609
  var _a, _b, _c;
59
610
  if (!replyMessage && !(caption === null || caption === void 0 ? void 0 : caption.trim()))
@@ -66,25 +617,135 @@ function buildReplyMetaData(replyMessage, caption) {
66
617
  })))), (trimmed && { caption: trimmed, captionMessage: trimmed }));
67
618
  }
68
619
  function prepareMediaAttachments(files) {
69
- // Hard-cap so public API / footer can't exceed one-message limit.
70
620
  const capped = takeMediaFiles(files, 0).accepted;
71
- return capped.map(file => ({
72
- nameWithExtension: file.name,
73
- mediaType: mediaTypeFromMime(file.type),
74
- mediaId: String(file.lastModified || Date.now()) + Math.random().toString(36).slice(2, 6),
75
- mimeType: file.type || 'application/octet-stream',
76
- size: file.size,
77
- file,
78
- }));
621
+ return capped.map(file => {
622
+ const mimeType = resolveMimeType(file);
623
+ return {
624
+ nameWithExtension: file.name,
625
+ mediaType: mediaTypeFromMime(mimeType),
626
+ mediaId: String(file.lastModified || Date.now()) + Math.random().toString(36).slice(2, 6),
627
+ mimeType,
628
+ size: file.size,
629
+ file,
630
+ };
631
+ });
79
632
  }
80
633
  function buildLocalMediaAttachments(files) {
81
- return files.map(file => ({
82
- name: file.name,
83
- size: file.size,
84
- type: (file.type || '').split('/')[0] || 'file',
85
- mediaUrl: typeof URL !== 'undefined' ? URL.createObjectURL(file) : '',
86
- mimeType: file.type || 'application/octet-stream',
87
- }));
634
+ return files.map(file => {
635
+ const mimeType = resolveMimeType(file);
636
+ return {
637
+ name: file.name,
638
+ size: file.size,
639
+ type: mimeType.split('/')[0] || 'file',
640
+ mediaUrl: typeof URL !== 'undefined' ? URL.createObjectURL(file) : '',
641
+ mimeType,
642
+ mediaType: mediaTypeFromMime(mimeType),
643
+ };
644
+ });
645
+ }
646
+ /** PDF (or a file named *.pdf). The app cannot paint these bytes with Image.network. */
647
+ function isPdfFileAttachment(file) {
648
+ const mime = String((file === null || file === void 0 ? void 0 : file.mimeType) || '').toLowerCase();
649
+ const name = String((file === null || file === void 0 ? void 0 : file.nameWithExtension) || (file === null || file === void 0 ? void 0 : file.name) || '').toLowerCase();
650
+ return mime === 'application/pdf' || name.endsWith('.pdf');
651
+ }
652
+ /** Word or Excel. Same thumbnail slot as PDF: a JPEG, with the file itself on mediaUrl. */
653
+ function isOfficeFileAttachment(file) {
654
+ return officePreviewKind(file) != null;
655
+ }
656
+ /**
657
+ * Public image URL for a document preview.
658
+ *
659
+ * Reuse this for PDF, Word, and Excel. Flutter draws `thumbnailUrl` with
660
+ * Image.network, so the value has to be a JPEG/PNG. Returns '' when the only
661
+ * candidate is the document file itself.
662
+ */
663
+ function documentThumbnailUrl(opts) {
664
+ const media = String(opts.mediaUrl || '').trim();
665
+ const thumb = String(opts.thumbnailUrl || '').trim();
666
+ if (!thumb || thumb === media)
667
+ return '';
668
+ if (looksLikeDocumentFileUrl(thumb))
669
+ return '';
670
+ return thumb;
671
+ }
672
+ /**
673
+ * First page of a PDF as a JPEG, for the same thumbnail slot videos already fill.
674
+ *
675
+ * pdf.js is loaded only when a PDF is sent (same CDN Flutter web documents in
676
+ * README_web.md). If the host page already set `window.pdfjsLib`, that copy is reused.
677
+ */
678
+ async function capturePdfThumbnailBlob(file) {
679
+ var _a;
680
+ if (typeof document === 'undefined')
681
+ return null;
682
+ if (!isPdfFileAttachment({ mimeType: file === null || file === void 0 ? void 0 : file.type, name: file === null || file === void 0 ? void 0 : file.name }))
683
+ return null;
684
+ try {
685
+ const pdfjs = await loadPdfJs();
686
+ const data = new Uint8Array(await file.arrayBuffer());
687
+ const loadingTask = pdfjs.getDocument({ data, disableWorker: true, isEvalSupported: false });
688
+ const pdf = await loadingTask.promise;
689
+ const page = await pdf.getPage(1);
690
+ const base = page.getViewport({ scale: 1 });
691
+ const longest = Math.max(base.width, base.height) || 1;
692
+ const scale = Math.min(2, 1024 / longest);
693
+ const viewport = page.getViewport({ scale });
694
+ const canvas = document.createElement('canvas');
695
+ canvas.width = Math.max(1, Math.floor(viewport.width));
696
+ canvas.height = Math.max(1, Math.floor(viewport.height));
697
+ const ctx = canvas.getContext('2d');
698
+ if (!ctx)
699
+ return null;
700
+ ctx.fillStyle = '#ffffff';
701
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
702
+ await page.render({ canvasContext: ctx, viewport }).promise;
703
+ const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg', 0.85));
704
+ await ((_a = pdf.destroy) === null || _a === void 0 ? void 0 : _a.call(pdf));
705
+ return blob;
706
+ }
707
+ catch (_b) {
708
+ return null;
709
+ }
710
+ }
711
+ const PDFJS_VERSION = '3.11.174';
712
+ /** Reuse a host-provided pdf.js, otherwise load the same build Flutter web uses. */
713
+ async function loadPdfJs() {
714
+ const existing = globalThis.pdfjsLib;
715
+ if (existing === null || existing === void 0 ? void 0 : existing.getDocument)
716
+ return existing;
717
+ await new Promise((resolve, reject) => {
718
+ var _a;
719
+ const timer = setTimeout(() => reject(new Error('pdf.js load timed out')), 8000);
720
+ const done = (err) => {
721
+ clearTimeout(timer);
722
+ if (err)
723
+ reject(err);
724
+ else
725
+ resolve();
726
+ };
727
+ const prior = document.querySelector('script[data-ism-pdfjs]');
728
+ if (prior) {
729
+ if ((_a = globalThis.pdfjsLib) === null || _a === void 0 ? void 0 : _a.getDocument) {
730
+ done();
731
+ return;
732
+ }
733
+ prior.addEventListener('load', () => done(), { once: true });
734
+ prior.addEventListener('error', () => done(new Error('pdf.js failed to load')), { once: true });
735
+ return;
736
+ }
737
+ const script = document.createElement('script');
738
+ script.src = `https://cdn.jsdelivr.net/npm/pdfjs-dist@${PDFJS_VERSION}/legacy/build/pdf.min.js`;
739
+ script.async = true;
740
+ script.dataset.ismPdfjs = '1';
741
+ script.onload = () => done();
742
+ script.onerror = () => done(new Error('pdf.js failed to load'));
743
+ document.head.appendChild(script);
744
+ });
745
+ const pdfjs = globalThis.pdfjsLib;
746
+ if (!(pdfjs === null || pdfjs === void 0 ? void 0 : pdfjs.getDocument))
747
+ throw new Error('pdf.js missing getDocument');
748
+ return pdfjs;
88
749
  }
89
750
  /**
90
751
  * Grab a JPEG frame from a local video File for thumbnailPresignedUrl upload.
@@ -135,7 +796,65 @@ async function captureVideoThumbnailBlob(file, seekSeconds = 0.1) {
135
796
  URL.revokeObjectURL(objectUrl);
136
797
  }
137
798
  }
138
- /** PUT media (+ video thumbnail when thumbnailPresignedUrl is present). */
799
+ /**
800
+ * Store a rendered document preview where the app reads `thumbnailUrl`.
801
+ *
802
+ * Shared by PDF pages and Word/Excel previews. Prefer the file's own thumbnail
803
+ * slot when it is a different URL from the document (same contract as video).
804
+ * Otherwise request a new image presign — Flutter does this with
805
+ * `isUpdateThumbnail` — so Image.network receives a JPEG.
806
+ */
807
+ async function putDocumentThumbnail(opts) {
808
+ var _a;
809
+ const slot = documentThumbnailUrl({
810
+ mediaUrl: opts.mediaUrl,
811
+ thumbnailUrl: opts.thumbnailUrl,
812
+ });
813
+ if (slot && opts.thumbnailPresignedUrl) {
814
+ const response = await fetch(opts.thumbnailPresignedUrl, {
815
+ method: 'PUT',
816
+ body: opts.blob,
817
+ headers: { 'Content-Type': 'image/jpeg' },
818
+ });
819
+ if (response.ok)
820
+ return slot;
821
+ }
822
+ if (!opts.conversationId)
823
+ return '';
824
+ const res = await M.getInstance().message.postMessagesPresignedurls({
825
+ conversationId: opts.conversationId,
826
+ attachments: [
827
+ {
828
+ nameWithExtension: `${opts.mediaId || 'doc'}-thumb.jpg`,
829
+ // 0 = image. A document presign (3) does not give the app a decodable preview.
830
+ mediaType: 0,
831
+ mediaId: `${opts.mediaId || 'doc'}-thumb`,
832
+ },
833
+ ],
834
+ });
835
+ const details = ((_a = res === null || res === void 0 ? void 0 : res.presignedUrls) === null || _a === void 0 ? void 0 : _a[0]) || ((res === null || res === void 0 ? void 0 : res.mediaUrl) || (res === null || res === void 0 ? void 0 : res.presignedUrl) ? res : null);
836
+ const putUrl = (details === null || details === void 0 ? void 0 : details.mediaPresignedUrl) || (details === null || details === void 0 ? void 0 : details.presignedUrl) || (details === null || details === void 0 ? void 0 : details.thumbnailPresignedUrl);
837
+ const publicUrl = documentThumbnailUrl({
838
+ mediaUrl: opts.mediaUrl,
839
+ thumbnailUrl: (details === null || details === void 0 ? void 0 : details.mediaUrl) || (details === null || details === void 0 ? void 0 : details.thumbnailUrl),
840
+ });
841
+ if (!putUrl || !publicUrl)
842
+ return '';
843
+ const response = await fetch(putUrl, {
844
+ method: 'PUT',
845
+ body: opts.blob,
846
+ headers: { 'Content-Type': 'image/jpeg' },
847
+ });
848
+ return response.ok ? publicUrl : '';
849
+ }
850
+ /**
851
+ * PUT the file, and for video, PDF, Word, and Excel also PUT a JPEG the app can show.
852
+ *
853
+ * [renderPdfThumbnail] and [renderOfficeThumbnail] are the production renderers.
854
+ * Tests pass a stub so they do not load pdf.js or paint a canvas. Callers should
855
+ * pass [conversationId] so a document can get its own image presign when the
856
+ * file slot's thumbnail URL is the document itself.
857
+ */
139
858
  async function uploadPresignedMediaAttachment(opts) {
140
859
  const { urlDetails, attachment } = opts;
141
860
  if (!attachment)
@@ -143,8 +862,14 @@ async function uploadPresignedMediaAttachment(opts) {
143
862
  const mediaPresignedUrl = (urlDetails === null || urlDetails === void 0 ? void 0 : urlDetails.mediaPresignedUrl) || (urlDetails === null || urlDetails === void 0 ? void 0 : urlDetails.presignedUrl);
144
863
  const mediaId = (urlDetails === null || urlDetails === void 0 ? void 0 : urlDetails.mediaId) || (urlDetails === null || urlDetails === void 0 ? void 0 : urlDetails.mediaUrl);
145
864
  const mediaUrl = urlDetails === null || urlDetails === void 0 ? void 0 : urlDetails.mediaUrl;
146
- const thumbnailUrl = (urlDetails === null || urlDetails === void 0 ? void 0 : urlDetails.thumbnailUrl) || mediaUrl;
147
865
  const thumbnailPresignedUrl = urlDetails === null || urlDetails === void 0 ? void 0 : urlDetails.thumbnailPresignedUrl;
866
+ const isPdf = isPdfFileAttachment(attachment);
867
+ const isOffice = isOfficeFileAttachment(attachment);
868
+ const needsImageThumb = isPdf || isOffice;
869
+ // Document files stay on mediaUrl. thumbnailUrl is only a JPEG/PNG the app can draw.
870
+ let thumbnailUrl = needsImageThumb
871
+ ? documentThumbnailUrl({ mediaUrl, thumbnailUrl: urlDetails === null || urlDetails === void 0 ? void 0 : urlDetails.thumbnailUrl })
872
+ : (urlDetails === null || urlDetails === void 0 ? void 0 : urlDetails.thumbnailUrl) || mediaUrl;
148
873
  if (!mediaPresignedUrl || !mediaUrl)
149
874
  return null;
150
875
  await fetch(mediaPresignedUrl, {
@@ -163,6 +888,32 @@ async function uploadPresignedMediaAttachment(opts) {
163
888
  });
164
889
  }
165
890
  }
891
+ // Skip the preview render when there is nowhere to store the JPEG. Otherwise a
892
+ // missing pdf.js load would block the document send.
893
+ const imageSlot = documentThumbnailUrl({ mediaUrl, thumbnailUrl: urlDetails === null || urlDetails === void 0 ? void 0 : urlDetails.thumbnailUrl });
894
+ const canStoreDocumentThumb = (isPdf && !!opts.renderPdfThumbnail) ||
895
+ (isOffice && !!opts.renderOfficeThumbnail) ||
896
+ !!opts.conversationId ||
897
+ !!(thumbnailPresignedUrl && imageSlot);
898
+ if (needsImageThumb && canStoreDocumentThumb) {
899
+ const render = isPdf
900
+ ? opts.renderPdfThumbnail || capturePdfThumbnailBlob
901
+ : opts.renderOfficeThumbnail || captureOfficeThumbnailBlob;
902
+ const thumb = await render(attachment.file);
903
+ if (thumb) {
904
+ const uploaded = await putDocumentThumbnail({
905
+ blob: thumb,
906
+ mediaUrl,
907
+ mediaId: String(mediaId || attachment.mediaId || ''),
908
+ conversationId: opts.conversationId,
909
+ thumbnailPresignedUrl,
910
+ thumbnailUrl: urlDetails === null || urlDetails === void 0 ? void 0 : urlDetails.thumbnailUrl,
911
+ });
912
+ if (uploaded)
913
+ thumbnailUrl = uploaded;
914
+ }
915
+ }
916
+ const fileExt = extensionFromFileName(attachment.nameWithExtension);
166
917
  return {
167
918
  mediaId,
168
919
  mediaUrl,
@@ -171,9 +922,10 @@ async function uploadPresignedMediaAttachment(opts) {
171
922
  nameWithExtension: attachment.nameWithExtension,
172
923
  name: attachment.nameWithExtension,
173
924
  mimeType: attachment.mimeType,
174
- extension: attachment.mimeType.split('/')[1] || '',
925
+ extension: fileExt,
175
926
  size: attachment.size,
176
- attachmentType: 0,
927
+ // Flutter: 0 is image — must match mediaType for documents (3).
928
+ attachmentType: attachment.mediaType,
177
929
  };
178
930
  }
179
931
  /** Presign → PUT files → postMessages. Returns API messageId. */
@@ -193,6 +945,7 @@ async function uploadAndPostMediaMessage(args) {
193
945
  if (!(presignedUrls === null || presignedUrls === void 0 ? void 0 : presignedUrls.length)) {
194
946
  throw new Error('No presigned URLs returned for media upload');
195
947
  }
948
+ /** Typed array so `postMessages` payload is not `any[]` (strict noImplicitAny). */
196
949
  const allPayloads = [];
197
950
  await Promise.all(presignedUrls.map(async (urlDetails, index) => {
198
951
  const attachmentPayload = attachments[index];
@@ -201,18 +954,19 @@ async function uploadAndPostMediaMessage(args) {
201
954
  const payload = await uploadPresignedMediaAttachment({
202
955
  urlDetails,
203
956
  attachment: attachmentPayload,
957
+ conversationId,
204
958
  });
205
959
  if (payload)
206
960
  allPayloads.push(payload);
207
961
  }));
208
- const customType = attachments.length === 1 ? customTypeFromMime(attachments[0].mimeType) : ATTACHMENT_BODY_PLACEHOLDER;
962
+ const customType = resolveCustomTypeForUpload(attachments);
209
963
  const payload = {
210
964
  showInConversation: true,
211
965
  messageType: replyMessage ? 2 : 0,
212
966
  parentMessageId: replyMessage === null || replyMessage === void 0 ? void 0 : replyMessage.messageId,
213
967
  encrypted: false,
214
968
  conversationId,
215
- body: attachmentBodyForApi(caption),
969
+ body: attachmentBodyForOutgoing(caption, attachments),
216
970
  customType,
217
971
  attachments: allPayloads,
218
972
  deviceId,
@@ -225,6 +979,6 @@ async function uploadAndPostMediaMessage(args) {
225
979
  return (sendMessageRes === null || sendMessageRes === void 0 ? void 0 : sendMessageRes.messageId) || null;
226
980
  }
227
981
 
228
- export { ATTACHMENT_BODY_PLACEHOLDER as A, attachmentBodyForApi as a, buildReplyMetaData as b, customTypeFromMime as c, buildLocalMediaAttachments as d, uploadPresignedMediaAttachment as e, attachmentCaption as f, isAttachmentBodyPlaceholder as i, mediaTypeFromMime as m, prepareMediaAttachments as p, uploadAndPostMediaMessage as u };
982
+ export { ATTACHMENT_BODY_PLACEHOLDER as A, attachmentBodyForApi as a, buildReplyMetaData as b, customTypeFromMime as c, buildLocalMediaAttachments as d, attachmentBodyForOutgoing as e, uploadPresignedMediaAttachment as f, attachmentCaption as g, isAttachmentBodyPlaceholder as i, mediaTypeFromMime as m, prepareMediaAttachments as p, resolveCustomTypeForUpload as r, uploadAndPostMediaMessage as u };
229
983
 
230
984
  //# sourceMappingURL=send-media.js.map