@bendyline/squisq-formats 1.4.2 → 2.0.1

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 (140) hide show
  1. package/README.md +48 -2
  2. package/dist/chunk-2KPARF2P.js +99 -0
  3. package/dist/chunk-2KPARF2P.js.map +1 -0
  4. package/dist/{chunk-5LSSWZPU.js → chunk-4VUWTSGM.js} +72 -25
  5. package/dist/chunk-4VUWTSGM.js.map +1 -0
  6. package/dist/{chunk-YESS7VY3.js → chunk-ABVI556T.js} +154 -39
  7. package/dist/chunk-ABVI556T.js.map +1 -0
  8. package/dist/{chunk-WWBIKRNP.js → chunk-CRAVSMPZ.js} +13 -11
  9. package/dist/chunk-CRAVSMPZ.js.map +1 -0
  10. package/dist/chunk-FE6OJV6O.js +560 -0
  11. package/dist/chunk-FE6OJV6O.js.map +1 -0
  12. package/dist/{chunk-D7IFPWNZ.js → chunk-GVS2XXV6.js} +27 -26
  13. package/dist/chunk-GVS2XXV6.js.map +1 -0
  14. package/dist/{chunk-RTS5XBZ7.js → chunk-HTW2M27H.js} +341 -100
  15. package/dist/chunk-HTW2M27H.js.map +1 -0
  16. package/dist/{chunk-46FMDOWZ.js → chunk-LXYLOOST.js} +49 -17
  17. package/dist/chunk-LXYLOOST.js.map +1 -0
  18. package/dist/{chunk-MJGRI6XR.js → chunk-MLX2BOJC.js} +12 -7
  19. package/dist/chunk-MLX2BOJC.js.map +1 -0
  20. package/dist/chunk-NKAJPJ4G.js +106 -0
  21. package/dist/chunk-NKAJPJ4G.js.map +1 -0
  22. package/dist/{chunk-DQAZR57U.js → chunk-O3GVVND4.js} +1 -1
  23. package/dist/chunk-ODL3SSPT.js +18 -0
  24. package/dist/chunk-ODL3SSPT.js.map +1 -0
  25. package/dist/chunk-QRVN6A6E.js +127 -0
  26. package/dist/chunk-QRVN6A6E.js.map +1 -0
  27. package/dist/chunk-U32AG3G3.js +195 -0
  28. package/dist/chunk-U32AG3G3.js.map +1 -0
  29. package/dist/{chunk-EHLGMSTE.js → chunk-VJJM2SSH.js} +10 -8
  30. package/dist/chunk-VJJM2SSH.js.map +1 -0
  31. package/dist/chunk-VSYHZECT.js +778 -0
  32. package/dist/chunk-VSYHZECT.js.map +1 -0
  33. package/dist/{chunk-SHLPSADL.js → chunk-WC7WULGV.js} +81 -189
  34. package/dist/chunk-WC7WULGV.js.map +1 -0
  35. package/dist/chunk-XKUMNGBW.js +131 -0
  36. package/dist/chunk-XKUMNGBW.js.map +1 -0
  37. package/dist/chunk-YRT7GQ5Y.js +28 -0
  38. package/dist/chunk-YRT7GQ5Y.js.map +1 -0
  39. package/dist/container/index.d.ts +13 -3
  40. package/dist/container/index.js +23 -20
  41. package/dist/container/index.js.map +1 -1
  42. package/dist/docx/index.d.ts +6 -2
  43. package/dist/docx/index.js +5 -3
  44. package/dist/epub/index.d.ts +3 -1
  45. package/dist/epub/index.js +3 -3
  46. package/dist/export-D2NkylDT.d.ts +69 -0
  47. package/dist/extract-H6RXJMHP.js +15 -0
  48. package/dist/extract-H6RXJMHP.js.map +1 -0
  49. package/dist/html/index.d.ts +15 -85
  50. package/dist/html/index.js +3 -3
  51. package/dist/images-7FBWPKE3.js +7 -0
  52. package/dist/images-7FBWPKE3.js.map +1 -0
  53. package/dist/import-DTkDxHmZ.d.ts +84 -0
  54. package/dist/import-K8mfc0fz.d.ts +136 -0
  55. package/dist/index.d.ts +14 -4
  56. package/dist/index.js +33 -12
  57. package/dist/infer/index.d.ts +138 -0
  58. package/dist/infer/index.js +28 -0
  59. package/dist/infer/index.js.map +1 -0
  60. package/dist/layouts-BHrgZ5FS.d.ts +150 -0
  61. package/dist/layouts-QVPK3ZCU.js +12 -0
  62. package/dist/layouts-QVPK3ZCU.js.map +1 -0
  63. package/dist/mapTheme-IR27S6IV.js +11 -0
  64. package/dist/mapTheme-IR27S6IV.js.map +1 -0
  65. package/dist/ooxml/index.d.ts +21 -127
  66. package/dist/ooxml/index.js +31 -9
  67. package/dist/pdf/index.d.ts +3 -1
  68. package/dist/pdf/index.js +1 -1
  69. package/dist/pptx/index.d.ts +8 -108
  70. package/dist/pptx/index.js +13 -4
  71. package/dist/reader-B9L8Ucbj.d.ts +140 -0
  72. package/dist/registry/index.d.ts +60 -8
  73. package/dist/registry/index.js +9 -4
  74. package/dist/themeReader-DJKErl_j.d.ts +56 -0
  75. package/dist/xlsx/index.d.ts +6 -66
  76. package/dist/xlsx/index.js +4 -2
  77. package/dist/zipLimits-BOKCB7qk.d.ts +31 -0
  78. package/package.json +8 -2
  79. package/src/__tests__/container.test.ts +41 -0
  80. package/src/__tests__/convert.test.ts +310 -1
  81. package/src/__tests__/epub.test.ts +102 -1
  82. package/src/__tests__/html.test.ts +62 -0
  83. package/src/__tests__/inferTheme.test.ts +135 -0
  84. package/src/__tests__/lossyWarnings.test.ts +41 -0
  85. package/src/__tests__/ooxml.test.ts +76 -2
  86. package/src/__tests__/ooxmlCancellation.test.ts +113 -0
  87. package/src/__tests__/ooxmlThemeReader.test.ts +92 -0
  88. package/src/__tests__/plainHtml.test.ts +15 -1
  89. package/src/__tests__/plainHtmlBundle.test.ts +18 -0
  90. package/src/__tests__/pptxImport.test.ts +30 -0
  91. package/src/__tests__/pptxInferFixtures.ts +314 -0
  92. package/src/__tests__/pptxLayoutInfer.test.ts +395 -0
  93. package/src/__tests__/zipSafety.test.ts +317 -0
  94. package/src/container/index.ts +37 -32
  95. package/src/docx/export.ts +4 -2
  96. package/src/docx/import.ts +4 -3
  97. package/src/epub/export.ts +94 -25
  98. package/src/html/docsHtmlBundle.ts +6 -2
  99. package/src/html/htmlTemplate.ts +31 -6
  100. package/src/html/imageUtils.ts +14 -5
  101. package/src/html/index.ts +12 -1
  102. package/src/html/plainHtml.ts +7 -3
  103. package/src/html/plainHtmlBundle.ts +11 -9
  104. package/src/index.ts +23 -0
  105. package/src/infer/extract.ts +127 -0
  106. package/src/infer/index.ts +199 -0
  107. package/src/infer/mapTheme.ts +176 -0
  108. package/src/infer/types.ts +27 -0
  109. package/src/ooxml/index.ts +14 -0
  110. package/src/ooxml/readUtils.ts +44 -0
  111. package/src/ooxml/reader.ts +129 -29
  112. package/src/ooxml/themeReader.ts +197 -0
  113. package/src/ooxml/types.ts +8 -9
  114. package/src/ooxml/writer.ts +28 -10
  115. package/src/pdf/export.ts +4 -2
  116. package/src/pdf/import.ts +40 -34
  117. package/src/pptx/export.ts +4 -2
  118. package/src/pptx/import.ts +214 -32
  119. package/src/pptx/index.ts +14 -0
  120. package/src/pptx/layouts.ts +1222 -0
  121. package/src/registry/convert.ts +168 -53
  122. package/src/registry/defaultFormats.ts +135 -45
  123. package/src/registry/index.ts +6 -1
  124. package/src/registry/types.ts +69 -6
  125. package/src/shared/boundedZipArchive.ts +383 -0
  126. package/src/shared/fidelity.ts +130 -0
  127. package/src/shared/zipEntryCount.ts +151 -0
  128. package/src/shared/zipLimits.ts +296 -0
  129. package/src/shared/zipSafety.ts +19 -0
  130. package/src/xlsx/import.ts +3 -2
  131. package/dist/chunk-46FMDOWZ.js.map +0 -1
  132. package/dist/chunk-5LSSWZPU.js.map +0 -1
  133. package/dist/chunk-D7IFPWNZ.js.map +0 -1
  134. package/dist/chunk-EHLGMSTE.js.map +0 -1
  135. package/dist/chunk-MJGRI6XR.js.map +0 -1
  136. package/dist/chunk-RTS5XBZ7.js.map +0 -1
  137. package/dist/chunk-SHLPSADL.js.map +0 -1
  138. package/dist/chunk-WWBIKRNP.js.map +0 -1
  139. package/dist/chunk-YESS7VY3.js.map +0 -1
  140. /package/dist/{chunk-DQAZR57U.js.map → chunk-O3GVVND4.js.map} +0 -0
