@bendyline/squisq 1.5.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 (268) hide show
  1. package/README.md +63 -10
  2. package/dist/{Doc-BBVGq1_9.d.ts → Doc-ylqWKDc_.d.ts} +248 -37
  3. package/dist/{ImageEditDoc-FuyGtt6o.d.ts → ImageEditDoc-D828IXJ1.d.ts} +1 -1
  4. package/dist/annotationCoercion-Dr_DY9Hx.d.ts +86 -0
  5. package/dist/{chunk-T5UK6YOB.js → chunk-2PWOO4ZE.js} +60 -17
  6. package/dist/chunk-2PWOO4ZE.js.map +1 -0
  7. package/dist/{chunk-VWUFZ6ZG.js → chunk-3E5F2XMR.js} +2 -29
  8. package/dist/chunk-3E5F2XMR.js.map +1 -0
  9. package/dist/chunk-4X3JQXNM.js +35 -0
  10. package/dist/chunk-4X3JQXNM.js.map +1 -0
  11. package/dist/{chunk-P3K7NLHF.js → chunk-5DKBFXPY.js} +31 -121
  12. package/dist/chunk-5DKBFXPY.js.map +1 -0
  13. package/dist/{chunk-DLXZMS5K.js → chunk-5J4HKRJF.js} +51 -3
  14. package/dist/chunk-5J4HKRJF.js.map +1 -0
  15. package/dist/chunk-5UYI3RJB.js +2503 -0
  16. package/dist/chunk-5UYI3RJB.js.map +1 -0
  17. package/dist/{chunk-BEQODJWV.js → chunk-66QO7XFB.js} +11 -291
  18. package/dist/chunk-66QO7XFB.js.map +1 -0
  19. package/dist/{chunk-HWVFJAAH.js → chunk-AMIR72JP.js} +28 -10
  20. package/dist/chunk-AMIR72JP.js.map +1 -0
  21. package/dist/chunk-CY2R2VPR.js +884 -0
  22. package/dist/chunk-CY2R2VPR.js.map +1 -0
  23. package/dist/chunk-FVJUUTEM.js +74 -0
  24. package/dist/chunk-FVJUUTEM.js.map +1 -0
  25. package/dist/{chunk-Q3ROPT5H.js → chunk-GZY66SDN.js} +1 -1
  26. package/dist/{chunk-Q3ROPT5H.js.map → chunk-GZY66SDN.js.map} +1 -1
  27. package/dist/chunk-JOQYPRDZ.js +127 -0
  28. package/dist/chunk-JOQYPRDZ.js.map +1 -0
  29. package/dist/{chunk-A4O7GIWE.js → chunk-MMPBOUK7.js} +10 -73
  30. package/dist/chunk-MMPBOUK7.js.map +1 -0
  31. package/dist/{chunk-LDQ2HJIX.js → chunk-PXLVXTLW.js} +252 -54
  32. package/dist/chunk-PXLVXTLW.js.map +1 -0
  33. package/dist/{chunk-TQWLI6S2.js → chunk-Q7LROV2H.js} +4 -2
  34. package/dist/{chunk-TQWLI6S2.js.map → chunk-Q7LROV2H.js.map} +1 -1
  35. package/dist/{chunk-GPLTCSXO.js → chunk-R2GC6RLD.js} +7 -7
  36. package/dist/chunk-R2GC6RLD.js.map +1 -0
  37. package/dist/chunk-R2YZTCLO.js +292 -0
  38. package/dist/chunk-R2YZTCLO.js.map +1 -0
  39. package/dist/chunk-S7A5D7ZJ.js +174 -0
  40. package/dist/chunk-S7A5D7ZJ.js.map +1 -0
  41. package/dist/chunk-TFJVXUHH.js +2358 -0
  42. package/dist/chunk-TFJVXUHH.js.map +1 -0
  43. package/dist/{chunk-LTN6I7QW.js → chunk-TUWMK62B.js} +55 -4
  44. package/dist/chunk-TUWMK62B.js.map +1 -0
  45. package/dist/{chunk-IMSCRLLV.js → chunk-VR7UPJ7C.js} +35 -25
  46. package/dist/chunk-VR7UPJ7C.js.map +1 -0
  47. package/dist/{chunk-KKNUBQ6Y.js → chunk-W4O2TX5I.js} +157 -92
  48. package/dist/chunk-W4O2TX5I.js.map +1 -0
  49. package/dist/{chunk-5TYS5V3G.js → chunk-X6DUONGT.js} +4204 -3560
  50. package/dist/chunk-X6DUONGT.js.map +1 -0
  51. package/dist/doc/index.d.ts +2334 -5
  52. package/dist/doc/index.js +127 -33
  53. package/dist/generate/index.d.ts +7 -2
  54. package/dist/generate/index.js +1 -1
  55. package/dist/imageEdit/index.d.ts +9 -6
  56. package/dist/imageEdit/index.js +3 -3
  57. package/dist/index.d.ts +12 -10
  58. package/dist/index.js +246 -80
  59. package/dist/jsonForm/index.d.ts +7 -3
  60. package/dist/jsonForm/index.js +9 -4
  61. package/dist/markdown/index.d.ts +6 -70
  62. package/dist/markdown/index.js +13 -9
  63. package/dist/narration/index.d.ts +618 -0
  64. package/dist/narration/index.js +82 -0
  65. package/dist/recommend/index.d.ts +15 -1
  66. package/dist/recommend/index.js +2 -2
  67. package/dist/schemas/index.d.ts +28 -6
  68. package/dist/schemas/index.js +15 -13
  69. package/dist/spatial/index.d.ts +0 -1
  70. package/dist/spatial/index.js +1 -1
  71. package/dist/storage/index.js +1 -1
  72. package/dist/{themeLibrary-CehcJhzz.d.ts → themeLibrary-RjVgLpUi.d.ts} +10 -11
  73. package/dist/timing/index.js +5 -3
  74. package/dist/transform/index.d.ts +35 -24
  75. package/dist/transform/index.js +9 -10
  76. package/dist/{types-DlAZ7MW4.d.ts → types-BwMPl2CB.d.ts} +1 -1
  77. package/dist/{types-D98li1gV.d.ts → types-C4kiRn_k.d.ts} +3 -1
  78. package/dist/versions/index.d.ts +2 -1
  79. package/dist/versions/index.js +2 -2
  80. package/package.json +6 -6
  81. package/src/__tests__/applyNarrationTiming.test.ts +190 -0
  82. package/src/__tests__/applyRenderStyle.test.ts +3 -3
  83. package/src/__tests__/asciiDiagramBattle.test.ts +246 -0
  84. package/src/__tests__/asciiDiagramDetect.test.ts +162 -0
  85. package/src/__tests__/asciiDiagramMapping.test.ts +38 -0
  86. package/src/__tests__/asciiDiagramParse.test.ts +233 -0
  87. package/src/__tests__/asciiDiagramPipeline.test.ts +273 -0
  88. package/src/__tests__/asciiDiagramRender.test.ts +162 -0
  89. package/src/__tests__/asciiDiagramRepair.test.ts +84 -0
  90. package/src/__tests__/asciiTimelineDetect.test.ts +157 -0
  91. package/src/__tests__/asciiTimelineParse.test.ts +205 -0
  92. package/src/__tests__/asciiTimelinePipeline.test.ts +349 -0
  93. package/src/__tests__/asciiTimelineRender.test.ts +376 -0
  94. package/src/__tests__/attrTokens.test.ts +5 -0
  95. package/src/__tests__/contentContainer.test.ts +43 -0
  96. package/src/__tests__/customTemplatesFrontmatter.test.ts +0 -15
  97. package/src/__tests__/customThemesFrontmatter.test.ts +1 -0
  98. package/src/__tests__/dataTable.test.ts +25 -15
  99. package/src/__tests__/diagramBlock.test.ts +3 -3
  100. package/src/__tests__/diagramText.test.ts +26 -0
  101. package/src/__tests__/docToMarkdownMedia.test.ts +83 -0
  102. package/src/__tests__/drawingBlock.test.ts +3 -3
  103. package/src/__tests__/fixtures/asciiDiagramBattle.ts +512 -0
  104. package/src/__tests__/fixtures/asciiDiagrams.ts +287 -0
  105. package/src/__tests__/fixtures/asciiTimelines.ts +35 -0
  106. package/src/__tests__/fixtures/treeviewFixtures.ts +243 -0
  107. package/src/__tests__/getLayers.test.ts +32 -18
  108. package/src/__tests__/getLayersFallback.test.ts +8 -8
  109. package/src/__tests__/imageEditVersions.test.ts +2 -0
  110. package/src/__tests__/jsonForm.pointer.test.ts +47 -1
  111. package/src/__tests__/layoutBlock.test.ts +3 -3
  112. package/src/__tests__/majorApiTypes.test.ts +18 -0
  113. package/src/__tests__/markdown.test.ts +54 -4
  114. package/src/__tests__/markdownSanitize.test.ts +7 -5
  115. package/src/__tests__/matchFontFamily.test.ts +114 -0
  116. package/src/__tests__/materializeBlockLayers.test.ts +135 -0
  117. package/src/__tests__/materializeTestUtils.ts +17 -0
  118. package/src/__tests__/narrationAlign.test.ts +150 -0
  119. package/src/__tests__/narrationFeatures.test.ts +71 -0
  120. package/src/__tests__/narrationNuclei.test.ts +45 -0
  121. package/src/__tests__/narrationPacing.test.ts +189 -0
  122. package/src/__tests__/narrationScript.test.ts +149 -0
  123. package/src/__tests__/narrationSessionRepro.test.ts +62 -0
  124. package/src/__tests__/narrationSidecar.test.ts +88 -0
  125. package/src/__tests__/narrationSyllables.test.ts +65 -0
  126. package/src/__tests__/narrationTestSignals.ts +167 -0
  127. package/src/__tests__/narrationVad.test.ts +66 -0
  128. package/src/__tests__/resolveDocTheme.test.ts +16 -2
  129. package/src/__tests__/rootExports.test.ts +18 -0
  130. package/src/__tests__/scopedContentContainer.test.ts +20 -0
  131. package/src/__tests__/shapeGeometry.test.ts +12 -0
  132. package/src/__tests__/templateAnnotationParse.test.ts +10 -0
  133. package/src/__tests__/templateInputs.test.ts +69 -0
  134. package/src/__tests__/templateMetadata.test.ts +2 -1
  135. package/src/__tests__/templates.test.ts +143 -17
  136. package/src/__tests__/themeCompile.test.ts +49 -22
  137. package/src/__tests__/transformProvenance.test.ts +160 -0
  138. package/src/__tests__/transformV2.test.ts +40 -14
  139. package/src/__tests__/treeviewBattle.test.ts +76 -0
  140. package/src/__tests__/treeviewDetect.test.ts +168 -0
  141. package/src/__tests__/treeviewParse.test.ts +118 -0
  142. package/src/__tests__/treeviewPipeline.test.ts +183 -0
  143. package/src/__tests__/treeviewRender.test.ts +91 -0
  144. package/src/__tests__/versions.test.ts +44 -0
  145. package/src/doc/applyNarrationTiming.ts +244 -0
  146. package/src/doc/asciiDiagram/chars.ts +210 -0
  147. package/src/doc/asciiDiagram/detect.ts +175 -0
  148. package/src/doc/asciiDiagram/index.ts +38 -0
  149. package/src/doc/asciiDiagram/mapping.ts +225 -0
  150. package/src/doc/asciiDiagram/parse.ts +1095 -0
  151. package/src/doc/asciiDiagram/render.ts +963 -0
  152. package/src/doc/asciiDiagram/repair.ts +400 -0
  153. package/src/doc/asciiDiagram/types.ts +65 -0
  154. package/src/doc/asciiTimeline/detect.ts +138 -0
  155. package/src/doc/asciiTimeline/index.ts +26 -0
  156. package/src/doc/asciiTimeline/mapping.ts +43 -0
  157. package/src/doc/asciiTimeline/parse.ts +870 -0
  158. package/src/doc/asciiTimeline/render.ts +427 -0
  159. package/src/doc/asciiTimeline/types.ts +73 -0
  160. package/src/doc/asciiTimeline/wrappedFlow.ts +427 -0
  161. package/src/doc/audioMapping.ts +60 -46
  162. package/src/doc/customTemplatesFrontmatter.ts +0 -41
  163. package/src/doc/docToMarkdown.ts +70 -2
  164. package/src/doc/index.ts +76 -4
  165. package/src/doc/markdownToDoc.ts +138 -2
  166. package/src/doc/materializeBlockLayers.ts +304 -0
  167. package/src/doc/mediaAnnotations.ts +20 -0
  168. package/src/doc/resolveDocTheme.ts +8 -7
  169. package/src/doc/templateInputs.ts +185 -2
  170. package/src/doc/templates/__tests__/customTemplateRegistry.test.ts +22 -8
  171. package/src/doc/templates/__tests__/listBlock.test.ts +64 -0
  172. package/src/doc/templates/diagramBlock.ts +237 -38
  173. package/src/doc/templates/fallbackBlock.ts +1 -1
  174. package/src/doc/templates/index.ts +134 -279
  175. package/src/doc/templates/inputDescriptors.ts +20 -1
  176. package/src/doc/templates/listBlock.ts +88 -30
  177. package/src/doc/templates/metadata.ts +10 -0
  178. package/src/doc/templates/persistentLayers.ts +12 -126
  179. package/src/doc/templates/registry.ts +88 -0
  180. package/src/doc/templates/templateNames.ts +22 -0
  181. package/src/doc/templates/timelineBlock.ts +613 -0
  182. package/src/doc/templates/treeBlock.ts +131 -0
  183. package/src/doc/treeview/chars.ts +72 -0
  184. package/src/doc/treeview/detect.ts +145 -0
  185. package/src/doc/treeview/index.ts +30 -0
  186. package/src/doc/treeview/mapping.ts +95 -0
  187. package/src/doc/treeview/parse.ts +201 -0
  188. package/src/doc/treeview/render.ts +41 -0
  189. package/src/doc/treeview/types.ts +43 -0
  190. package/src/doc/utils/applyRenderStyle.ts +2 -9
  191. package/src/doc/utils/diagramText.ts +78 -0
  192. package/src/doc/utils/shapeGeometry.ts +67 -5
  193. package/src/doc/validate.ts +1 -1
  194. package/src/generate/templateMapper.ts +7 -0
  195. package/src/imageEdit/export.ts +6 -5
  196. package/src/imageEdit/versionPaths.ts +13 -26
  197. package/src/imageEdit/versions.ts +21 -100
  198. package/src/index.ts +1 -0
  199. package/src/internal/immutable.ts +58 -0
  200. package/src/jsonForm/index.ts +9 -1
  201. package/src/jsonForm/pointer.ts +68 -23
  202. package/src/markdown/attrTokens.ts +7 -5
  203. package/src/markdown/index.ts +1 -0
  204. package/src/markdown/stringify.ts +4 -9
  205. package/src/markdown/utils.ts +36 -14
  206. package/src/narration/align.ts +514 -0
  207. package/src/narration/features.ts +231 -0
  208. package/src/narration/index.ts +86 -0
  209. package/src/narration/nuclei.ts +118 -0
  210. package/src/narration/pacing.ts +211 -0
  211. package/src/narration/script.ts +239 -0
  212. package/src/narration/session.ts +100 -0
  213. package/src/narration/sidecar.ts +187 -0
  214. package/src/narration/syllables.ts +85 -0
  215. package/src/narration/trace.ts +50 -0
  216. package/src/narration/types.ts +299 -0
  217. package/src/narration/vad.ts +131 -0
  218. package/src/recommend/numberHighlight.ts +25 -0
  219. package/src/recommend/templates.ts +108 -12
  220. package/src/schemas/BlockTemplates.ts +156 -7
  221. package/src/schemas/Doc.ts +72 -9
  222. package/src/schemas/Media.ts +12 -2
  223. package/src/schemas/Theme.ts +45 -25
  224. package/src/schemas/Viewport.ts +2 -2
  225. package/src/schemas/fontStacks.ts +79 -0
  226. package/src/schemas/themeCompile.ts +15 -0
  227. package/src/schemas/themeConstants.ts +2 -0
  228. package/src/schemas/themeLibrary.ts +25 -19
  229. package/src/schemas/themeValidator.ts +1 -1
  230. package/src/schemas/themes/gezellig.json +1 -1
  231. package/src/spatial/Geohash.ts +0 -3
  232. package/src/storage/ContentContainer.ts +17 -9
  233. package/src/storage/ScopedContentContainer.ts +45 -15
  234. package/src/transform/applyTransform.ts +5 -5
  235. package/src/transform/index.ts +3 -1
  236. package/src/transform/registry.ts +169 -49
  237. package/src/transform/templateSelector.ts +21 -2
  238. package/src/transform/timingAllocator.ts +152 -21
  239. package/src/transform/types.ts +14 -1
  240. package/src/versions/gitignore.ts +34 -0
  241. package/src/versions/index.ts +2 -0
  242. package/src/versions/operations.ts +18 -104
  243. package/src/versions/paths.ts +13 -28
  244. package/src/versions/snapshotStore.ts +202 -0
  245. package/src/versions/types.ts +3 -1
  246. package/dist/chunk-5TYS5V3G.js.map +0 -1
  247. package/dist/chunk-A4O7GIWE.js.map +0 -1
  248. package/dist/chunk-BEQODJWV.js.map +0 -1
  249. package/dist/chunk-DLXZMS5K.js.map +0 -1
  250. package/dist/chunk-GPLTCSXO.js.map +0 -1
  251. package/dist/chunk-HWVFJAAH.js.map +0 -1
  252. package/dist/chunk-IMSCRLLV.js.map +0 -1
  253. package/dist/chunk-JELIRVDP.js +0 -24
  254. package/dist/chunk-JELIRVDP.js.map +0 -1
  255. package/dist/chunk-KKNUBQ6Y.js.map +0 -1
  256. package/dist/chunk-LDQ2HJIX.js.map +0 -1
  257. package/dist/chunk-LTN6I7QW.js.map +0 -1
  258. package/dist/chunk-P3K7NLHF.js.map +0 -1
  259. package/dist/chunk-T5UK6YOB.js.map +0 -1
  260. package/dist/chunk-UY7KGQ5R.js +0 -192
  261. package/dist/chunk-UY7KGQ5R.js.map +0 -1
  262. package/dist/chunk-VLJJHDAC.js +0 -218
  263. package/dist/chunk-VLJJHDAC.js.map +0 -1
  264. package/dist/chunk-VWUFZ6ZG.js.map +0 -1
  265. package/dist/story/index.d.ts +0 -1801
  266. package/dist/story/index.js +0 -279
  267. package/src/doc/getLayers.ts +0 -195
  268. /package/dist/{story → narration}/index.js.map +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schemas/Doc.ts","../src/schemas/themeCompile.ts"],"sourcesContent":["/**\n * Doc Schema\n *\n * Defines the JSON format for AI-scriptable visual docs that accompany\n * audio narration. A Doc describes a sequence of animated blocks\n * with text overlays, images, and transitions synchronized to audio.\n *\n * The format is designed to be:\n * 1. AI-generatable - Claude can create scripts from article content\n * 2. Browser-renderable - SVG + CSS animations (ES2015 compatible)\n * 3. Video-exportable - Frame-by-frame capture via Playwright\n *\n * Timing: Blocks are timed to match narration audio segments. Each article\n * has 3-6 MP3 files (intro + sections), and blocks are grouped by segment.\n */\n\nimport type { Transition } from './Transitions.js';\nexport type { Transition, TransitionType, TransitionDirection } from './Transitions.js';\n\n// ============================================\n// Core Types\n// ============================================\n\n/**\n * A directed connection from one block to another.\n *\n * Populated from a heading's Pandoc-style `{connectsTo=…}` attribute\n * (e.g. `## Step 1 {#step1 connectsTo=foo:flow,bar}`). Each item is\n * `target` or `target:type`. Used by diagram-style layouts that draw\n * edges between blocks.\n */\nexport interface BlockConnection {\n /** Target block id (matches another block's `id`). */\n target: string;\n /** Optional connection type/label (e.g., \"flow\", \"requires\"). */\n type?: string;\n}\n\n/**\n * Configuration for the Start/resting block shown before playback begins.\n */\nexport interface StartBlockConfig {\n /** Hero image path (relative to article media). When omitted, a theme-driven background is used. */\n heroSrc?: string;\n /** Alt text for the hero image */\n heroAlt?: string;\n /** Title to display over the hero */\n title: string;\n /** Optional subtitle */\n subtitle?: string;\n /** Ambient motion for the hero image */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n /** Photo credit / artist name for the hero image */\n heroCredit?: string;\n /** License identifier for the hero image */\n heroLicense?: string;\n}\n\n/**\n * A structural problem detected while converting or validating a document.\n *\n * Diagnostics ride on `Doc.diagnostics` so any consumer — the editor, the\n * CLI `validate` command, or an agent re-parsing its own output — gets the\n * same feedback without watching the console. Conversion never throws for\n * content problems; it degrades gracefully and records a diagnostic.\n */\nexport interface DocDiagnostic {\n /** `error` = the author's intent could not be honored (e.g. unparseable\n * data fence); `warning` = something looks wrong but rendering proceeds\n * with a fallback (e.g. unknown template name); `info` = nothing is\n * broken, but the author may want to know (e.g. a redundant annotation). */\n severity: 'error' | 'warning' | 'info';\n /** Stable machine-readable code (e.g. `unknown-template`, `duplicate-id`,\n * `unresolved-connection`, `data-fence-parse`, `missing-asset`). */\n code: string;\n /** Human-readable description, including a suggestion when one exists. */\n message: string;\n /** Id of the block the problem belongs to, when attributable. */\n blockId?: string;\n /** 1-based line number in the markdown source, when known. */\n line?: number;\n}\n\n/**\n * A complete visual doc for an article.\n */\nexport interface Doc {\n /** Article ID this doc belongs to */\n articleId: string;\n\n /** Total duration in seconds (sum of all audio segments) */\n duration: number;\n\n /** Ordered list of blocks */\n blocks: Block[];\n\n /** Audio track configuration */\n audio: AudioTrack;\n\n /** Caption track for closed captions (generated by postprocess-doc) */\n captions?: CaptionTrack;\n\n /**\n * Start/resting block shown before playback begins.\n * Displays hero image with title - acts as a \"poster\" for the doc.\n * The player shows this until the user starts playback.\n */\n startBlock?: StartBlockConfig;\n\n /**\n * Persistent layers rendered on every block (behind and/or on top of content).\n * Used for consistent branding overlays, background gradients, etc.\n */\n persistentLayers?: import('./BlockTemplates.js').PersistentLayerConfig;\n\n /**\n * Optional theme identifier. Resolved at render time via `resolveTheme()`.\n * When omitted, the renderer uses the default theme ('documentary').\n */\n themeId?: string;\n\n /** Optional metadata */\n meta?: {\n generatedAt?: string;\n generatedBy?: string;\n version?: number;\n };\n\n /**\n * YAML frontmatter from the source markdown.\n * Carries rendering hints like `document-render-as` and custom metadata.\n */\n frontmatter?: Record<string, unknown>;\n\n /**\n * User-defined block templates inlined into this doc.\n *\n * Populated from the markdown frontmatter key\n * `squisq-custom-templates`. The template-expansion pipeline\n * (`expandDocBlocks` in `doc/templates/index.ts`) merges these into\n * the registry before walking blocks, so a heading annotated\n * `{[myhero]}` resolves against a doc-defined template named `myhero`.\n *\n * Library templates (stored in localStorage on the editor side) are\n * NOT auto-loaded here — applying a library template to a block\n * copies its definition into this list so the doc remains\n * self-sufficient for SSR and export.\n */\n customTemplates?: import('./CustomTemplates.js').CustomTemplateDefinition[];\n\n /**\n * User-defined themes inlined into this doc.\n *\n * The theme analog of {@link Doc.customTemplates}. Populated from the\n * markdown frontmatter key `squisq-custom-themes`. Exactly one is active\n * at a time — selected by id via `squisq-theme` / {@link Doc.themeId},\n * the doc-level counterpart of a block's `{[name]}` template annotation —\n * but the payload is a list so a doc can carry a small catalog and stay\n * self-sufficient for SSR / export. `resolveThemeForDoc(doc, id)` resolves\n * against this list first (pure, doc-scoped) before built-ins, mirroring\n * how `buildRegistry` resolves custom templates.\n */\n customThemes?: import('./Theme.js').Theme[];\n\n /**\n * Structural problems found while building this doc (unknown templates,\n * unparseable data fences, duplicate ids, unresolved connections, …).\n * Populated by `markdownToDoc()`; extended by `validateMarkdownDoc()`.\n * Absent when the document is clean.\n */\n diagnostics?: DocDiagnostic[];\n\n /**\n * Document-spanning timed media (e.g. a full-length narration MP3/MP4),\n * authored as a media annotation in the preamble (before the first\n * heading) with `anchor=document`. Each clip is timed from the document\n * start and may play across every block. See `resolveMediaSchedule`.\n */\n documentMedia?: import('./Media.js').MediaClip[];\n}\n\n/**\n * A single block in the doc.\n *\n * Blocks can be flat (audio-synced timeline) or nested (markdown-driven hierarchy).\n * When derived from markdown, a block corresponds to a heading section:\n * - `sourceHeading` references the original MarkdownHeading node\n * - `contents` holds the body markdown between this heading and the next\n * - `children` holds sub-heading blocks (e.g., H2s under an H1)\n *\n * Four adjacent fields carry template information — do not confuse them:\n * - `template` — the *resolved* template id this block renders with.\n * - `templateOverrides` — raw `{[…]}` inline params (always strings).\n * - `templateData` — structured inputs from a data fence / GFM table\n * (parsed types, not strings).\n * - `sourceAnnotation.template` — the raw *requested* template name for a\n * standalone-annotation block (before alias resolution).\n * Merge order at render time: template defaults → `templateData` →\n * `templateOverrides`.\n */\nexport interface Block {\n /** Unique identifier for this block.\n * Defaults to a slug derived from the heading text. May be overridden by\n * a Pandoc-style `{#custom-id}` attribute on the heading. */\n id: string;\n\n /** When this block appears (seconds from start).\n * Overridden by a heading attribute `startTime=…` when present. */\n startTime: number;\n\n /** How long this block is visible (seconds).\n * Overridden by a heading attribute `duration=…` when present. */\n duration: number;\n\n /** Which audio segment this block belongs to (0-indexed) */\n audioSegment: number;\n\n /**\n * Transform provenance: the source block id this block was derived\n * from (see `BaseTemplateBlock.sourceBlockId`). Present on blocks a\n * transform produced; lets a persisted transformed Doc keep its typed\n * link back to the source content.\n */\n sourceBlockId?: string;\n /** All source block ids when this block summarizes several. */\n sourceBlockIds?: string[];\n /** Char offset of the extraction inside the source block's plain text. */\n sourceCharOffset?: number;\n\n /**\n * Pre-computed visual layers, rendered back-to-front.\n *\n * Optional — template-derived blocks typically omit this and compute\n * layers on demand via `materializeBlockLayers()` from `@bendyline/squisq/doc`.\n * Raw blocks (e.g., hand-crafted by AI) may provide layers directly.\n */\n layers?: Layer[];\n\n /** Entry transition from previous block */\n transition?: Transition;\n\n /** Resolved template id this block renders with (see the quartet note above). */\n template?: string;\n\n /**\n * True when `template` was chosen by content-aware auto-picking\n * (`markdownToDoc`'s `autoTemplates`) rather than authored. Ephemeral:\n * `docToMarkdown` does not materialize auto-picked templates as heading\n * annotations, keeping the markdown round-trip lossless.\n */\n autoTemplate?: boolean;\n\n /**\n * True when this block was produced from a *standalone* `{[templateName …]}`\n * annotation paragraph in another block's body (rather than from a heading).\n * Such blocks have no `sourceHeading`; `docToMarkdown` re-emits their\n * annotation as a synthesized paragraph before their `contents` so the\n * markdown round-trips. See `annotationBlocks.ts`.\n *\n * Presence-marker: only ever `true` (never `false`). Test with\n * `block.standaloneAnnotation` presence, not as a boolean toggle.\n */\n standaloneAnnotation?: true;\n\n /**\n * The annotation a standalone block was built from — the raw (un-resolved)\n * template name and its params, in author order. Round-tripped by\n * `docToMarkdown` (via `serializeAnnotation`) and read by validation as the\n * raw requested template name (symmetric with\n * `sourceHeading.templateAnnotation`). Present only when\n * `standaloneAnnotation` is true.\n */\n sourceAnnotation?: { template?: string; params?: Record<string, string> };\n\n /**\n * Display title for template rendering.\n * Extracted from the sourceHeading when the block is created by markdownToDoc().\n * Templates like sectionHeader and titleBlock read this for their title layer.\n */\n title?: string;\n\n // ── Markdown-driven hierarchy (optional) ──\n\n /**\n * Nested sub-blocks (heading hierarchy).\n * When a doc is derived from markdown, sub-headings within this\n * heading's section become child blocks. For example, H2 blocks\n * under an H1 block appear here.\n */\n children?: Block[];\n\n /**\n * Markdown body content for this block's section.\n * Contains the block-level markdown nodes (paragraphs, lists, code,\n * blockquotes, etc.) that appear between this heading and the next\n * heading or sub-heading. Empty for pure structural blocks.\n */\n contents?: import('../markdown/types.js').MarkdownBlockNode[];\n\n /**\n * Reference to the MarkdownHeading node that created this block.\n * Present when the block was derived from markdown via markdownToDoc().\n * Enables round-tripping back to markdown and provides heading depth.\n * Absent for the preamble block (content before the first heading).\n */\n sourceHeading?: import('../markdown/types.js').MarkdownHeading;\n\n /**\n * Template overrides extracted from a heading's `{[templateName key=value]}`\n * annotation. Only carries template-specific params (e.g. `colorScheme=blue`).\n * Block-level metadata lives in `x` / `y` / `connectsTo` / `metadata` and is\n * sourced from the Pandoc-style `{#id .class key=value}` attribute block instead.\n */\n templateOverrides?: Record<string, string>;\n\n /**\n * Structured template inputs sourced from the block's body content:\n * a ```json data / ```yaml data fence under the heading, or — for the\n * `dataTable` template — the first GFM table in the section. Unlike\n * `templateOverrides` (always strings), values here keep their parsed\n * types (arrays, numbers, nested objects). Merge order at render time:\n * template defaults → `templateData` → `templateOverrides`.\n */\n templateData?: Record<string, unknown>;\n\n // ── Block-level metadata from Pandoc-style `{#id .class key=value}` ──\n\n /**\n * X coordinate for diagram-style positioning (in author-defined units).\n * Sourced from a heading attribute `x=…`.\n */\n x?: number;\n\n /**\n * Y coordinate for diagram-style positioning (in author-defined units).\n * Sourced from a heading attribute `y=…`.\n */\n y?: number;\n\n /**\n * Outgoing connections to other blocks, by id. Sourced from a heading\n * attribute `connectsTo=target1,target2:type,target3`.\n */\n connectsTo?: BlockConnection[];\n\n /**\n * CSS-style class tokens from a heading's Pandoc attribute (e.g. `{.important .v2}`).\n * Parsed and stored; downstream consumers may use them for styling or filtering.\n */\n classes?: string[];\n\n /**\n * Free-form metadata for heading attribute keys outside the typed registry\n * (anything that isn't `x` / `y` / `connectsTo` / `startTime` / `duration`).\n * Values are raw strings exactly as authored.\n */\n metadata?: Record<string, string>;\n\n /**\n * Timed media clips attached to this block, authored as body-level\n * `{[audio …]}` / `{[video …]}` annotations. Each clip is timed relative\n * to this block's `startTime` (via `startAt`) and optionally spills past\n * the block's end. See `MediaClip` / `resolveMediaSchedule`.\n */\n media?: import('./Media.js').MediaClip[];\n}\n\n// ============================================\n// Layer Types\n// ============================================\n\n/**\n * A visual element within a block.\n * Layers are composited back-to-front (first layer is background).\n */\nexport type Layer =\n | ImageLayer\n | TextLayer\n | ShapeLayer\n | PathLayer\n | MapLayer\n | VideoLayer\n | TableLayer\n | TreeLayer;\n\ninterface BaseLayer {\n /** Unique identifier for this layer */\n id: string;\n\n /** Position and size */\n position: Position;\n\n /** Animation to apply */\n animation?: Animation;\n}\n\n/**\n * Photographic treatment applied to an image layer — a theme-level \"grade\"\n * so the same photo looks native in every theme. Rendered as CSS filter\n * functions, which behave identically in the browser player and headless\n * frame capture (video/still export).\n */\nexport interface ImageTreatment {\n /**\n * mono: desaturate toward archival black & white.\n * duotone: single-hue tint (hue taken from `color`).\n * warm / cool: gentle temperature grade.\n */\n type: 'none' | 'mono' | 'duotone' | 'warm' | 'cool';\n /** Blend strength 0..1. Default 0.6. */\n strength?: number;\n /** Duotone tint color (themes default this to their primary). */\n color?: string;\n}\n\n/**\n * Image layer - displays an image with optional Ken Burns effect.\n */\nexport interface ImageLayer extends BaseLayer {\n type: 'image';\n content: {\n /** Path to image file (relative to article media dir) */\n src: string;\n /** Alt text for accessibility */\n alt: string;\n /** How to fit image in bounds */\n fit?: 'cover' | 'contain' | 'fill';\n /** Photo credit / artist name */\n credit?: string;\n /** License identifier (e.g., 'CC BY-SA 4.0') */\n license?: string;\n /** Theme-derived photographic grade (see ImageTreatment). */\n treatment?: ImageTreatment;\n /** Gaussian blur radius in px (background/atmosphere imagery). */\n blur?: number;\n };\n}\n\n/**\n * Text layer - displays text with styling.\n */\nexport interface TextLayer extends BaseLayer {\n type: 'text';\n content: {\n /**\n * Plain text (supports \\n for line breaks). Source of truth for plain\n * consumers — PDF/markdown export, search, accessibility — and the SVG\n * `<text>` fallback. When `html` is set, this is its plain-text\n * projection and must be kept in sync.\n */\n text: string;\n /**\n * Optional sanitized **inline** HTML for rich formatting (bold/italic/\n * links, and — for layout textboxes — headings/lists). When present the\n * renderer draws it via `<foreignObject>` instead of SVG `<text>`. Treated\n * as untrusted and re-sanitized at render time. See `RichTextLayer` in\n * `@bendyline/squisq-react`.\n */\n html?: string;\n /** Text styling */\n style: TextStyle;\n };\n}\n\n/**\n * A two-stop linear gradient fill, shared by shape/path fills and text\n * backgrounds. When present it overrides the solid `fill` color.\n *\n * `angle` is in degrees: 0 = top→bottom, 90 = left→right, increasing\n * clockwise. Defaults to 0. Rendered as an SVG `<linearGradient>` in\n * objectBoundingBox units so it scales with the layer's box.\n */\nexport interface LinearGradient {\n from: string;\n to: string;\n angle?: number;\n}\n\n/** Border line style, mapped to an SVG stroke-dasharray by the renderer. */\nexport type BorderStyle = 'solid' | 'dashed' | 'dotted';\n\n/**\n * Shape layer - simple geometric shapes for visual accents.\n */\n/**\n * Repeating SVG pattern fill for a shape (dots, grid, diagonal lines).\n * Rendered as a native `<pattern>` def — fully vector and export-safe.\n */\nexport interface ShapePattern {\n kind: 'dots' | 'grid' | 'diagonal';\n /** Pattern ink color. */\n color: string;\n /** Tile size in px (default 24). */\n size?: number;\n /** Pattern opacity 0–1 (default 1; tint via a translucent color or this). */\n opacity?: number;\n}\n\n/**\n * Procedural filter applied to a shape. `noise` renders static film grain\n * via SVG feTurbulence — deliberately not animated so frame capture and\n * the live player agree.\n */\nexport interface ShapeFilter {\n type: 'noise';\n /** feTurbulence base frequency (default 0.8 — fine grain). */\n baseFrequency?: number;\n /** Grain opacity 0–1 (default 0.05). */\n opacity?: number;\n}\n\nexport interface ShapeLayer extends BaseLayer {\n type: 'shape';\n content: {\n /** Shape type */\n shape: 'rect' | 'circle' | 'line';\n /** Fill color (CSS color or 'none') */\n fill?: string;\n /** Fill opacity 0–1 (applies to solid and gradient fills). */\n fillOpacity?: number;\n /** Gradient fill; overrides `fill` when set. */\n gradient?: LinearGradient;\n /** Repeating pattern fill; overrides `fill`/`gradient` when set. */\n pattern?: ShapePattern;\n /** Procedural filter (film grain). */\n filter?: ShapeFilter;\n /** Stroke color */\n stroke?: string;\n /** Stroke width in pixels */\n strokeWidth?: number;\n /** Border line style (solid/dashed/dotted). Default solid. */\n borderStyle?: BorderStyle;\n /** Corner radius for rect */\n borderRadius?: number;\n };\n}\n\n/**\n * End-of-line marker style for a path/connector endpoint.\n * `arrow` is a filled triangle (the classic arrowhead); `open` is a stroked\n * V; `diamond`/`circle`/`square` are filled glyphs; `none` draws nothing.\n */\nexport type MarkerStyle = 'none' | 'arrow' | 'open' | 'diamond' | 'circle' | 'square';\n\n/**\n * Path layer - renders an SVG `<path>` for arbitrary curves, connectors,\n * arrows, or filled regions. Used by the diagram template for edges\n * between nodes, the drawing template for non-rect/circle/line shapes, and\n * available to any template that needs a custom geometry.\n *\n * The `position` field carries the layer's bounding box (so animations\n * and clipping work the same as for other layers), but the actual\n * geometry is encoded in the `d` attribute using absolute SVG path\n * coordinates relative to the block viewport.\n */\nexport interface PathLayer extends BaseLayer {\n type: 'path';\n content: {\n /** SVG path `d` attribute (e.g. \"M 10 10 L 90 90\"). Absolute viewBox coords. */\n d: string;\n /**\n * Named shape kind (e.g. `'diamond'`, `'star'`, `'arrow-right'`) for\n * path layers that represent one of Squisq's standard shapes. When\n * set, the renderer re-derives `d` from the layer's `position` box\n * (resolved against the viewport) instead of using the stored `d` —\n * so the shape moves, resizes, and adapts to any aspect ratio like\n * the native rect/circle/line layers do. Plain paths (connectors,\n * freehand) leave this unset and keep their absolute `d`.\n */\n shapeKind?: string;\n /** Stroke color (default: theme text color). */\n stroke?: string;\n /** Stroke width in pixels (default: 2). */\n strokeWidth?: number;\n /** Optional fill color (default: 'none' — pure connectors). */\n fill?: string;\n /** Fill opacity 0–1 (applies to solid and gradient fills). */\n fillOpacity?: number;\n /** Gradient fill; overrides `fill` when set. */\n gradient?: LinearGradient;\n /**\n * Border line style (solid/dashed/dotted). A convenience over\n * `dasharray` for named shapes; when set the renderer derives the\n * dash pattern from it (scaled by stroke width).\n */\n borderStyle?: BorderStyle;\n /** Optional stroke dash pattern (SVG `stroke-dasharray` syntax). */\n dasharray?: string;\n /** Marker at the path start. */\n startMarker?: MarkerStyle;\n /** Marker at the path end. */\n endMarker?: MarkerStyle;\n };\n}\n\n/**\n * Map layer - displays a geographic map with optional markers.\n *\n * Maps are rendered as composite tile images from free tile providers.\n * Supported styles use open-source/free tiles requiring attribution.\n */\nexport interface MapLayer extends BaseLayer {\n type: 'map';\n content: {\n /** Center coordinates for the map */\n center: {\n lat: number;\n lng: number;\n };\n /** Zoom level (0-18, typically 8-14 for doc blocks) */\n zoom: number;\n /** Map tile style */\n style: MapTileStyle;\n /** Optional markers to display on the map */\n markers?: MapMarker[];\n /** Pre-rendered static image path (for video export reliability) */\n staticSrc?: string;\n /** Show attribution text (default: true) */\n showAttribution?: boolean;\n };\n}\n\n/**\n * Video layer - displays a short video clip, always muted (narration provides audio).\n *\n * Rendered via an HTML5 <video> element inside <foreignObject>, similar to how\n * ImageLayer uses <img> for Ken Burns effects. clipStart/clipEnd define the window\n * within the source video to play. During Playwright frame capture (seekTo mode),\n * the video is seeked programmatically rather than playing in real time.\n */\nexport interface VideoLayer extends BaseLayer {\n type: 'video';\n content: {\n /** Path to video file (relative to article media dir) */\n src: string;\n /** Path to poster frame (shown before video loads / during seek) */\n posterSrc?: string;\n /** Alt text for accessibility */\n alt: string;\n /** How to fit video in bounds */\n fit?: 'cover' | 'contain' | 'fill';\n /** Start time within the source video (seconds) */\n clipStart: number;\n /** End time within the source video (seconds) */\n clipEnd: number;\n /** Total source video duration (for validation) */\n sourceDuration?: number;\n /**\n * Seconds into the owning block before this video begins playing\n * (the block-relative `startAt`). Default 0 — plays from block start.\n */\n startAt?: number;\n /**\n * When true, the video keeps playing past the block's end (the\n * playback scheduler re-homes it to the player level). Default false.\n */\n spillover?: boolean;\n /** Video credit / artist name */\n credit?: string;\n /** License identifier (e.g., 'CC BY-SA 4.0') */\n license?: string;\n };\n}\n\n/**\n * Table layer - renders a data table with themed styling.\n * Uses foreignObject inside SVG for HTML-based table layout.\n */\nexport interface TableLayer extends BaseLayer {\n type: 'table';\n content: {\n /** Header cell values */\n headers: string[];\n /** Data rows (array of cell value arrays) */\n rows: string[][];\n /** Per-column alignment */\n align?: (('left' | 'right' | 'center') | null)[];\n /** Visual styling */\n style: TableLayerStyle;\n };\n}\n\n/**\n * Styling options for a TableLayer.\n */\nexport interface TableLayerStyle {\n /** Header row background color */\n headerBackground: string;\n /** Header row text color */\n headerColor: string;\n /** Body cell background color */\n cellBackground: string;\n /** Body cell text color */\n cellColor: string;\n /** Border/divider color */\n borderColor: string;\n /** Font size in pixels */\n fontSize: number;\n /** Font family */\n fontFamily?: string;\n /** Header font family (falls back to fontFamily) */\n headerFontFamily?: string;\n /** Corner radius for the table container */\n borderRadius?: number;\n}\n\n/**\n * One node in a `TreeLayer` — a JSON-serializable hierarchy item (mirrors\n * the treeview codec's `TreeItem`). Rendered as an indented filesystem-style\n * row with a folder/file icon and connector rails.\n */\nexport interface TreeLayerItem {\n id: string;\n label: string;\n /** True renders a folder (container) icon; else a file (leaf) icon. */\n isDir?: boolean;\n /** Trailing comment shown muted after the label. */\n comment?: string;\n children: TreeLayerItem[];\n}\n\n/**\n * A hierarchical treeview rendered as interactive HTML inside a\n * `<foreignObject>` (like `TableLayer`): folder/file icons, connector\n * rails, and collapse chevrons. Interactive (collapse/expand) in the live\n * React player; captured fully-expanded and static in frame/PDF export.\n */\nexport interface TreeLayer extends BaseLayer {\n type: 'tree';\n content: {\n items: TreeLayerItem[];\n style: TreeLayerStyle;\n };\n}\n\n/** Styling options for a TreeLayer. */\nexport interface TreeLayerStyle {\n /** Leaf (file) row text color. */\n rowColor: string;\n /** Container (folder) row text color. */\n dirColor: string;\n /** Connector rail / branch color. */\n connectorColor: string;\n /** Icon color. */\n iconColor: string;\n /** Muted comment color. */\n commentColor: string;\n /** Font size in pixels. */\n fontSize: number;\n /** Row label font family. */\n fontFamily?: string;\n /** Monospace font for the connector rails. */\n monoFontFamily?: string;\n /** Indent step per depth level, in pixels. */\n indentPx: number;\n /** FontAwesome icon token for containers (default `folder`). */\n folderIcon?: string;\n /** FontAwesome icon token for leaves (default `file`). */\n fileIcon?: string;\n}\n\n/**\n * Available map tile styles from free/open-source providers.\n */\nexport type MapTileStyle =\n | 'terrain' // OpenTopoMap - topographic/terrain (default)\n | 'satellite' // ESRI World Imagery\n | 'road' // OpenStreetMap standard\n | 'toner' // Stadia Toner (high contrast B&W)\n | 'watercolor'; // Stadia Watercolor (artistic)\n\n/**\n * A marker to display on the map.\n */\nexport interface MapMarker {\n /** Marker latitude */\n lat: number;\n /** Marker longitude */\n lng: number;\n /** Optional label text */\n label?: string;\n /** Marker color (CSS color, default: #ef4444) */\n color?: string;\n /** Marker icon type */\n icon?: 'pin' | 'circle' | 'star';\n}\n\n// ============================================\n// Position & Styling\n// ============================================\n\n/**\n * Position and dimensions for a layer.\n * Values can be pixels (number) or percentages (string like \"50%\").\n */\nexport interface Position {\n /** X position (pixels or percentage) */\n x: number | string;\n /** Y position (pixels or percentage) */\n y: number | string;\n /** Width (pixels or percentage) */\n width?: number | string;\n /** Height (pixels or percentage) */\n height?: number | string;\n /** Anchor point for positioning */\n anchor?: 'center' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n}\n\n/**\n * Text styling options.\n */\nexport interface TextStyle {\n /** Font size in pixels */\n fontSize: number;\n /** Font family (defaults to system sans-serif) */\n fontFamily?: string;\n /** Font weight */\n fontWeight?: 'normal' | 'bold';\n /** Font style. Also the inherited baseline for rich `content.html`. */\n fontStyle?: 'normal' | 'italic';\n /** Text color (CSS color) */\n color: string;\n /** Horizontal text alignment within the layer's position box. */\n textAlign?: 'left' | 'center' | 'right';\n /**\n * Vertical alignment of the text within the layer's position box.\n * Requires a `position.height` to have an effect. When omitted, the\n * vertical baseline is derived from `position.anchor` (legacy behavior).\n */\n verticalAlign?: 'top' | 'middle' | 'bottom';\n /** Line height multiplier */\n lineHeight?: number;\n /** Add drop shadow for readability over images */\n shadow?: boolean;\n /** Background color for text box */\n background?: string;\n /** Background opacity 0–1 (applies to solid and gradient backgrounds). */\n backgroundOpacity?: number;\n /** Gradient background; overrides `background` when set. */\n backgroundGradient?: LinearGradient;\n /** Border (stroke) color for the text box. */\n borderColor?: string;\n /** Border width in pixels. A border renders when > 0 and a color is set. */\n borderWidth?: number;\n /** Border line style (solid/dashed/dotted). Default solid. */\n borderStyle?: BorderStyle;\n /** Padding around text (pixels) */\n padding?: number;\n /** Maximum number of lines before truncation (adds \"...\" to last line) */\n maxLines?: number;\n}\n\n// ============================================\n// Animation & Transitions\n// ============================================\n\n/**\n * Animation to apply to a layer.\n */\nexport interface Animation {\n /** Animation type */\n type: AnimationType;\n /** Duration in seconds (defaults to layer's block duration) */\n duration?: number;\n /** Delay before animation starts (seconds) */\n delay?: number;\n /** CSS easing function */\n easing?: string;\n /** For Ken Burns: zoom direction */\n direction?: 'in' | 'out';\n /** For pan animations: pan direction */\n panDirection?: 'left' | 'right' | 'up' | 'down';\n}\n\n/**\n * Available animation types.\n */\nexport type AnimationType =\n | 'none'\n | 'fadeIn'\n | 'fadeOut'\n | 'slowZoom' // Slow zoom with optional pan\n | 'zoomIn'\n | 'zoomOut'\n | 'panLeft'\n | 'panRight'\n | 'typewriter'; // Text appears letter by letter\n\n// ============================================\n// Audio Configuration\n// ============================================\n\n/**\n * Audio track configuration.\n * Articles have multiple MP3 segments (intro + sections).\n */\nexport interface AudioTrack {\n /** Audio segments in playback order */\n segments: AudioSegment[];\n}\n\n// ============================================\n// Captions\n// ============================================\n\n/**\n * A single word with precise timing, used for word-level highlighting\n * in social-style captions. Populated from TTS timing data when available.\n */\nexport interface CaptionWord {\n /** The word text */\n text: string;\n /** Start time in seconds (relative to doc start) */\n startTime: number;\n /** End time in seconds */\n endTime: number;\n}\n\n/**\n * A single caption phrase to display during playback.\n */\nexport interface CaptionPhrase {\n /** The text to display */\n text: string;\n /** Start time in seconds (relative to doc start) */\n startTime: number;\n /** End time in seconds */\n endTime: number;\n /** Which audio segment this caption belongs to (0-indexed) */\n audioSegment: number;\n /**\n * Optional per-word timing from TTS timing data.\n * When present, enables precise word-level highlighting in social\n * caption style. When absent, word timing is interpolated evenly\n * across the phrase duration.\n */\n words?: CaptionWord[];\n}\n\n/**\n * Caption track for a doc.\n */\nexport interface CaptionTrack {\n /** Caption phrases in chronological order */\n phrases: CaptionPhrase[];\n /** When the captions were generated. Optional so that conversion stays\n * deterministic — `markdownToDoc()` only sets it when the caller\n * supplies a timestamp via `captionsGeneratedAt`. */\n generatedAt?: string;\n /** Algorithm version for regeneration detection */\n version: number;\n}\n\n/**\n * A single audio segment (one MP3 file).\n */\nexport interface AudioSegment {\n /** Path to MP3 file (relative to article media dir) */\n src: string;\n /** Segment name (e.g., \"intro\", \"history\") */\n name: string;\n /** Duration in seconds */\n duration: number;\n /** Start time in overall timeline (calculated) */\n startTime: number;\n}\n\n// ============================================\n// Audio Timing Data (from TTS)\n// ============================================\n\n/**\n * A single word-level timing bookmark from TTS synthesis.\n * Used for precise audio-to-content mapping and word-level caption sync.\n */\nexport interface AudioBookmark {\n /** Unique identifier (e.g., \"word-0\", \"word-1\") */\n id: string;\n /** Timestamp in seconds from audio start */\n time: number;\n /** Character offset in the source text */\n charOffset: number;\n /** The word text at this position */\n textFragment?: string;\n}\n\n/**\n * Timing data for an audio segment, typically from a `.timing.json` file\n * generated alongside TTS audio. Contains the source text and per-word\n * timing bookmarks for precise content matching and caption sync.\n */\nexport interface AudioTimingData {\n /** The normalized plain text that was synthesized */\n sourceText: string;\n /** Word-level timing bookmarks */\n bookmarks: AudioBookmark[];\n /** Total audio duration in seconds */\n duration: number;\n}\n\n// ============================================\n// Helper Functions\n// ============================================\n\n/**\n * Calculate total duration from audio segments.\n */\nexport function calculateDuration(audio: AudioTrack): number {\n return audio.segments.reduce((sum, seg) => sum + seg.duration, 0);\n}\n\n/**\n * Find which audio segment is playing at a given time.\n */\nexport function getSegmentAtTime(audio: AudioTrack, time: number): number {\n let elapsed = 0;\n for (let i = 0; i < audio.segments.length; i++) {\n elapsed += audio.segments[i].duration;\n if (time < elapsed) return i;\n }\n return audio.segments.length - 1;\n}\n\n/**\n * Find which block should be visible at a given time.\n */\nexport function getBlockAtTime(blocks: Block[], time: number): Block | null {\n for (let i = blocks.length - 1; i >= 0; i--) {\n const block = blocks[i];\n if (time >= block.startTime && time < block.startTime + block.duration) {\n return block;\n }\n }\n return blocks[0] || null;\n}\n\n/**\n * Find the caption phrase that should be displayed at a given time.\n */\nexport function getCaptionAtTime(\n captions: CaptionTrack | undefined,\n time: number,\n): CaptionPhrase | null {\n if (!captions || !captions.phrases.length) return null;\n\n for (const phrase of captions.phrases) {\n if (time >= phrase.startTime && time < phrase.endTime) {\n return phrase;\n }\n }\n return null;\n}\n","/**\n * Theme Compilation\n *\n * Turns a partial Theme (typically authored by the customizer panel from\n * a few seed colors and preset choices) into a complete, validated Theme\n * by:\n *\n * 1. Filling unspecified fields from a hardcoded `STARTER_THEME`.\n * 2. Deriving missing color slots from `seedColors` via OKLCh math.\n * 3. Validating the result.\n *\n * Built-in themes ship as fully-specified Theme JSON and skip this step.\n */\n\nimport type {\n Theme,\n DeepPartial,\n ThemeColorPalette,\n ThemeColorScheme,\n ThemeSeedColors,\n FontFamily,\n} from './Theme.js';\nimport { THEME_SCHEMA_VERSION, createTheme } from './Theme.js';\nimport { assertTheme } from './themeValidator.js';\nimport {\n oklchLighten,\n oklchDarken,\n oklchSetChroma,\n pickContrastingText,\n relativeLuminance,\n deriveScale,\n isHex,\n} from './colorUtils.js';\n\n/** Internal default theme used to fill in fields the customizer doesn't expose. */\nconst STARTER_BODY_FONT: FontFamily = { stackId: 'system-sans' };\nconst STARTER_TITLE_FONT: FontFamily = { stackId: 'system-serif' };\nconst STARTER_MONO_FONT: FontFamily = { stackId: 'system-mono' };\n\nconst STARTER_COLOR_SCHEMES: Record<string, ThemeColorScheme> = {\n blue: { bg: '#1a365d', text: '#63b3ed', accent: '#90cdf4' },\n green: { bg: '#22543d', text: '#9ae6b4', accent: '#68d391' },\n purple: { bg: '#44337a', text: '#d6bcfa', accent: '#b794f4' },\n red: { bg: '#742a2a', text: '#fc8181', accent: '#feb2b2' },\n orange: { bg: '#744210', text: '#fbd38d', accent: '#f6ad55' },\n teal: { bg: '#234e52', text: '#81e6d9', accent: '#4fd1c5' },\n};\n\nexport const STARTER_THEME: Theme = {\n schemaVersion: THEME_SCHEMA_VERSION,\n id: 'custom',\n name: 'Custom Theme',\n description: 'Customizer starter — gets overridden by user choices.',\n colors: {\n primary: '#3182ce',\n secondary: '#4a5568',\n background: '#1a202c',\n backgroundLight: '#2d3748',\n text: '#f7fafc',\n textMuted: '#a0aec0',\n highlight: '#4299e1',\n warning: '#fc8181',\n },\n typography: {\n bodyFont: STARTER_BODY_FONT,\n titleFont: STARTER_TITLE_FONT,\n monoFont: STARTER_MONO_FONT,\n titleWeight: 'bold',\n },\n style: {\n textShadow: true,\n overlayOpacity: 0.45,\n animationSpeed: 1.0,\n borderRadius: 6,\n },\n renderStyle: {\n name: 'standard',\n defaultTextAnimation: 'fadeIn',\n defaultImageAnimation: 'slowZoom',\n ambientMotion: true,\n defaultTransition: { type: 'fade', duration: 0.7 },\n },\n colorSchemes: STARTER_COLOR_SCHEMES,\n};\n\n/**\n * Derive a full `ThemeColorPalette` from `seedColors`, with any explicit\n * `partialColors` taking precedence over derived values. Background and\n * text are guessed from luminance when the user gave only a primary.\n */\nexport function deriveColorPalette(\n seeds: ThemeSeedColors,\n partialColors: Partial<ThemeColorPalette> = {},\n opts: { contrast?: 'subtle' | 'balanced' | 'high' } = {},\n): ThemeColorPalette {\n const spread = opts.contrast === 'high' ? 0.22 : opts.contrast === 'subtle' ? 0.08 : 0.15;\n\n const primary = seeds.primary;\n const secondary = seeds.secondary ?? oklchSetChroma(oklchLighten(primary, 0.05), 0.5);\n const accent = seeds.accent ?? oklchLighten(primary, spread);\n\n // Decide light vs dark surface from the explicit background, the seed background,\n // or default to dark.\n const bgSeed = partialColors.background ?? seeds.background;\n let background: string;\n if (bgSeed) {\n background = bgSeed;\n } else {\n // Pick a dark or light background that contrasts with primary\n background = relativeLuminance(primary) > 0.5 ? '#0a0a0a' : '#1a202c';\n }\n const isLightSurface = relativeLuminance(background) > 0.5;\n\n const backgroundLight =\n partialColors.backgroundLight ??\n (isLightSurface ? oklchDarken(background, 0.04) : oklchLighten(background, 0.04));\n\n const text =\n partialColors.text ?? seeds.text ?? pickContrastingText(background, '#f7fafc', '#1a202c');\n const textMuted =\n partialColors.textMuted ??\n (isLightSurface ? oklchLighten(text, 0.25) : oklchDarken(text, 0.25));\n\n const highlight = partialColors.highlight ?? accent;\n const warning = partialColors.warning ?? '#fc8181';\n\n return {\n primary: partialColors.primary ?? primary,\n secondary: partialColors.secondary ?? secondary,\n background,\n backgroundLight,\n text,\n textMuted,\n highlight,\n warning,\n };\n}\n\n/**\n * Expand one accent color into a full `{bg, text, accent}` color scheme via\n * the OKLCh scale — dark saturated bg, light readable text, the picked accent.\n * Falls back to a neutral scheme when the input isn't a valid hex. Shared by\n * the editor's accent list and file-import theme inference so both derive\n * identical schemes from the same accent.\n */\nexport function accentToColorScheme(accent: string): ThemeColorScheme {\n if (!isHex(accent)) return { bg: '#1a202c', text: '#e2e8f0', accent: '#63b3ed' };\n const scale = deriveScale(accent, 0.3);\n return { bg: scale.darker2, text: scale.lighter2, accent: scale.base };\n}\n\n/** Map a contrast preset to numeric spread used by `deriveColorPalette`. */\nexport type ContrastPreset = 'subtle' | 'balanced' | 'high';\n\nexport interface CompileOptions {\n /** Contrast level for OKLCh derivation (default 'balanced'). */\n contrast?: ContrastPreset;\n /**\n * Base theme to inherit from. When provided, the partial is deep-merged\n * over this theme instead of the neutral `STARTER_THEME`, so the compiled\n * theme inherits the base's render style, color schemes, typography, and\n * persistent layers — and only the fields the user changed are overridden.\n * The base's id is recorded on the result as `basedOn`.\n */\n base?: Theme;\n}\n\n/**\n * Compile a partial Theme into a complete one. Fills missing fields from\n * the base (`opts.base` when given, else `STARTER_THEME`), derives missing\n * color slots from `seedColors` (when present), and validates the result.\n */\nexport function compileTheme(partial: DeepPartial<Theme>, opts: CompileOptions = {}): Theme {\n // Step 1: deep-merge over the base (a chosen theme, or the neutral starter)\n const base = opts.base ?? STARTER_THEME;\n const merged = createTheme(base, partial);\n merged.schemaVersion = THEME_SCHEMA_VERSION;\n // Record which theme this was derived from so a customizer can re-inherit.\n if (opts.base && !merged.basedOn) merged.basedOn = opts.base.id;\n\n // Step 1b: typography fonts are discriminated unions ({stackId} | {custom}),\n // so deep-merge would leave stale keys from the starter when the partial\n // switches form. Replace each font wholesale when explicitly provided.\n const partialTypography = partial.typography;\n if (partialTypography) {\n if (partialTypography.titleFont !== undefined) {\n merged.typography.titleFont = partialTypography.titleFont as FontFamily;\n }\n if (partialTypography.bodyFont !== undefined) {\n merged.typography.bodyFont = partialTypography.bodyFont as FontFamily;\n }\n if (partialTypography.monoFont !== undefined) {\n merged.typography.monoFont = partialTypography.monoFont as FontFamily;\n }\n }\n\n // Step 1c: colorSchemes is a map the user edits wholesale (add / remove\n // accents). Deep-merge can't delete keys, so replace it outright when the\n // partial provides it — mirroring the font replacement above. This lets a\n // removed accent actually disappear rather than lingering from the base.\n if (partial.colorSchemes !== undefined) {\n merged.colorSchemes = partial.colorSchemes as Record<string, ThemeColorScheme>;\n }\n\n // Step 2: derive missing color slots from seeds, if present\n if (merged.seedColors) {\n const partialColors = (partial.colors ?? {}) as Partial<ThemeColorPalette>;\n merged.colors = deriveColorPalette(merged.seedColors, partialColors, {\n contrast: opts.contrast,\n });\n }\n\n // Step 3: validate\n return assertTheme(merged, `compiled theme \"${merged.id}\"`);\n}\n\n/**\n * Parse a JSON string into a validated Theme. Throws on invalid input.\n */\nexport function parseTheme(json: string): Theme {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`Invalid theme JSON: ${msg}`);\n }\n return assertTheme(parsed, 'parsed theme');\n}\n\n/**\n * Serialize a Theme to a stable, pretty-printed JSON string. Round-trips\n * cleanly through `parseTheme`.\n */\nexport function serializeTheme(theme: Theme): string {\n return JSON.stringify(theme, null, 2);\n}\n"],"mappings":"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","names":[]}
