@bevel-software/platform-core-frontend 0.11.2 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/THIRD-PARTY-NOTICES.md +670 -395
  2. package/package.json +6 -2
  3. package/src/lib/__tests__/api.test.ts +95 -0
  4. package/src/lib/api.ts +30 -2
  5. package/src/lib/clipboard.ts +25 -0
  6. package/src/modules/access/__tests__/useFileAccess.test.tsx +47 -0
  7. package/src/modules/access/hooks/useFileAccess.ts +23 -5
  8. package/src/modules/library/utils/clipboard.ts +4 -20
  9. package/src/modules/workspace/components/FileExplorer.tsx +6 -14
  10. package/src/modules/workspace/components/FileViewer.tsx +17 -4
  11. package/src/modules/workspace/components/KbPageHeader.tsx +1 -1
  12. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +3 -1
  13. package/src/modules/workspace/components/__tests__/FileViewer.test.tsx +17 -0
  14. package/src/modules/workspace/components/__tests__/KbPageHeader.test.tsx +15 -0
  15. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +11 -2
  16. package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +88 -0
  17. package/src/modules/workspace/components/renderers/EmailRenderer.tsx +309 -0
  18. package/src/modules/workspace/components/renderers/LegacyOfficeRenderer.tsx +60 -0
  19. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +261 -33
  20. package/src/modules/workspace/components/renderers/PptxRenderer.tsx +184 -0
  21. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +195 -45
  22. package/src/modules/workspace/components/renderers/__tests__/DownloadFileButton.test.tsx +48 -0
  23. package/src/modules/workspace/components/renderers/__tests__/EmailRenderer.test.tsx +176 -0
  24. package/src/modules/workspace/components/renderers/__tests__/PdfRenderer.test.tsx +214 -76
  25. package/src/modules/workspace/components/renderers/__tests__/PptxRenderer.test.tsx +125 -0
  26. package/src/modules/workspace/components/renderers/__tests__/XlsxRenderer.test.tsx +245 -0
  27. package/src/modules/workspace/components/renderers/__tests__/emailBody.test.ts +117 -0
  28. package/src/modules/workspace/components/renderers/__tests__/emailMessage.test.ts +404 -0
  29. package/src/modules/workspace/components/renderers/__tests__/pptxOutline.test.ts +448 -0
  30. package/src/modules/workspace/components/renderers/__tests__/readBodyCapped.test.ts +117 -0
  31. package/src/modules/workspace/components/renderers/__tests__/rendererLayout.test.ts +73 -7
  32. package/src/modules/workspace/components/renderers/__tests__/rendererSelection.test.tsx +107 -0
  33. package/src/modules/workspace/components/renderers/downloadFile.ts +33 -0
  34. package/src/modules/workspace/components/renderers/emailBody.ts +168 -0
  35. package/src/modules/workspace/components/renderers/emailMessage.ts +223 -0
  36. package/src/modules/workspace/components/renderers/emlMessage.ts +91 -0
  37. package/src/modules/workspace/components/renderers/htmlSandbox.ts +9 -2
  38. package/src/modules/workspace/components/renderers/index.ts +82 -6
  39. package/src/modules/workspace/components/renderers/lazyRenderer.tsx +9 -2
  40. package/src/modules/workspace/components/renderers/msgMessage.ts +219 -0
  41. package/src/modules/workspace/components/renderers/pptxOutline.ts +317 -0
  42. package/src/modules/workspace/components/renderers/readBodyCapped.ts +97 -0
  43. package/src/modules/workspace/components/renderers/xmlReading.ts +0 -0
  44. package/src/url-suffix-imports.d.ts +12 -0