@@ -8,9 +8,25 @@
8
8
  * methods, so pulling in the registry never eagerly bundles heavy converters.
9
9
  */
10
10
 
11
- import type { Doc } from '@bendyline/squisq/schemas';
11
+ import type { Doc, ThemeRegistry } from '@bendyline/squisq/schemas';
12
+ import type { TransformStyleInput, TransformStyleRegistry } from '@bendyline/squisq/transform';
12
13
  import type { MarkdownDocument } from '@bendyline/squisq/markdown';
13
14
  import type { ContentContainer } from '@bendyline/squisq/storage';
15
+ import type { ParseOptions, StringifyOptions } from '@bendyline/squisq/markdown';
16
+ import type { DocxExportOptions } from '../docx/export.js';
17
+ import type { DocxImportOptions } from '../docx/import.js';
18
+ import type { PptxExportOptions } from '../pptx/export.js';
19
+ import type { PptxImportOptions } from '../pptx/import.js';
20
+ import type { XlsxExportOptions } from '../xlsx/export.js';
21
+ import type { XlsxImportOptions } from '../xlsx/import.js';
22
+ import type { CsvExportOptions, CsvImportOptions } from '../csv/index.js';
23
+ import type { PdfExportOptions } from '../pdf/export.js';
24
+ import type { PdfImportOptions } from '../pdf/import.js';
25
+ import type { HtmlExportOptions } from '../html/htmlTemplate.js';
26
+ import type { HtmlImportOptions } from '../html/import.js';
27
+ import type { EpubExportOptions } from '../epub/export.js';
28
+ import type { ContainerToZipOptions } from '../container/index.js';
29
+ import type { ZipSafetyLimits } from '../shared/zipSafety.js';
14
30
 
