@bendyline/squisq 2.0.0 → 2.1.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.
- package/dist/{Doc-ylqWKDc_.d.ts → Doc-DynJleo-.d.ts} +159 -2
- package/dist/{ImageEditDoc-D828IXJ1.d.ts → ImageEditDoc-Ca4Tr9uN.d.ts} +1 -1
- package/dist/{chunk-PXLVXTLW.js → chunk-ILWDXLUK.js} +24 -6
- package/dist/chunk-ILWDXLUK.js.map +1 -0
- package/dist/{chunk-6PJRB2CF.js → chunk-JHZWYRSW.js} +570 -2
- package/dist/chunk-JHZWYRSW.js.map +1 -0
- package/dist/{chunk-GF3BVNLU.js → chunk-JI77MGAK.js} +195 -27
- package/dist/chunk-JI77MGAK.js.map +1 -0
- package/dist/{chunk-QVANWDPH.js → chunk-OTKVFVL6.js} +1403 -41
- package/dist/chunk-OTKVFVL6.js.map +1 -0
- package/dist/{chunk-LYNJEOAC.js → chunk-QUUPYOSP.js} +8 -2
- package/dist/chunk-QUUPYOSP.js.map +1 -0
- package/dist/chunk-VWCJ2WXC.js +215 -0
- package/dist/chunk-VWCJ2WXC.js.map +1 -0
- package/dist/{chunk-QTSJOY54.js → chunk-VYFRI7R6.js} +2 -2
- package/dist/{chunk-T3TI7GSZ.js → chunk-XNLB57UD.js} +2 -2
- package/dist/doc/index.d.ts +144 -5
- package/dist/doc/index.js +24 -4
- package/dist/generate/index.d.ts +1 -1
- package/dist/imageEdit/index.d.ts +3 -3
- package/dist/index.d.ts +6 -5
- package/dist/index.js +66 -8
- package/dist/jsonForm/index.d.ts +1 -1
- package/dist/jsonForm/index.js +4 -4
- package/dist/materializePageSection-DDzubQXo.d.ts +223 -0
- package/dist/narration/index.d.ts +1 -1
- package/dist/narration/index.js +3 -3
- package/dist/schemas/index.d.ts +30 -5
- package/dist/schemas/index.js +41 -3
- package/dist/{themeLibrary-RjVgLpUi.d.ts → themeLibrary-B72m0W1y.d.ts} +1 -1
- package/dist/transform/index.d.ts +8 -9
- package/dist/transform/index.js +1 -1
- package/package.json +1 -1
- package/src/__tests__/customThemesFrontmatter.test.ts +1 -0
- package/src/__tests__/markdown.test.ts +13 -4
- package/src/__tests__/markdownSanitize.test.ts +7 -5
- package/src/__tests__/materializeBlockLayers.test.ts +32 -0
- package/src/__tests__/materializePageSections.test.ts +404 -0
- package/src/__tests__/pageStyle.test.ts +258 -0
- package/src/__tests__/templateAnnotationParse.test.ts +13 -0
- package/src/doc/index.ts +34 -0
- package/src/doc/markdownToDoc.ts +3 -1
- package/src/doc/materializeBlockLayers.ts +170 -9
- package/src/doc/page/PageSection.ts +174 -0
- package/src/doc/page/materializePageSection.ts +616 -0
- package/src/doc/page/resolvePageBlock.ts +108 -0
- package/src/doc/page/sectionExtractors.ts +466 -0
- package/src/doc/pageCss.ts +628 -0
- package/src/doc/templateInputs.ts +1 -0
- package/src/doc/templates/__tests__/listBlock.test.ts +64 -0
- package/src/doc/templates/listBlock.ts +88 -30
- package/src/schemas/Doc.ts +22 -1
- package/src/schemas/PageStyle.ts +213 -0
- package/src/schemas/Theme.ts +7 -0
- package/src/schemas/index.ts +2 -0
- package/src/schemas/pageStyleDefaults.ts +204 -0
- package/src/schemas/themeCompile.ts +7 -0
- package/src/schemas/themeValidator.ts +183 -0
- package/src/schemas/themes/bold.json +29 -0
- package/src/schemas/themes/cinematic.json +32 -0
- package/src/schemas/themes/documentary.json +29 -0
- package/src/schemas/themes/gezellig.json +31 -1
- package/src/schemas/themes/magazine.json +37 -0
- package/src/schemas/themes/minimalist.json +29 -0
- package/src/schemas/themes/morning-light.json +32 -0
- package/src/schemas/themes/standard-dark.json +24 -0
- package/src/schemas/themes/standard.json +24 -0
- package/src/schemas/themes/tech-dark.json +42 -0
- package/src/schemas/themes/warm-earth.json +24 -0
- package/src/transform/registry.ts +19 -0
- package/src/transform/styles/dataDriven.ts +1 -0
- package/src/transform/styles/documentary.ts +1 -0
- package/src/transform/styles/magazine.ts +1 -0
- package/src/transform/styles/minimal.ts +1 -0
- package/src/transform/styles/narrative.ts +1 -0
- package/src/transform/types.ts +7 -0
- package/dist/chunk-6PJRB2CF.js.map +0 -1
- package/dist/chunk-FVJUUTEM.js +0 -74
- package/dist/chunk-FVJUUTEM.js.map +0 -1
- package/dist/chunk-GF3BVNLU.js.map +0 -1
- package/dist/chunk-LYNJEOAC.js.map +0 -1
- package/dist/chunk-PXLVXTLW.js.map +0 -1
- package/dist/chunk-QVANWDPH.js.map +0 -1
- /package/dist/{chunk-QTSJOY54.js.map → chunk-VYFRI7R6.js.map} +0 -0
- /package/dist/{chunk-T3TI7GSZ.js.map → chunk-XNLB57UD.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
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":";;;;;;;;;;;;;;AA++BO,SAAS,kBAAkB,OAA2B;AAC3D,SAAO,MAAM,SAAS,OAAO,CAAC,KAAK,QAAQ,MAAM,IAAI,UAAU,CAAC;AAClE;AAKO,SAAS,iBAAiB,OAAmB,MAAsB;AACxE,MAAI,UAAU;AACd,WAAS,IAAI,GAAG,IAAI,MAAM,SAAS,QAAQ,KAAK;AAC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AqB;AAC9C,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,IAAI;AAAA,EAC1B,SAAS,KAAc;AACrB,UAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC3D,UAAM,IAAI,MAAM,uBAAuB,GAAG,EAAE;AAAA,EAC9C;AACA,SAAO,YAAY,QAAQ,cAAc;AAC3C;AAMO,SAAS,eAAe,OAAsB;AACnD,SAAO,KAAK,UAAU,OAAO,MAAM,CAAC;AACtC;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/transform/styles/documentary.ts","../src/transform/styles/magazine.ts","../src/transform/styles/dataDriven.ts","../src/transform/styles/narrative.ts","../src/transform/styles/minimal.ts","../src/transform/registry.ts","../src/transform/blockAnalyzer.ts","../src/transform/templateSelector.ts","../src/transform/timingAllocator.ts","../src/transform/applyTransform.ts"],"sourcesContent":["import type { TransformStyleConfig } from '../types.js';\n\n/** Conservative style — sparse highlights, preserves most text as-is. */\nexport const documentaryStyle: TransformStyleConfig = {\n id: 'documentary',\n name: 'Documentary',\n description: 'Conservative — highlights only the strongest stats, dates, and quotes',\n minConfidence: 0.5,\n transformRatio: 0.3,\n preferredTypes: ['stat', 'date', 'quote', 'fact'],\n colorSchemes: ['blue', 'green', 'purple'],\n insertSectionHeaders: false,\n interleaveImages: true,\n blocksPerSection: { max: 3 },\n transitionStyle: 'fade',\n suggestedThemeId: 'documentary',\n};\n","import type { TransformStyleConfig } from '../types.js';\n\n/** Visual variety — pull quotes, definitions, image-heavy layout. */\nexport const magazineStyle: TransformStyleConfig = {\n id: 'magazine',\n name: 'Magazine',\n description: 'Visual variety with pull quotes, facts, and rich image layouts',\n minConfidence: 0.4,\n transformRatio: 0.6,\n preferredTypes: ['quote', 'fact', 'list', 'definition', 'stat', 'impactLine'],\n colorSchemes: ['blue', 'green', 'purple', 'orange', 'red'],\n insertSectionHeaders: true,\n interleaveImages: true,\n blocksPerSection: { max: 5 },\n transitionStyle: 'dissolve',\n suggestedThemeId: 'magazine',\n templateMap: { quote: 'pullQuote', impactLine: 'fullBleedQuote' },\n};\n","import type { TransformStyleConfig } from '../types.js';\n\n/** Numbers-forward — aggressively extracts stats, comparisons, and dates. */\nexport const dataDrivenStyle: TransformStyleConfig = {\n id: 'data-driven',\n name: 'Data-Driven',\n description: 'Aggressively highlights statistics, comparisons, and timelines',\n minConfidence: 0.3,\n transformRatio: 0.8,\n preferredTypes: ['stat', 'comparison', 'date', 'list', 'fact'],\n colorSchemes: ['blue', 'orange', 'green', 'purple', 'red'],\n insertSectionHeaders: true,\n interleaveImages: false,\n blocksPerSection: { max: 6 },\n transitionStyle: 'cut',\n suggestedThemeId: 'tech-dark',\n};\n","import type { TransformStyleConfig } from '../types.js';\n\n/** Timeline-focused — emphasizes dates, quotes, and story arc. */\nexport const narrativeStyle: TransformStyleConfig = {\n id: 'narrative',\n name: 'Narrative',\n description: 'Story-driven with timeline events, quotes, and impact moments',\n minConfidence: 0.4,\n transformRatio: 0.5,\n preferredTypes: ['date', 'quote', 'impactLine', 'fact', 'stat'],\n colorSchemes: ['blue', 'purple', 'green'],\n insertSectionHeaders: true,\n interleaveImages: true,\n blocksPerSection: { max: 4 },\n transitionStyle: 'fade',\n suggestedThemeId: 'cinematic',\n pacing: { intro: true, outro: true },\n};\n","import type { TransformStyleConfig } from '../types.js';\n\n/** Light touch — only the highest-confidence items get transformed. */\nexport const minimalStyle: TransformStyleConfig = {\n id: 'minimal',\n name: 'Minimal',\n description: 'Light touch — only the strongest highlights, mostly text',\n minConfidence: 0.6,\n transformRatio: 0.2,\n preferredTypes: ['stat', 'quote'],\n colorSchemes: ['blue', 'green'],\n insertSectionHeaders: false,\n interleaveImages: false,\n blocksPerSection: { max: 2 },\n transitionStyle: 'fade',\n suggestedThemeId: 'minimalist',\n};\n","/**\n * Transform Style Registry\n *\n * Immutable built-in lookup plus explicit caller-owned custom registries.\n * There is deliberately no process-global mutable registry.\n */\n\nimport type { TransformStyleConfig, TransformStyleInput, TransformStyleRegistry } from './types.js';\nimport { documentaryStyle } from './styles/documentary.js';\nimport { magazineStyle } from './styles/magazine.js';\nimport { dataDrivenStyle } from './styles/dataDriven.js';\nimport { narrativeStyle } from './styles/narrative.js';\nimport { minimalStyle } from './styles/minimal.js';\nimport { cloneAndFreezeData } from '../internal/immutable.js';\n\n/** All built-in transform styles, keyed by id. */\nconst TRANSFORM_STYLES: Readonly<Record<string, TransformStyleConfig>> = Object.freeze({\n [documentaryStyle.id]: cloneAndFreezeData(documentaryStyle),\n [magazineStyle.id]: cloneAndFreezeData(magazineStyle),\n [dataDrivenStyle.id]: cloneAndFreezeData(dataDrivenStyle),\n [narrativeStyle.id]: cloneAndFreezeData(narrativeStyle),\n [minimalStyle.id]: cloneAndFreezeData(minimalStyle),\n});\n\n/** Default style used when no id is provided. */\nexport const DEFAULT_TRANSFORM_STYLE_ID = 'documentary';\n\nconst EXTRACTION_TYPES = new Set([\n 'stat',\n 'date',\n 'quote',\n 'comparison',\n 'fact',\n 'impactLine',\n 'list',\n 'definition',\n]);\nconst TRANSITION_STYLES = new Set(['cut', 'fade', 'dissolve', 'mixed']);\n\nfunction validateTransformStyle(style: TransformStyleConfig): void {\n const candidate = style as unknown as Record<string, unknown>;\n const fail = (message: string): never => {\n throw new TypeError(`Invalid transform style: ${message}`);\n };\n for (const key of ['id', 'name', 'description']) {\n if (typeof candidate[key] !== 'string' || !(candidate[key] as string).trim()) {\n fail(`${key} must be a non-empty string`);\n }\n }\n for (const key of ['minConfidence', 'transformRatio']) {\n const value = candidate[key];\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {\n fail(`${key} must be a finite number between 0 and 1`);\n }\n }\n if (\n !Array.isArray(candidate.preferredTypes) ||\n candidate.preferredTypes.some((type) => !EXTRACTION_TYPES.has(type))\n ) {\n fail('preferredTypes contains an unknown extraction type');\n }\n if (\n !Array.isArray(candidate.colorSchemes) ||\n candidate.colorSchemes.length === 0 ||\n candidate.colorSchemes.some((scheme) => typeof scheme !== 'string' || !scheme)\n ) {\n fail('colorSchemes must contain at least one non-empty string');\n }\n for (const key of ['insertSectionHeaders', 'interleaveImages']) {\n if (typeof candidate[key] !== 'boolean') fail(`${key} must be a boolean`);\n }\n const blocks = candidate.blocksPerSection as { max?: unknown } | undefined;\n if (!blocks || !Number.isInteger(blocks.max) || (blocks.max as number) < 1) {\n fail('blocksPerSection.max must be a positive integer');\n }\n if (\n typeof candidate.transitionStyle !== 'string' ||\n !TRANSITION_STYLES.has(candidate.transitionStyle)\n ) {\n fail('transitionStyle must be cut, fade, dissolve, or mixed');\n }\n const templateMap = candidate.templateMap;\n if (templateMap !== undefined) {\n if (!templateMap || typeof templateMap !== 'object' || Array.isArray(templateMap)) {\n fail('templateMap must be an object');\n }\n for (const [type, template] of Object.entries(templateMap as Record<string, unknown>)) {\n if (!EXTRACTION_TYPES.has(type) || typeof template !== 'string' || !template) {\n fail('templateMap must map known extraction types to non-empty template names');\n }\n }\n }\n if (\n candidate.suggestedThemeId !== undefined &&\n (typeof candidate.suggestedThemeId !== 'string' || !candidate.suggestedThemeId)\n ) {\n fail('suggestedThemeId must be a non-empty string');\n }\n const pacingValue = candidate.pacing;\n if (pacingValue !== undefined) {\n if (!pacingValue || typeof pacingValue !== 'object' || Array.isArray(pacingValue)) {\n fail('pacing must be an object');\n }\n const pacing = pacingValue as { intro?: unknown; outro?: unknown };\n for (const key of ['intro', 'outro'] as const) {\n if (pacing[key] !== undefined && typeof pacing[key] !== 'boolean') {\n fail(`pacing.${key} must be a boolean`);\n }\n }\n }\n const budget = candidate.budget as { slidesPerMinute?: unknown } | undefined;\n if (\n candidate.budget !== undefined &&\n (!budget || typeof budget !== 'object' || Array.isArray(budget))\n ) {\n fail('budget must be an object');\n }\n if (budget && budget.slidesPerMinute !== undefined) {\n const value = budget.slidesPerMinute;\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n fail('budget.slidesPerMinute must be a positive finite number');\n }\n }\n}\n\nfunction styleSnapshot(style: TransformStyleConfig): TransformStyleConfig {\n validateTransformStyle(style);\n return cloneAndFreezeData(style);\n}\n\n/** Stored documents emitted before the canonical kebab-case id. Not exported. */\nfunction normalizeBuiltinStyleId(id: string): string {\n return id === 'dataDriven' ? 'data-driven' : id;\n}\n\nfunction resolveBuiltinStyle(id: string): TransformStyleConfig {\n return (\n TRANSFORM_STYLES[normalizeBuiltinStyleId(id)] ?? TRANSFORM_STYLES[DEFAULT_TRANSFORM_STYLE_ID]\n );\n}\n\n/**\n * Create a caller-owned registry. Custom styles are validated, cloned, and\n * deeply frozen at registration time. Built-in resolution remains in the\n * top-level helpers, separate from the registry's caller-owned state.\n */\nexport function createTransformStyleRegistry(\n initialStyles: readonly TransformStyleConfig[] = [],\n): TransformStyleRegistry {\n const registeredStyles = new Map<string, TransformStyleConfig>();\n const registry: TransformStyleRegistry = {\n register(style): void {\n const snapshot = styleSnapshot(style);\n registeredStyles.set(snapshot.id, snapshot);\n },\n unregister(id): boolean {\n return registeredStyles.delete(id);\n },\n get(id): TransformStyleConfig | undefined {\n return registeredStyles.get(id);\n },\n list(): TransformStyleConfig[] {\n return Array.from(registeredStyles.values());\n },\n };\n for (const style of initialStyles) registry.register(style);\n return Object.freeze(registry);\n}\n\n/**\n * Resolve a built-in id, explicit-registry id, or call-scoped style config.\n * Unknown ids fall back to the default style.\n */\nexport function resolveTransformStyle(\n style: TransformStyleInput,\n registry?: TransformStyleRegistry,\n): TransformStyleConfig {\n if (typeof style !== 'string') return styleSnapshot(style);\n return registry?.get(style) ?? resolveBuiltinStyle(style);\n}\n\n/** Get built-in ids plus ids from an optional caller-owned registry. */\nexport function getTransformStyleIds(registry?: TransformStyleRegistry): string[] {\n return Array.from(\n new Set([\n ...Object.keys(TRANSFORM_STYLES),\n ...(registry?.list().map((style) => style.id) ?? []),\n ]),\n );\n}\n\n/** Get summaries for built-ins plus an optional caller-owned registry. */\nexport function getTransformStyleSummaries(registry?: TransformStyleRegistry) {\n return getTransformStyleIds(registry).map((id) => {\n const { name, description } = resolveTransformStyle(id, registry);\n return { id, name, description };\n });\n}\n","/**\n * Block Analyzer\n *\n * Walks Doc blocks, extracts plain text from their markdown contents,\n * and runs the content extractor on each block to identify stats, dates,\n * quotes, etc. that can be promoted to visual template blocks.\n */\n\nimport type { Block } from '../schemas/Doc.js';\nimport type { MarkdownBlockNode, MarkdownNode } from '../markdown/types.js';\nimport type { ExtractedElement, ExtractionOptions } from '../generate/contentExtractor.js';\nimport type { TransformImage } from './types.js';\nimport { extractContent, stripMarkdown } from '../generate/contentExtractor.js';\nimport { extractPlainText, getChildren } from '../markdown/utils.js';\n\n/** An image found in a block's markdown contents. */\nexport interface BlockImage {\n /** Image URL (relative or absolute). */\n src: string;\n /** Alt text. */\n alt: string;\n /** Index of the source block in the analyzed array. */\n sourceBlockIndex: number;\n}\n\n/** A block enriched with extraction analysis. */\nexport interface AnalyzedBlock {\n /** The original block. */\n block: Block;\n /** Plain text extracted from the block's contents. */\n plainText: string;\n /** Content extractions found in the block's text. */\n extractions: ExtractedElement[];\n /** Whether this block has child blocks. */\n hasChildren: boolean;\n /** Word count of the block's body text. */\n bodyWordCount: number;\n /** Images found in this block's markdown contents. */\n images: BlockImage[];\n}\n\n/**\n * Extract plain text from an array of MarkdownBlockNodes.\n */\nfunction contentsToPlainText(contents: MarkdownBlockNode[]): string {\n return contents.map((node) => extractPlainText(node)).join('\\n');\n}\n\n/**\n * Recursively walk a markdown node tree and collect all images.\n */\nfunction collectImages(node: MarkdownNode): Array<{ src: string; alt: string }> {\n const results: Array<{ src: string; alt: string }> = [];\n\n if ('type' in node && node.type === 'image' && 'url' in node) {\n const img = node as { url: string; alt?: string };\n if (img.url) {\n results.push({ src: img.url, alt: img.alt ?? '' });\n }\n }\n\n for (const child of getChildren(node)) {\n results.push(...collectImages(child));\n }\n\n return results;\n}\n\n/**\n * Extract images from a block's markdown contents.\n */\nfunction extractBlockImages(block: Block, blockIndex: number): BlockImage[] {\n if (!block.contents || block.contents.length === 0) return [];\n\n const images: BlockImage[] = [];\n for (const node of block.contents) {\n for (const img of collectImages(node)) {\n images.push({ ...img, sourceBlockIndex: blockIndex });\n }\n }\n return images;\n}\n\n/**\n * Collect all unique images from all blocks in a Doc.\n * Returns them as TransformImages for use in the transform pipeline.\n */\nexport function extractDocImages(blocks: Block[]): TransformImage[] {\n const seen = new Set<string>();\n const images: TransformImage[] = [];\n\n function walk(blockList: Block[]): void {\n for (const block of blockList) {\n if (block.contents) {\n for (const node of block.contents) {\n for (const img of collectImages(node)) {\n if (!seen.has(img.src)) {\n seen.add(img.src);\n images.push({ src: img.src, alt: img.alt });\n }\n }\n }\n }\n if (block.children) {\n walk(block.children);\n }\n }\n }\n\n walk(blocks);\n return images;\n}\n\n/**\n * Collect leaf blocks from a nested block tree.\n * Only returns blocks that have their own `contents` but no children,\n * preventing parent blocks from duplicating text that also appears\n * in their children. Parent-only blocks (with a title but no body\n * content) are included as structural placeholders.\n */\nfunction collectLeafBlocks(blocks: Block[]): Block[] {\n const result: Block[] = [];\n for (const block of blocks) {\n if (block.children && block.children.length > 0) {\n // Parent block — only include it as a structural marker\n // (title only, no body extraction) if it has no contents of its own.\n // Then recurse into children for the actual content.\n if (!block.contents || block.contents.length === 0) {\n result.push(block);\n }\n result.push(...collectLeafBlocks(block.children));\n } else {\n // Leaf block — include for content analysis\n result.push(block);\n }\n }\n return result;\n}\n\n/**\n * Analyze all blocks in a Doc, extracting text and running content extraction.\n *\n * @param blocks - The Doc's block array (may be nested via children).\n * @param options - Extraction options (minConfidence, types filter).\n * @returns Analyzed blocks with extractions, in flattened order.\n */\nexport function analyzeBlocks(blocks: Block[], options?: ExtractionOptions): AnalyzedBlock[] {\n const flat = collectLeafBlocks(blocks);\n const results: AnalyzedBlock[] = [];\n\n for (const block of flat) {\n let plainText = '';\n\n if (block.contents && block.contents.length > 0) {\n plainText = contentsToPlainText(block.contents);\n } else if (block.title) {\n plainText = block.title;\n }\n\n // Strip any remaining markdown syntax\n const stripped = stripMarkdown(plainText);\n const bodyWordCount = stripped.split(/\\s+/).filter((w) => w.length > 0).length;\n\n // Run content extraction\n const extraction = extractContent(stripped, options);\n\n // Extract images from markdown contents\n const images = extractBlockImages(block, results.length);\n\n results.push({\n block,\n plainText: stripped,\n extractions: extraction.elements,\n hasChildren: !!(block.children && block.children.length > 0),\n bodyWordCount,\n images,\n });\n }\n\n return results;\n}\n","/**\n * Template Selector\n *\n * Selects which extracted elements to promote to visual template blocks\n * and handles color scheme rotation, image interleaving, and template\n * variety. Ported and generalized from qualla-internal's TemplateSelector.\n */\n\nimport type { Block, TransitionType } from '../schemas/Doc.js';\nimport type {\n TemplateBlock,\n AccentImage,\n AccentPosition,\n ImageWithCaptionInput,\n SectionHeaderInput,\n QuoteBlockInput,\n FullBleedQuoteInput,\n StatHighlightInput,\n} from '../schemas/BlockTemplates.js';\nimport type { ExtractedElement } from '../generate/contentExtractor.js';\nimport type { TransformStyleConfig, TransformImage } from './types.js';\nimport type { AnalyzedBlock } from './blockAnalyzer.js';\nimport { mapElementToBlock } from '../generate/templateMapper.js';\nimport { SeededRandom } from '../random/SeededRandom.js';\nimport { estimateTimeFromText } from '../timing/narrationTiming.js';\n\n/** Accent positions to rotate through. */\nconst ACCENT_POSITIONS: AccentPosition[] = [\n 'left-strip',\n 'right-strip',\n 'bottom-strip',\n 'corner-inset',\n];\n\n/** Ambient motions to rotate on image blocks. */\nconst AMBIENT_MOTIONS: Array<'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight'> = [\n 'zoomIn',\n 'zoomOut',\n 'panLeft',\n 'panRight',\n];\n\n/** A selected element paired with its source block. */\ninterface SelectedExtraction {\n element: ExtractedElement;\n sourceBlock: Block;\n /** Index in the original analyzed blocks array. */\n sourceIndex: number;\n}\n\n/** Result of template selection. */\nexport interface SelectionResult {\n /** Replacement blocks: a mix of original blocks and new template blocks. */\n blocks: Array<Block | TemplateBlock>;\n /** How many blocks were transformed. */\n transformedCount: number;\n /** How many blocks were inserted (images, section headers). */\n insertedCount: number;\n}\n\n/**\n * Select extractions and build a transformed block sequence.\n *\n * @param analyzed - Analyzed blocks from blockAnalyzer.\n * @param config - The transform style configuration.\n * @param images - Available images for interleaving.\n * @param seed - Random seed for deterministic output.\n */\nexport function selectAndBuild(\n analyzed: AnalyzedBlock[],\n config: TransformStyleConfig,\n images: TransformImage[],\n seed: number,\n): SelectionResult {\n const rng = new SeededRandom(seed);\n\n // 1. Collect all extractions across all blocks, filtered by config\n const candidates = collectCandidates(analyzed, config);\n\n // 2. Determine how many blocks to transform. `transformRatio` scales\n // with block count; an optional duration-based budget (slides per\n // minute) caps runaway promotion on long dense documents.\n const ratioCap = Math.max(1, Math.floor(analyzed.length * config.transformRatio));\n const slidesPerMinute = config.budget?.slidesPerMinute;\n const totalDurationSeconds = analyzed.reduce((sum, ab) => sum + (ab.block.duration || 0), 0);\n const budgetCap =\n slidesPerMinute && totalDurationSeconds > 0\n ? Math.max(1, Math.round((totalDurationSeconds / 60) * slidesPerMinute))\n : Infinity;\n const maxTransforms = Math.min(ratioCap, budgetCap);\n const selected = candidates.slice(0, maxTransforms);\n\n // 3. Build the output block sequence\n const result = buildBlockSequence(analyzed, selected, config, images, rng);\n\n return result;\n}\n\n/**\n * Collect candidate extractions from all analyzed blocks, sorted by\n * a combined score of confidence and type preference.\n */\nfunction collectCandidates(\n analyzed: AnalyzedBlock[],\n config: TransformStyleConfig,\n): SelectedExtraction[] {\n const candidates: SelectedExtraction[] = [];\n\n for (let i = 0; i < analyzed.length; i++) {\n const ab = analyzed[i];\n // Skip blocks with no meaningful text\n if (ab.bodyWordCount < 5) continue;\n\n for (const element of ab.extractions) {\n if (element.confidence < config.minConfidence) continue;\n\n candidates.push({\n element,\n sourceBlock: ab.block,\n sourceIndex: i,\n });\n }\n }\n\n // Sort by: preferred type rank (lower = better), then confidence (higher = better)\n const typeRank = new Map(config.preferredTypes.map((t, i) => [t, i]));\n const maxRank = config.preferredTypes.length;\n\n candidates.sort((a, b) => {\n const rankA = typeRank.get(a.element.type) ?? maxRank;\n const rankB = typeRank.get(b.element.type) ?? maxRank;\n if (rankA !== rankB) return rankA - rankB;\n return b.element.confidence - a.element.confidence;\n });\n\n // Deduplicate: if the same extracted text appears multiple times\n // (e.g., from overlapping parent/child blocks), keep only the\n // highest-ranked occurrence.\n const seenTexts = new Set<string>();\n const deduplicated: SelectedExtraction[] = [];\n for (const candidate of candidates) {\n const key = candidate.element.text.trim().toLowerCase();\n if (seenTexts.has(key)) continue;\n seenTexts.add(key);\n deduplicated.push(candidate);\n }\n\n return deduplicated;\n}\n\n/**\n * Build the output block sequence, replacing source blocks with template\n * blocks where extractions were selected, and interleaving images.\n */\nfunction buildBlockSequence(\n analyzed: AnalyzedBlock[],\n selected: SelectedExtraction[],\n config: TransformStyleConfig,\n images: TransformImage[],\n rng: SeededRandom,\n): SelectionResult {\n // Map: sourceIndex → list of selected extractions for that block\n const blockExtractions = new Map<number, SelectedExtraction[]>();\n for (const sel of selected) {\n const list = blockExtractions.get(sel.sourceIndex) ?? [];\n list.push(sel);\n blockExtractions.set(sel.sourceIndex, list);\n }\n\n // Limit extractions per block: cap at blocksPerSection.max and ensure\n // template type variety within each block (no two same-type extractions).\n for (const [idx, list] of blockExtractions) {\n const diverse: SelectedExtraction[] = [];\n const usedTypes = new Set<string>();\n for (const sel of list) {\n if (usedTypes.has(sel.element.type)) continue;\n usedTypes.add(sel.element.type);\n diverse.push(sel);\n if (diverse.length >= config.blocksPerSection.max) break;\n }\n blockExtractions.set(idx, diverse);\n }\n\n const blocks: Array<Block | TemplateBlock> = [];\n let transformedCount = 0;\n let insertedCount = 0;\n let colorIndex = 0;\n let blockIdCounter = 0;\n let imageIndex = 0;\n let accentPositionIndex = 0;\n let elementsSinceImage = 0;\n let prevTemplateType = '';\n\n // Calculate image interleaving interval\n const totalTransformed = Array.from(blockExtractions.values()).reduce(\n (sum, list) => sum + list.length,\n 0,\n );\n const imageInterval =\n config.interleaveImages && images.length > 0 && totalTransformed > 0\n ? Math.max(2, Math.floor(totalTransformed / (images.length + 1)))\n : Infinity;\n\n for (let i = 0; i < analyzed.length; i++) {\n const ab = analyzed[i];\n const extractions = blockExtractions.get(i);\n\n if (!extractions || extractions.length === 0) {\n // Keep the original block unchanged\n blocks.push(ab.block);\n continue;\n }\n\n // Insert section header before a group of transformed blocks (if enabled)\n if (config.insertSectionHeaders && ab.block.title) {\n const headerBlock: SectionHeaderInput = {\n template: 'sectionHeader',\n id: `transform-header-${blockIdCounter++}`,\n duration: ab.block.duration > 0 ? Math.min(3, ab.block.duration * 0.2) : 3,\n audioSegment: ab.block.audioSegment,\n title: ab.block.title,\n colorScheme: config.colorSchemes[colorIndex % config.colorSchemes.length],\n sourceBlockId: ab.block.id,\n };\n blocks.push(headerBlock);\n insertedCount++;\n }\n\n // Convert each selected extraction to a template block.\n // Track the last template used globally (not just within this block)\n // to avoid consecutive same-template slides across the entire output.\n for (const sel of extractions) {\n const colorScheme = config.colorSchemes[colorIndex % config.colorSchemes.length];\n\n // Build accent image if we have images in the pool\n let accentImage: AccentImage | undefined;\n if (images.length > 0 && config.interleaveImages) {\n const img = images[imageIndex % images.length];\n accentImage = {\n src: img.src,\n alt: img.alt ?? '',\n position: ACCENT_POSITIONS[accentPositionIndex % ACCENT_POSITIONS.length],\n ambientMotion: rng.pick(AMBIENT_MOTIONS) ?? 'zoomIn',\n credit: img.credit,\n license: img.license,\n };\n accentPositionIndex++;\n }\n\n // `sourcePosition` is a CHAR OFFSET into the analyzed plain text;\n // `sourceStartTime` is doc-timeline SECONDS. Convert via spoken-word\n // proportion over the source block's timing — which, when the doc\n // carries a narration take (applyNarrationTiming ran upstream), is\n // the recorded voice: summarized slides land where the words are\n // actually spoken.\n const slideShare = ab.block.duration > 0 ? ab.block.duration / extractions.length : 6;\n const offsetInBlock =\n ab.block.duration > 0\n ? estimateTimeFromText(ab.plainText, sel.element.sourcePosition, ab.block.duration)\n : 0;\n let templateBlock = mapElementToBlock(sel.element, {\n id: `transform-${blockIdCounter++}`,\n duration: slideShare,\n audioSegment: ab.block.audioSegment,\n colorScheme,\n accentImage,\n sourceStartTime: ab.block.startTime + offsetInBlock,\n sourceDuration: slideShare,\n sourceBlockId: ab.block.id,\n sourceCharOffset: sel.element.sourcePosition,\n });\n\n // Style-level extraction→template remap (v2 contract). Only known\n // text-compatible pairings translate; image-backed targets consume\n // the accent image as their background. Unknown pairings keep the\n // default mapping.\n const remapTarget = config.templateMap?.[sel.element.data.type];\n if (remapTarget && remapTarget !== templateBlock.template) {\n const translated = translateTemplateBlock(templateBlock, remapTarget);\n if (translated) templateBlock = translated;\n }\n\n // Apply transition based on style\n if (config.transitionStyle !== 'cut') {\n const transitionType: TransitionType =\n config.transitionStyle === 'mixed'\n ? (rng.pick<TransitionType>(['fade', 'dissolve']) ?? 'fade')\n : config.transitionStyle;\n templateBlock.transition = {\n type: transitionType,\n duration: 0.5,\n };\n }\n\n // Avoid consecutive same-template blocks by bumping color for variety\n if (templateBlock.template === prevTemplateType) {\n colorIndex++;\n }\n prevTemplateType = templateBlock.template;\n\n blocks.push(templateBlock);\n transformedCount++;\n colorIndex++;\n elementsSinceImage++;\n\n // Interleave standalone image at intervals\n if (\n config.interleaveImages &&\n imageIndex < images.length &&\n elementsSinceImage >= imageInterval\n ) {\n const img = images[imageIndex];\n const imageBlock: ImageWithCaptionInput = {\n template: 'imageWithCaption',\n id: `transform-img-${blockIdCounter++}`,\n duration: 4,\n audioSegment: ab.block.audioSegment,\n imageSrc: img.src,\n imageAlt: img.alt ?? '',\n ambientMotion: rng.pick(AMBIENT_MOTIONS) ?? 'zoomIn',\n sourceBlockId: ab.block.id,\n };\n blocks.push(imageBlock);\n imageIndex++;\n insertedCount++;\n elementsSinceImage = 0;\n }\n }\n }\n\n return { blocks, transformedCount, insertedCount };\n}\n\n/**\n * Translate a mapped template block into a style-requested target\n * template. Only text-compatible pairings are supported; returns null\n * (keep the default) for unknown pairs or when a required input —\n * a background image for `pullQuote` — is unavailable.\n */\nfunction translateTemplateBlock(block: TemplateBlock, target: string): TemplateBlock | null {\n const base = {\n id: block.id,\n duration: block.duration,\n audioSegment: block.audioSegment,\n sourceStartTime: block.sourceStartTime,\n sourceDuration: block.sourceDuration,\n sourceBlockId: block.sourceBlockId,\n sourceCharOffset: block.sourceCharOffset,\n };\n\n if (block.template === 'quote') {\n const quote = block as QuoteBlockInput;\n if (target === 'fullBleedQuote') {\n return { ...base, template: 'fullBleedQuote', text: quote.quote };\n }\n if (target === 'pullQuote') {\n // pullQuote requires a full-bleed background image — reuse the\n // accent image the selector already assigned to this block.\n const bg = quote.accentImage;\n if (!bg) return null;\n return {\n ...base,\n template: 'pullQuote',\n text: quote.quote,\n attribution: quote.attribution,\n backgroundImage: { src: bg.src, alt: bg.alt, credit: bg.credit, license: bg.license },\n };\n }\n return null;\n }\n\n if (block.template === 'fullBleedQuote' && target === 'quote') {\n const fbq = block as FullBleedQuoteInput;\n return { ...base, template: 'quote', quote: fbq.text };\n }\n\n if (block.template === 'statHighlight' && target === 'factCard') {\n const stat = block as StatHighlightInput;\n return {\n ...base,\n template: 'factCard',\n fact: stat.stat,\n explanation: stat.description,\n accentImage: stat.accentImage,\n };\n }\n\n return null;\n}\n","/**\n * Timing Allocator\n *\n * Distributes timing (startTime, duration) across transformed blocks.\n * When the source Doc has audio, blocks are fitted to the overall duration.\n * When no audio is present, uses reading-time estimation.\n */\n\nimport type { Block } from '../schemas/Doc.js';\nimport type { TemplateBlock } from '../schemas/BlockTemplates.js';\nimport { isTemplateBlock } from '../schemas/BlockTemplates.js';\n\n/** Minimum block duration in seconds. */\nconst MIN_BLOCK_DURATION = 3;\n/** Maximum block duration in seconds. */\nconst MAX_BLOCK_DURATION = 20;\n/** Default duration when no timing info is available. */\nconst DEFAULT_BLOCK_DURATION = 6;\n\n/**\n * Allocate startTime and duration across a mixed array of blocks and\n * template blocks. Template blocks get timing assigned; existing blocks\n * retain their original timing when possible.\n *\n * @param blocks - The output from templateSelector (mixed Block | TemplateBlock).\n * @param totalDuration - The Doc's total duration (from audio or estimation).\n * @returns A new array of Blocks with consistent timing. Template blocks\n * are returned as Blocks (with startTime/duration set, layers empty).\n */\nexport function allocateTiming(\n blocks: Array<Block | TemplateBlock>,\n totalDuration: number,\n): Block[] {\n if (blocks.length === 0) return [];\n\n // Template blocks carrying a numeric `sourceStartTime` are ANCHORED to\n // the doc timeline — when the source doc is narration-timed\n // (`applyNarrationTiming`), those anchors are where the words are\n // actually spoken, and rescaling would tear the slides away from the\n // voice. Anchored blocks keep their positions; floating blocks\n // (intro/outro bookends, section headers, interleaved images) fill the\n // gaps between anchors. With no anchors at all, behavior is the\n // historical rescale-to-fit.\n const hasAnchors = blocks.some(\n (b) => isTemplateBlock(b) && typeof b.sourceStartTime === 'number',\n );\n return hasAnchors\n ? allocateAnchored(blocks, totalDuration)\n : allocateRescaled(blocks, totalDuration);\n}\n\n/** Historical behavior: scale every duration to fill the total, clamp 3–20 s. */\nfunction allocateRescaled(blocks: Array<Block | TemplateBlock>, totalDuration: number): Block[] {\n const effectiveDuration = totalDuration > 0 ? totalDuration : estimateDefaultDuration(blocks);\n\n // First pass: assign raw durations\n const durations = blocks.map((block) => {\n if (!isTemplateBlock(block) && block.duration > 0) {\n // Existing block with known duration — keep it\n return block.duration;\n }\n if (isTemplateBlock(block) && block.duration > 0) {\n return block.duration;\n }\n return DEFAULT_BLOCK_DURATION;\n });\n\n // Scale durations to fit the total\n const rawTotal = durations.reduce((sum, d) => sum + d, 0);\n if (rawTotal > 0 && effectiveDuration > 0) {\n const scale = effectiveDuration / rawTotal;\n for (let i = 0; i < durations.length; i++) {\n durations[i] = clampDuration(durations[i] * scale);\n }\n }\n\n // Second pass: assign startTimes and build output Blocks\n let currentTime = 0;\n const result: Block[] = [];\n for (let i = 0; i < blocks.length; i++) {\n result.push(toOutputBlock(blocks[i], currentTime, durations[i]));\n currentTime += durations[i];\n }\n return result;\n}\n\n/** Minimum duration for a floating block squeezed between anchors. */\nconst MIN_FLOATING_DURATION = 1;\n\n/**\n * Anchor-aware allocation: anchored entries (template blocks with a\n * numeric `sourceStartTime`, and untransformed source Blocks with their\n * own real timing) are PLACED at their timeline positions; runs of\n * floating blocks (bookends, headers, images) distribute across the gap\n * before the next anchor. Durations then derive from consecutive starts\n * so the timeline stays CONTIGUOUS — a slide summarizing unpromoted\n * source content simply holds until the next slide begins, which is\n * what keeps every narration second covered by some block.\n */\nfunction allocateAnchored(blocks: Array<Block | TemplateBlock>, totalDuration: number): Block[] {\n interface Entry {\n block: Block | TemplateBlock;\n anchorStart: number | null;\n rawDuration: number;\n }\n const entries: Entry[] = blocks.map((block) => {\n if (isTemplateBlock(block)) {\n return {\n block,\n anchorStart: typeof block.sourceStartTime === 'number' ? block.sourceStartTime : null,\n rawDuration: block.duration > 0 ? block.duration : DEFAULT_BLOCK_DURATION,\n };\n }\n // Untransformed source blocks carry real (possibly narration) timing.\n return {\n block,\n anchorStart: block.startTime,\n rawDuration: block.duration > 0 ? block.duration : DEFAULT_BLOCK_DURATION,\n };\n });\n\n // Pass 1: starts. Anchors pin their positions (the cursor then jumps\n // past the anchor's authored span, so following floats land AFTER it).\n // Float runs place differently by position: LEADING floats (before any\n // anchor — intro bookends) fill the opening gap from t=0; MID floats\n // (section headers, images) end-align just before the next anchor —\n // a header belongs to the section it introduces; TRAILING floats\n // (outro) run sequentially after the last anchor's span.\n const starts = new Array<number>(entries.length);\n let cursor = 0;\n let seenAnchor = false;\n let i = 0;\n while (i < entries.length) {\n const entry = entries[i];\n if (entry.anchorStart !== null) {\n const start = Math.max(cursor, entry.anchorStart);\n starts[i] = start;\n const hint = isTemplateBlock(entry.block)\n ? (entry.block.sourceDuration ?? entry.rawDuration)\n : entry.rawDuration;\n cursor = start + Math.max(MIN_FLOATING_DURATION, hint);\n seenAnchor = true;\n i++;\n continue;\n }\n const runStart = i;\n while (i < entries.length && entries[i].anchorStart === null) i++;\n const run = entries.slice(runStart, i);\n const rawSum = run.reduce((sum, e) => sum + e.rawDuration, 0);\n const nextAnchorStart =\n i < entries.length ? Math.max(entries[i].anchorStart ?? cursor, cursor) : null;\n\n if (nextAnchorStart === null) {\n // Trailing floats: natural sizes after the last anchor's span.\n let acc = cursor;\n for (let k = 0; k < run.length; k++) {\n starts[runStart + k] = acc;\n acc += run[k].rawDuration;\n }\n cursor = acc;\n } else if (!seenAnchor) {\n // Leading floats: fill [cursor, nextAnchorStart) proportionally.\n const gap = nextAnchorStart - cursor;\n let acc = cursor;\n for (let k = 0; k < run.length; k++) {\n starts[runStart + k] = acc;\n acc += rawSum > 0 ? (run[k].rawDuration / rawSum) * gap : gap / run.length;\n }\n cursor = nextAnchorStart;\n } else {\n // Mid floats: end-aligned at natural size, capped by the gap.\n const gap = Math.max(0, nextAnchorStart - cursor);\n const scale = rawSum > 0 ? Math.min(1, gap / rawSum) : 0;\n let acc = Math.max(cursor, nextAnchorStart - rawSum * scale);\n for (let k = 0; k < run.length; k++) {\n starts[runStart + k] = acc;\n acc += run[k].rawDuration * scale;\n }\n cursor = nextAnchorStart;\n }\n }\n\n // Pass 2: strictly increasing starts, then contiguous durations.\n for (let k = 0; k < starts.length; k++) {\n const floor = k > 0 ? starts[k - 1] + MIN_FLOATING_DURATION : 0;\n if (starts[k] < floor) starts[k] = floor;\n }\n const result: Block[] = [];\n for (let k = 0; k < entries.length; k++) {\n const entry = entries[k];\n let duration: number;\n if (k + 1 < entries.length) {\n duration = Math.max(MIN_FLOATING_DURATION, starts[k + 1] - starts[k]);\n } else {\n const authored = isTemplateBlock(entry.block)\n ? (entry.block.sourceDuration ?? entry.rawDuration)\n : entry.rawDuration;\n // The final block covers through the end of the doc/narration when\n // the caller knows it runs longer.\n duration = Math.max(MIN_FLOATING_DURATION, authored, totalDuration - starts[k]);\n }\n result.push(toOutputBlock(entry.block, starts[k], duration));\n }\n return result;\n}\n\n/**\n * Convert an entry to an output Block shell. Template blocks preserve all\n * template-specific fields (stat, quote, description, …) so they survive\n * through to the player's template expansion step.\n */\nfunction toOutputBlock(block: Block | TemplateBlock, startTime: number, duration: number): Block {\n if (isTemplateBlock(block)) {\n return {\n ...block,\n startTime,\n duration,\n title: getTemplateTitle(block),\n } as unknown as Block;\n }\n return { ...block, startTime, duration };\n}\n\n/** Clamp a duration to the min/max range. */\nfunction clampDuration(d: number): number {\n return Math.max(MIN_BLOCK_DURATION, Math.min(MAX_BLOCK_DURATION, d));\n}\n\n/** Estimate a total duration from block contents when no audio is available. */\nfunction estimateDefaultDuration(blocks: Array<Block | TemplateBlock>): number {\n let totalSeconds = 0;\n for (const block of blocks) {\n if (!isTemplateBlock(block) && block.duration > 0) {\n totalSeconds += block.duration;\n } else {\n totalSeconds += DEFAULT_BLOCK_DURATION;\n }\n }\n return Math.max(totalSeconds, blocks.length * MIN_BLOCK_DURATION);\n}\n\n/** Extract a display title from a template block if available. */\nfunction getTemplateTitle(block: TemplateBlock): string | undefined {\n if ('title' in block && typeof block.title === 'string') {\n return block.title;\n }\n if ('stat' in block && typeof block.stat === 'string') {\n return block.stat;\n }\n if ('fact' in block && typeof block.fact === 'string') {\n return block.fact;\n }\n if ('quote' in block && typeof block.quote === 'string') {\n return block.quote.slice(0, 60);\n }\n return undefined;\n}\n","/**\n * Apply Transform\n *\n * Main entry point for the transform module. Takes a Doc and a style,\n * analyzes block content, selects extractions to promote, and returns\n * a new Doc with blocks optimized for visual presentation.\n *\n * The input Doc is never mutated — a fresh Doc is always returned.\n */\n\nimport type { Doc } from '../schemas/Doc.js';\nimport type { DocBlock, TitleBlockInput, SectionHeaderInput } from '../schemas/BlockTemplates.js';\nimport type { TransformStyleInput, TransformOptions, TransformResult } from './types.js';\nimport { resolveTransformStyle } from './registry.js';\nimport { analyzeBlocks, extractDocImages } from './blockAnalyzer.js';\nimport { selectAndBuild } from './templateSelector.js';\nimport { allocateTiming } from './timingAllocator.js';\nimport { hashString } from '../random/SeededRandom.js';\n\n/**\n * Apply a transform style to a Doc, producing a new Doc with blocks\n * optimized for visual presentation.\n *\n * @param doc - The source Doc (not mutated).\n * @param style - Built-in/registry id or a call-scoped declarative style.\n * @param options - Optional seed, images, theme override, and explicit registry.\n * @returns TransformResult with the new Doc and stats.\n */\nexport function applyTransform(\n doc: Doc,\n style: TransformStyleInput,\n options?: TransformOptions,\n): TransformResult {\n const baseConfig = resolveTransformStyle(style, options?.registry);\n const config = options?.overrides\n ? { ...baseConfig, ...options.overrides, id: baseConfig.id }\n : baseConfig;\n\n const seed = options?.seed ?? hashString(doc.articleId || 'transform');\n\n // Use provided images or auto-extract from the doc's markdown content\n const images = options?.images ?? extractDocImages(doc.blocks);\n\n // 1. Analyze blocks\n const analyzed = analyzeBlocks(doc.blocks, {\n minConfidence: config.minConfidence,\n types: config.preferredTypes,\n });\n\n // If no blocks have meaningful content, return the doc unchanged\n const hasContent = analyzed.some((ab) => ab.bodyWordCount >= 5);\n if (!hasContent) {\n return {\n doc: { ...doc },\n stats: {\n totalInputBlocks: doc.blocks.length,\n transformedBlocks: 0,\n insertedBlocks: 0,\n },\n };\n }\n\n // 2. Select extractions and build template blocks\n const selection = selectAndBuild(analyzed, config, images, seed);\n\n // 2b. Pacing bookends: an opening title beat and/or a closing beat.\n let paced: DocBlock[] = selection.blocks;\n let pacingInserted = 0;\n const docTitle = firstTitle(doc);\n if (config.pacing?.intro && docTitle && !doc.startBlock) {\n const intro: TitleBlockInput = {\n template: 'title',\n id: 'transform-intro',\n duration: 4,\n audioSegment: 0,\n title: docTitle,\n };\n paced = [intro, ...paced];\n pacingInserted++;\n }\n if (config.pacing?.outro && docTitle) {\n const outro: SectionHeaderInput = {\n template: 'sectionHeader',\n id: 'transform-outro',\n duration: 3,\n audioSegment: 0,\n title: docTitle,\n colorScheme: config.colorSchemes[0],\n };\n paced = [...paced, outro];\n pacingInserted++;\n }\n\n // 3. Allocate timing across the new block sequence\n const timedBlocks = allocateTiming(paced, doc.duration);\n\n // 4. Assemble the output Doc. A style's suggested theme applies only\n // when neither the caller nor the doc declares one.\n const transformedDoc: Doc = {\n ...doc,\n blocks: timedBlocks,\n themeId: options?.themeId ?? doc.themeId ?? config.suggestedThemeId,\n };\n\n return {\n doc: transformedDoc,\n stats: {\n totalInputBlocks: doc.blocks.length,\n transformedBlocks: selection.transformedCount,\n insertedBlocks: selection.insertedCount + pacingInserted,\n },\n };\n}\n\n/** First non-empty block title (the doc's working title). */\nfunction firstTitle(doc: Doc): string | undefined {\n if (doc.startBlock?.title) return doc.startBlock.title;\n for (const block of doc.blocks) {\n if (block.title) return block.title;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAGO,IAAM,mBAAyC;AAAA,EACpD,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,aAAa;AAAA,EACb,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,gBAAgB,CAAC,QAAQ,QAAQ,SAAS,MAAM;AAAA,EAChD,cAAc,CAAC,QAAQ,SAAS,QAAQ;AAAA,EACxC,sBAAsB;AAAA,EACtB,kBAAkB;AAAA,EAClB,kBAAkB,EAAE,KAAK,EAAE;AAAA,EAC3B,iBAAiB;AAAA,EACjB,kBAAkB;AACpB;;;ACbO,IAAM,gBAAsC;AAAA,EACjD,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,aAAa;AAAA,EACb,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,gBAAgB,CAAC,SAAS,QAAQ,QAAQ,cAAc,QAAQ,YAAY;AAAA,EAC5E,cAAc,CAAC,QAAQ,SAAS,UAAU,UAAU,KAAK;AAAA,EACzD,sBAAsB;AAAA,EACtB,kBAAkB;AAAA,EAClB,kBAAkB,EAAE,KAAK,EAAE;AAAA,EAC3B,iBAAiB;AAAA,EACjB,kBAAkB;AAAA,EAClB,aAAa,EAAE,OAAO,aAAa,YAAY,iBAAiB;AAClE;;;ACdO,IAAM,kBAAwC;AAAA,EACnD,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,aAAa;AAAA,EACb,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,gBAAgB,CAAC,QAAQ,cAA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