@@ -0,0 +1,448 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import JSZip from 'jszip';
3
+ import { extractPptxOutline } from '../pptxOutline';
4
+
5
+ /**
6
+ * The parser against real zips, built here from minimal slide XML — the same
7
+ * fixtures a crafted-by-PowerPoint file reduces to. The conventions pinned
8
+ * here are shared with the backend's `extract-pptx.ts`, so an agent's
9
+ * `read_file` and this viewer describe the same deck the same way: numeric
10
+ * slide order, runs joined with NO separator, entities decoded, notes
11
+ * attached to their slide.
12
+ */
13
+
14
+ /** One `<a:p>` paragraph whose `<a:t>` runs are exactly `runs`. */
15
+ function para(...runs: string[]): string {
16
+ return `<a:p>${runs.map((r) => `<a:r><rPr b="1"/><a:t>${r}</a:t></a:r>`).join('')}</a:p>`;
17
+ }
18
+
19
+ function slideXml(...paragraphs: string[]): string {
20
+ return `<?xml version="1.0"?><p:sld xmlns:a="urn:a" xmlns:p="urn:p"><p:cSld><p:spTree>${paragraphs.join('')}</p:spTree></p:cSld></p:sld>`;
21
+ }
22
+
23
+ async function zipBytes(entries: Record<string, string>): Promise<ArrayBuffer> {
24
+ const zip = new JSZip();
25
+ for (const [name, content] of Object.entries(entries)) zip.file(name, content);
26
+ return zip.generateAsync({ type: 'arraybuffer' });
27
+ }
28
+
29
+ describe('extractPptxOutline', () => {
30
+ it('joins a paragraph\'s runs with no separator — PowerPoint splits them mid-word', async () => {
31
+ const bytes = await zipBytes({
32
+ 'ppt/slides/slide1.xml': slideXml(para('Quart', 'erly ', 'results')),
33
+ });
34
+ const slides = await extractPptxOutline(bytes);
35
+ expect(slides).toHaveLength(1);
36
+ expect(slides[0].paragraphs).toEqual(['Quarterly results']);
37
+ });
38
+
39
+ it('decodes XML entities, named and numeric', async () => {
40
+ const bytes = await zipBytes({
41
+ 'ppt/slides/slide1.xml': slideXml(
42
+ para('R&amp;D &lt;2026&gt;'),
43
+ para('&#65;&#x42; &quot;quoted&apos;'),
44
+ ),
45
+ });
46
+ const slides = await extractPptxOutline(bytes);
47
+ expect(slides[0].paragraphs).toEqual(['R&D <2026>', 'AB "quoted\'']);
48
+ });
49
+
50
+ it('orders slides numerically by package number, not lexicographically', async () => {
51
+ const bytes = await zipBytes({
52
+ // Deliberately declared out of order, with a two-digit number that
53
+ // sorts before "2" as a STRING.
54
+ 'ppt/slides/slide10.xml': slideXml(para('tenth')),
55
+ 'ppt/slides/slide2.xml': slideXml(para('second')),
56
+ 'ppt/slides/slide1.xml': slideXml(para('first')),
57
+ });
58
+ const slides = await extractPptxOutline(bytes);
59
+ expect(slides.map((s) => s.number)).toEqual([1, 2, 10]);
60
+ expect(slides.map((s) => s.paragraphs[0])).toEqual(['first', 'second', 'tenth']);
61
+ });
62
+
63
+ // No rels parts in this fixture — proves the numeric-name FALLBACK holds.
64
+ it('attaches speaker notes to their slide by numeric name when no rels part exists', async () => {
65
+ const bytes = await zipBytes({
66
+ 'ppt/slides/slide1.xml': slideXml(para('The pitch')),
67
+ 'ppt/slides/slide2.xml': slideXml(para('The ask')),
68
+ 'ppt/notesSlides/notesSlide2.xml': slideXml(para('pause here'), para('make eye contact')),
69
+ });
70
+ const slides = await extractPptxOutline(bytes);
71
+ expect(slides[0].notes).toEqual([]);
72
+ expect(slides[1].notes).toEqual(['pause here', 'make eye contact']);
73
+ });
74
+
75
+ const RELS_NS = 'xmlns="http://schemas.openxmlformats.org/package/2006/relationships"';
76
+ const NOTES_TYPE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide';
77
+
78
+ it('pairs notes through each slide\'s rels — the notes part number need not match the slide number', async () => {
79
+ const bytes = await zipBytes({
80
+ 'ppt/slides/slide1.xml': slideXml(para('First')),
81
+ 'ppt/slides/slide2.xml': slideXml(para('Second')),
82
+ // Notes for slide 2 live in a part numbered 7 — only the rels say so.
83
+ 'ppt/notesSlides/notesSlide7.xml': slideXml(para('note for slide two')),
84
+ 'ppt/slides/_rels/slide1.xml.rels': `<?xml version="1.0"?><Relationships ${RELS_NS}></Relationships>`,
85
+ 'ppt/slides/_rels/slide2.xml.rels':
86
+ `<?xml version="1.0"?><Relationships ${RELS_NS}>` +
87
+ `<Relationship Id="rId9" Type="${NOTES_TYPE}" Target="../notesSlides/notesSlide7.xml"/>` +
88
+ '</Relationships>',
89
+ });
90
+ const slides = await extractPptxOutline(bytes);
91
+ expect(slides[0].notes).toEqual([]);
92
+ expect(slides[1].notes).toEqual(['note for slide two']);
93
+ });
94
+
95
+ it('a rels part WITHOUT a notesSlide relationship means no notes — the numeric twin is not guessed at', async () => {
96
+ const bytes = await zipBytes({
97
+ 'ppt/slides/slide1.xml': slideXml(para('Solo')),
98
+ 'ppt/notesSlides/notesSlide1.xml': slideXml(para('orphan notes part')),
99
+ 'ppt/slides/_rels/slide1.xml.rels': `<?xml version="1.0"?><Relationships ${RELS_NS}></Relationships>`,
100
+ });
101
+ const slides = await extractPptxOutline(bytes);
102
+ expect(slides[0].notes).toEqual([]);
103
+ });
104
+
105
+ it('rejects a deck whose slide part inflates past the 50 MB per-entry bound', async () => {
106
+ const padded = slideXml(para('tiny text')) + ' '.repeat(51 * 1024 * 1024);
107
+ const bytes = await zipBytes({ 'ppt/slides/slide1.xml': padded });
108
+ await expect(extractPptxOutline(bytes)).rejects.toThrow(
109
+ /could not be parsed as a \.pptx \(.*extraction bound/,
110
+ );
111
+ }, 30_000);
112
+
113
+ it('drops empty paragraphs and keeps a text-free slide as an empty outline entry', async () => {
114
+ const bytes = await zipBytes({
115
+ 'ppt/slides/slide1.xml': slideXml(para('kept'), '<a:p></a:p>', para(' ')),
116
+ // A picture-only slide: present in the deck, so present in the outline.
117
+ 'ppt/slides/slide2.xml': slideXml(),
118
+ });
119
+ const slides = await extractPptxOutline(bytes);
120
+ expect(slides[0].paragraphs).toEqual(['kept']);
121
+ expect(slides[1]).toEqual({ number: 2, paragraphs: [], notes: [] });
122
+ });
123
+
124
+ it('rejects bytes that are not a zip', async () => {
125
+ const bytes = new TextEncoder().encode('this is not a zip archive').buffer as ArrayBuffer;
126
+ await expect(extractPptxOutline(bytes)).rejects.toThrow(
127
+ /could not be parsed as a \.pptx/,
128
+ );
129
+ });
130
+
131
+ it('rejects a zip with no slides in it', async () => {
132
+ const bytes = await zipBytes({ 'word/document.xml': '<w:document/>' });
133
+ await expect(extractPptxOutline(bytes)).rejects.toThrow(
134
+ /could not be parsed as a \.pptx \(no ppt\/slides/,
135
+ );
136
+ });
137
+
138
+ it('pairs notes through a namespace-PREFIXED <r:Relationship> — prefixed rels must not drop notes', async () => {
139
+ const bytes = await zipBytes({
140
+ 'ppt/slides/slide1.xml': slideXml(para('Deck')),
141
+ 'ppt/notesSlides/notesSlide4.xml': slideXml(para('prefixed note')),
142
+ 'ppt/slides/_rels/slide1.xml.rels':
143
+ '<?xml version="1.0"?><r:Relationships xmlns:r="http://schemas.openxmlformats.org/package/2006/relationships">' +
144
+ `<r:Relationship r:Id="rId2" r:Type="${NOTES_TYPE}" r:Target="../notesSlides/notesSlide4.xml"/>` +
145
+ '</r:Relationships>',
146
+ });
147
+ const slides = await extractPptxOutline(bytes);
148
+ expect(slides[0].notes).toEqual(['prefixed note']);
149
+ });
150
+
151
+ it('ignores a Target-looking sequence INSIDE another rels attribute value', async () => {
152
+ const bytes = await zipBytes({
153
+ 'ppt/slides/slide1.xml': slideXml(para('Deck')),
154
+ 'ppt/notesSlides/notesSlide2.xml': slideXml(para('the real note')),
155
+ 'ppt/notesSlides/evil.xml': slideXml(para('decoy')),
156
+ 'ppt/slides/_rels/slide1.xml.rels':
157
+ `<?xml version="1.0"?><Relationships ${RELS_NS}>` +
158
+ `<Relationship Id="rId1" Comment="Target='../notesSlides/evil.xml'" Type="${NOTES_TYPE}" Target="../notesSlides/notesSlide2.xml"/>` +
159
+ '</Relationships>',
160
+ });
161
+ const slides = await extractPptxOutline(bytes);
162
+ expect(slides[0].notes).toEqual(['the real note']);
163
+ });
164
+
165
+ it('pairs notes through a NON-ASCII namespace prefix (full XML NCName) — \\w-only matching dropped these', async () => {
166
+ const bytes = await zipBytes({
167
+ 'ppt/slides/slide1.xml': slideXml(para('Deck')),
168
+ 'ppt/notesSlides/notesSlide5.xml': slideXml(para('accented note')),
169
+ 'ppt/slides/_rels/slide1.xml.rels':
170
+ '<?xml version="1.0"?><sé:Relationships xmlns:sé="http://schemas.openxmlformats.org/package/2006/relationships">' +
171
+ `<sé:Relationship sé:Id="rId2" sé:Type="${NOTES_TYPE}" sé:Target="../notesSlides/notesSlide5.xml"/>` +
172
+ '</sé:Relationships>',
173
+ });
174
+ const slides = await extractPptxOutline(bytes);
175
+ expect(slides[0].notes).toEqual(['accented note']);
176
+ });
177
+
178
+ it('ignores xmlns:Type / xmlns:Target namespace DECLARATIONS on the Relationship element', async () => {
179
+ const bytes = await zipBytes({
180
+ 'ppt/slides/slide1.xml': slideXml(para('Deck')),
181
+ 'ppt/notesSlides/notesSlide2.xml': slideXml(para('the real note')),
182
+ 'ppt/slides/_rels/slide1.xml.rels':
183
+ '<?xml version="1.0"?><Relationships>' +
184
+ `<Relationship xmlns:Target="http://ns.example/decl" Id="r1" Type="${NOTES_TYPE}" Target="../notesSlides/notesSlide2.xml"/>` +
185
+ '</Relationships>',
186
+ });
187
+ const slides = await extractPptxOutline(bytes);
188
+ expect(slides[0].notes).toEqual(['the real note']);
189
+ });
190
+
191
+ it('emits ONE slide per number — slide1.xml and slide01.xml must not become duplicate keys', async () => {
192
+ const bytes = await zipBytes({
193
+ // Declared canonical-first, so a zip-order tiebreak would pick the other
194
+ // part than the rule below does.
195
+ 'ppt/slides/slide1.xml': slideXml(para('canonical one')),
196
+ 'ppt/slides/slide01.xml': slideXml(para('zero-padded twin')),
197
+ 'ppt/slides/slide2.xml': slideXml(para('two')),
198
+ });
199
+ const slides = await extractPptxOutline(bytes);
200
+ expect(slides.map((s) => s.number)).toEqual([1, 2]);
201
+ // The winner is the first in ascending PART-NAME order — `slide01.xml`
202
+ // sorts before `slide1.xml` because '0' < '1'. Zip entry order is not a
203
+ // contract, so the name is what decides, and the backend twin
204
+ // (`extract-pptx.ts` `collectNumbered`) applies the identical rule: the
205
+ // same deck must not read one way in the viewer and another through an
206
+ // agent's `read_file`. The backend fixture for this parity lives in
207
+ // core-backend's `doc-extract.test.ts`
208
+ // ('extractPptx — two part names parsing to the SAME slide number'), and
209
+ // asserts this same text.
210
+ expect(slides[0].paragraphs).toEqual(['zero-padded twin']);
211
+ expect(slides[1].paragraphs).toEqual(['two']);
212
+ });
213
+
214
+ it('follows the SELECTED part name to the rels — a zero-padded winner keeps its own notes', async () => {
215
+ // The regression the dedup above introduced: the winner is chosen by
216
+ // NAME, but the notes lookup rebuilt the rels path from the NUMBER. With
217
+ // `slide01.xml` winning, `ppt/slides/_rels/slide1.xml.rels` is the LOSING
218
+ // part's relationships — so slide 1 either lost its notes or was handed
219
+ // the other file's. Same fixture as the backend twin's.
220
+ const bytes = await zipBytes({
221
+ 'ppt/slides/slide1.xml': slideXml(para('canonical one')),
222
+ 'ppt/slides/slide01.xml': slideXml(para('zero-padded twin')),
223
+ 'ppt/slides/_rels/slide01.xml.rels':
224
+ `<?xml version="1.0"?><Relationships ${RELS_NS}>` +
225
+ `<Relationship Id="rId1" Type="${NOTES_TYPE}" Target="../notesSlides/notesSlide01.xml"/>` +
226
+ '</Relationships>',
227
+ 'ppt/notesSlides/notesSlide01.xml': slideXml(para('the padded twin speaks')),
228
+ 'ppt/slides/_rels/slide1.xml.rels':
229
+ `<?xml version="1.0"?><Relationships ${RELS_NS}>` +
230
+ `<Relationship Id="rId1" Type="${NOTES_TYPE}" Target="../notesSlides/notesSlide1.xml"/>` +
231
+ '</Relationships>',
232
+ 'ppt/notesSlides/notesSlide1.xml': slideXml(para('notes of the part that LOST')),
233
+ });
234
+ const slides = await extractPptxOutline(bytes);
235
+ expect(slides).toEqual([
236
+ { number: 1, paragraphs: ['zero-padded twin'], notes: ['the padded twin speaks'] },
237
+ ]);
238
+ });
239
+
240
+ it('and the no-rels fallback mirrors the name too — slide01.xml pairs with notesSlide01.xml', async () => {
241
+ const bytes = await zipBytes({
242
+ 'ppt/slides/slide01.xml': slideXml(para('only slide')),
243
+ 'ppt/notesSlides/notesSlide01.xml': slideXml(para('padded notes')),
244
+ });
245
+ const slides = await extractPptxOutline(bytes);
246
+ expect(slides).toEqual([{ number: 1, paragraphs: ['only slide'], notes: ['padded notes'] }]);
247
+ });
248
+
249
+ // Fix for the peak-memory restructure: parts are parsed as they are read
250
+ // (per slide, then its notes) — the outline must be identical to the old
251
+ // hold-everything-then-parse order for a deck mixing rels-paired notes,
252
+ // numeric-fallback notes, and slides without notes.
253
+ it('streams part-by-part and still yields the identical outline for a mixed deck', async () => {
254
+ const bytes = await zipBytes({
255
+ 'ppt/slides/slide3.xml': slideXml(para('third')),
256
+ 'ppt/slides/slide1.xml': slideXml(para('first')),
257
+ 'ppt/slides/slide2.xml': slideXml(para('second')),
258
+ // Slide 1: rels-paired notes in an oddly numbered part.
259
+ 'ppt/slides/_rels/slide1.xml.rels':
260
+ `<?xml version="1.0"?><Relationships ${RELS_NS}>` +
261
+ `<Relationship Id="rId9" Type="${NOTES_TYPE}" Target="../notesSlides/notesSlide8.xml"/>` +
262
+ '</Relationships>',
263
+ 'ppt/notesSlides/notesSlide8.xml': slideXml(para('one note')),
264
+ // Slide 2: numeric fallback (no rels part).
265
+ 'ppt/notesSlides/notesSlide2.xml': slideXml(para('two note')),
266
+ // Slide 3: rels part naming no notes — the numeric twin must NOT attach.
267
+ 'ppt/slides/_rels/slide3.xml.rels': `<?xml version="1.0"?><Relationships ${RELS_NS}></Relationships>`,
268
+ 'ppt/notesSlides/notesSlide3.xml': slideXml(para('orphan')),
269
+ });
270
+ const slides = await extractPptxOutline(bytes);
271
+ expect(slides).toEqual([
272
+ { number: 1, paragraphs: ['first'], notes: ['one note'] },
273
+ { number: 2, paragraphs: ['second'], notes: ['two note'] },
274
+ { number: 3, paragraphs: ['third'], notes: [] },
275
+ ]);
276
+ });
277
+ const SLIDE_TYPE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide';
278
+
279
+ it('follows a REORDERED sldIdLst — the prefixed r:id resolves, and numbers are positions', async () => {
280
+ // Reordering slides in PowerPoint rewrites `<p:sldIdLst>` and leaves the
281
+ // part names alone, so `slide3.xml` here is the deck's FIRST slide. Each
282
+ // `<p:sldId>` carries its own bare numeric `id` BEFORE the relationship
283
+ // reference `r:id`, exactly as PowerPoint writes them — so the PREFIXED
284
+ // attribute must be the one resolved through the rels (the backend twin's
285
+ // `prefixedAttrByLocalName` rule). Plain local-name matching answered
286
+ // with the bare id, resolved nothing, and fell back to filename order.
287
+ const bytes = await zipBytes({
288
+ 'ppt/slides/slide1.xml': slideXml(para('was first')),
289
+ 'ppt/slides/slide2.xml': slideXml(para('was second')),
290
+ 'ppt/slides/slide3.xml': slideXml(para('was third')),
291
+ 'ppt/presentation.xml':
292
+ '<?xml version="1.0"?><p:presentation xmlns:p="urn:p" xmlns:r="urn:r"><p:sldIdLst>' +
293
+ '<p:sldId id="258" r:id="rId3"/>' +
294
+ '<p:sldId id="256" r:id="rId1"/>' +
295
+ '<p:sldId id="257" r:id="rId2"/>' +
296
+ '</p:sldIdLst></p:presentation>',
297
+ 'ppt/_rels/presentation.xml.rels':
298
+ `<?xml version="1.0"?><Relationships ${RELS_NS}>` +
299
+ `<Relationship Id="rId1" Type="${SLIDE_TYPE}" Target="slides/slide1.xml"/>` +
300
+ `<Relationship Id="rId2" Type="${SLIDE_TYPE}" Target="slides/slide2.xml"/>` +
301
+ `<Relationship Id="rId3" Type="${SLIDE_TYPE}" Target="slides/slide3.xml"/>` +
302
+ '</Relationships>',
303
+ });
304
+ const slides = await extractPptxOutline(bytes);
305
+ // Numbers are POSITIONS in the list, and the text follows the list.
306
+ expect(slides.map((s) => s.number)).toEqual([1, 2, 3]);
307
+ expect(slides.map((s) => s.paragraphs[0])).toEqual(['was third', 'was first', 'was second']);
308
+ });
309
+
310
+ /**
311
+ * The viewer carried the SAME quadratic the backend extractors did: the
312
+ * `<a:p(?:\s[^>]*)?>([\s\S]*?)</a:p>` pattern re-scanned the rest of the
313
+ * slide part from every opener whose close tag never came, so cost grew as
314
+ * openers x bytes (measured on the backend twin: 391 KB took 19.4 s and
315
+ * quadrupled per doubling). A deck is opened in the user's own tab, which
316
+ * cannot be closed while the main thread is pinned.
317
+ *
318
+ * The bound is deliberately generous (seconds, against parses measured in
319
+ * tens of milliseconds): it exists to catch a RETURN of a quadratic —
320
+ * 20 s and up on these fixtures — not to police CI's scheduler, the same
321
+ * convention as the backend suite's GENEROUS_MS (`doc-extract.test.ts`).
322
+ */
323
+ const GENEROUS_MS = 5_000;
324
+
325
+ it('a slide of 40k unmatched <a:p> openers still yields its real text, fast', async () => {
326
+ const bytes = await zipBytes({
327
+ 'ppt/slides/slide1.xml': slideXml(para('Alive') + '<a:p algn="ctr">'.repeat(40_000)),
328
+ });
329
+ const t0 = performance.now();
330
+ const slides = await extractPptxOutline(bytes);
331
+ const ms = performance.now() - t0;
332
+ expect(slides[0].paragraphs).toEqual(['Alive']);
333
+ expect(ms).toBeLessThan(GENEROUS_MS);
334
+ });
335
+
336
+ // Every opener's attribute scan here reaches the `>` of the `</p:spTree>`
337
+ // that sits PAST the wall, so each scan succeeds and a failure-only memo
338
+ // records nothing — then the `lastIndexOf` guard rejects the opener anyway,
339
+ // one full traversal at a time. Measured on this exact path before the memo
340
+ // covered successes: 20k openers took 21.9 s.
341
+ it('an unterminated attribute quote ends the scan instead of restarting per opener', async () => {
342
+ const bytes = await zipBytes({
343
+ 'ppt/slides/slide1.xml': slideXml(para('Alive') + '<a:p algn="never closed'.repeat(20_000)),
344
+ });
345
+ const t0 = performance.now();
346
+ const slides = await extractPptxOutline(bytes);
347
+ const ms = performance.now() - t0;
348
+ expect(slides[0].paragraphs).toEqual(['Alive']);
349
+ expect(ms).toBeLessThan(GENEROUS_MS);
350
+ });
351
+
352
+ it('reads a comment as text, so a commented paragraph neither outlines nor fills the memo', async () => {
353
+ // A comment is WELL-FORMED xml and may hold anything, `<a:p ` included.
354
+ // Read as markup it was wrong twice: the commented paragraph outlined as
355
+ // if it were slide content, and its every `<` was charged to the tag memo
356
+ // — so a deck with a big enough comment tripped the MAX_TAG_MEMO bound and
357
+ // dropped every paragraph after it. The backend twin pins the same rule.
358
+ const bytes = await zipBytes({
359
+ 'ppt/slides/slide1.xml': slideXml(
360
+ `<!-- ${para('Ghost')}${'<a:p '.repeat(300_000)} -->${para('Alive')}`,
361
+ ),
362
+ });
363
+ const t0 = performance.now();
364
+ const slides = await extractPptxOutline(bytes);
365
+ const ms = performance.now() - t0;
366
+ expect(slides[0].paragraphs).toEqual(['Alive']);
367
+ expect(ms).toBeLessThan(GENEROUS_MS);
368
+ });
369
+
370
+ it('stays linear on an ORDINARY deck — the one with no sections at all', async () => {
371
+ // Asking "does a section start before this close tag?" with an `indexOf`
372
+ // per element scanned to the end of the part, once per PARAGRAPH, on any
373
+ // deck without a comment — which is nearly every deck. Quadratic rendering
374
+ // on valid input, on the user's own main thread. The index is built once.
375
+ const bytes = await zipBytes({
376
+ 'ppt/slides/slide1.xml': slideXml(para('x').repeat(20_000)),
377
+ });
378
+ const t0 = performance.now();
379
+ const slides = await extractPptxOutline(bytes);
380
+ const ms = performance.now() - t0;
381
+ expect(slides[0].paragraphs).toHaveLength(20_000);
382
+ expect(ms).toBeLessThan(GENEROUS_MS);
383
+ });
384
+
385
+ it('a `</a:p>` inside a comment does not end the paragraph that holds it', async () => {
386
+ // The close search used to stop at the first literal `</a:p>` wherever it
387
+ // sat, so a well-formed paragraph mentioning its own close tag inside a
388
+ // comment was truncated there. The backend twin pins the same rule.
389
+ const bytes = await zipBytes({
390
+ 'ppt/slides/slide1.xml': slideXml(
391
+ '<a:p><a:r><a:t>keep</a:t></a:r><!-- </a:p> --><a:r><a:t> and this</a:t></a:r></a:p>',
392
+ ),
393
+ });
394
+ const slides = await extractPptxOutline(bytes);
395
+ expect(slides[0].paragraphs).toEqual(['keep and this']);
396
+ });
397
+
398
+ it('CHANGED: a `>` inside a quoted attribute no longer leaks into the outline', async () => {
399
+ // `[^>]*` stopped at the FIRST `>` even inside a quoted value, truncating
400
+ // the tag: this run used to render as `q">Hi`. Quote-awareness fixes it,
401
+ // and matches what the backend extractor now emits for the same deck.
402
+ const bytes = await zipBytes({
403
+ 'ppt/slides/slide1.xml': slideXml('<a:p algn="a > b"><a:r><a:t x="p>q">Hi</a:t></a:r></a:p>'),
404
+ });
405
+ const slides = await extractPptxOutline(bytes);
406
+ expect(slides[0].paragraphs).toEqual(['Hi']);
407
+ });
408
+
409
+ it('a self-closing <a:p/> stays invisible — the outline drops blank paragraphs', async () => {
410
+ // The scanner now reads `<a:p/>` as an EMPTY paragraph rather than no
411
+ // paragraph at all; the outline filters blanks either way, so the viewer's
412
+ // output is unchanged. Pinned so the parity with the backend (which DOES
413
+ // keep the blank line, because a docx body preserves empty paragraphs) is
414
+ // a decision on record rather than an accident.
415
+ const bytes = await zipBytes({
416
+ 'ppt/slides/slide1.xml': slideXml('<a:p/>' + para('kept') + '<a:p style="s"/>'),
417
+ });
418
+ const slides = await extractPptxOutline(bytes);
419
+ expect(slides[0].paragraphs).toEqual(['kept']);
420
+ });
421
+
422
+ it('leaves a malformed or out-of-range reference literal', async () => {
423
+ // `&#12A;` must not decode as `&#12` with the `A` shrugged off — that
424
+ // invented a U+000C nobody wrote.
425
+ // A reference PAST the last code point is the one case that does not stay
426
+ // literal: XML calls it an invalid character reference. The parser yields a
427
+ // replacement character, which the viewer drops — the backend keeps the
428
+ // reference literal, and a character XML cannot contain is the one thing
429
+ // neither side should render as content.
430
+ const bytes = await zipBytes({
431
+ 'ppt/slides/slide1.xml': slideXml(
432
+ para('x&#12A;y'),
433
+ para('x&nosuch;y'),
434
+ para('x&#1114112;y'),
435
+ ),
436
+ });
437
+ const slides = await extractPptxOutline(bytes);
438
+ expect(slides[0].paragraphs).toEqual(['x&#12A;y', 'x&nosuch;y', 'xy']);
439
+ });
440
+
441
+ it('reads a CDATA-wrapped paragraph as text, not as markup — like a commented one', async () => {
442
+ const bytes = await zipBytes({
443
+ 'ppt/slides/slide1.xml': slideXml(`<![CDATA[${para('ghost')}]]>${para('real')}`),
444
+ });
445
+ const slides = await extractPptxOutline(bytes);
446
+ expect(slides[0].paragraphs).toEqual(['real']);
447
+ });
448
+ });
@@ -0,0 +1,117 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import { readBodyCapped } from '../readBodyCapped';
3
+
4
+ /**
5
+ * The shared cap the binary viewers read through. Two things have to hold at
6
+ * once: an oversized response never lands in the tab (and its transfer ends),
7
+ * and an ACCEPTED one comes back byte-for-byte — the single-copy path fills a
8
+ * preallocated buffer as the chunks arrive, so an off-by-one there would hand
9
+ * a parser a corrupt file rather than fail loudly.
10
+ */
11
+
12
+ const CAP = 1024;
13
+
14
+ /** A response double: `headers.get` + a one-shot stream over `chunks`. */
15
+ function streamed(chunks: Uint8Array[], contentLength?: number | string) {
16
+ let i = 0;
17
+ const cancel = vi.fn(async () => {});
18
+ const res = {
19
+ headers: {
20
+ get: (name: string) =>
21
+ name === 'content-length' && contentLength !== undefined ? String(contentLength) : null,
22
+ },
23
+ body: {
24
+ getReader: () => ({
25
+ read: async () =>
26
+ i < chunks.length ? { done: false, value: chunks[i++] } : { done: true, value: undefined },
27
+ cancel,
28
+ }),
29
+ },
30
+ arrayBuffer: async () => {
31
+ throw new Error('must not buffer a streamable body');
32
+ },
33
+ } as unknown as Response;
34
+ return { res, cancel, readSoFar: () => i };
35
+ }
36
+
37
+ function bytes(n: number, seed = 0): Uint8Array {
38
+ return Uint8Array.from({ length: n }, (_, k) => (k + seed) % 251);
39
+ }
40
+
41
+ describe('readBodyCapped', () => {
42
+ it('returns exactly the declared bytes, copied once into the preallocated buffer', async () => {
43
+ const whole = bytes(600, 7);
44
+ const chunks = [whole.subarray(0, 100), whole.subarray(100, 517), whole.subarray(517)];
45
+ const { res } = streamed(chunks, 600);
46
+
47
+ const out = await readBodyCapped(res, CAP, new AbortController());
48
+
49
+ expect(out).not.toBeNull();
50
+ expect(new Uint8Array(out!)).toEqual(whole);
51
+ });
52
+
53
+ it('refuses an over-cap Content-Length without reading the body, and aborts the request', async () => {
54
+ const { res, readSoFar } = streamed([bytes(10)], CAP + 1);
55
+ const abort = new AbortController();
56
+
57
+ expect(await readBodyCapped(res, CAP, abort)).toBeNull();
58
+ expect(abort.signal.aborted).toBe(true);
59
+ expect(readSoFar()).toBe(0);
60
+ });
61
+
62
+ it('takes the oversized path even when cancelling the body would reject', async () => {
63
+ // `body.cancel()` rejects on a stream that has already errored; the guard
64
+ // aborts the controller instead, which cannot reject, so the caller still
65
+ // sees `null` rather than a thrown error on its generic failure path.
66
+ const res = {
67
+ headers: { get: () => String(CAP + 1) },
68
+ body: {
69
+ cancel: () => Promise.reject(new Error('stream already errored')),
70
+ getReader: () => {
71
+ throw new Error('must not read an over-declared body');
72
+ },
73
+ },
74
+ } as unknown as Response;
75
+
76
+ await expect(readBodyCapped(res, CAP, new AbortController())).resolves.toBeNull();
77
+ });
78
+
79
+ it('abandons an UNDECLARED body the moment it crosses the cap', async () => {
80
+ const chunks = [bytes(400), bytes(400), bytes(400)];
81
+ const { res, cancel, readSoFar } = streamed(chunks);
82
+
83
+ expect(await readBodyCapped(res, CAP, new AbortController())).toBeNull();
84
+ // Stopped on the third chunk (1,200 > 1,024) — never held whole.
85
+ expect(readSoFar()).toBe(3);
86
+ expect(cancel).toHaveBeenCalled();
87
+ });
88
+
89
+ it('recovers when Content-Length UNDERSTATES the body: the spill still merges in order', async () => {
90
+ // A decoded transfer can arrive longer than the encoded length announced.
91
+ const whole = bytes(500, 3);
92
+ const chunks = [whole.subarray(0, 180), whole.subarray(180, 260), whole.subarray(260)];
93
+ const { res } = streamed(chunks, 200);
94
+
95
+ const out = await readBodyCapped(res, CAP, new AbortController());
96
+
97
+ expect(new Uint8Array(out!)).toEqual(whole);
98
+ });
99
+
100
+ it('trims the trailing zeros when Content-Length OVERSTATES the body', async () => {
101
+ const whole = bytes(90, 11);
102
+ const { res } = streamed([whole], 900);
103
+
104
+ const out = await readBodyCapped(res, CAP, new AbortController());
105
+
106
+ expect(out!.byteLength).toBe(90);
107
+ expect(new Uint8Array(out!)).toEqual(whole);
108
+ });
109
+
110
+ it('still bounds a response with no stream at all', async () => {
111
+ const small = { arrayBuffer: async () => bytes(10).buffer } as unknown as Response;
112
+ const big = { arrayBuffer: async () => bytes(CAP + 1).buffer } as unknown as Response;
113
+
114
+ expect((await readBodyCapped(small, CAP, new AbortController()))!.byteLength).toBe(10);
115
+ expect(await readBodyCapped(big, CAP, new AbortController())).toBeNull();
116
+ });
117
+ });
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect } from 'vitest';
2
- import { getRendererLayout, isBinaryFile } from '../index';
2
+ import { getRendererLayout, isBinaryFile, isViewOnlyFile } from '../index';
3
3
 
4
4
  /**
5
5
  * The layout choice is the one thing in WP1 that cannot fail loudly: pick
@@ -13,6 +13,19 @@ describe('getRendererLayout', () => {
13
13
  'Knowledge/notes.txt',
14
14
  'Knowledge/report.docx',
15
15
  'Knowledge/no-extension-file',
16
+ // The pptx outline view is a text document, not a viewport.
17
+ 'Inbox/all-hands.pptx',
18
+ // The legacy-format / ODF no-preview note is one paragraph on the prose
19
+ // measure.
20
+ 'old/memo.doc',
21
+ 'old/deck.ppt',
22
+ 'old/sheet.xls',
23
+ 'docs/spec.odt',
24
+ 'decks/pitch.odp',
25
+ 'data/numbers.ods',
26
+ // An email is a letter: headers + a text body on the prose measure.
27
+ 'Inbox/offer.eml',
28
+ 'Inbox/thread.msg',
16
29
  ])('lays out %s as a document', (path) => {
17
30
  expect(getRendererLayout(path)).toBe('prose');
18
31
  });
@@ -37,12 +50,26 @@ describe('getRendererLayout', () => {
37
50
  * interpret.
38
51
  */
39
52
  describe('isBinaryFile', () => {
40
- it.each(['Inbox/brief.pdf', 'Inbox/diagram.png', 'Inbox/report.docx', 'Data/book.xlsx'])(
41
- 'knows %s holds no countable text',
42
- (path) => {
43
- expect(isBinaryFile(path)).toBe(true);
44
- },
45
- );
53
+ it.each([
54
+ 'Inbox/brief.pdf',
55
+ 'Inbox/diagram.png',
56
+ 'Inbox/report.docx',
57
+ 'Data/book.xlsx',
58
+ 'Inbox/all-hands.pptx',
59
+ 'old/memo.doc',
60
+ 'old/deck.ppt',
61
+ 'old/sheet.xls',
62
+ 'docs/spec.odt',
63
+ 'decks/pitch.odp',
64
+ 'data/numbers.ods',
65
+ // .msg is binary CFB; .eml is the .svg case — its bytes are text, but the
66
+ // viewer fetches raw bytes and parses the MIME, so the text buffer a
67
+ // character count would describe is never shown.
68
+ 'Inbox/thread.msg',
69
+ 'Inbox/offer.eml',
70
+ ])('knows %s holds no countable text', (path) => {
71
+ expect(isBinaryFile(path)).toBe(true);
72
+ });
46
73
 
47
74
  // The one file whose bytes ARE text and still must not be counted: it goes
48
75
  // to `ImageRenderer` as a picture, so the character count would describe a
@@ -62,3 +89,42 @@ describe('isBinaryFile', () => {
62
89
  },
63
90
  );
64
91
  });
92
+
93
+ /**
94
+ * View-only routes render a no-preview note — there is no editing surface, so
95
+ * the page's write action (Edit / Propose) must not be offered for them.
96
+ */
97
+ describe('isViewOnlyFile', () => {
98
+ it.each([
99
+ 'old/memo.doc',
100
+ 'old/deck.ppt',
101
+ 'old/sheet.xls',
102
+ 'docs/spec.odt',
103
+ 'decks/pitch.odp',
104
+ 'data/numbers.ods',
105
+ 'docs/SPEC.ODT',
106
+ // A message snapshot has no editing surface either.
107
+ 'Inbox/offer.eml',
108
+ 'Inbox/thread.msg',
109
+ 'Inbox/OFFER.EML',
110
+ // CHANGED: these DO render — as HTML, a grid, an outline, pages, a picture
111
+ // — but none of those viewers has an editing surface, so Edit acquired the
112
+ // lock and flipped the page into a mode the renderer ignores.
113
+ 'Inbox/report.docx',
114
+ 'Data/model.xlsx',
115
+ 'decks/pitch.pptx',
116
+ 'Inbox/brief.pdf',
117
+ 'img/diagram.png',
118
+ 'img/PHOTO.JPG',
119
+ 'img/chart.svg',
120
+ ])('marks %s view-only', (path) => {
121
+ expect(isViewOnlyFile(path)).toBe(true);
122
+ });
123
+
124
+ it.each(['Knowledge/Foo.md', 'Data/velocity.csv', 'notes/todo.txt'])(
125
+ 'leaves %s with its write action',
126
+ (path) => {
127
+ expect(isViewOnlyFile(path)).toBe(false);
128
+ },
129
+ );
130
+ });