15
31
  /** A format identifier (e.g. `'docx'`). Strings so hosts can register their own. */
16
32
  export type FormatId = string;
@@ -41,6 +57,33 @@ export interface ConversionResult {
41
57
  warnings: string[];
42
58
  }
43
59
 
60
+ export interface MarkdownFormatOptions {
61
+ parse?: ParseOptions;
62
+ stringify?: StringifyOptions;
63
+ }
64
+
65
+ /** Resource limits applied when importing a DBK/ZIP container. */
66
+ export type DbkFormatOptions = ZipSafetyLimits & ContainerToZipOptions;
67
+
68
+ /**
69
+ * Strongly typed option bags for built-in formats. Import and export options
70
+ * share a bag because a single conversion may use the format on either side.
71
+ * Custom registries may add arbitrary keys through the intersection used by
72
+ * {@link ConvertOptions.formatOptions}.
73
+ */
74
+ export interface BuiltinFormatOptions {
75
+ md: MarkdownFormatOptions;
76
+ docx: DocxImportOptions & DocxExportOptions;
77
+ pptx: PptxImportOptions & PptxExportOptions;
78
+ xlsx: XlsxImportOptions & XlsxExportOptions;
79
+ csv: CsvImportOptions & CsvExportOptions;
80
+ pdf: PdfImportOptions & PdfExportOptions;
81
+ html: HtmlImportOptions & Partial<Omit<HtmlExportOptions, 'playerScript'>>;
82
+ htmlzip: Partial<Omit<HtmlExportOptions, 'playerScript'>>;
83
+ epub: EpubExportOptions;
84
+ dbk: DbkFormatOptions;
85
+ }
86
+
44
87
  /**
45
88
  * A source normalized into every shape an exporter might need. `doc` is always
46
89
  * present; `markdownDoc` is present when the source was markdown-shaped (an
@@ -55,22 +98,42 @@ export interface NormalizedInput {
55
98
 
56
99
  /** Options threaded through `convert()` and into every format method. */
