@bendyline/squisq-formats 2.1.0 → 2.2.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 (195) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE.md +20 -0
  3. package/README.md +1 -1
  4. package/dist/{chunk-NNHKUXKA.js → chunk-26ISNJ7Y.js} +85 -65
  5. package/dist/{chunk-NKAJPJ4G.js → chunk-2JJ5RFDZ.js} +0 -1
  6. package/dist/{chunk-WQSHGBLN.js → chunk-3NKXBZSR.js} +193 -42
  7. package/dist/{chunk-KURGXM4I.js → chunk-4V3KCHAP.js} +3 -4
  8. package/dist/{chunk-MLX2BOJC.js → chunk-6RQOV3B3.js} +1 -2
  9. package/dist/{chunk-EW54IRRS.js → chunk-6S6GU3ZG.js} +5 -6
  10. package/dist/{chunk-FE6OJV6O.js → chunk-7AWFHP5U.js} +1 -1
  11. package/dist/{chunk-RFAPOKHJ.js → chunk-AD2WT564.js} +59 -9
  12. package/dist/{chunk-O3GVVND4.js → chunk-AONELFLA.js} +0 -1
  13. package/dist/{chunk-SC67HYQJ.js → chunk-EJTNGKEA.js} +5 -8
  14. package/dist/chunk-GX7RAUME.js +121 -0
  15. package/dist/{chunk-SSUPBUF5.js → chunk-IIQYS2YH.js} +0 -1
  16. package/dist/{chunk-RLU7UFYU.js → chunk-IPN56VLW.js} +83 -58
  17. package/dist/{chunk-DTDF6QDP.js → chunk-JE6LSIHE.js} +81 -20
  18. package/dist/{chunk-U4MRIFKL.js → chunk-JU2RHXUB.js} +0 -1
  19. package/dist/{chunk-4VUWTSGM.js → chunk-K6XRMVPW.js} +64 -31
  20. package/dist/{chunk-ODL3SSPT.js → chunk-KXOZMWBS.js} +0 -1
  21. package/dist/chunk-OGS5VCGJ.js +446 -0
  22. package/dist/{chunk-GVS2XXV6.js → chunk-PJXJI2LY.js} +449 -57
  23. package/dist/{chunk-74GO3FVS.js → chunk-PU7REGWV.js} +5 -8
  24. package/dist/{chunk-PN52A5AA.js → chunk-SBUW7NHR.js} +0 -1
  25. package/dist/{chunk-QFLDYKCR.js → chunk-TAAENIRB.js} +5 -8
  26. package/dist/{chunk-7ARKUCQT.js → chunk-X2DEAXNK.js} +54 -2
  27. package/dist/container/index.js +1 -2
  28. package/dist/csv/index.d.ts +27 -2
  29. package/dist/csv/index.js +1 -2
  30. package/dist/docx/index.d.ts +5 -1
  31. package/dist/docx/index.js +9 -11
  32. package/dist/epub/index.d.ts +2 -0
  33. package/dist/epub/index.js +5 -6
  34. package/dist/{export-D2NkylDT.d.ts → export-D9msROJS.d.ts} +18 -6
  35. package/dist/extract-MN7LA3NL.js +13 -0
  36. package/dist/html/index.d.ts +11 -4
  37. package/dist/html/index.js +3 -4
  38. package/dist/images-ESPQKVTW.js +6 -0
  39. package/dist/{import-K8mfc0fz.d.ts → import-C3htUTss.d.ts} +5 -1
  40. package/dist/{import-DTkDxHmZ.d.ts → import-C8whCC7_.d.ts} +6 -0
  41. package/dist/index.d.ts +7 -7
  42. package/dist/index.js +28 -26
  43. package/dist/infer/index.d.ts +3 -3
  44. package/dist/infer/index.js +7 -9
  45. package/dist/{layouts-BHrgZ5FS.d.ts → layouts-CTdPlB-u.d.ts} +1 -1
  46. package/dist/layouts-DRWZGSPD.js +10 -0
  47. package/dist/{mapTheme-IR27S6IV.js → mapTheme-4TWH25FT.js} +1 -2
  48. package/dist/ooxml/index.d.ts +3 -3
  49. package/dist/ooxml/index.js +14 -13
  50. package/dist/pdf/index.d.ts +18 -0
  51. package/dist/pdf/index.js +2 -3
  52. package/dist/pptx/index.d.ts +4 -4
  53. package/dist/pptx/index.js +11 -13
  54. package/dist/{reader-B9L8Ucbj.d.ts → reader-B_m1aKZC.d.ts} +30 -1
  55. package/dist/registry/index.d.ts +21 -5
  56. package/dist/registry/index.js +9 -6
  57. package/dist/{themeReader-DJKErl_j.d.ts → themeReader-DCtwC83Q.d.ts} +1 -1
  58. package/dist/xlsx/index.d.ts +3 -3
  59. package/dist/xlsx/index.js +6 -7
  60. package/package.json +6 -3
  61. package/dist/chunk-4VUWTSGM.js.map +0 -1
  62. package/dist/chunk-6M7Z25LA.js +0 -46
  63. package/dist/chunk-6M7Z25LA.js.map +0 -1
  64. package/dist/chunk-74GO3FVS.js.map +0 -1
  65. package/dist/chunk-7ARKUCQT.js.map +0 -1
  66. package/dist/chunk-DTDF6QDP.js.map +0 -1
  67. package/dist/chunk-EW54IRRS.js.map +0 -1
  68. package/dist/chunk-FE6OJV6O.js.map +0 -1
  69. package/dist/chunk-GVS2XXV6.js.map +0 -1
  70. package/dist/chunk-KURGXM4I.js.map +0 -1
  71. package/dist/chunk-MLX2BOJC.js.map +0 -1
  72. package/dist/chunk-NKAJPJ4G.js.map +0 -1
  73. package/dist/chunk-NNHKUXKA.js.map +0 -1
  74. package/dist/chunk-O3GVVND4.js.map +0 -1
  75. package/dist/chunk-ODL3SSPT.js.map +0 -1
  76. package/dist/chunk-PN52A5AA.js.map +0 -1
  77. package/dist/chunk-QFLDYKCR.js.map +0 -1
  78. package/dist/chunk-RFAPOKHJ.js.map +0 -1
  79. package/dist/chunk-RLU7UFYU.js.map +0 -1
  80. package/dist/chunk-SC67HYQJ.js.map +0 -1
  81. package/dist/chunk-SSUPBUF5.js.map +0 -1
  82. package/dist/chunk-U4MRIFKL.js.map +0 -1
  83. package/dist/chunk-UGYF5AZE.js +0 -275
  84. package/dist/chunk-UGYF5AZE.js.map +0 -1
  85. package/dist/chunk-WQSHGBLN.js.map +0 -1
  86. package/dist/chunk-YRT7GQ5Y.js +0 -28
  87. package/dist/chunk-YRT7GQ5Y.js.map +0 -1
  88. package/dist/container/index.js.map +0 -1
  89. package/dist/csv/index.js.map +0 -1
  90. package/dist/docx/index.js.map +0 -1
  91. package/dist/epub/index.js.map +0 -1
  92. package/dist/extract-OJ7ZQV6P.js +0 -15
  93. package/dist/extract-OJ7ZQV6P.js.map +0 -1
  94. package/dist/html/index.js.map +0 -1
  95. package/dist/images-7FBWPKE3.js +0 -7
  96. package/dist/images-7FBWPKE3.js.map +0 -1
  97. package/dist/index.js.map +0 -1
  98. package/dist/infer/index.js.map +0 -1
  99. package/dist/layouts-5VDIRPIJ.js +0 -12
  100. package/dist/layouts-5VDIRPIJ.js.map +0 -1
  101. package/dist/mapTheme-IR27S6IV.js.map +0 -1
  102. package/dist/ooxml/index.js.map +0 -1
  103. package/dist/pdf/index.js.map +0 -1
  104. package/dist/pptx/index.js.map +0 -1
  105. package/dist/registry/index.js.map +0 -1
  106. package/dist/xlsx/index.js.map +0 -1
  107. package/src/__tests__/container.test.ts +0 -230
  108. package/src/__tests__/convert.test.ts +0 -495
  109. package/src/__tests__/csvImport.test.ts +0 -84
  110. package/src/__tests__/docxExport.test.ts +0 -491
  111. package/src/__tests__/docxImport.test.ts +0 -531
  112. package/src/__tests__/epub.test.ts +0 -649
  113. package/src/__tests__/exportThemeReconciliation.test.ts +0 -87
  114. package/src/__tests__/formatRegistry.test.ts +0 -174
  115. package/src/__tests__/html.test.ts +0 -439
  116. package/src/__tests__/htmlImport.test.ts +0 -57
  117. package/src/__tests__/inferTheme.test.ts +0 -135
  118. package/src/__tests__/lossyWarnings.test.ts +0 -146
  119. package/src/__tests__/ooxml.test.ts +0 -271
  120. package/src/__tests__/ooxmlCancellation.test.ts +0 -113
  121. package/src/__tests__/ooxmlThemeReader.test.ts +0 -92
  122. package/src/__tests__/pdfExport.test.ts +0 -322
  123. package/src/__tests__/pdfImport.test.ts +0 -384
  124. package/src/__tests__/plainHtml.test.ts +0 -417
  125. package/src/__tests__/plainHtmlBundle.test.ts +0 -253
  126. package/src/__tests__/pptxExport.test.ts +0 -138
  127. package/src/__tests__/pptxImport.test.ts +0 -145
  128. package/src/__tests__/pptxInferFixtures.ts +0 -314
  129. package/src/__tests__/pptxLayoutInfer.test.ts +0 -395
  130. package/src/__tests__/roundTrip.test.ts +0 -201
  131. package/src/__tests__/roundTripAssets.test.ts +0 -50
  132. package/src/__tests__/roundTripMatrix.fixtures.ts +0 -86
  133. package/src/__tests__/roundTripMatrix.helpers.ts +0 -154
  134. package/src/__tests__/roundTripMatrix.test.ts +0 -142
  135. package/src/__tests__/sharedContainer.test.ts +0 -41
  136. package/src/__tests__/sharedImages.test.ts +0 -61
  137. package/src/__tests__/xlsxExport.test.ts +0 -164
  138. package/src/__tests__/xlsxImport.test.ts +0 -80
  139. package/src/__tests__/zipSafety.test.ts +0 -317
  140. package/src/container/index.ts +0 -94
  141. package/src/csv/index.ts +0 -188
  142. package/src/docx/export.ts +0 -1375
  143. package/src/docx/import.ts +0 -1250
  144. package/src/docx/index.ts +0 -26
  145. package/src/docx/styles.ts +0 -145
  146. package/src/epub/export.ts +0 -968
  147. package/src/epub/index.ts +0 -20
  148. package/src/html/docsHtmlBundle.ts +0 -373
  149. package/src/html/htmlTemplate.ts +0 -385
  150. package/src/html/imageUtils.ts +0 -61
  151. package/src/html/import.ts +0 -297
  152. package/src/html/index.ts +0 -212
  153. package/src/html/plainHtml.ts +0 -790
  154. package/src/html/plainHtmlBundle.ts +0 -421
  155. package/src/index.ts +0 -109
  156. package/src/infer/extract.ts +0 -127
  157. package/src/infer/index.ts +0 -199
  158. package/src/infer/mapTheme.ts +0 -176
  159. package/src/infer/types.ts +0 -27
  160. package/src/ooxml/index.ts +0 -111
  161. package/src/ooxml/namespaces.ts +0 -217
  162. package/src/ooxml/readUtils.ts +0 -44
  163. package/src/ooxml/reader.ts +0 -318
  164. package/src/ooxml/themeReader.ts +0 -197
  165. package/src/ooxml/types.ts +0 -103
  166. package/src/ooxml/writer.ts +0 -339
  167. package/src/ooxml/xmlUtils.ts +0 -123
  168. package/src/pdf/export.ts +0 -1084
  169. package/src/pdf/import.ts +0 -1164
  170. package/src/pdf/index.ts +0 -29
  171. package/src/pdf/styles.ts +0 -180
  172. package/src/pptx/export.ts +0 -1184
  173. package/src/pptx/import.ts +0 -455
  174. package/src/pptx/index.ts +0 -52
  175. package/src/pptx/layouts.ts +0 -1222
  176. package/src/pptx/styles.ts +0 -96
  177. package/src/pptx/templates.ts +0 -187
  178. package/src/registry/convert.ts +0 -433
  179. package/src/registry/defaultFormats.ts +0 -413
  180. package/src/registry/errors.ts +0 -46
  181. package/src/registry/index.ts +0 -43
  182. package/src/registry/registry.ts +0 -48
  183. package/src/registry/types.ts +0 -170
  184. package/src/shared/boundedZipArchive.ts +0 -383
  185. package/src/shared/container.ts +0 -28
  186. package/src/shared/fidelity.ts +0 -130
  187. package/src/shared/images.ts +0 -44
  188. package/src/shared/inlineRuns.ts +0 -99
  189. package/src/shared/text.ts +0 -41
  190. package/src/shared/zipEntryCount.ts +0 -151
  191. package/src/shared/zipLimits.ts +0 -296
  192. package/src/shared/zipSafety.ts +0 -19
  193. package/src/xlsx/export.ts +0 -253
  194. package/src/xlsx/import.ts +0 -160
  195. package/src/xlsx/index.ts +0 -35
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/registry/types.ts","../src/shared/fidelity.ts","../src/registry/defaultFormats.ts","../src/registry/registry.ts","../src/registry/convert.ts"],"sourcesContent":["/**\n * Format registry — shared types.\n *\n * The registry is the programmatic heart of `convert()`: it maps a small set of\n * format ids (`md`, `docx`, `pdf`, …) to `FormatDefinition`s, each of which\n * knows how to import to / export from squisq's markdown + Doc model. Every\n * converter module is loaded lazily via `import()` inside the definition\n * methods, so pulling in the registry never eagerly bundles heavy converters.\n */\n\nimport type { Doc, ThemeRegistry } from '@bendyline/squisq/schemas';\nimport type { TransformStyleInput, TransformStyleRegistry } from '@bendyline/squisq/transform';\nimport type { MarkdownDocument } from '@bendyline/squisq/markdown';\nimport type { ContentContainer } from '@bendyline/squisq/storage';\nimport type { ParseOptions, StringifyOptions } from '@bendyline/squisq/markdown';\nimport type { DocxExportOptions } from '../docx/export.js';\nimport type { DocxImportOptions } from '../docx/import.js';\nimport type { PptxExportOptions } from '../pptx/export.js';\nimport type { PptxImportOptions } from '../pptx/import.js';\nimport type { XlsxExportOptions } from '../xlsx/export.js';\nimport type { XlsxImportOptions } from '../xlsx/import.js';\nimport type { CsvExportOptions, CsvImportOptions } from '../csv/index.js';\nimport type { PdfExportOptions } from '../pdf/export.js';\nimport type { PdfImportOptions } from '../pdf/import.js';\nimport type { HtmlExportOptions } from '../html/htmlTemplate.js';\nimport type { HtmlImportOptions } from '../html/import.js';\nimport type { EpubExportOptions } from '../epub/export.js';\nimport type { ContainerToZipOptions } from '../container/index.js';\nimport type { ZipSafetyLimits } from '../shared/zipSafety.js';\n\n/** A format identifier (e.g. `'docx'`). Strings so hosts can register their own. */\nexport type FormatId = string;\n\n/** The built-in formats the default registry ships with. */\nexport const BUILTIN_FORMAT_IDS = [\n 'md',\n 'docx',\n 'pdf',\n 'pptx',\n 'xlsx',\n 'csv',\n 'html',\n 'htmlzip',\n 'epub',\n 'dbk',\n] as const;\n\n/** The bytes + metadata produced by a successful export. */\nexport interface ConversionResult {\n /** Encoded output bytes. */\n bytes: Uint8Array;\n /** MIME type of the output. */\n mimeType: string;\n /** A sensible download filename (`<baseName>.<ext>`). */\n suggestedFilename: string;\n /** Non-fatal notes accumulated during conversion (may be empty). */\n warnings: string[];\n}\n\nexport interface MarkdownFormatOptions {\n parse?: ParseOptions;\n stringify?: StringifyOptions;\n}\n\n/** Resource limits applied when importing a DBK/ZIP container. */\nexport type DbkFormatOptions = ZipSafetyLimits & ContainerToZipOptions;\n\n/**\n * Strongly typed option bags for built-in formats. Import and export options\n * share a bag because a single conversion may use the format on either side.\n * Custom registries may add arbitrary keys through the intersection used by\n * {@link ConvertOptions.formatOptions}.\n */\nexport interface BuiltinFormatOptions {\n md: MarkdownFormatOptions;\n docx: DocxImportOptions & DocxExportOptions;\n pptx: PptxImportOptions & PptxExportOptions;\n xlsx: XlsxImportOptions & XlsxExportOptions;\n csv: CsvImportOptions & CsvExportOptions;\n pdf: PdfImportOptions & PdfExportOptions;\n html: HtmlImportOptions & Partial<Omit<HtmlExportOptions, 'playerScript'>>;\n htmlzip: Partial<Omit<HtmlExportOptions, 'playerScript'>>;\n epub: EpubExportOptions;\n dbk: DbkFormatOptions;\n}\n\n/**\n * A source normalized into every shape an exporter might need. `doc` is always\n * present; `markdownDoc` is present when the source was markdown-shaped (an\n * exporter that wants markdown but finds none derives it from `doc`).\n */\nexport interface NormalizedInput {\n doc: Doc;\n markdownDoc?: MarkdownDocument;\n container: ContentContainer;\n baseName: string;\n}\n\n/** Options threaded through `convert()` and into every format method. */\nexport interface ConvertOptions {\n /** Cancel normalization, transformation, or export at the next bounded work boundary. */\n signal?: AbortSignal;\n /** Registry to resolve formats against. Defaults to `defaultRegistry()`. */\n registry?: FormatRegistry;\n /** Explicit source format id (skips extension/byte sniffing). */\n from?: FormatId;\n /** Theme id to apply to the exported document. */\n themeId?: string;\n /** Explicit caller-owned registry for non-document custom themes. */\n themeRegistry?: ThemeRegistry;\n /** Built-in/registry id or call-scoped style to apply before export. */\n transformStyle?: TransformStyleInput;\n /** Explicit caller-owned registry used to resolve transform style ids. */\n transformRegistry?: TransformStyleRegistry;\n /** Content-aware auto-templating when deriving a Doc from markdown. */\n autoTemplates?: boolean;\n /** Title hint for exporters that expose document metadata. */\n title?: string;\n /** Lazily resolve the standalone player IIFE bundle (required for HTML export). */\n resolvePlayerScript?: () => Promise<string>;\n /** Typed per-format options for built-ins; custom format ids remain extensible. */\n formatOptions?: Partial<BuiltinFormatOptions> & Record<FormatId, unknown>;\n}\n\n/** Target-only options accepted after a source has already been normalized and transformed. */\nexport type PreparedExportOptions = Pick<\n ConvertOptions,\n 'signal' | 'title' | 'resolvePlayerScript' | 'formatOptions'\n>;\n\n/**\n * An opaque normalized conversion snapshot. The source and transform pipeline\n * has already completed; each call exports that same snapshot to one target.\n */\nexport interface PreparedConversion {\n convert(to: FormatId, options?: PreparedExportOptions): Promise<ConversionResult>;\n}\n\n/** Describes how a single format imports to / exports from the squisq model. */\nexport interface FormatDefinition {\n id: FormatId;\n label: string;\n mimeType: string;\n extensions: readonly string[];\n /** Import raw bytes to a MarkdownDocument. */\n importDoc?(data: ArrayBuffer, options: ConvertOptions): Promise<MarkdownDocument>;\n /** Import raw bytes to a ContentContainer (markdown + extracted media). */\n importContainer?(data: ArrayBuffer, options: ConvertOptions): Promise<ContentContainer>;\n /** Export a normalized input to bytes. */\n exportDoc?(input: NormalizedInput, options: ConvertOptions): Promise<ConversionResult>;\n}\n\n/** A mutable collection of format definitions keyed by id. */\nexport interface FormatRegistry {\n register(def: FormatDefinition): void;\n get(id: FormatId): FormatDefinition | undefined;\n byExtension(ext: string): FormatDefinition | undefined;\n list(): FormatDefinition[];\n}\n\n/** The three shapes `convert()` accepts as a source. */\nexport type ConvertSource =\n | { kind: 'bytes'; data: ArrayBuffer | Uint8Array; filename?: string }\n | {\n kind: 'markdown';\n markdown: string | MarkdownDocument;\n container?: ContentContainer;\n baseName?: string;\n }\n | { kind: 'doc'; doc: Doc; container?: ContentContainer; baseName?: string };\n","/**\n * Shared Markdown fidelity reporting for exporters that intentionally support\n * only a subset of the core Markdown AST. Keeping the capability profiles in\n * one exhaustive table prevents each exporter from silently drifting as the\n * core AST grows.\n */\n\nimport type {\n MarkdownBlockNode,\n MarkdownDocument,\n MarkdownInlineNode,\n} from '@bendyline/squisq/markdown';\n\ntype ContentNodeType = MarkdownBlockNode['type'] | MarkdownInlineNode['type'];\nexport type MarkdownExportProfile = 'docx' | 'pdf' | 'pptx' | 'epub';\n\n/**\n * Exhaustive by construction: adding a Markdown node type in core makes this\n * package fail typechecking until its export fidelity is considered here.\n */\nconst CONTENT_NODE_TYPES: Record<ContentNodeType, true> = {\n heading: true,\n paragraph: true,\n blockquote: true,\n list: true,\n code: true,\n thematicBreak: true,\n table: true,\n htmlBlock: true,\n math: true,\n definition: true,\n footnoteDefinition: true,\n containerDirective: true,\n leafDirective: true,\n definitionList: true,\n text: true,\n emphasis: true,\n strong: true,\n delete: true,\n inlineCode: true,\n link: true,\n image: true,\n break: true,\n htmlInline: true,\n inlineMath: true,\n footnoteReference: true,\n linkReference: true,\n imageReference: true,\n textDirective: true,\n mention: true,\n inlineIcon: true,\n};\n\nconst COMMON_SUPPORTED: readonly ContentNodeType[] = [\n 'heading',\n 'paragraph',\n 'blockquote',\n 'list',\n 'code',\n 'thematicBreak',\n 'table',\n 'htmlBlock',\n 'math',\n 'text',\n 'emphasis',\n 'strong',\n 'delete',\n 'inlineCode',\n 'link',\n 'image',\n 'break',\n 'htmlInline',\n 'inlineMath',\n];\n\nconst PROFILE_SUPPORT: Record<MarkdownExportProfile, ReadonlySet<ContentNodeType>> = {\n docx: new Set([...COMMON_SUPPORTED, 'footnoteDefinition', 'footnoteReference']),\n pdf: new Set([...COMMON_SUPPORTED, 'footnoteDefinition', 'footnoteReference']),\n pptx: new Set(COMMON_SUPPORTED),\n epub: new Set(COMMON_SUPPORTED),\n};\n\nconst PROFILE_LABELS: Record<MarkdownExportProfile, string> = {\n docx: 'DOCX',\n pdf: 'PDF',\n pptx: 'PPTX',\n epub: 'EPUB',\n};\n\ninterface AstLikeNode {\n type?: string;\n children?: unknown;\n}\n\n/** Return a user-facing warning when an exporter will omit Markdown nodes. */\nexport function markdownFidelityWarnings(\n document: MarkdownDocument,\n profile: MarkdownExportProfile,\n): string[] {\n const supported = PROFILE_SUPPORT[profile];\n const omitted = new Map<ContentNodeType, number>();\n\n const visit = (candidate: unknown): void => {\n if (!candidate || typeof candidate !== 'object') return;\n const node = candidate as AstLikeNode;\n const type = node.type as ContentNodeType | undefined;\n\n if (type && Object.prototype.hasOwnProperty.call(CONTENT_NODE_TYPES, type)) {\n if (!supported.has(type)) {\n // The exporter drops this whole subtree, so report the highest-fidelity\n // boundary once instead of inflating the count with its descendants.\n omitted.set(type, (omitted.get(type) ?? 0) + 1);\n return;\n }\n }\n\n if (Array.isArray(node.children)) {\n for (const child of node.children) visit(child);\n }\n };\n\n for (const child of document.children) visit(child);\n if (omitted.size === 0) return [];\n\n const total = [...omitted.values()].reduce((sum, count) => sum + count, 0);\n const details = [...omitted].map(([type, count]) => `${type} (${count})`).join(', ');\n return [\n `${PROFILE_LABELS[profile]} export omitted ${total} unsupported Markdown node(s): ${details}.`,\n ];\n}\n","/**\n * Built-in format definitions.\n *\n * Each definition loads its converter module lazily via `import()` inside the\n * method body, so importing the registry never eagerly bundles a heavy\n * converter (pdf-lib, jszip, the OOXML writers, …). The capability of each\n * format — which of import/export it supports — is expressed purely by which\n * methods are present.\n */\n\nimport type { ContentContainer } from '@bendyline/squisq/storage';\nimport type { MarkdownDocument } from '@bendyline/squisq/markdown';\nimport { ConversionError } from './errors.js';\nimport { markdownFidelityWarnings } from '../shared/fidelity.js';\nimport type {\n ConversionResult,\n BuiltinFormatOptions,\n ConvertOptions,\n FormatDefinition,\n NormalizedInput,\n} from './types.js';\n\n// ── MIME constants ──────────────────────────────────────────────────\n\nconst MIME = {\n md: 'text/markdown',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n pdf: 'application/pdf',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n csv: 'text/csv',\n html: 'text/html',\n zip: 'application/zip',\n epub: 'application/epub+zip',\n} as const;\n\n// ── Small shared helpers ────────────────────────────────────────────\n\n/** Normalize any binary export return shape to Uint8Array. */\nasync function toBytes(data: ArrayBuffer | Uint8Array | Blob): Promise<Uint8Array> {\n if (data instanceof Uint8Array) return data;\n if (data instanceof ArrayBuffer) return new Uint8Array(data);\n // Blob. Prefer the modern arrayBuffer() method; fall back to FileReader for\n // environments (e.g. some jsdom builds) whose Blob lacks it.\n if (typeof data.arrayBuffer === 'function') {\n return new Uint8Array(await data.arrayBuffer());\n }\n const buffer = await new Promise<ArrayBuffer>((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as ArrayBuffer);\n reader.onerror = () => reject(reader.error);\n reader.readAsArrayBuffer(data);\n });\n return new Uint8Array(buffer);\n}\n\n/** The theme to apply: explicit option wins, then the doc's own theme. */\nfunction resolveThemeId(input: NormalizedInput, options: ConvertOptions): string | undefined {\n return options.themeId ?? input.doc.themeId;\n}\n\nfunction optionsFor<K extends keyof BuiltinFormatOptions>(\n options: ConvertOptions,\n id: K,\n): BuiltinFormatOptions[K] {\n return (options.formatOptions?.[id] ?? {}) as BuiltinFormatOptions[K];\n}\n\n/** The markdown shape an exporter needs — reuse the source's, else derive it. */\nasync function markdownOf(input: NormalizedInput): Promise<MarkdownDocument> {\n if (input.markdownDoc) return input.markdownDoc;\n const { docToMarkdown } = await import('@bendyline/squisq/doc');\n return docToMarkdown(input.doc);\n}\n\n/**\n * Collect image files from a container, keyed by both their container path and\n * their bare filename. Exporters that resolve by url (PPTX) and the standalone\n * player (HTML) both match against one of those two keys.\n */\nasync function collectContainerImages(\n container: ContentContainer,\n): Promise<Map<string, ArrayBuffer>> {\n const images = new Map<string, ArrayBuffer>();\n const files = await container.listFiles();\n for (const file of files) {\n if (!/\\.(jpg|jpeg|png|gif|webp|svg|bmp|avif)$/i.test(file.path)) continue;\n const data = await container.readFile(file.path);\n if (!data) continue;\n images.set(file.path, data);\n const slash = file.path.lastIndexOf('/');\n if (slash !== -1) images.set(file.path.slice(slash + 1), data);\n }\n return images;\n}\n\nasync function collectContainerDocxImages(\n container: ContentContainer,\n): Promise<Map<string, { data: ArrayBuffer; contentType: string }>> {\n const images = await collectContainerImages(container);\n const { extToMime } = await import('../shared/images.js');\n return new Map(\n [...images].map(([path, data]) => [\n path,\n { data, contentType: extToMime(path.split('.').pop() ?? '') },\n ]),\n );\n}\n\n/** Copy a container and make its primary document match the normalized source. */\nasync function snapshotContainerWithDocument(input: NormalizedInput): Promise<ContentContainer> {\n const { MemoryContentContainer } = await import('@bendyline/squisq/storage');\n const snapshot = new MemoryContentContainer();\n const entries = await input.container.listFiles();\n for (const entry of entries) {\n const data = await input.container.readFile(entry.path);\n if (data) await snapshot.writeFile(entry.path, new Uint8Array(data), entry.mimeType);\n }\n const { stringifyMarkdown } = await import('@bendyline/squisq/markdown');\n const documentPath = (await input.container.getDocumentPath()) ?? 'index.md';\n await snapshot.writeDocument(stringifyMarkdown(await markdownOf(input)), documentPath);\n return snapshot;\n}\n\n/** Resolve the player IIFE bundle or throw a helpful missing-dependency error. */\nasync function requirePlayerScript(options: ConvertOptions, format: string): Promise<string> {\n const script = await options.resolvePlayerScript?.();\n if (!script) {\n throw new ConversionError('missing-dependency', 'HTML export needs a player script.', {\n format,\n hint: \"pass resolvePlayerScript, e.g. () => import('@bendyline/squisq-react/standalone-source').then(m => m.PLAYER_BUNDLE)\",\n });\n }\n return script;\n}\n\nfunction ok(bytes: Uint8Array, mimeType: string, warnings: string[] = []): ConversionResult {\n // suggestedFilename is filled in by convert() once the baseName is known.\n return { bytes, mimeType, suggestedFilename: '', warnings };\n}\n\n/**\n * Narrow the untyped per-format escape hatch (`options.formatOptions.pptx`)\n * into the PPTX importer's options. Theme + layout inference default ON;\n * only an explicit `false` disables them.\n */\nfunction pptxImportOptionsFrom(options: ConvertOptions): BuiltinFormatOptions['pptx'] {\n const raw = optionsFor(options, 'pptx');\n return {\n ...raw,\n inferTheme: raw?.inferTheme !== false,\n inferLayouts: raw?.inferLayouts !== false,\n };\n}\n\n// ── Definitions ─────────────────────────────────────────────────────\n\nexport function defaultFormats(): FormatDefinition[] {\n const md: FormatDefinition = {\n id: 'md',\n label: 'Markdown',\n mimeType: MIME.md,\n extensions: ['.md', '.markdown'],\n async importDoc(data, options): Promise<MarkdownDocument> {\n const { parseMarkdown } = await import('@bendyline/squisq/markdown');\n return parseMarkdown(new TextDecoder().decode(data), optionsFor(options, 'md').parse);\n },\n async exportDoc(input, options): Promise<ConversionResult> {\n const { stringifyMarkdown } = await import('@bendyline/squisq/markdown');\n const text = stringifyMarkdown(await markdownOf(input), optionsFor(options, 'md').stringify);\n return ok(new TextEncoder().encode(text), MIME.md);\n },\n };\n\n const docx: FormatDefinition = {\n id: 'docx',\n label: 'Word (DOCX)',\n mimeType: MIME.docx,\n extensions: ['.docx'],\n async importContainer(data, options): Promise<ContentContainer> {\n const { docxToContainer } = await import('../docx/index.js');\n return docxToContainer(data, optionsFor(options, 'docx'));\n },\n async importDoc(data, options): Promise<MarkdownDocument> {\n const { docxToMarkdownDoc } = await import('../docx/index.js');\n return docxToMarkdownDoc(data, optionsFor(options, 'docx'));\n },\n async exportDoc(input, options): Promise<ConversionResult> {\n const { markdownDocToDocx } = await import('../docx/index.js');\n const raw = optionsFor(options, 'docx');\n const markdownDoc = await markdownOf(input);\n const containerImages = await collectContainerDocxImages(input.container);\n const images = new Map([...containerImages, ...(raw.images ?? new Map())]);\n const buf = await markdownDocToDocx(markdownDoc, {\n ...raw,\n ...(options.title !== undefined ? { title: options.title } : {}),\n themeId: resolveThemeId(input, options),\n themeRegistry: options.themeRegistry ?? raw.themeRegistry,\n images,\n });\n return ok(await toBytes(buf), MIME.docx, markdownFidelityWarnings(markdownDoc, 'docx'));\n },\n };\n\n const pdf: FormatDefinition = {\n id: 'pdf',\n label: 'PDF',\n mimeType: MIME.pdf,\n extensions: ['.pdf'],\n async importContainer(data, options): Promise<ContentContainer> {\n const { pdfToContainer } = await import('../pdf/index.js');\n return pdfToContainer(data, optionsFor(options, 'pdf'));\n },\n async importDoc(data, options): Promise<MarkdownDocument> {\n const { pdfToMarkdownDoc } = await import('../pdf/index.js');\n return pdfToMarkdownDoc(data, optionsFor(options, 'pdf'));\n },\n async exportDoc(input, options): Promise<ConversionResult> {\n const { markdownDocToPdf } = await import('../pdf/index.js');\n const raw = optionsFor(options, 'pdf');\n const markdownDoc = await markdownOf(input);\n const buf = await markdownDocToPdf(markdownDoc, {\n ...raw,\n ...(options.title !== undefined ? { title: options.title } : {}),\n themeId: resolveThemeId(input, options),\n themeRegistry: options.themeRegistry ?? raw.themeRegistry,\n });\n return ok(await toBytes(buf), MIME.pdf, markdownFidelityWarnings(markdownDoc, 'pdf'));\n },\n };\n\n const pptx: FormatDefinition = {\n id: 'pptx',\n label: 'PowerPoint (PPTX)',\n mimeType: MIME.pptx,\n extensions: ['.pptx'],\n async importContainer(data, options): Promise<ContentContainer> {\n const { pptxToContainer } = await import('../pptx/index.js');\n return pptxToContainer(data, pptxImportOptionsFrom(options));\n },\n async importDoc(data, options): Promise<MarkdownDocument> {\n const { pptxToMarkdownDoc } = await import('../pptx/index.js');\n return pptxToMarkdownDoc(data, pptxImportOptionsFrom(options));\n },\n async exportDoc(input, options): Promise<ConversionResult> {\n const { markdownDocToPptx } = await import('../pptx/index.js');\n const raw = optionsFor(options, 'pptx');\n const markdownDoc = await markdownOf(input);\n const containerImages = await collectContainerImages(input.container);\n const images = new Map([...containerImages, ...(raw.images ?? new Map())]);\n const buf = await markdownDocToPptx(markdownDoc, {\n ...raw,\n ...(options.title !== undefined ? { title: options.title } : {}),\n themeId: resolveThemeId(input, options),\n themeRegistry: options.themeRegistry ?? raw.themeRegistry,\n images,\n });\n return ok(await toBytes(buf), MIME.pptx, markdownFidelityWarnings(markdownDoc, 'pptx'));\n },\n };\n\n const xlsx: FormatDefinition = {\n id: 'xlsx',\n label: 'Excel (XLSX)',\n mimeType: MIME.xlsx,\n extensions: ['.xlsx'],\n async importDoc(data, options): Promise<MarkdownDocument> {\n const { xlsxToMarkdownDoc } = await import('../xlsx/index.js');\n return xlsxToMarkdownDoc(data, optionsFor(options, 'xlsx'));\n },\n async exportDoc(input, options): Promise<ConversionResult> {\n const { markdownDocToXlsx } = await import('../xlsx/index.js');\n const markdownDoc = await markdownOf(input);\n // XLSX fidelity is tables-only: `table` nodes become worksheets and\n // headings name them, but every other top-level block (prose, lists,\n // images, code, …) is dropped. Count those and warn honestly.\n const omitted = markdownDoc.children.filter(\n (n) => n.type !== 'table' && n.type !== 'heading',\n ).length;\n const warnings =\n omitted > 0\n ? [`XLSX export is tables-only; ${omitted} non-table block(s) were omitted.`]\n : [];\n const blob = await markdownDocToXlsx(markdownDoc, {\n ...optionsFor(options, 'xlsx'),\n ...(options.title !== undefined ? { title: options.title } : {}),\n });\n return ok(await toBytes(blob), MIME.xlsx, warnings);\n },\n };\n\n const csv: FormatDefinition = {\n id: 'csv',\n label: 'CSV',\n mimeType: MIME.csv,\n extensions: ['.csv'],\n async importDoc(data, options): Promise<MarkdownDocument> {\n const { csvToMarkdownDoc } = await import('../csv/index.js');\n return csvToMarkdownDoc(data, optionsFor(options, 'csv'));\n },\n async exportDoc(input, options): Promise<ConversionResult> {\n const { markdownDocToCsv } = await import('../csv/index.js');\n const markdownDoc = await markdownOf(input);\n const raw = optionsFor(options, 'csv');\n const tableCount = markdownDoc.children.filter((n) => n.type === 'table').length;\n const warnings: string[] = [];\n if (tableCount > 1 && raw.tableIndex === undefined) {\n warnings.push(\n `Document has ${tableCount} tables; CSV export emitted only the first. Use the csv converter's tableIndex option to select another.`,\n );\n }\n const text = markdownDocToCsv(markdownDoc, raw);\n return ok(new TextEncoder().encode(text), MIME.csv, warnings);\n },\n };\n\n const html: FormatDefinition = {\n id: 'html',\n label: 'HTML (single file)',\n mimeType: MIME.html,\n extensions: ['.html', '.htm'],\n async importDoc(data, options): Promise<MarkdownDocument> {\n const { htmlToMarkdownDoc } = await import('../html/index.js');\n return htmlToMarkdownDoc(data, optionsFor(options, 'html'));\n },\n // importContainer omitted: HTML import already inlines images as data URIs,\n // so there is nothing to extract into a container this wave.\n async exportDoc(input, options): Promise<ConversionResult> {\n const playerScript = await requirePlayerScript(options, 'html');\n const { docToHtml } = await import('../html/index.js');\n const raw = optionsFor(options, 'html');\n const containerImages = await collectContainerImages(input.container);\n const images = new Map([...containerImages, ...(raw.images ?? new Map())]);\n const htmlText = docToHtml(input.doc, {\n ...raw,\n playerScript,\n images,\n title: options.title ?? input.baseName,\n mode: raw.mode ?? 'static',\n themeId: resolveThemeId(input, options),\n themeRegistry: options.themeRegistry ?? raw.themeRegistry,\n });\n return ok(new TextEncoder().encode(htmlText), MIME.html);\n },\n };\n\n const htmlzip: FormatDefinition = {\n id: 'htmlzip',\n label: 'HTML (ZIP archive)',\n mimeType: MIME.zip,\n extensions: ['.html.zip'],\n async exportDoc(input, options): Promise<ConversionResult> {\n const playerScript = await requirePlayerScript(options, 'htmlzip');\n const { docToHtmlZip } = await import('../html/index.js');\n const raw = optionsFor(options, 'htmlzip');\n const containerImages = await collectContainerImages(input.container);\n const images = new Map([...containerImages, ...(raw.images ?? new Map())]);\n const blob = await docToHtmlZip(input.doc, {\n ...raw,\n playerScript,\n images,\n title: options.title ?? input.baseName,\n mode: raw.mode ?? 'static',\n themeId: resolveThemeId(input, options),\n themeRegistry: options.themeRegistry ?? raw.themeRegistry,\n });\n return ok(await toBytes(blob), MIME.zip);\n },\n };\n\n const epub: FormatDefinition = {\n id: 'epub',\n label: 'EPUB',\n mimeType: MIME.epub,\n extensions: ['.epub'],\n async exportDoc(input, options): Promise<ConversionResult> {\n const { markdownDocToEpub } = await import('../epub/index.js');\n const raw = optionsFor(options, 'epub');\n const markdownDoc = await markdownOf(input);\n const containerImages = await collectContainerImages(input.container);\n const images = new Map([...containerImages, ...(raw.images ?? new Map())]);\n const buf = await markdownDocToEpub(markdownDoc, {\n ...raw,\n title: options.title ?? input.baseName,\n themeId: resolveThemeId(input, options),\n themeRegistry: options.themeRegistry ?? raw.themeRegistry,\n images,\n });\n return ok(await toBytes(buf), MIME.epub, markdownFidelityWarnings(markdownDoc, 'epub'));\n },\n };\n\n const dbk: FormatDefinition = {\n id: 'dbk',\n label: 'Squisq container (DBK)',\n mimeType: MIME.zip,\n extensions: ['.dbk', '.zip'],\n async importContainer(data, options): Promise<ContentContainer> {\n const { zipToContainer } = await import('../container/index.js');\n return zipToContainer(data, optionsFor(options, 'dbk'));\n },\n async exportDoc(input, options): Promise<ConversionResult> {\n const { containerToZip } = await import('../container/index.js');\n const blob = await containerToZip(\n await snapshotContainerWithDocument(input),\n optionsFor(options, 'dbk'),\n );\n return ok(await toBytes(blob), MIME.zip);\n },\n };\n\n return [md, docx, pdf, pptx, xlsx, csv, html, htmlzip, epub, dbk];\n}\n","/**\n * Format registry implementation.\n *\n * `createRegistry()` returns an empty, mutable registry (last-write-wins by id);\n * `defaultRegistry()` returns one preloaded with every built-in format.\n */\n\nimport type { FormatDefinition, FormatId, FormatRegistry } from './types.js';\nimport { defaultFormats } from './defaultFormats.js';\n\n/** Normalize an extension to lowercase, without a leading dot. */\nfunction normalizeExt(ext: string): string {\n return ext.replace(/^\\.+/, '').toLowerCase();\n}\n\n/** Create an empty registry. Registering an existing id overwrites it. */\nexport function createRegistry(): FormatRegistry {\n const byId = new Map<FormatId, FormatDefinition>();\n\n return {\n register(def: FormatDefinition): void {\n byId.set(def.id, def);\n },\n get(id: FormatId): FormatDefinition | undefined {\n return byId.get(id);\n },\n byExtension(ext: string): FormatDefinition | undefined {\n const target = normalizeExt(ext);\n if (!target) return undefined;\n for (const def of byId.values()) {\n if (def.extensions.some((e) => normalizeExt(e) === target)) return def;\n }\n return undefined;\n },\n list(): FormatDefinition[] {\n return [...byId.values()];\n },\n };\n}\n\n/** Create a registry preloaded with all built-in formats. */\nexport function defaultRegistry(): FormatRegistry {\n const registry = createRegistry();\n for (const def of defaultFormats()) {\n registry.register(def);\n }\n return registry;\n}\n","/**\n * Programmatic `convert()` — the format-registry front door.\n *\n * Normalizes any {@link ConvertSource} into a {@link NormalizedInput} (always\n * yielding a `Doc`, keeping the `MarkdownDocument` when the source was\n * markdown-shaped, and always carrying a `ContentContainer` for media), applies\n * an optional transform, then hands off to the target format's exporter.\n */\n\nimport type { MarkdownDocument } from '@bendyline/squisq/markdown';\nimport type { ContentContainer } from '@bendyline/squisq/storage';\nimport type { TransformStyleInput, TransformStyleRegistry } from '@bendyline/squisq/transform';\nimport { ConversionError } from './errors.js';\nimport { defaultRegistry } from './registry.js';\nimport { openBoundedZipArchive, ZipSafetyError } from '../shared/zipSafety.js';\nimport type {\n BuiltinFormatOptions,\n ConversionResult,\n ConvertOptions,\n ConvertSource,\n FormatDefinition,\n FormatId,\n FormatRegistry,\n NormalizedInput,\n PreparedConversion,\n PreparedExportOptions,\n} from './types.js';\n\nfunction markdownFormatOptions(options: ConvertOptions): BuiltinFormatOptions['md'] {\n return (options.formatOptions?.md ?? {}) as BuiltinFormatOptions['md'];\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (!signal?.aborted) return;\n if (signal.reason !== undefined) throw signal.reason;\n const error = new Error('Document conversion was cancelled.');\n error.name = 'AbortError';\n throw error;\n}\n\n// ── Byte sniffing ───────────────────────────────────────────────────\n\nfunction hasPrefix(bytes: Uint8Array, prefix: number[]): boolean {\n if (bytes.length < prefix.length) return false;\n for (let i = 0; i < prefix.length; i++) {\n if (bytes[i] !== prefix[i]) return false;\n }\n return true;\n}\n\nconst ZIP_MAGIC = [0x50, 0x4b, 0x03, 0x04]; // \"PK\\x03\\x04\"\nconst PDF_MAGIC = [0x25, 0x50, 0x44, 0x46]; // \"%PDF\"\n\n/**\n * Disambiguate a ZIP-based file. OOXML formats (docx/pptx/xlsx) all carry a\n * `[Content_Types].xml` whose content-type strings name the flavor; a squisq\n * container (.dbk) is a plain ZIP with no such part, so absence of the OOXML\n * marker means `dbk`.\n */\nasync function sniffZip(bytes: Uint8Array): Promise<FormatId> {\n const archive = await openBoundedZipArchive(bytes).catch((cause: unknown) => {\n if (cause instanceof ZipSafetyError && cause.code !== 'invalid-archive') throw cause;\n throw new ConversionError('invalid-input', 'Input is not a readable ZIP archive.', { cause });\n });\n const contentTypes = archive.entries.find((entry) => entry.path === '[Content_Types].xml');\n if (!contentTypes) return 'dbk';\n const maxContentTypesBytes = 1024 * 1024;\n if ((contentTypes.declaredSize ?? 0) > maxContentTypesBytes) {\n throw new ConversionError('invalid-input', 'OOXML content-types metadata is too large.');\n }\n const xmlBytes = await archive.read(contentTypes.path, maxContentTypesBytes);\n if (!xmlBytes) return 'dbk';\n const xml = new TextDecoder().decode(xmlBytes);\n if (xml.includes('wordprocessingml')) return 'docx';\n if (xml.includes('presentationml')) return 'pptx';\n if (xml.includes('spreadsheetml')) return 'xlsx';\n return 'dbk';\n}\n\n/** Determine the source format for raw bytes. */\nasync function detectByteFormat(\n bytes: Uint8Array,\n filename: string | undefined,\n options: ConvertOptions,\n registry: FormatRegistry,\n): Promise<FormatId> {\n if (options.from) return options.from;\n\n const ext = filename ? extractExt(filename) : undefined;\n if (ext) {\n const byExt = registry.byExtension(ext);\n if (byExt) return byExt.id;\n }\n\n if (hasPrefix(bytes, PDF_MAGIC)) return 'pdf';\n if (hasPrefix(bytes, ZIP_MAGIC)) return sniffZip(bytes);\n\n // No magic and no recognized extension → assume UTF-8 markdown.\n return 'md';\n}\n\n// ── Filename helpers ────────────────────────────────────────────────\n\n/** Lowercased extension without the leading dot (`report.DocX` → `docx`). */\nfunction extractExt(filename: string): string {\n const normalized = filename.replace(/\\\\/g, '/');\n const base = normalized.split('/').pop() ?? normalized;\n const dot = base.lastIndexOf('.');\n if (dot <= 0) return '';\n return base.slice(dot + 1).toLowerCase();\n}\n\n/** Basename without its final extension (`a/b/report.docx` → `report`). */\nfunction baseNameOf(filename: string): string {\n const normalized = filename.replace(/\\\\/g, '/');\n const base = normalized.split('/').pop() ?? normalized;\n const dot = base.lastIndexOf('.');\n return dot > 0 ? base.slice(0, dot) : base;\n}\n\n// ── Normalization ───────────────────────────────────────────────────\n\ninterface Normalized {\n input: NormalizedInput;\n warnings: string[];\n}\n\nasync function normalizeBytes(\n source: Extract<ConvertSource, { kind: 'bytes' }>,\n options: ConvertOptions,\n registry: FormatRegistry,\n): Promise<Normalized> {\n const bytes = source.data instanceof Uint8Array ? source.data : new Uint8Array(source.data);\n const buffer = bytes.buffer.slice(\n bytes.byteOffset,\n bytes.byteOffset + bytes.byteLength,\n ) as ArrayBuffer;\n\n const fromId = await detectByteFormat(bytes, source.filename, options, registry);\n const fromDef = registry.get(fromId);\n if (!fromDef) {\n throw new ConversionError('unknown-format', `Unknown source format \"${fromId}\".`, {\n format: fromId,\n });\n }\n if (!fromDef.importContainer && !fromDef.importDoc) {\n throw new ConversionError(\n 'unsupported-input',\n `Format \"${fromDef.label}\" cannot be used as a conversion source.`,\n {\n format: fromId,\n hint: 'This format is export-only.',\n },\n );\n }\n\n const { markdownToDoc } = await import('@bendyline/squisq/doc');\n const { parseMarkdown, stringifyMarkdown } = await import('@bendyline/squisq/markdown');\n\n const warnings: string[] = [];\n let markdownDoc: MarkdownDocument;\n let container: ContentContainer;\n\n if (fromDef.importContainer) {\n container = await fromDef.importContainer(buffer, options);\n // PDF embedded-image extraction needs a browser canvas; under Node it's\n // skipped inside pdfToContainer. importContainer has no warnings channel of\n // its own, so surface that degraded path here where warnings are collected.\n if (fromDef.id === 'pdf' && typeof document === 'undefined') {\n warnings.push(\n 'PDF embedded images were skipped — image decoding requires a browser canvas (running under Node).',\n );\n }\n const text = await container.readDocument();\n markdownDoc = text\n ? parseMarkdown(text, markdownFormatOptions(options).parse)\n : { type: 'document', children: [] };\n } else {\n // importDoc is guaranteed present by the guard above.\n markdownDoc = await fromDef.importDoc!(buffer, options);\n const { MemoryContentContainer } = await import('@bendyline/squisq/storage');\n const mem = new MemoryContentContainer();\n await mem.writeDocument(stringifyMarkdown(markdownDoc));\n container = mem;\n }\n\n const doc = markdownToDoc(markdownDoc, { autoTemplates: options.autoTemplates });\n const baseName = source.filename ? baseNameOf(source.filename) : 'document';\n\n return {\n input: { doc, markdownDoc, container, baseName },\n warnings,\n };\n}\n\nasync function normalizeMarkdown(\n source: Extract<ConvertSource, { kind: 'markdown' }>,\n options: ConvertOptions,\n): Promise<Normalized> {\n const { markdownToDoc } = await import('@bendyline/squisq/doc');\n const { parseMarkdown } = await import('@bendyline/squisq/markdown');\n\n const { stringifyMarkdown } = await import('@bendyline/squisq/markdown');\n\n const markdownDoc =\n typeof source.markdown === 'string'\n ? parseMarkdown(source.markdown, markdownFormatOptions(options).parse)\n : source.markdown;\n\n let container = source.container;\n if (!container) {\n // Seed a fresh container with the document so container-backed exports\n // (dbk) and media resolution have the markdown to serialize.\n const { MemoryContentContainer } = await import('@bendyline/squisq/storage');\n const mem = new MemoryContentContainer();\n await mem.writeDocument(stringifyMarkdown(markdownDoc));\n container = mem;\n }\n\n const doc = markdownToDoc(markdownDoc, { autoTemplates: options.autoTemplates });\n const baseName = source.baseName ?? 'document';\n\n return { input: { doc, markdownDoc, container, baseName }, warnings: [] };\n}\n\nasync function normalizeDoc(source: Extract<ConvertSource, { kind: 'doc' }>): Promise<Normalized> {\n let container = source.container;\n if (!container) {\n const { MemoryContentContainer } = await import('@bendyline/squisq/storage');\n const { docToMarkdown } = await import('@bendyline/squisq/doc');\n const { stringifyMarkdown } = await import('@bendyline/squisq/markdown');\n const mem = new MemoryContentContainer();\n await mem.writeDocument(stringifyMarkdown(docToMarkdown(source.doc)));\n container = mem;\n }\n const baseName = source.baseName ?? 'document';\n // markdownDoc is intentionally omitted — exporters derive it lazily via docToMarkdown.\n return { input: { doc: source.doc, container, baseName }, warnings: [] };\n}\n\nasync function normalize(\n source: ConvertSource,\n options: ConvertOptions,\n registry: FormatRegistry,\n): Promise<Normalized> {\n switch (source.kind) {\n case 'bytes':\n return normalizeBytes(source, options, registry);\n case 'markdown':\n return normalizeMarkdown(source, options);\n case 'doc':\n return normalizeDoc(source);\n }\n}\n\n// ── Transform ───────────────────────────────────────────────────────\n\nasync function applyTransformStyle(\n input: NormalizedInput,\n transformStyle: TransformStyleInput,\n themeId?: string,\n registry?: TransformStyleRegistry,\n): Promise<string[]> {\n const { applyTransform, extractDocImages } = await import('@bendyline/squisq/transform');\n const { docToMarkdown, markdownToDoc } = await import('@bendyline/squisq/doc');\n const images = extractDocImages(input.doc.blocks);\n const result = applyTransform(input.doc, transformStyle, { themeId, images, registry });\n input.doc = result.doc;\n const markdownDoc = docToMarkdown(result.doc);\n input.markdownDoc = markdownDoc;\n\n // Lossy-path detection: transforms can emit template blocks whose data lives\n // in template inputs rather than in round-trippable markdown `contents`, so\n // `docToMarkdown` silently drops them. Re-parse with auto-templating off (so\n // the comparison stays ~1:1 and isn't confused by content-aware promotion)\n // and compare block counts. Best-effort — most blocks carry `contents` and\n // round-trip fine, so this only fires on a genuine collapse.\n const roundTripped = markdownToDoc(markdownDoc, { autoTemplates: false });\n if (roundTripped.blocks.length < result.doc.blocks.length) {\n return [\n 'Transform produced blocks that don’t round-trip to markdown; export may be incomplete.',\n ];\n }\n return [];\n}\n\n// ── prepare / convert ───────────────────────────────────────────────\n\n/** Normalize and transform a source once, then safely export that snapshot many times. */\nexport async function prepareConversion(\n source: ConvertSource,\n options: ConvertOptions = {},\n): Promise<PreparedConversion> {\n return prepareConversionInternal(source, options);\n}\n\nasync function prepareConversionInternal(\n source: ConvertSource,\n options: ConvertOptions,\n failureFormat?: FormatId,\n): Promise<PreparedConversion> {\n throwIfAborted(options.signal);\n const registry = options.registry ?? defaultRegistry();\n\n let normalized: Normalized;\n try {\n normalized = await normalize(source, options, registry);\n throwIfAborted(options.signal);\n } catch (err: unknown) {\n throwIfAborted(options.signal);\n if (err instanceof ConversionError) throw err;\n const message = err instanceof Error ? err.message : String(err);\n throw new ConversionError('invalid-input', message, {\n format: options.from,\n cause: err,\n });\n }\n const { input, warnings } = normalized;\n\n // Respect an existing doc theme; only fill it in from options when absent.\n if (options.themeId && !input.doc.themeId) {\n input.doc = { ...input.doc, themeId: options.themeId };\n }\n\n try {\n if (options.transformStyle) {\n warnings.push(\n ...(await applyTransformStyle(\n input,\n options.transformStyle,\n options.themeId ?? input.doc.themeId,\n options.transformRegistry,\n )),\n );\n throwIfAborted(options.signal);\n }\n } catch (err: unknown) {\n throwIfAborted(options.signal);\n if (err instanceof ConversionError) throw err;\n const message = err instanceof Error ? err.message : String(err);\n throw new ConversionError('conversion-failed', message, {\n format: failureFormat,\n cause: err,\n });\n }\n\n const preparedWarnings = Object.freeze([...warnings]);\n const preparedInput = { ...input };\n return Object.freeze({\n async convert(to: FormatId, targetOptions: PreparedExportOptions = {}) {\n const target = requireExportTarget(registry, to);\n const exportOptions = mergePreparedExportOptions(options, targetOptions);\n throwIfAborted(exportOptions.signal);\n let result: ConversionResult;\n try {\n result = await target.exportDoc!({ ...preparedInput }, exportOptions);\n throwIfAborted(exportOptions.signal);\n } catch (err: unknown) {\n throwIfAborted(exportOptions.signal);\n if (err instanceof ConversionError) throw err;\n const message = err instanceof Error ? err.message : String(err);\n throw new ConversionError('conversion-failed', message, { format: to, cause: err });\n }\n\n const ext = target.extensions[0]?.replace(/^\\.+/, '') ?? to;\n return {\n ...result,\n suggestedFilename: `${preparedInput.baseName}.${ext}`,\n warnings: [...preparedWarnings, ...result.warnings],\n };\n },\n });\n}\n\nfunction requireExportTarget(registry: FormatRegistry, to: FormatId): FormatDefinition {\n const target = registry.get(to);\n if (!target) {\n throw new ConversionError('unknown-format', `Unknown target format \"${to}\".`, { format: to });\n }\n if (!target.exportDoc) {\n throw new ConversionError(\n 'unsupported-output',\n `Format \"${target.label}\" does not support export.`,\n { format: to, hint: 'This format is import-only.' },\n );\n }\n return target;\n}\n\nfunction mergePreparedExportOptions(\n prepared: ConvertOptions,\n target: PreparedExportOptions,\n): ConvertOptions {\n return {\n ...prepared,\n signal: mergeAbortSignals(prepared.signal, target.signal),\n title: target.title ?? prepared.title,\n resolvePlayerScript: target.resolvePlayerScript ?? prepared.resolvePlayerScript,\n formatOptions:\n target.formatOptions === undefined\n ? prepared.formatOptions\n : { ...(prepared.formatOptions ?? {}), ...target.formatOptions },\n };\n}\n\nfunction mergeAbortSignals(\n preparedSignal?: AbortSignal,\n targetSignal?: AbortSignal,\n): AbortSignal | undefined {\n if (!preparedSignal) return targetSignal;\n if (!targetSignal || preparedSignal === targetSignal) return preparedSignal;\n return AbortSignal.any([preparedSignal, targetSignal]);\n}\n\n/**\n * Convert a source document to a target format.\n *\n * @param source - A bytes / markdown / doc source.\n * @param to - The target format id (must be registered and support export).\n * @param options - Conversion options (registry, theme, transform, …).\n * @throws {@link ConversionError} on any failure, with a stable `code`.\n */\nexport async function convert(\n source: ConvertSource,\n to: FormatId,\n options: ConvertOptions = {},\n): Promise<ConversionResult> {\n throwIfAborted(options.signal);\n const registry = options.registry ?? defaultRegistry();\n requireExportTarget(registry, to);\n const prepared = await prepareConversionInternal(source, { ...options, registry }, to);\n return prepared.convert(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AAI,CAAC,eAAgB,QAAO;AAC5B,MAAI,CAAC,gBAAgB,mBAAmB,aAAc,QAAO;AAC7D,SAAO,YAAY,IAAI,CAAC,gBAAgB,YAAY,CAAC;AACvD;AAUA,eAAsB,QACpB,QACA,IACA,UAA0B,CAAC,GACA;AAC3B,iBAAe,QAAQ,MAAM;AAC7B,QAAM,WAAW,QAAQ,YAAY,gBAAgB;AACrD,sBAAoB,UAAU,EAAE;AAChC,QAAM,WAAW,MAAM,0BAA0B,QAAQ,EAAE,GAAG,SAAS,SAAS,GAAG,EAAE;AACrF,SAAO,SAAS,QAAQ,EAAE;AAC5B;","names":["document"]}
@@ -1,28 +0,0 @@
1
- // src/ooxml/readUtils.ts
2
- function attrNS(el, ns, local, qualified) {
3
- return el.getAttributeNS(ns, local) ?? el.getAttribute(qualified);
4
- }
5
- function baseDirOf(path) {
6
- const slash = path.lastIndexOf("/");
7
- return slash === -1 ? "" : path.slice(0, slash);
8
- }
9
- function resolveTarget(baseDir, target) {
10
- if (target.startsWith("/")) return target.replace(/^\//, "");
11
- const stack = baseDir ? baseDir.split("/") : [];
12
- for (const seg of target.split("/")) {
13
- if (seg === "..") stack.pop();
14
- else if (seg !== ".") stack.push(seg);
15
- }
16
- return stack.join("/");
17
- }
18
- function findRelByType(rels, type) {
19
- return rels.find((r) => r.type === type);
20
- }
21
-
22
- export {
23
- attrNS,
24
- baseDirOf,
25
- resolveTarget,
26
- findRelByType
27
- };
28
- //# sourceMappingURL=chunk-YRT7GQ5Y.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/ooxml/readUtils.ts"],"sourcesContent":["/**\n * Shared DOM-read helpers for OOXML importers.\n *\n * Every importer walks parts with `getElementsByTagNameNS` and resolves\n * relationship targets relative to the referencing part; these helpers hold\n * the common pieces so new readers (theme, slide layouts) don't re-implement\n * them per format.\n */\n\nimport type { Relationship } from './types.js';\n\n/**\n * Read a namespaced attribute with a qualified-name fallback for documents\n * whose producer omitted the namespace declaration (e.g. `r:id`).\n */\nexport function attrNS(el: Element, ns: string, local: string, qualified: string): string | null {\n return el.getAttributeNS(ns, local) ?? el.getAttribute(qualified);\n}\n\n/** Directory portion of a part path, e.g. `ppt/slides/slide1.xml` → `ppt/slides`. */\nexport function baseDirOf(path: string): string {\n const slash = path.lastIndexOf('/');\n return slash === -1 ? '' : path.slice(0, slash);\n}\n\n/**\n * Resolve a relationship target against the referencing part's directory.\n * Absolute targets (leading `/`) are package-rooted; relative targets may\n * climb with `..` segments (e.g. `../slideLayouts/slideLayout1.xml`).\n */\nexport function resolveTarget(baseDir: string, target: string): string {\n if (target.startsWith('/')) return target.replace(/^\\//, '');\n const stack = baseDir ? baseDir.split('/') : [];\n for (const seg of target.split('/')) {\n if (seg === '..') stack.pop();\n else if (seg !== '.') stack.push(seg);\n }\n return stack.join('/');\n}\n\n/** First relationship of the given type, if any. */\nexport function findRelByType(rels: Relationship[], type: string): Relationship | undefined {\n return rels.find((r) => r.type === type);\n}\n"],"mappings":";AAeO,SAAS,OAAO,IAAa,IAAY,OAAe,WAAkC;AAC/F,SAAO,GAAG,eAAe,IAAI,KAAK,KAAK,GAAG,aAAa,SAAS;AAClE;AAGO,SAAS,UAAU,MAAsB;AAC9C,QAAM,QAAQ,KAAK,YAAY,GAAG;AAClC,SAAO,UAAU,KAAK,KAAK,KAAK,MAAM,GAAG,KAAK;AAChD;AAOO,SAAS,cAAc,SAAiB,QAAwB;AACrE,MAAI,OAAO,WAAW,GAAG,EAAG,QAAO,OAAO,QAAQ,OAAO,EAAE;AAC3D,QAAM,QAAQ,UAAU,QAAQ,MAAM,GAAG,IAAI,CAAC;AAC9C,aAAW,OAAO,OAAO,MAAM,GAAG,GAAG;AACnC,QAAI,QAAQ,KAAM,OAAM,IAAI;AAAA,aACnB,QAAQ,IAAK,OAAM,KAAK,GAAG;AAAA,EACtC;AACA,SAAO,MAAM,KAAK,GAAG;AACvB;AAGO,SAAS,cAAc,MAAsB,MAAwC;AAC1F,SAAO,KAAK,KAAK,CAAC,MAAM,EAAE,SAAS,IAAI;AACzC;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/container/index.ts"],"sourcesContent":["/**\n * Container ZIP serialization — convert between ContentContainer and ZIP archives.\n *\n * Uses JSZip (already a formats dependency) to serialize a ContentContainer to\n * a ZIP blob and to deserialize a ZIP blob into a MemoryContentContainer.\n *\n * ZIP structure mirrors the container's flat path hierarchy directly:\n * index.md\n * images/hero.jpg\n * audio/narration.mp3\n * timing.json\n */\n\nimport JSZip from 'jszip';\nimport type { ContentContainer } from '@bendyline/squisq/storage';\nimport { MemoryContentContainer } from '@bendyline/squisq/storage';\nimport {\n assertSafeZipPath,\n openBoundedZipArchive,\n ZipSafetyError,\n type ZipSafetyLimits,\n type ZipSafetyErrorCode,\n type ZipSafetyErrorOptions,\n} from '../shared/zipSafety.js';\n\nexport type ZipToContainerOptions = ZipSafetyLimits;\nexport interface ContainerToZipOptions {\n /** STORE avoids producing archives that violate strict import compression-ratio policies. */\n compression?: 'STORE' | 'DEFLATE';\n /** JSZip DEFLATE level; ignored for STORE. */\n compressionLevel?: number;\n}\nexport { ZipSafetyError };\nexport type { ZipSafetyLimits, ZipSafetyErrorCode, ZipSafetyErrorOptions };\n\n/**\n * Serialize a ContentContainer to a ZIP blob.\n *\n * All files in the container are written to the ZIP archive preserving\n * their path structure. The resulting blob can be saved as a .zip file.\n *\n * @param container — The container to serialize\n * @returns A Blob containing the ZIP archive\n */\nexport async function containerToZip(\n container: ContentContainer,\n options: ContainerToZipOptions = {},\n): Promise<Blob> {\n const zip = new JSZip();\n const entries = await container.listFiles();\n\n for (const entry of entries) {\n assertSafeZipPath(entry.path);\n const data = await container.readFile(entry.path);\n if (data) {\n zip.file(entry.path, new Uint8Array(data));\n }\n }\n\n const compression = options.compression ?? 'DEFLATE';\n const compressionLevel = options.compressionLevel ?? 6;\n if (!Number.isSafeInteger(compressionLevel) || compressionLevel < 1 || compressionLevel > 9) {\n throw new Error('ZIP compression level must be an integer between 1 and 9');\n }\n return zip.generateAsync({\n type: 'blob',\n compression,\n ...(compression === 'DEFLATE' ? { compressionOptions: { level: compressionLevel } } : {}),\n });\n}\n\n/**\n * Deserialize a ZIP archive into a MemoryContentContainer.\n *\n * Reads all files from the ZIP and writes them into a new MemoryContentContainer.\n * Directory entries are skipped. The resulting container can be used immediately\n * for rendering, editing, or saving to persistent storage.\n *\n * @param zipData — The ZIP archive as ArrayBuffer, Uint8Array, or Blob\n * @returns A MemoryContentContainer populated with the ZIP's contents\n */\nexport async function zipToContainer(\n zipData: ArrayBuffer | Uint8Array | Blob,\n options: ZipToContainerOptions = {},\n): Promise<MemoryContentContainer> {\n const archive = await openBoundedZipArchive(zipData, options);\n const container = new MemoryContentContainer();\n for (const { path } of archive.entries) {\n const data = await archive.read(path);\n if (data) await container.writeFile(path, data);\n archive.release(path);\n }\n return container;\n}\n"],"mappings":";;;;;;;AAaA,OAAO,WAAW;AAElB,SAAS,8BAA8B;AA6BvC,eAAsB,eACpB,WACA,UAAiC,CAAC,GACnB;AACf,QAAM,MAAM,IAAI,MAAM;AACtB,QAAM,UAAU,MAAM,UAAU,UAAU;AAE1C,aAAW,SAAS,SAAS;AAC3B,sBAAkB,MAAM,IAAI;AAC5B,UAAM,OAAO,MAAM,UAAU,SAAS,MAAM,IAAI;AAChD,QAAI,MAAM;AACR,UAAI,KAAK,MAAM,MAAM,IAAI,WAAW,IAAI,CAAC;AAAA,IAC3C;AAAA,EACF;AAEA,QAAM,cAAc,QAAQ,eAAe;AAC3C,QAAM,mBAAmB,QAAQ,oBAAoB;AACrD,MAAI,CAAC,OAAO,cAAc,gBAAgB,KAAK,mBAAmB,KAAK,mBAAmB,GAAG;AAC3F,UAAM,IAAI,MAAM,0DAA0D;AAAA,EAC5E;AACA,SAAO,IAAI,cAAc;AAAA,IACvB,MAAM;AAAA,IACN;AAAA,IACA,GAAI,gBAAgB,YAAY,EAAE,oBAAoB,EAAE,OAAO,iBAAiB,EAAE,IAAI,CAAC;AAAA,EACzF,CAAC;AACH;AAYA,eAAsB,eACpB,SACA,UAAiC,CAAC,GACD;AACjC,QAAM,UAAU,MAAM,sBAAsB,SAAS,OAAO;AAC5D,QAAM,YAAY,IAAI,uBAAuB;AAC7C,aAAW,EAAE,KAAK,KAAK,QAAQ,SAAS;AACtC,UAAM,OAAO,MAAM,QAAQ,KAAK,IAAI;AACpC,QAAI,KAAM,OAAM,UAAU,UAAU,MAAM,IAAI;AAC9C,YAAQ,QAAQ,IAAI;AAAA,EACtB;AACA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,15 +0,0 @@
1
- import {
2
- extractDocxTheme,
3
- extractPptxTheme,
4
- extractXlsxTheme
5
- } from "./chunk-74GO3FVS.js";
6
- import "./chunk-SC67HYQJ.js";
7
- import "./chunk-YRT7GQ5Y.js";
8
- import "./chunk-7ARKUCQT.js";
9
- import "./chunk-FE6OJV6O.js";
10
- export {
11
- extractDocxTheme,
12
- extractPptxTheme,
13
- extractXlsxTheme
14
- };
15
- //# sourceMappingURL=extract-OJ7ZQV6P.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,7 +0,0 @@
1
- import {
2
- extToMime
3
- } from "./chunk-O3GVVND4.js";
4
- export {
5
- extToMime
6
- };
7
- //# sourceMappingURL=images-7FBWPKE3.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,12 +0,0 @@
1
- import {
2
- analyzePptxLayouts,
3
- inspectPptxLayouts
4
- } from "./chunk-QFLDYKCR.js";
5
- import "./chunk-YRT7GQ5Y.js";
6
- import "./chunk-7ARKUCQT.js";
7
- import "./chunk-FE6OJV6O.js";
8
- export {
9
- analyzePptxLayouts,
10
- inspectPptxLayouts
11
- };
12
- //# sourceMappingURL=layouts-5VDIRPIJ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,230 +0,0 @@
1
- /**
2
- * Tests for container ZIP serialization: containerToZip, zipToContainer.
3
- *
4
- * Verifies round-trip fidelity: write files to a container, serialize to ZIP,
5
- * deserialize back, and confirm all files are intact.
6
- */
7
-
8
- import { describe, it, expect } from 'vitest';
9
- import JSZip from 'jszip';
10
- import { MemoryContentContainer } from '@bendyline/squisq/storage';
11
- import { containerToZip, zipToContainer } from '../container/index';
12
-
13
- // ============================================
14
- // Helpers
15
- // ============================================
16
-
17
- /** Helper to read a Blob as ArrayBuffer (works in jsdom) */
18
- async function blobToArrayBuffer(blob: Blob): Promise<ArrayBuffer> {
19
- return new Promise((resolve, reject) => {
20
- const reader = new FileReader();
21
- reader.onload = () => resolve(reader.result as ArrayBuffer);
22
- reader.onerror = () => reject(reader.error);
23
- reader.readAsArrayBuffer(blob);
24
- });
25
- }
26
-
27
- // ============================================
28
- // containerToZip
29
- // ============================================
30
-
31
- describe('containerToZip', () => {
32
- it('creates a valid ZIP from an empty container', async () => {
33
- const container = new MemoryContentContainer();
34
- const blob = await containerToZip(container);
35
- expect(blob).toBeInstanceOf(Blob);
36
- expect(blob.size).toBeGreaterThan(0);
37
-
38
- // Should be parseable as a ZIP with no files
39
- const zip = await JSZip.loadAsync(await blobToArrayBuffer(blob));
40
- expect(Object.keys(zip.files)).toHaveLength(0);
41
- });
42
-
43
- it('includes all files from the container', async () => {
44
- const container = new MemoryContentContainer();
45
- await container.writeDocument('# Hello World');
46
- await container.writeFile('images/hero.jpg', new Uint8Array([0xff, 0xd8, 0xff]), 'image/jpeg');
47
- await container.writeFile('timing.json', new TextEncoder().encode('{"duration":10}'));
48
-
49
- const blob = await containerToZip(container);
50
- const zip = await JSZip.loadAsync(await blobToArrayBuffer(blob));
51
-
52
- const filenames = Object.keys(zip.files)
53
- .filter((f) => !zip.files[f].dir)
54
- .sort();
55
- expect(filenames).toEqual(['images/hero.jpg', 'index.md', 'timing.json']);
56
- });
57
-
58
- it('preserves file content', async () => {
59
- const container = new MemoryContentContainer();
60
- const markdown = '# Test Document\n\nSome content.';
61
- await container.writeDocument(markdown);
62
-
63
- const blob = await containerToZip(container);
64
- const zip = await JSZip.loadAsync(await blobToArrayBuffer(blob));
65
-
66
- const content = await zip.file('index.md')!.async('string');
67
- expect(content).toBe(markdown);
68
- });
69
-
70
- it('preserves binary content', async () => {
71
- const container = new MemoryContentContainer();
72
- const binaryData = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
73
- await container.writeFile('image.png', binaryData, 'image/png');
74
-
75
- const blob = await containerToZip(container);
76
- const zip = await JSZip.loadAsync(await blobToArrayBuffer(blob));
77
-
78
- const data = await zip.file('image.png')!.async('uint8array');
79
- expect(data).toEqual(binaryData);
80
- });
81
-
82
- it('refuses to create a ZIP with an unsafe container path', async () => {
83
- const container = new MemoryContentContainer();
84
- await container.writeFile('../outside.txt', new TextEncoder().encode('nope'));
85
-
86
- await expect(containerToZip(container)).rejects.toThrow(/path is unsafe/i);
87
- });
88
- });
89
-
90
- // ============================================
91
- // zipToContainer
92
- // ============================================
93
-
94
- describe('zipToContainer', () => {
95
- it('loads files from a ZIP', async () => {
96
- const zip = new JSZip();
97
- zip.file('index.md', '# Hello');
98
- zip.file('images/photo.jpg', new Uint8Array([0xff, 0xd8]));
99
- const zipBlob = await zip.generateAsync({ type: 'blob' });
100
-
101
- const container = await zipToContainer(zipBlob);
102
- const entries = await container.listFiles();
103
- expect(entries.map((e) => e.path).sort()).toEqual(['images/photo.jpg', 'index.md']);
104
- });
105
-
106
- it('preserves text content', async () => {
107
- const zip = new JSZip();
108
- zip.file('index.md', '# My Document\n\nParagraph.');
109
- const zipBlob = await zip.generateAsync({ type: 'blob' });
110
-
111
- const container = await zipToContainer(zipBlob);
112
- expect(await container.readDocument()).toBe('# My Document\n\nParagraph.');
113
- });
114
-
115
- it('preserves binary content', async () => {
116
- const original = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
117
- const zip = new JSZip();
118
- zip.file('data.bin', original);
119
- const zipBlob = await zip.generateAsync({ type: 'blob' });
120
-
121
- const container = await zipToContainer(zipBlob);
122
- const data = await container.readFile('data.bin');
123
- expect(new Uint8Array(data!)).toEqual(original);
124
- });
125
-
126
- it('skips directory entries', async () => {
127
- const zip = new JSZip();
128
- zip.folder('images');
129
- zip.file('images/photo.jpg', new Uint8Array([0xff]));
130
- const zipBlob = await zip.generateAsync({ type: 'blob' });
131
-
132
- const container = await zipToContainer(zipBlob);
133
- const entries = await container.listFiles();
134
- // Only the file, not the directory
135
- expect(entries).toHaveLength(1);
136
- expect(entries[0].path).toBe('images/photo.jpg');
137
- });
138
-
139
- it('works with ArrayBuffer input', async () => {
140
- const zip = new JSZip();
141
- zip.file('readme.md', '# Read me');
142
- const ab = await zip.generateAsync({ type: 'arraybuffer' });
143
-
144
- const container = await zipToContainer(ab);
145
- expect(await container.readDocument()).toBe('# Read me');
146
- });
147
-
148
- it('rejects archives that exceed the configured entry limit', async () => {
149
- const zip = new JSZip();
150
- zip.file('one.txt', '1');
151
- zip.file('two.txt', '2');
152
- const data = await zip.generateAsync({ type: 'arraybuffer' });
153
- await expect(zipToContainer(data, { maxEntries: 1 })).rejects.toThrow(/archive has 2 files/);
154
- });
155
-
156
- it('rejects archives that exceed the configured uncompressed byte limit', async () => {
157
- const zip = new JSZip();
158
- zip.file('large.txt', '12345');
159
- const data = await zip.generateAsync({ type: 'arraybuffer' });
160
- await expect(zipToContainer(data, { maxUncompressedBytes: 4 })).rejects.toThrow(
161
- /uncompressed content exceeds 4 byte limit/,
162
- );
163
- });
164
-
165
- it('rejects traversal paths even when JSZip sanitizes their loaded key', async () => {
166
- const zip = new JSZip();
167
- zip.file('../outside.txt', 'nope');
168
- const data = await zip.generateAsync({ type: 'arraybuffer' });
169
-
170
- await expect(zipToContainer(data)).rejects.toThrow(/unsafe path.*\.\.\/outside\.txt/i);
171
- });
172
-
173
- it('rejects absolute and Windows-style archive paths', async () => {
174
- for (const path of ['/absolute.txt', 'C:\\outside.txt']) {
175
- const zip = new JSZip();
176
- zip.file(path, 'nope');
177
- const data = await zip.generateAsync({ type: 'arraybuffer' });
178
- await expect(zipToContainer(data)).rejects.toThrow(/unsafe path/i);
179
- }
180
- });
181
- });
182
-
183
- // ============================================
184
- // Round-trip
185
- // ============================================
186
-
187
- describe('containerToZip / zipToContainer round-trip', () => {
188
- it('round-trips a container with markdown and media', async () => {
189
- // Create original container
190
- const original = new MemoryContentContainer();
191
- const markdown = '# Round Trip Test\n\n![hero](images/hero.jpg)\n\nSome text.';
192
- await original.writeDocument(markdown);
193
- await original.writeFile(
194
- 'images/hero.jpg',
195
- new Uint8Array([0xff, 0xd8, 0xff, 0xe0]),
196
- 'image/jpeg',
197
- );
198
- await original.writeFile(
199
- 'audio/narration.mp3',
200
- new Uint8Array([0x49, 0x44, 0x33]),
201
- 'audio/mpeg',
202
- );
203
- await original.writeFile('timing.json', new TextEncoder().encode('{"segments":[]}'));
204
-
205
- // Serialize to ZIP
206
- const zipBlob = await containerToZip(original);
207
-
208
- // Deserialize back
209
- const restored = await zipToContainer(zipBlob);
210
-
211
- // Verify document
212
- expect(await restored.readDocument()).toBe(markdown);
213
- expect(await restored.getDocumentPath()).toBe('index.md');
214
-
215
- // Verify all files present
216
- const entries = (await restored.listFiles()).map((e) => e.path).sort();
217
- expect(entries).toEqual(['audio/narration.mp3', 'images/hero.jpg', 'index.md', 'timing.json']);
218
-
219
- // Verify binary content
220
- const heroData = new Uint8Array((await restored.readFile('images/hero.jpg'))!);
221
- expect(heroData).toEqual(new Uint8Array([0xff, 0xd8, 0xff, 0xe0]));
222
-
223
- const audioData = new Uint8Array((await restored.readFile('audio/narration.mp3'))!);
224
- expect(audioData).toEqual(new Uint8Array([0x49, 0x44, 0x33]));
225
-
226
- // Verify JSON sidecar
227
- const timingData = new TextDecoder().decode((await restored.readFile('timing.json'))!);
228
- expect(timingData).toBe('{"segments":[]}');
229
- });
230
- });