@@ -2,18 +2,22 @@ import {
2
2
  extractContent,
3
3
  mapElementToBlock,
4
4
  stripMarkdown
5
- } from "./chunk-TQWLI6S2.js";
6
- import {
7
- SeededRandom,
8
- hashString
9
- } from "./chunk-FVTQSNR7.js";
5
+ } from "./chunk-Q7LROV2H.js";
10
6
  import {
7
+ cloneAndFreezeData,
11
8
  isTemplateBlock
12
- } from "./chunk-DLXZMS5K.js";
9
+ } from "./chunk-5J4HKRJF.js";
13
10
  import {
14
11
  extractPlainText,
15
12
  getChildren
16
- } from "./chunk-HWVFJAAH.js";
13
+ } from "./chunk-AMIR72JP.js";
14
+ import {
15
+ estimateTimeFromText
16
+ } from "./chunk-3E5F2XMR.js";
17
+ import {
18
+ SeededRandom,
19
+ hashString
20
+ } from "./chunk-FVTQSNR7.js";
17
21
 
18
22
  // src/transform/styles/documentary.ts
19
23
  var documentaryStyle = {
@@ -98,34 +102,139 @@ var minimalStyle = {
98
102
  };
99
103
 
100
104
  // src/transform/registry.ts
101
- var TRANSFORM_STYLES = {
102
- [documentaryStyle.id]: documentaryStyle,
103
- [magazineStyle.id]: magazineStyle,
104
- [dataDrivenStyle.id]: dataDrivenStyle,
105
- [narrativeStyle.id]: narrativeStyle,
106
- [minimalStyle.id]: minimalStyle
107
- };
108
- var STYLE_ALIASES = {
109
- dataDriven: "data-driven"
110
- };
111
- var registeredStyles = /* @__PURE__ */ new Map();
105
+ var TRANSFORM_STYLES = Object.freeze({
106
+ [documentaryStyle.id]: cloneAndFreezeData(documentaryStyle),
107
+ [magazineStyle.id]: cloneAndFreezeData(magazineStyle),
108
+ [dataDrivenStyle.id]: cloneAndFreezeData(dataDrivenStyle),
109
+ [narrativeStyle.id]: cloneAndFreezeData(narrativeStyle),
110
+ [minimalStyle.id]: cloneAndFreezeData(minimalStyle)
111
+ });
112
112
  var DEFAULT_TRANSFORM_STYLE_ID = "documentary";
113
- function registerTransformStyle(style) {
114
- registeredStyles.set(style.id, style);
113
+ var EXTRACTION_TYPES = /* @__PURE__ */ new Set([
114
+ "stat",
115
+ "date",
116
+ "quote",
117
+ "comparison",
118
+ "fact",
119
+ "impactLine",
120
+ "list",
121
+ "definition"
122
+ ]);
123
+ var TRANSITION_STYLES = /* @__PURE__ */ new Set(["cut", "fade", "dissolve", "mixed"]);
124
+ function validateTransformStyle(style) {
125
+ const candidate = style;
126
+ const fail = (message) => {
127
+ throw new TypeError(`Invalid transform style: ${message}`);
128
+ };
129
+ for (const key of ["id", "name", "description"]) {
130
+ if (typeof candidate[key] !== "string" || !candidate[key].trim()) {
131
+ fail(`${key} must be a non-empty string`);
132
+ }
133
+ }
134
+ for (const key of ["minConfidence", "transformRatio"]) {
135
+ const value = candidate[key];
136
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) {
137
+ fail(`${key} must be a finite number between 0 and 1`);
138
+ }
139
+ }
140
+ if (!Array.isArray(candidate.preferredTypes) || candidate.preferredTypes.some((type) => !EXTRACTION_TYPES.has(type))) {
141
+ fail("preferredTypes contains an unknown extraction type");
142
+ }
143
+ if (!Array.isArray(candidate.colorSchemes) || candidate.colorSchemes.length === 0 || candidate.colorSchemes.some((scheme) => typeof scheme !== "string" || !scheme)) {
144
+ fail("colorSchemes must contain at least one non-empty string");
145
+ }
146
+ for (const key of ["insertSectionHeaders", "interleaveImages"]) {
147
+ if (typeof candidate[key] !== "boolean") fail(`${key} must be a boolean`);
148
+ }
149
+ const blocks = candidate.blocksPerSection;
150
+ if (!blocks || !Number.isInteger(blocks.max) || blocks.max < 1) {
151
+ fail("blocksPerSection.max must be a positive integer");
152
+ }
153
+ if (typeof candidate.transitionStyle !== "string" || !TRANSITION_STYLES.has(candidate.transitionStyle)) {
154
+ fail("transitionStyle must be cut, fade, dissolve, or mixed");
155
+ }
156
+ const templateMap = candidate.templateMap;
157
+ if (templateMap !== void 0) {
158
+ if (!templateMap || typeof templateMap !== "object" || Array.isArray(templateMap)) {
159
+ fail("templateMap must be an object");
160
+ }
161
+ for (const [type, template] of Object.entries(templateMap)) {
162
+ if (!EXTRACTION_TYPES.has(type) || typeof template !== "string" || !template) {
163
+ fail("templateMap must map known extraction types to non-empty template names");
164
+ }
165
+ }
166
+ }
167
+ if (candidate.suggestedThemeId !== void 0 && (typeof candidate.suggestedThemeId !== "string" || !candidate.suggestedThemeId)) {
168
+ fail("suggestedThemeId must be a non-empty string");
169
+ }
170
+ const pacingValue = candidate.pacing;
171
+ if (pacingValue !== void 0) {
172
+ if (!pacingValue || typeof pacingValue !== "object" || Array.isArray(pacingValue)) {
173
+ fail("pacing must be an object");
174
+ }
175
+ const pacing = pacingValue;
176
+ for (const key of ["intro", "outro"]) {
177
+ if (pacing[key] !== void 0 && typeof pacing[key] !== "boolean") {
178
+ fail(`pacing.${key} must be a boolean`);
179
+ }
180
+ }
181
+ }
182
+ const budget = candidate.budget;
183
+ if (candidate.budget !== void 0 && (!budget || typeof budget !== "object" || Array.isArray(budget))) {
184
+ fail("budget must be an object");
185
+ }
186
+ if (budget && budget.slidesPerMinute !== void 0) {
187
+ const value = budget.slidesPerMinute;
188
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
189
+ fail("budget.slidesPerMinute must be a positive finite number");
190
+ }
191
+ }
115
192
  }