57
100
  export interface ConvertOptions {
101
+ /** Cancel normalization, transformation, or export at the next bounded work boundary. */
102
+ signal?: AbortSignal;
58
103
  /** Registry to resolve formats against. Defaults to `defaultRegistry()`. */
59
104
  registry?: FormatRegistry;
60
105
  /** Explicit source format id (skips extension/byte sniffing). */
61
106
  from?: FormatId;
62
107
  /** Theme id to apply to the exported document. */
63
108
  themeId?: string;
64
- /** Transform style id to apply before export. */
65
- transformStyle?: string;
109
+ /** Explicit caller-owned registry for non-document custom themes. */
110
+ themeRegistry?: ThemeRegistry;
111
+ /** Built-in/registry id or call-scoped style to apply before export. */
112
+ transformStyle?: TransformStyleInput;
113
+ /** Explicit caller-owned registry used to resolve transform style ids. */
114
+ transformRegistry?: TransformStyleRegistry;
66
115
  /** Content-aware auto-templating when deriving a Doc from markdown. */
67
116
  autoTemplates?: boolean;
68
- /** Title hint for exporters that support one (epub, html). */
117
+ /** Title hint for exporters that expose document metadata. */
69
118
  title?: string;
70
119
  /** Lazily resolve the standalone player IIFE bundle (required for HTML export). */
71
120
  resolvePlayerScript?: () => Promise<string>;
72
- /** Per-format escape hatch for extra options. */
73
- formatOptions?: Record<FormatId, Record<string, unknown>>;
121
+ /** Typed per-format options for built-ins; custom format ids remain extensible. */
122
+ formatOptions?: Partial<BuiltinFormatOptions> & Record<FormatId, unknown>;
123
+ }
124
+
125
+ /** Target-only options accepted after a source has already been normalized and transformed. */
126
+ export type PreparedExportOptions = Pick<
127
+ ConvertOptions,
128
+ 'signal' | 'title' | 'resolvePlayerScript' | 'formatOptions'
129
+ >;
130
+
131
+ /**
132
+ * An opaque normalized conversion snapshot. The source and transform pipeline
133
+ * has already completed; each call exports that same snapshot to one target.
134
+ */
135
+ export interface PreparedConversion {
136
+ convert(to: FormatId, options?: PreparedExportOptions): Promise<ConversionResult>;
74
137
  }
75
138
 
76
139
  /** Describes how a single format imports to / exports from the squisq model. */