116
- function unregisterTransformStyle(id) {
117
- registeredStyles.delete(id);
193
+ function styleSnapshot(style) {
194
+ validateTransformStyle(style);
195
+ return cloneAndFreezeData(style);
118
196
  }
119
- function resolveTransformStyle(id) {
120
- const canonical = STYLE_ALIASES[id] ?? id;
121
- return registeredStyles.get(canonical) ?? TRANSFORM_STYLES[canonical] ?? TRANSFORM_STYLES[DEFAULT_TRANSFORM_STYLE_ID];
197
+ function normalizeBuiltinStyleId(id) {
198
+ return id === "dataDriven" ? "data-driven" : id;
122
199
  }
123
- function getTransformStyleIds() {
124
- return Array.from(/* @__PURE__ */ new Set([...Object.keys(TRANSFORM_STYLES), ...registeredStyles.keys()]));
200
+ function resolveBuiltinStyle(id) {
201
+ return TRANSFORM_STYLES[normalizeBuiltinStyleId(id)] ?? TRANSFORM_STYLES[DEFAULT_TRANSFORM_STYLE_ID];
125
202
  }
126
- function getTransformStyleSummaries() {
127
- return getTransformStyleIds().map((id) => {
128
- const { name, description } = resolveTransformStyle(id);
203
+ function createTransformStyleRegistry(initialStyles = []) {
204
+ const registeredStyles = /* @__PURE__ */ new Map();
205
+ const registry = {
206
+ register(style) {
207
+ const snapshot = styleSnapshot(style);
208
+ registeredStyles.set(snapshot.id, snapshot);
209
+ },
210
+ unregister(id) {
211
+ return registeredStyles.delete(id);
212
+ },
213
+ get(id) {
214
+ return registeredStyles.get(id);
215
+ },
216
+ list() {
217
+ return Array.from(registeredStyles.values());
218
+ }
219
+ };
220
+ for (const style of initialStyles) registry.register(style);
221
+ return Object.freeze(registry);
222
+ }
223
+ function resolveTransformStyle(style, registry) {
224
+ if (typeof style !== "string") return styleSnapshot(style);
225
+ return registry?.get(style) ?? resolveBuiltinStyle(style);
226
+ }
227
+ function getTransformStyleIds(registry) {
228
+ return Array.from(
229
+ /* @__PURE__ */ new Set([
230
+ ...Object.keys(TRANSFORM_STYLES),
231
+ ...registry?.list().map((style) => style.id) ?? []
232
+ ])
233
+ );
234
+ }
235
+ function getTransformStyleSummaries(registry) {
236
+ return getTransformStyleIds(registry).map((id) => {
237
+ const { name, description } = resolveTransformStyle(id, registry);
129
238
  return { id, name, description };
130
239
  });
131
240
  }
@@ -323,7 +432,8 @@ function buildBlockSequence(analyzed, selected, config, images, rng) {
323
432
  duration: ab.block.duration > 0 ? Math.min(3, ab.block.duration * 0.2) : 3,
324
433
  audioSegment: ab.block.audioSegment,
325
434
  title: ab.block.title,
326
- colorScheme: config.colorSchemes[colorIndex % config.colorSchemes.length]
435
+ colorScheme: config.colorSchemes[colorIndex % config.colorSchemes.length],
436
+ sourceBlockId: ab.block.id
327
437
  };
328
438
  blocks.push(headerBlock);
329
439
  insertedCount++;
@@ -343,13 +453,18 @@ function buildBlockSequence(analyzed, selected, config, images, rng) {
343
453
  };
344
454
  accentPositionIndex++;
345
455
  }
456
+ const slideShare = ab.block.duration > 0 ? ab.block.duration / extractions.length : 6;
457
+ const offsetInBlock = ab.block.duration > 0 ? estimateTimeFromText(ab.plainText, sel.element.sourcePosition, ab.block.duration) : 0;
346
458
  let templateBlock = mapElementToBlock(sel.element, {
347
459
  id: `transform-${blockIdCounter++}`,
348
- duration: ab.block.duration > 0 ? ab.block.duration / extractions.length : 6,
460
+ duration: slideShare,
349
461
  audioSegment: ab.block.audioSegment,
350
462
  colorScheme,
351
463
  accentImage,
352
- sourceStartTime: sel.element.sourcePosition
464
+ sourceStartTime: ab.block.startTime + offsetInBlock,
465
+ sourceDuration: slideShare,
466
+ sourceBlockId: ab.block.id,
467
+ sourceCharOffset: sel.element.sourcePosition
353
468
  });
354
469
  const remapTarget = config.templateMap?.[sel.element.data.type];
355
470
  if (remapTarget && remapTarget !== templateBlock.template) {
@@ -380,7 +495,8 @@ function buildBlockSequence(analyzed, selected, config, images, rng) {
380
495
  audioSegment: ab.block.audioSegment,
381
496
  imageSrc: img.src,
382
497
  imageAlt: img.alt ?? "",
383
- ambientMotion: rng.pick(AMBIENT_MOTIONS) ?? "zoomIn"
498
+ ambientMotion: rng.pick(AMBIENT_MOTIONS) ?? "zoomIn",
499
+ sourceBlockId: ab.block.id
384
500
  };
385
501
  blocks.push(imageBlock);
386
502
  imageIndex++;
@@ -397,7 +513,9 @@ function translateTemplateBlock(block, target) {
397
513
  duration: block.duration,
398
514
  audioSegment: block.audioSegment,
399
515
  sourceStartTime: block.sourceStartTime,
400
- sourceDuration: block.sourceDuration
516
+ sourceDuration: block.sourceDuration,
517
+ sourceBlockId: block.sourceBlockId,
518
+ sourceCharOffset: block.sourceCharOffset
401
519
  };
402
520
  if (block.template === "quote") {
403
521
  const quote = block;
@@ -440,6 +558,12 @@ var MAX_BLOCK_DURATION = 20;
440
558
  var DEFAULT_BLOCK_DURATION = 6;
441
559
  function allocateTiming(blocks, totalDuration) {
442
560
  if (blocks.length === 0) return [];
561
+ const hasAnchors = blocks.some(
562
+ (b) => isTemplateBlock(b) && typeof b.sourceStartTime === "number"
563
+ );
564
+ return hasAnchors ? allocateAnchored(blocks, totalDuration) : allocateRescaled(blocks, totalDuration);
565
+ }
566
+ function allocateRescaled(blocks, totalDuration) {
443
567
  const effectiveDuration = totalDuration > 0 ? totalDuration : estimateDefaultDuration(blocks);
444
568
  const durations = blocks.map((block) => {
445
569
  if (!isTemplateBlock(block) && block.duration > 0) {
@@ -460,27 +584,102 @@ function allocateTiming(blocks, totalDuration) {
460
584
  let currentTime = 0;
461
585
  const result = [];
462
586
  for (let i = 0; i < blocks.length; i++) {
463
- const block = blocks[i];
464
- const duration = durations[i];
587
+ result.push(toOutputBlock(blocks[i], currentTime, durations[i]));
588
+ currentTime += durations[i];
589
+ }
590
+ return result;
591
+ }
592
+ var MIN_FLOATING_DURATION = 1;
593
+ function allocateAnchored(blocks, totalDuration) {
594
+ const entries = blocks.map((block) => {
465
595
  if (isTemplateBlock(block)) {
466
- const outputBlock = {
467
- ...block,
468
- startTime: currentTime,
469
- duration,
470
- title: getTemplateTitle(block)
596
+ return {
597
+ block,
598
+ anchorStart: typeof block.sourceStartTime === "number" ? block.sourceStartTime : null,
599
+ rawDuration: block.duration > 0 ? block.duration : DEFAULT_BLOCK_DURATION
471
600
  };
472
- result.push(outputBlock);
601
+ }
602
+ return {
603
+ block,
604
+ anchorStart: block.startTime,
605
+ rawDuration: block.duration > 0 ? block.duration : DEFAULT_BLOCK_DURATION
606
+ };
607
+ });
608
+ const starts = new Array(entries.length);
609
+ let cursor = 0;
610
+ let seenAnchor = false;
611
+ let i = 0;
612
+ while (i < entries.length) {
613
+ const entry = entries[i];
614
+ if (entry.anchorStart !== null) {
615
+ const start = Math.max(cursor, entry.anchorStart);
616
+ starts[i] = start;
617
+ const hint = isTemplateBlock(entry.block) ? entry.block.sourceDuration ?? entry.rawDuration : entry.rawDuration;
618
+ cursor = start + Math.max(MIN_FLOATING_DURATION, hint);
619
+ seenAnchor = true;
620
+ i++;
621
+ continue;
622
+ }
623
+ const runStart = i;
624
+ while (i < entries.length && entries[i].anchorStart === null) i++;
625
+ const run = entries.slice(runStart, i);
626
+ const rawSum = run.reduce((sum, e) => sum + e.rawDuration, 0);
627
+ const nextAnchorStart = i < entries.length ? Math.max(entries[i].anchorStart ?? cursor, cursor) : null;
628
+ if (nextAnchorStart === null) {
629
+ let acc = cursor;
630
+ for (let k = 0; k < run.length; k++) {
631
+ starts[runStart + k] = acc;
632
+ acc += run[k].rawDuration;
633
+ }
634
+ cursor = acc;
635
+ } else if (!seenAnchor) {
636
+ const gap = nextAnchorStart - cursor;
637
+ let acc = cursor;
638
+ for (let k = 0; k < run.length; k++) {
639
+ starts[runStart + k] = acc;
640
+ acc += rawSum > 0 ? run[k].rawDuration / rawSum * gap : gap / run.length;
641
+ }
642
+ cursor = nextAnchorStart;
473
643
  } else {
474
- result.push({
475
- ...block,
476
- startTime: currentTime,
477
- duration
478
- });
644
+ const gap = Math.max(0, nextAnchorStart - cursor);
645
+ const scale = rawSum > 0 ? Math.min(1, gap / rawSum) : 0;
646
+ let acc = Math.max(cursor, nextAnchorStart - rawSum * scale);
647
+ for (let k = 0; k < run.length; k++) {
648
+ starts[runStart + k] = acc;
649
+ acc += run[k].rawDuration * scale;
650
+ }
651
+ cursor = nextAnchorStart;
652
+ }
653
+ }
654
+ for (let k = 0; k < starts.length; k++) {
655
+ const floor = k > 0 ? starts[k - 1] + MIN_FLOATING_DURATION : 0;
656
+ if (starts[k] < floor) starts[k] = floor;
657
+ }
658
+ const result = [];
659
+ for (let k = 0; k < entries.length; k++) {
660
+ const entry = entries[k];
661
+ let duration;
662
+ if (k + 1 < entries.length) {
663
+ duration = Math.max(MIN_FLOATING_DURATION, starts[k + 1] - starts[k]);
664
+ } else {
665
+ const authored = isTemplateBlock(entry.block) ? entry.block.sourceDuration ?? entry.rawDuration : entry.rawDuration;
666
+ duration = Math.max(MIN_FLOATING_DURATION, authored, totalDuration - starts[k]);
479
667
  }
480
- currentTime += duration;
668
+ result.push(toOutputBlock(entry.block, starts[k], duration));
481
669
  }
482
670
  return result;
483
671
  }
672
+ function toOutputBlock(block, startTime, duration) {
673
+ if (isTemplateBlock(block)) {
674
+ return {
675
+ ...block,
676
+ startTime,
677
+ duration,
678
+ title: getTemplateTitle(block)
679
+ };
680
+ }
681
+ return { ...block, startTime, duration };
682
+ }
484
683
  function clampDuration(d) {
485
684
  return Math.max(MIN_BLOCK_DURATION, Math.min(MAX_BLOCK_DURATION, d));
486
685
  }
@@ -512,8 +711,8 @@ function getTemplateTitle(block) {
512
711
  }
513
712
 
514
713
  // src/transform/applyTransform.ts
515
- function applyTransform(doc, styleId, options) {
516
- const baseConfig = resolveTransformStyle(styleId);
714
+ function applyTransform(doc, style, options) {
715
+ const baseConfig = resolveTransformStyle(style, options?.registry);
517
716
  const config = options?.overrides ? { ...baseConfig, ...options.overrides, id: baseConfig.id } : baseConfig;
518
717
  const seed = options?.seed ?? hashString(doc.articleId || "transform");
519
718
  const images = options?.images ?? extractDocImages(doc.blocks);
@@ -584,8 +783,7 @@ function firstTitle(doc) {
584
783
 
585
784
  export {
586
785
  DEFAULT_TRANSFORM_STYLE_ID,
587
- registerTransformStyle,
588
- unregisterTransformStyle,
786
+ createTransformStyleRegistry,
589
787
  resolveTransformStyle,
590
788
  getTransformStyleIds,
591
789
  getTransformStyleSummaries,
@@ -593,4 +791,4 @@ export {
593
791
  analyzeBlocks,
594
792
  applyTransform
595
793
  };
596
- //# sourceMappingURL=chunk-LDQ2HJIX.js.map
794
+ //# sourceMappingURL=chunk-PXLVXTLW.js.map