@@ -0,0 +1,383 @@
1
+ /** Incremental JSZip member reads governed by one shared archive budget. */
2
+
3
+ import JSZip from 'jszip';
4
+ import {
5
+ archiveTooLargeError,
6
+ assertNonNegativeFinite,
7
+ compressionRatio,
8
+ compressionRatioError,
9
+ entryTooLargeError,
10
+ resolveZipSafetyLimits,
11
+ throwIfZipAborted,
12
+ validateZipArchive,
13
+ tooManyEntriesError,
14
+ ZipSafetyError,
15
+ type ResolvedZipSafetyLimits,
16
+ type ValidatedZipEntry,
17
+ type ZipSafetyErrorCode,
18
+ type ZipSafetyLimits,
19
+ } from './zipLimits.js';
20
+ import { declaredZipEntryCount, prepareZipInput, type ZipInput } from './zipEntryCount.js';
21
+
22
+ interface ActiveZipRead {
23
+ stop(error: unknown): void;
24
+ }
25
+
26
+ interface ZipChunkStream {
27
+ on(event: 'data', callback: (chunk: Uint8Array) => void): ZipChunkStream;
28
+ on(event: 'error', callback: (error: unknown) => void): ZipChunkStream;
29
+ on(event: 'end', callback: () => void): ZipChunkStream;
30
+ pause(): ZipChunkStream;
31
+ resume(): ZipChunkStream;
32
+ }
33
+
34
+ interface StreamableZipObject {
35
+ internalStream(type: 'uint8array'): ZipChunkStream;
36
+ }
37
+
38
+ /**
39
+ * A JSZip archive whose member reads share one actual-byte budget.
40
+ *
41
+ * JSZip's promise API accumulates a complete inflated member before returning.
42
+ * This wrapper instead consumes `internalStream('uint8array')`, checks every
43
+ * emitted chunk, and pauses every active stream as soon as any limit fails.
44
+ * Completed reads are cached so repeated OOXML part access is neither inflated
45
+ * nor charged twice.
46
+ */
47
+ export interface BoundedZipArchive {
48
+ readonly zip: JSZip;
49
+ readonly entries: readonly ValidatedZipEntry[];
50
+ readonly emittedUncompressedBytes: number;
51
+ read(path: string, maxBytes?: number): Promise<Uint8Array | null>;
52
+ readText(path: string, maxBytes?: number): Promise<string | null>;
53
+ release(path: string): void;
54
+ }
55
+
56
+ class JsZipBoundedArchive implements BoundedZipArchive {
57
+ readonly zip: JSZip;
58
+ readonly entries: readonly ValidatedZipEntry[];
59
+
60
+ private readonly limits: ResolvedZipSafetyLimits;
61
+ private readonly entriesByPath: ReadonlyMap<string, ValidatedZipEntry>;
62
+ private readonly signal?: AbortSignal;
63
+ private readonly reads = new Map<string, Promise<Uint8Array>>();
64
+ private readonly activeReads = new Set<ActiveZipRead>();
65
+ private terminalError?: ZipSafetyError;
66
+ private emittedBytes = 0;
67
+
68
+ constructor(
69
+ zip: JSZip,
70
+ entries: readonly ValidatedZipEntry[],
71
+ limits: ResolvedZipSafetyLimits,
72
+ signal?: AbortSignal,
73
+ ) {
74
+ this.zip = zip;
75
+ this.entries = entries;
76
+ this.limits = limits;
77
+ this.signal = signal;
78
+ this.entriesByPath = new Map(entries.map((entry) => [entry.path, entry]));
79
+ }
80
+
81
+ /** Actual uncompressed bytes accepted from JSZip streams so far. */
82
+ get emittedUncompressedBytes(): number {
83
+ return this.emittedBytes;
84
+ }
85
+
86
+ /** Read and cache one member, returning null when it does not exist. */
87
+ async read(path: string, maxBytes?: number): Promise<Uint8Array | null> {
88
+ throwIfZipAborted(this.signal);
89
+ this.throwIfFailed();
90
+ if (maxBytes !== undefined) assertNonNegativeFinite('member read limit', maxBytes);
91
+ const entry = this.entriesByPath.get(path);
92
+ if (!entry) return null;
93
+
94
+ let pending = this.reads.get(path);
95
+ if (!pending) {
96
+ pending = this.streamEntry(entry, maxBytes);
97
+ this.reads.set(path, pending);
98
+ }
99
+ let bytes: Uint8Array;
100
+ try {
101
+ bytes = await pending;
102
+ } catch (error: unknown) {
103
+ // Cancellation is scoped to the current operation, not archive
104
+ // corruption. Do not leave a cancelled read cached for a later caller.
105
+ if (this.reads.get(path) === pending && !this.terminalError) this.reads.delete(path);
106
+ throw error;
107
+ }
108
+ throwIfZipAborted(this.signal);
109
+ if (maxBytes !== undefined && bytes.byteLength > maxBytes) {
110
+ const error = entryTooLargeError(path, bytes.byteLength, maxBytes);
111
+ this.failArchive(error);
112
+ throw error;
113
+ }
114
+ return bytes;
115
+ }
116
+
117
+ /** Read one UTF-8 text member, returning null when it does not exist. */
118
+ async readText(path: string, maxBytes?: number): Promise<string | null> {
119
+ const bytes = await this.read(path, maxBytes);
120
+ return bytes ? new TextDecoder().decode(bytes) : null;
121
+ }
122
+
123
+ /** Release a cached member when a sequential consumer has taken ownership. */
124
+ release(path: string): void {
125
+ this.reads.delete(path);
126
+ }
127
+
128
+ private streamEntry(metadata: ValidatedZipEntry, readLimit?: number): Promise<Uint8Array> {
129
+ throwIfZipAborted(this.signal);
130
+ const { path, entry, declaredSize, crc32: expectedCrc } = metadata;
131
+ const effectiveEntryLimit = Math.min(
132
+ this.limits.maxEntryUncompressedBytes,
133
+ readLimit ?? Number.POSITIVE_INFINITY,
134
+ );
135
+ // Never trust a declaration enough to allocate it up front. A forged
136
+ // 511 MiB size must not force 511 MiB of memory for a tiny member.
137
+ let output: Uint8Array = new Uint8Array(0);
138
+ let stream: ZipChunkStream;
139
+ try {
140
+ stream = (entry as unknown as StreamableZipObject).internalStream('uint8array');
141
+ } catch (error: unknown) {
142
+ const safeError = asZipSafetyError(error, path);
143
+ this.failArchive(safeError);
144
+ return Promise.reject(safeError);
145
+ }
146
+
147
+ return new Promise<Uint8Array>((resolve, reject) => {
148
+ let settled = false;
149
+ let written = 0;
150
+ let crc = 0xffffffff;
151
+ const removeAbortListener = (): void =>
152
+ this.signal?.removeEventListener('abort', handleAbort);
153
+ const handleAbort = (): void =>
154
+ controller.stop(this.signal?.reason ?? new Error('ZIP operation was cancelled'));
155
+
156
+ const controller: ActiveZipRead = {
157
+ stop: (error) => {
158
+ if (settled) return;
159
+ settled = true;
160
+ this.activeReads.delete(controller);
161
+ removeAbortListener();
162
+ // Public JSZip cancellation is cooperative. It prevents another
163
+ // compressed-input tick; data already emitted synchronously by the
164
+ // current tick is ignored because `settled` is now true.
165
+ try {
166
+ stream.pause();
167
+ } catch {
168
+ // Reject with the original safety failure even if a malformed
169
+ // third-party stream cannot be paused cleanly.
170
+ }
171
+ reject(error);
172
+ },
173
+ };
174
+ this.activeReads.add(controller);
175
+ if (this.signal) {
176
+ this.signal.addEventListener('abort', handleAbort, { once: true });
177
+ if (this.signal.aborted) {
178
+ handleAbort();
179
+ return;
180
+ }
181
+ }
182
+
183
+ stream
184
+ .on('data', (chunk: Uint8Array) => {
185
+ if (settled) return;
186
+ const nextWritten = written + chunk.byteLength;
187
+ try {
188
+ throwIfZipAborted(this.signal);
189
+ this.assertChunkAllowed(metadata, nextWritten, chunk.byteLength, effectiveEntryLimit);
190
+ output = growOutput(output, nextWritten, declaredSize, effectiveEntryLimit);
191
+ output.set(chunk, written);
192
+ written = nextWritten;
193
+ crc = updateCrc32(crc, chunk);
194
+ } catch (error: unknown) {
195
+ if (this.signal?.aborted) controller.stop(error);
196
+ else this.failArchive(asZipSafetyError(error, path));
197
+ }
198
+ })
199
+ .on('error', (error: unknown) => {
200
+ if (settled) return;
201
+ const message = error instanceof Error ? error.message : String(error);
202
+ const code: ZipSafetyErrorCode = message.includes('uncompressed data size mismatch')
203
+ ? 'size-mismatch'
204
+ : 'decompression-failed';
205
+ this.failArchive(
206
+ new ZipSafetyError(code, `ZIP import: could not decompress ${path}: ${message}`, {
207
+ path,
208
+ cause: error,
209
+ }),
210
+ );
211
+ })
212
+ .on('end', () => {
213
+ if (settled) return;
214
+ if (declaredSize !== undefined && written !== declaredSize) {
215
+ this.failArchive(
216
+ new ZipSafetyError(
217
+ 'size-mismatch',
218
+ `ZIP import: archive member size does not match its metadata: ${path}.`,
219
+ { path, actual: written },
220
+ ),
221
+ );
222
+ return;
223
+ }
224
+ const actualCrc = (crc ^ 0xffffffff) >>> 0;
225
+ if (expectedCrc !== undefined && actualCrc !== expectedCrc >>> 0) {
226
+ this.failArchive(
227
+ new ZipSafetyError('crc-mismatch', `ZIP import: CRC32 mismatch for ${path}.`, {
228
+ path,
229
+ }),
230
+ );
231
+ return;
232
+ }
233
+
234
+ settled = true;
235
+ this.activeReads.delete(controller);
236
+ removeAbortListener();
237
+ resolve(output.byteLength === written ? output : output.slice(0, written));
238
+ })
239
+ .resume();
240
+ });
241
+ }
242
+
243
+ private assertChunkAllowed(
244
+ entry: ValidatedZipEntry,
245
+ nextEntryBytes: number,
246
+ chunkBytes: number,
247
+ effectiveEntryLimit: number,
248
+ ): void {
249
+ if (entry.declaredSize !== undefined && nextEntryBytes > entry.declaredSize) {
250
+ throw new ZipSafetyError(
251
+ 'size-mismatch',
252
+ `ZIP import: archive member size does not match its metadata: ${entry.path}.`,
253
+ { path: entry.path, actual: nextEntryBytes },
254
+ );
255
+ }
256
+ if (
257
+ effectiveEntryLimit < this.limits.maxUncompressedBytes &&
258
+ nextEntryBytes > effectiveEntryLimit
259
+ ) {
260
+ throw entryTooLargeError(entry.path, nextEntryBytes, effectiveEntryLimit);
261
+ }
262
+
263
+ const nextTotal = this.emittedBytes + chunkBytes;
264
+ if (nextTotal > this.limits.maxUncompressedBytes) {
265
+ throw archiveTooLargeError(nextTotal, this.limits.maxUncompressedBytes);
266
+ }
267
+ if (nextEntryBytes > effectiveEntryLimit) {
268
+ throw entryTooLargeError(entry.path, nextEntryBytes, effectiveEntryLimit);
269
+ }
270
+
271
+ const ratio =
272
+ entry.compressedSize === undefined
273
+ ? undefined
274
+ : compressionRatio(nextEntryBytes, entry.compressedSize);
275
+ if (ratio !== undefined && ratio > this.limits.maxCompressionRatio) {
276
+ throw compressionRatioError(entry.path, ratio, this.limits.maxCompressionRatio);
277
+ }
278
+ this.emittedBytes = nextTotal;
279
+ }
280
+
281
+ private failArchive(error: ZipSafetyError): void {
282
+ if (this.terminalError) return;
283
+ this.terminalError = error;
284
+ for (const active of [...this.activeReads]) active.stop(error);
285
+ }
286
+
287
+ private throwIfFailed(): void {
288
+ if (this.terminalError) throw this.terminalError;
289
+ }
290
+ }
291
+
292
+ /** Load with JSZip, validate metadata, and create a shared bounded read session. */
293
+ export async function openBoundedZipArchive(
294
+ data: ZipInput,
295
+ limits: ZipSafetyLimits = {},
296
+ ): Promise<BoundedZipArchive> {
297
+ throwIfZipAborted(limits.signal);
298
+ const resolved = resolveZipSafetyLimits(limits);
299
+ let prepared: { input: ZipInput; bytes?: Uint8Array };
300
+ try {
301
+ prepared = await prepareZipInput(data, limits.signal);
302
+ } catch (error: unknown) {
303
+ if (limits.signal?.aborted) throw limits.signal.reason ?? error;
304
+ throw invalidArchiveError(error);
305
+ }
306
+ throwIfZipAborted(limits.signal);
307
+ if (prepared.bytes) {
308
+ const declaredEntries = declaredZipEntryCount(prepared.bytes);
309
+ if (declaredEntries !== undefined && declaredEntries > resolved.maxEntries) {
310
+ throw tooManyEntriesError(declaredEntries, resolved.maxEntries);
311
+ }
312
+ }
313
+ let zip: JSZip;
314
+ try {
315
+ zip = await JSZip.loadAsync(prepared.input);
316
+ } catch (error: unknown) {
317
+ if (limits.signal?.aborted) throw limits.signal.reason ?? error;
318
+ throw invalidArchiveError(error);
319
+ }
320
+ throwIfZipAborted(limits.signal);
321
+ return createBoundedZipArchive(zip, limits);
322
+ }
323
+
324
+ function invalidArchiveError(cause: unknown): ZipSafetyError {
325
+ return new ZipSafetyError('invalid-archive', 'ZIP import: archive is not readable.', { cause });
326
+ }
327
+
328
+ /** Wrap an existing JSZip instance in the same validation and shared budget. */
329
+ export function createBoundedZipArchive(
330
+ zip: JSZip,
331
+ limits: ZipSafetyLimits = {},
332
+ ): BoundedZipArchive {
333
+ throwIfZipAborted(limits.signal);
334
+ const resolved = resolveZipSafetyLimits(limits);
335
+ const entries = validateZipArchive(zip, limits);
336
+ throwIfZipAborted(limits.signal);
337
+ return new JsZipBoundedArchive(zip, entries, resolved, limits.signal);
338
+ }
339
+
340
+ function asZipSafetyError(error: unknown, path: string): ZipSafetyError {
341
+ if (error instanceof ZipSafetyError) return error;
342
+ return new ZipSafetyError(
343
+ 'decompression-failed',
344
+ `ZIP import: could not decompress ${path}: ${error instanceof Error ? error.message : String(error)}`,
345
+ { path, cause: error },
346
+ );
347
+ }
348
+
349
+ function growOutput(
350
+ current: Uint8Array,
351
+ required: number,
352
+ declaredSize: number | undefined,
353
+ limit: number,
354
+ ): Uint8Array {
355
+ if (required <= current.byteLength) return current;
356
+ const maximum = Math.min(declaredSize ?? limit, limit);
357
+ const grownSize = current.byteLength === 0 ? required : current.byteLength * 2;
358
+ const nextSize = Math.min(maximum, Math.max(required, grownSize));
359
+ const next = new Uint8Array(nextSize);
360
+ next.set(current);
361
+ return next;
362
+ }
363
+
364
+ let crcTable: Uint32Array | undefined;
365
+
366
+ function updateCrc32(crc: number, bytes: Uint8Array): number {
367
+ const table = crcTable ?? (crcTable = makeCrcTable());
368
+ let next = crc >>> 0;
369
+ for (const byte of bytes) next = table[(next ^ byte) & 0xff]! ^ (next >>> 8);
370
+ return next >>> 0;
371
+ }
372
+
373
+ function makeCrcTable(): Uint32Array {
374
+ const table = new Uint32Array(256);
375
+ for (let n = 0; n < table.length; n++) {
376
+ let value = n;
377
+ for (let bit = 0; bit < 8; bit++) {
378
+ value = (value & 1) !== 0 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
379
+ }
380
+ table[n] = value >>> 0;
381
+ }
382
+ return table;
383
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Shared Markdown fidelity reporting for exporters that intentionally support
3
+ * only a subset of the core Markdown AST. Keeping the capability profiles in
4
+ * one exhaustive table prevents each exporter from silently drifting as the
5
+ * core AST grows.
6
+ */
7
+
8
+ import type {
9
+ MarkdownBlockNode,
10
+ MarkdownDocument,
11
+ MarkdownInlineNode,
12
+ } from '@bendyline/squisq/markdown';
13
+
14
+ type ContentNodeType = MarkdownBlockNode['type'] | MarkdownInlineNode['type'];
15
+ export type MarkdownExportProfile = 'docx' | 'pdf' | 'pptx' | 'epub';
16
+
17
+ /**
18
+ * Exhaustive by construction: adding a Markdown node type in core makes this
19
+ * package fail typechecking until its export fidelity is considered here.
20
+ */
21
+ const CONTENT_NODE_TYPES: Record<ContentNodeType, true> = {
22
+ heading: true,
23
+ paragraph: true,
24
+ blockquote: true,
25
+ list: true,
26
+ code: true,
27
+ thematicBreak: true,
28
+ table: true,
29
+ htmlBlock: true,
30
+ math: true,
31
+ definition: true,
32
+ footnoteDefinition: true,
33
+ containerDirective: true,
34
+ leafDirective: true,
35
+ definitionList: true,
36
+ text: true,
37
+ emphasis: true,
38
+ strong: true,
39
+ delete: true,
40
+ inlineCode: true,
41
+ link: true,
42
+ image: true,
43
+ break: true,
44
+ htmlInline: true,
45
+ inlineMath: true,
46
+ footnoteReference: true,
47
+ linkReference: true,
48
+ imageReference: true,
49
+ textDirective: true,
50
+ mention: true,
51
+ inlineIcon: true,
52
+ };
53
+
54
+ const COMMON_SUPPORTED: readonly ContentNodeType[] = [
55
+ 'heading',
56
+ 'paragraph',
57
+ 'blockquote',
58
+ 'list',
59
+ 'code',
60
+ 'thematicBreak',
61
+ 'table',
62
+ 'htmlBlock',
63
+ 'math',
64
+ 'text',
65
+ 'emphasis',
66
+ 'strong',
67
+ 'delete',
68
+ 'inlineCode',
69
+ 'link',
70
+ 'image',
71
+ 'break',
72
+ 'htmlInline',
73
+ 'inlineMath',
74
+ ];
75
+
76
+ const PROFILE_SUPPORT: Record<MarkdownExportProfile, ReadonlySet<ContentNodeType>> = {
77
+ docx: new Set([...COMMON_SUPPORTED, 'footnoteDefinition', 'footnoteReference']),
78
+ pdf: new Set([...COMMON_SUPPORTED, 'footnoteDefinition', 'footnoteReference']),
79
+ pptx: new Set(COMMON_SUPPORTED),
80
+ epub: new Set(COMMON_SUPPORTED),
81
+ };
82
+
83
+ const PROFILE_LABELS: Record<MarkdownExportProfile, string> = {
84
+ docx: 'DOCX',
85
+ pdf: 'PDF',
86
+ pptx: 'PPTX',
87
+ epub: 'EPUB',
88
+ };
89
+
90
+ interface AstLikeNode {
91
+ type?: string;
92
+ children?: unknown;
93
+ }
94
+
95
+ /** Return a user-facing warning when an exporter will omit Markdown nodes. */
96
+ export function markdownFidelityWarnings(
97
+ document: MarkdownDocument,
98
+ profile: MarkdownExportProfile,
99
+ ): string[] {
100
+ const supported = PROFILE_SUPPORT[profile];
101
+ const omitted = new Map<ContentNodeType, number>();
102
+
103
+ const visit = (candidate: unknown): void => {
104
+ if (!candidate || typeof candidate !== 'object') return;
105
+ const node = candidate as AstLikeNode;
106
+ const type = node.type as ContentNodeType | undefined;
107
+
108
+ if (type && Object.prototype.hasOwnProperty.call(CONTENT_NODE_TYPES, type)) {
109
+ if (!supported.has(type)) {
110
+ // The exporter drops this whole subtree, so report the highest-fidelity
111
+ // boundary once instead of inflating the count with its descendants.
112
+ omitted.set(type, (omitted.get(type) ?? 0) + 1);
113
+ return;
114
+ }
115
+ }
116
+
117
+ if (Array.isArray(node.children)) {
118
+ for (const child of node.children) visit(child);
119
+ }
120
+ };
121
+
122
+ for (const child of document.children) visit(child);
123
+ if (omitted.size === 0) return [];
124
+
125
+ const total = [...omitted.values()].reduce((sum, count) => sum + count, 0);
126
+ const details = [...omitted].map(([type, count]) => `${type} (${count})`).join(', ');
127
+ return [
128
+ `${PROFILE_LABELS[profile]} export omitted ${total} unsupported Markdown node(s): ${details}.`,
129
+ ];
130
+ }