@keboola/design 11.5.0 → 11.6.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.
@@ -1 +1 @@
1
- {"version":3,"file":"MermaidDiagram-CXG5tC6J.js","names":[],"sources":["../src/blocks/MermaidDiagram/mermaidTheme.ts","../src/blocks/MermaidDiagram/MermaidDiagram.tsx"],"sourcesContent":["import type { RenderOptions } from 'beautiful-mermaid';\nimport type { MermaidConfig } from 'mermaid';\n\nimport type { ResolvedColorScheme } from '../../components/ThemeProvider/types';\nimport { createTokenResolver } from '../../utils/themeTokens';\n\nconst DIAGRAM_FONT = 'Inter, system-ui, sans-serif';\n\n/**\n * Fallback channels for the tokens the diagram palette reads, mirroring the\n * `:root` / `[data-theme='dark']` blocks of `styles.css`.\n *\n * `resolveToken` only reaches these when the live custom property is missing —\n * SSR, or a unit test that loads no CSS. In the browser the computed value wins,\n * which is what makes a customer brand re-skin the diagram for free.\n */\nconst FALLBACK_CHANNELS = {\n card: { light: '255 255 255', dark: '34 34 40' },\n 'card-foreground': { light: '30 41 59', dark: '229 230 236' },\n foreground: { light: '30 41 59', dark: '229 230 236' },\n muted: { light: '241 245 249', dark: '38 38 45' },\n 'muted-foreground': { light: '100 116 139', dark: '141 144 153' },\n border: { light: '229 231 235', dark: '52 53 62' },\n primary: { light: '37 99 235', dark: '31 143 255' },\n accent: { light: '224 242 254', dark: '30 58 95' },\n 'accent-foreground': { light: '13 65 127', dark: '147 197 253' },\n warning: { light: '138 82 16', dark: '255 190 92' },\n success: { light: '24 122 76', dark: '62 207 127' },\n destructive: { light: '220 38 38', dark: '229 72 77' },\n} as const;\n\ntype TokenName = keyof typeof FALLBACK_CHANNELS;\n\n/**\n * Binds a token lookup to one `getComputedStyle` snapshot for the whole palette.\n * Built per call, never hoisted: the values move with the scheme and the brand.\n */\nconst tokenReader = (scheme: ResolvedColorScheme, from?: Element | null) => {\n const resolve = createTokenResolver(from);\n return (name: TokenName, alpha?: number): string =>\n resolve(name, FALLBACK_CHANNELS[name][scheme], alpha);\n};\n\n/**\n * Palette for `beautiful-mermaid`'s synchronous renderer. It sets these as CSS\n * variables on the `<svg>` and derives everything else it needs from `bg` + `fg`\n * with `color-mix()` — which is why leaving them at the library defaults painted\n * a near-white node fill (#f8f8f8, mixed from a white `bg`) on a dark page.\n *\n * `transparent` keeps the page background showing through, so `bg` only feeds\n * those derivations; the node fill is pinned explicitly via `surface`.\n */\nexport const fastRenderOptions = (\n scheme: ResolvedColorScheme,\n from?: Element | null,\n): RenderOptions => {\n const token = tokenReader(scheme, from);\n\n return {\n bg: token('card'),\n fg: token('foreground'),\n line: token('border'),\n accent: token('primary'),\n muted: token('muted-foreground'),\n surface: token('muted'),\n border: token('border'),\n transparent: true,\n font: DIAGRAM_FONT,\n };\n};\n\n/**\n * Config for the async `mermaid` renderer (the fallback for dialects the fast\n * renderer can't parse, and for icon-pack diagrams).\n *\n * Built on the `base` theme so every colour comes from `themeVariables` rather\n * than mermaid's own light/dark palettes. Node chrome maps to the `accent` pair\n * (a tinted surface with a legible foreground in both schemes), containers to\n * `card`, and the gantt/note states to the status tokens — consumed as a low\n * alpha tint plus a solid mark, per the brand-neutrality contract, since the\n * status tokens themselves are text-legible colours rather than fills.\n */\nexport const mermaidConfig = (\n scheme: ResolvedColorScheme,\n from?: Element | null,\n): MermaidConfig => {\n const token = tokenReader(scheme, from);\n\n const surface = token('accent');\n const onSurface = token('accent-foreground');\n const container = token('card');\n const onContainer = token('card-foreground');\n const line = token('border');\n const stroke = token('primary');\n const text = token('foreground');\n\n return {\n startOnLoad: false,\n securityLevel: 'strict',\n theme: 'base',\n themeVariables: {\n darkMode: scheme === 'dark',\n background: container,\n primaryColor: surface,\n primaryTextColor: onSurface,\n primaryBorderColor: stroke,\n secondaryColor: container,\n secondaryTextColor: onContainer,\n secondaryBorderColor: line,\n tertiaryColor: token('warning', 0.15),\n tertiaryTextColor: token('warning'),\n tertiaryBorderColor: token('warning'),\n lineColor: line,\n textColor: text,\n mainBkg: surface,\n nodeBorder: stroke,\n clusterBkg: container,\n clusterBorder: line,\n titleColor: text,\n edgeLabelBackground: container,\n nodeTextColor: onSurface,\n actorBorder: stroke,\n actorBkg: surface,\n actorTextColor: onSurface,\n actorLineColor: line,\n signalColor: text,\n signalTextColor: text,\n labelBoxBkgColor: surface,\n labelBoxBorderColor: stroke,\n labelTextColor: onSurface,\n loopTextColor: text,\n noteBorderColor: token('warning'),\n noteBkgColor: token('warning', 0.15),\n noteTextColor: text,\n sectionBkgColor: surface,\n altSectionBkgColor: container,\n sectionBkgColor2: token('muted'),\n taskBorderColor: stroke,\n taskBkgColor: surface,\n taskTextColor: onSurface,\n taskTextDarkColor: text,\n taskTextLightColor: text,\n activeTaskBorderColor: stroke,\n activeTaskBkgColor: token('primary', 0.25),\n doneTaskBorderColor: token('success'),\n doneTaskBkgColor: token('success', 0.15),\n critBorderColor: token('destructive'),\n critBkgColor: token('destructive', 0.15),\n fontFamily: DIAGRAM_FONT,\n fontSize: '14px',\n },\n };\n};\n","import { useEffect, useId, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport { renderMermaidSVG } from 'beautiful-mermaid';\nimport type mermaid from 'mermaid';\n\nimport type { ResolvedColorScheme } from '../../components/ThemeProvider/types';\nimport { useThemeAttributes } from '../../components/ThemeProvider/useThemeAttributes';\nimport { ZoomableSvg } from '../../components/ZoomableSvg';\nimport { DiagramSkeleton } from '../DiagramShared/DiagramSkeleton';\nimport { DiagramSource } from '../DiagramShared/DiagramSource';\nimport {\n flattenForeignObjectLabels,\n hasDrawnContent,\n makeResponsive,\n} from '../DiagramShared/svgTransforms';\n\nimport { fastRenderOptions, mermaidConfig } from './mermaidTheme';\n\ntype MermaidModule = { default: typeof mermaid };\n\nlet mermaidPromise: Promise<MermaidModule> | null = null;\n\n// Iconify icon pack registered with mermaid so `@{ icon: \"lucide:name\" }` node\n// shapes and `architecture-beta service <id>(lucide:name)` render — keeping\n// diagram glyphs consistent with the Lucide icons used across the rest of the UI.\n// The pack JSON resolves from a workspace dependency (no CDN fetch) via a dynamic\n// import, so it lands in its own lazy chunk and icons render offline / under a\n// strict CSP without weighing down the initial bundle.\nconst registerLucideIconPack = (m: typeof mermaid): void => {\n m.registerIconPacks([\n {\n name: 'lucide',\n loader: () => import('@iconify-json/lucide/icons.json').then((mod) => mod.default),\n },\n ]);\n};\n\nconst getMermaid = (): Promise<MermaidModule> => {\n if (!mermaidPromise) {\n mermaidPromise = import('mermaid')\n .then((m) => {\n registerLucideIconPack(m.default);\n return m;\n })\n .catch((err) => {\n mermaidPromise = null;\n throw err;\n });\n }\n return mermaidPromise;\n};\n\nconst stripFontImports = (svg: string): string =>\n svg.replace(/@import\\s+url\\([^)]*fonts\\.googleapis\\.com[^)]*\\);?\\s*/g, '');\n\n// beautiful-mermaid's synchronous renderer has no icon-pack support, so a diagram\n// using icon syntax must skip the fast path and take the async mermaid render\n// (which registers the pack). Matches:\n// - the flowchart / treeView icon shape `@{ icon: \"pack:name\" }`\n// - `architecture-beta` / `treeView` refs `icon|service|group <id>(pack:name)`\n// (the id between keyword and `(` is optional)\n// - legacy FontAwesome refs `fa:fa-*` / `fab:` embedded in node text\nconst hasIconSyntax = (code: string): boolean =>\n /@\\{[^}]*\\bicon\\s*:/.test(code) ||\n /\\b(?:icon|service|group)\\b[^\\n(]*\\(\\s*[\\w-]+:/.test(code) ||\n /\\bfa[bslr]?:fa-/.test(code);\n\nconst tryFastRender = (\n code: string,\n scheme: ResolvedColorScheme,\n from: Element | null,\n): string | null => {\n if (hasIconSyntax(code)) return null;\n try {\n const svg = stripFontImports(renderMermaidSVG(code, fastRenderOptions(scheme, from)));\n // A zero-sized result is a silent layout failure, not a diagram — take the\n // async fallback rather than caching an empty box. See `hasDrawnContent`.\n return hasDrawnContent(svg) ? svg : null;\n } catch (err) {\n // beautiful-mermaid can't parse every mermaid dialect; the async mermaid\n // renderer is the fallback. Log at debug so regressions are diagnosable\n // without noising up the console on the expected unsupported-syntax path.\n console.debug('[MermaidDiagram] fast render unavailable, using async fallback:', err);\n return null;\n }\n};\n\n/**\n * Whether a mermaid parse error means \"ran out of input\" rather than \"bad syntax\".\n *\n * - Mermaid's jison parsers report the end of input as token `1`, so a source\n * truncated mid-diagram — every intermediate frame of a streaming answer —\n * fails with `hash.token === 1`.\n * - Genuinely invalid syntax fails on a real token (`'ONLY_ONE'`, …) instead.\n * - Only a lower bound: some truncations do land on a real token and read as\n * invalid. Those fall through to the `<pre>` fallback for one frame and clear\n * when the next chunk arrives, which is the pre-existing behaviour.\n */\nconst isTruncatedDiagram = (err: unknown): boolean =>\n typeof err === 'object' && err !== null && 'hash' in err\n ? (err as { hash?: { token?: unknown } }).hash?.token === 1\n : false;\n\nconst RENDER_DEBOUNCE_MS = 300;\n\n// How long a truncated diagram is held as \"still arriving\" before it is shown as\n// source. Comfortably longer than the gap between streamed chunks, short enough\n// that an abandoned stream resolves while the reader is still looking at it.\nconst TRUNCATION_GRACE_MS = 2_000;\n\n// Module-level SVG cache — persists across component remounts (e.g. tab switches\n// that cause React to remount the tree). The colours are baked into the markup,\n// so the key is the code *plus* the theme key (scheme + brand): the same diagram\n// is a different SVG under a different colour scheme or brand.\nconst svgCache = new Map<string, string>();\n\nconst diagramCacheKey = (code: string, themeKey: string): string => `${themeKey}\\n${code}`;\n\n// Resolve an SVG synchronously: cache hit first, otherwise a fast synchronous\n// render. Caches the result and returns it, or null when neither is available\n// (the caller then falls back to the async mermaid render).\nconst resolveSyncSvg = (\n code: string,\n cacheKey: string,\n scheme: ResolvedColorScheme,\n from: Element | null,\n): string | null => {\n const cached = svgCache.get(cacheKey);\n if (cached) return cached;\n const fast = tryFastRender(code, scheme, from);\n if (fast) svgCache.set(cacheKey, fast);\n return fast;\n};\n\ntype Props = {\n /** Mermaid diagram source code. Supports flowchart, sequence, class, state, ER,\n * pie, gantt, and mindmap. Gantt `dateFormat HH:mm` (time-only) is not supported\n * by mermaid's dayjs parser — use `dateFormat YYYY-MM-DD HH:mm` with `axisFormat %H:%M` instead. */\n code: string;\n /** Extra toolbar controls (e.g. an `ExportMenu`), forwarded to `ZoomableSvg`.\n * Receives the sanitized SVG. Omit to keep the default toolbar. */\n renderActions?: (safeSvg: string) => ReactNode;\n};\n\nexport const MermaidDiagram = ({ code, renderActions }: Props) => {\n const id = useId();\n // Re-renders whenever the active colour scheme or brand changes, so the\n // diagram is re-rendered in the new palette instead of staying a light island\n // on a dark page. The scheme comes out of the same read as the key, so the\n // palette can never be resolved under one scheme and cached under the other —\n // see `useThemeAttributes` for why the theme context is a step ahead of the\n // CSS variables it stands for.\n // `scope` is the element the live tokens are read off — the enclosing `ThemeScope`'s own,\n // or `null` for `<html>`. It is part of `themeKey`, so a palette built before the scope\n // answered is never served afterwards.\n const { scheme, cacheKey: themeKey, scope } = useThemeAttributes();\n const cacheKey = diagramCacheKey(code, themeKey);\n\n const [svg, setSvg] = useState<string | null>(() =>\n resolveSyncSvg(code, cacheKey, scheme, scope),\n );\n const [renderFailed, setRenderFailed] = useState(false);\n const [truncated, setTruncated] = useState(false);\n const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const renderIdRef = useRef(0);\n\n // Synchronously reset stale state when the code or the theme changes, to avoid\n // a one-frame flash of the previous diagram.\n const [prevKey, setPrevKey] = useState(cacheKey);\n if (cacheKey !== prevKey) {\n setPrevKey(cacheKey);\n setSvg(resolveSyncSvg(code, cacheKey, scheme, scope));\n setRenderFailed(false);\n setTruncated(false);\n }\n\n useEffect(() => {\n // Synchronous results (cache hit / fast render) are already applied and\n // cached by the useState initializer (mount) and the render-phase reset\n // (code / theme change). Only the async fallback needs an effect.\n if (svgCache.has(cacheKey)) return;\n\n const currentRenderId = ++renderIdRef.current;\n\n if (debounceRef.current) {\n clearTimeout(debounceRef.current);\n }\n\n debounceRef.current = setTimeout(() => {\n getMermaid()\n .then(async (mermaidModule) => {\n if (renderIdRef.current !== currentRenderId) return;\n const rendererId = `mermaid-${id.replaceAll(':', '')}`;\n const container = document.createElement('div');\n container.style.visibility = 'hidden';\n container.style.position = 'absolute';\n container.style.top = '-9999px';\n container.style.width = '900px';\n document.body.appendChild(container);\n // Re-applied per render rather than once at import: `initialize` is the\n // only way to change mermaid's palette, and the palette follows the\n // active scheme/brand.\n mermaidModule.default.initialize(mermaidConfig(scheme, scope));\n try {\n const result = await mermaidModule.default.render(rendererId, code, container);\n if (renderIdRef.current === currentRenderId && result) {\n const svgOutput = flattenForeignObjectLabels(result.svg);\n svgCache.set(cacheKey, svgOutput);\n setSvg(svgOutput);\n setRenderFailed(false);\n setTruncated(false);\n }\n } finally {\n container.remove();\n }\n })\n .catch((err: unknown) => {\n if (renderIdRef.current !== currentRenderId) return;\n setSvg(null);\n // A diagram arriving a chunk at a time is invalid at almost every\n // intermediate length, so a truncation is treated as \"not ready\" and\n // holds the skeleton instead of the raw-code `<pre>`. It is held for a\n // bounded wait, not indefinitely: a stream that dies mid-entity — or a\n // diagram a user simply left unterminated — never gets a next chunk, and\n // a skeleton that stays forever is worse than showing the source. The\n // timer is cleared by the effect teardown, so any further chunk cancels\n // it and re-renders.\n if (isTruncatedDiagram(err)) {\n console.debug('[MermaidDiagram] incomplete diagram, awaiting more input:', err);\n setTruncated(true);\n return;\n }\n console.error('[MermaidDiagram] fallback failed:', err);\n setRenderFailed(true);\n });\n }, RENDER_DEBOUNCE_MS);\n\n const timer = debounceRef.current;\n const renderId = renderIdRef;\n return () => {\n renderId.current++;\n if (timer) {\n clearTimeout(timer);\n }\n };\n }, [cacheKey, code, id, scheme, scope]);\n\n // A truncated diagram is held as \"still arriving\" for a bounded wait, not\n // indefinitely: a stream that dies mid-entity — or a diagram a user left\n // unterminated — never sends another chunk, and a skeleton that stays forever\n // is worse than showing the source. Any further chunk changes `code`, which\n // resets `truncated` and tears this timer down.\n useEffect(() => {\n if (!truncated) return;\n const timer = setTimeout(() => setRenderFailed(true), TRUNCATION_GRACE_MS);\n return () => clearTimeout(timer);\n }, [truncated, cacheKey]);\n\n const processedSvg = svg ? makeResponsive(svg) : null;\n\n if (renderFailed) {\n return <DiagramSource code={code} />;\n }\n\n if (processedSvg) {\n return (\n <ZoomableSvg\n key={code}\n html={processedSvg}\n copyText={`\\`\\`\\`mermaid\\n${code}\\n\\`\\`\\``}\n className=\"tw:my-3\"\n allowForeignObject\n renderActions={renderActions}\n />\n );\n }\n\n return <DiagramSkeleton />;\n};\n"],"mappings":";;;;;;;;;AAMA,MAAM,eAAe;;;;;;;;;AAUrB,MAAM,oBAAoB;CACxB,MAAM;EAAE,OAAO;EAAe,MAAM;CAAW;CAC/C,mBAAmB;EAAE,OAAO;EAAY,MAAM;CAAc;CAC5D,YAAY;EAAE,OAAO;EAAY,MAAM;CAAc;CACrD,OAAO;EAAE,OAAO;EAAe,MAAM;CAAW;CAChD,oBAAoB;EAAE,OAAO;EAAe,MAAM;CAAc;CAChE,QAAQ;EAAE,OAAO;EAAe,MAAM;CAAW;CACjD,SAAS;EAAE,OAAO;EAAa,MAAM;CAAa;CAClD,QAAQ;EAAE,OAAO;EAAe,MAAM;CAAW;CACjD,qBAAqB;EAAE,OAAO;EAAa,MAAM;CAAc;CAC/D,SAAS;EAAE,OAAO;EAAa,MAAM;CAAa;CAClD,SAAS;EAAE,OAAO;EAAa,MAAM;CAAa;CAClD,aAAa;EAAE,OAAO;EAAa,MAAM;CAAY;AACvD;;;;;AAQA,MAAM,eAAe,QAA6B,SAA0B;CAC1E,MAAM,UAAU,oBAAoB,IAAI;CACxC,QAAQ,MAAiB,UACvB,QAAQ,MAAM,kBAAkB,KAAK,CAAC,SAAS,KAAK;AACxD;;;;;;;;;;AAWA,MAAa,qBACX,QACA,SACkB;CAClB,MAAM,QAAQ,YAAY,QAAQ,IAAI;CAEtC,OAAO;EACL,IAAI,MAAM,MAAM;EAChB,IAAI,MAAM,YAAY;EACtB,MAAM,MAAM,QAAQ;EACpB,QAAQ,MAAM,SAAS;EACvB,OAAO,MAAM,kBAAkB;EAC/B,SAAS,MAAM,OAAO;EACtB,QAAQ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AAO,GAAG;MACvD,SAAS,IAAI,UAAU,SAAS;MAChC,OAAO,SAAS;MAChB,gBAAgB,KAAK;MACrB,aAAa,KAAK;KACpB;IACF,UAAU;KACR,UAAU,OAAO;IACnB;GACF,CAAC,CAAC,CACD,OAAO,QAAiB;IACvB,IAAI,YAAY,YAAY,iBAAiB;IAC7C,OAAO,IAAI;IASX,IAAI,mBAAmB,GAAG,GAAG;KAC3B,QAAQ,MAAM,6DAA6D,GAAG;KAC9E,aAAa,IAAI;KACjB;IACF;IACA,QAAQ,MAAM,qCAAqC,GAAG;IACtD,gBAAgB,IAAI;GACtB,CAAC;EACL,GAAG,kBAAkB;EAErB,MAAM,QAAQ,YAAY;EAC1B,MAAM,WAAW;EACjB,aAAa;GACX,SAAS;GACT,IAAI,OACF,aAAa,KAAK;EAEtB;CACF,GAAG;EAAC;EAAU;EAAM;EAAI;EAAQ;CAAK,CAAC;CAOtC,gBAAgB;EACd,IAAI,CAAC,WAAW;EAChB,MAAM,QAAQ,iBAAiB,gBAAgB,IAAI,GAAG,mBAAmB;EACzE,aAAa,aAAa,KAAK;CACjC,GAAG,CAAC,WAAW,QAAQ,CAAC;CAExB,MAAM,eAAe,MAAM,eAAe,GAAG,IAAI;CAEjD,IAAI,cACF,OAAO,oBAAC,eAAD,EAAqB,KAAO,CAAA;CAGrC,IAAI,cACF,OACE,oBAAC,aAAD;EAEE,MAAM;EACN,UAAU,kBAAkB,KAAK;EACjC,WAAU;EACV,oBAAA;EACe;CAChB,GANM,IAMN;CAIL,OAAO,oBAAC,iBAAD,CAAkB,CAAA;AAC3B"}
1
+ {"version":3,"file":"MermaidDiagram-DSI7xMu2.js","names":[],"sources":["../src/blocks/MermaidDiagram/mermaidTheme.ts","../src/blocks/MermaidDiagram/MermaidDiagram.tsx"],"sourcesContent":["import type { RenderOptions } from 'beautiful-mermaid';\nimport type { MermaidConfig } from 'mermaid';\n\nimport type { ResolvedColorScheme } from '../../components/ThemeProvider/types';\nimport { createTokenResolver } from '../../utils/themeTokens';\n\nconst DIAGRAM_FONT = 'Inter, system-ui, sans-serif';\n\n/**\n * Fallback channels for the tokens the diagram palette reads, mirroring the\n * `:root` / `[data-theme='dark']` blocks of `styles.css`.\n *\n * `resolveToken` only reaches these when the live custom property is missing —\n * SSR, or a unit test that loads no CSS. In the browser the computed value wins,\n * which is what makes a customer brand re-skin the diagram for free.\n */\nconst FALLBACK_CHANNELS = {\n card: { light: '255 255 255', dark: '34 34 40' },\n 'card-foreground': { light: '30 41 59', dark: '229 230 236' },\n foreground: { light: '30 41 59', dark: '229 230 236' },\n muted: { light: '241 245 249', dark: '38 38 45' },\n 'muted-foreground': { light: '100 116 139', dark: '141 144 153' },\n border: { light: '229 231 235', dark: '52 53 62' },\n primary: { light: '37 99 235', dark: '31 143 255' },\n accent: { light: '224 242 254', dark: '30 58 95' },\n 'accent-foreground': { light: '13 65 127', dark: '147 197 253' },\n warning: { light: '138 82 16', dark: '255 190 92' },\n success: { light: '24 122 76', dark: '62 207 127' },\n destructive: { light: '220 38 38', dark: '229 72 77' },\n} as const;\n\ntype TokenName = keyof typeof FALLBACK_CHANNELS;\n\n/**\n * Binds a token lookup to one `getComputedStyle` snapshot for the whole palette.\n * Built per call, never hoisted: the values move with the scheme and the brand.\n */\nconst tokenReader = (scheme: ResolvedColorScheme, from?: Element | null) => {\n const resolve = createTokenResolver(from);\n return (name: TokenName, alpha?: number): string =>\n resolve(name, FALLBACK_CHANNELS[name][scheme], alpha);\n};\n\n/**\n * Palette for `beautiful-mermaid`'s synchronous renderer. It sets these as CSS\n * variables on the `<svg>` and derives everything else it needs from `bg` + `fg`\n * with `color-mix()` — which is why leaving them at the library defaults painted\n * a near-white node fill (#f8f8f8, mixed from a white `bg`) on a dark page.\n *\n * `transparent` keeps the page background showing through, so `bg` only feeds\n * those derivations; the node fill is pinned explicitly via `surface`.\n */\nexport const fastRenderOptions = (\n scheme: ResolvedColorScheme,\n from?: Element | null,\n): RenderOptions => {\n const token = tokenReader(scheme, from);\n\n return {\n bg: token('card'),\n fg: token('foreground'),\n line: token('border'),\n accent: token('primary'),\n muted: token('muted-foreground'),\n surface: token('muted'),\n border: token('border'),\n transparent: true,\n font: DIAGRAM_FONT,\n };\n};\n\n/**\n * Config for the async `mermaid` renderer (the fallback for dialects the fast\n * renderer can't parse, and for icon-pack diagrams).\n *\n * Built on the `base` theme so every colour comes from `themeVariables` rather\n * than mermaid's own light/dark palettes. Node chrome maps to the `accent` pair\n * (a tinted surface with a legible foreground in both schemes), containers to\n * `card`, and the gantt/note states to the status tokens — consumed as a low\n * alpha tint plus a solid mark, per the brand-neutrality contract, since the\n * status tokens themselves are text-legible colours rather than fills.\n */\nexport const mermaidConfig = (\n scheme: ResolvedColorScheme,\n from?: Element | null,\n): MermaidConfig => {\n const token = tokenReader(scheme, from);\n\n const surface = token('accent');\n const onSurface = token('accent-foreground');\n const container = token('card');\n const onContainer = token('card-foreground');\n const line = token('border');\n const stroke = token('primary');\n const text = token('foreground');\n\n return {\n startOnLoad: false,\n securityLevel: 'strict',\n theme: 'base',\n themeVariables: {\n darkMode: scheme === 'dark',\n background: container,\n primaryColor: surface,\n primaryTextColor: onSurface,\n primaryBorderColor: stroke,\n secondaryColor: container,\n secondaryTextColor: onContainer,\n secondaryBorderColor: line,\n tertiaryColor: token('warning', 0.15),\n tertiaryTextColor: token('warning'),\n tertiaryBorderColor: token('warning'),\n lineColor: line,\n textColor: text,\n mainBkg: surface,\n nodeBorder: stroke,\n clusterBkg: container,\n clusterBorder: line,\n titleColor: text,\n edgeLabelBackground: container,\n nodeTextColor: onSurface,\n actorBorder: stroke,\n actorBkg: surface,\n actorTextColor: onSurface,\n actorLineColor: line,\n signalColor: text,\n signalTextColor: text,\n labelBoxBkgColor: surface,\n labelBoxBorderColor: stroke,\n labelTextColor: onSurface,\n loopTextColor: text,\n noteBorderColor: token('warning'),\n noteBkgColor: token('warning', 0.15),\n noteTextColor: text,\n sectionBkgColor: surface,\n altSectionBkgColor: container,\n sectionBkgColor2: token('muted'),\n taskBorderColor: stroke,\n taskBkgColor: surface,\n taskTextColor: onSurface,\n taskTextDarkColor: text,\n taskTextLightColor: text,\n activeTaskBorderColor: stroke,\n activeTaskBkgColor: token('primary', 0.25),\n doneTaskBorderColor: token('success'),\n doneTaskBkgColor: token('success', 0.15),\n critBorderColor: token('destructive'),\n critBkgColor: token('destructive', 0.15),\n fontFamily: DIAGRAM_FONT,\n fontSize: '14px',\n },\n };\n};\n","import { useEffect, useId, useRef, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport { renderMermaidSVG } from 'beautiful-mermaid';\nimport type mermaid from 'mermaid';\n\nimport type { ResolvedColorScheme } from '../../components/ThemeProvider/types';\nimport { useThemeAttributes } from '../../components/ThemeProvider/useThemeAttributes';\nimport { ZoomableSvg } from '../../components/ZoomableSvg';\nimport { DiagramSkeleton } from '../DiagramShared/DiagramSkeleton';\nimport { DiagramSource } from '../DiagramShared/DiagramSource';\nimport {\n flattenForeignObjectLabels,\n hasDrawnContent,\n makeResponsive,\n} from '../DiagramShared/svgTransforms';\n\nimport { fastRenderOptions, mermaidConfig } from './mermaidTheme';\n\ntype MermaidModule = { default: typeof mermaid };\n\nlet mermaidPromise: Promise<MermaidModule> | null = null;\n\n// Iconify icon pack registered with mermaid so `@{ icon: \"lucide:name\" }` node\n// shapes and `architecture-beta service <id>(lucide:name)` render — keeping\n// diagram glyphs consistent with the Lucide icons used across the rest of the UI.\n// The pack JSON resolves from a workspace dependency (no CDN fetch) via a dynamic\n// import, so it lands in its own lazy chunk and icons render offline / under a\n// strict CSP without weighing down the initial bundle.\nconst registerLucideIconPack = (m: typeof mermaid): void => {\n m.registerIconPacks([\n {\n name: 'lucide',\n loader: () => import('@iconify-json/lucide/icons.json').then((mod) => mod.default),\n },\n ]);\n};\n\nconst getMermaid = (): Promise<MermaidModule> => {\n if (!mermaidPromise) {\n mermaidPromise = import('mermaid')\n .then((m) => {\n registerLucideIconPack(m.default);\n return m;\n })\n .catch((err) => {\n mermaidPromise = null;\n throw err;\n });\n }\n return mermaidPromise;\n};\n\nconst stripFontImports = (svg: string): string =>\n svg.replace(/@import\\s+url\\([^)]*fonts\\.googleapis\\.com[^)]*\\);?\\s*/g, '');\n\n// beautiful-mermaid's synchronous renderer has no icon-pack support, so a diagram\n// using icon syntax must skip the fast path and take the async mermaid render\n// (which registers the pack). Matches:\n// - the flowchart / treeView icon shape `@{ icon: \"pack:name\" }`\n// - `architecture-beta` / `treeView` refs `icon|service|group <id>(pack:name)`\n// (the id between keyword and `(` is optional)\n// - legacy FontAwesome refs `fa:fa-*` / `fab:` embedded in node text\nconst hasIconSyntax = (code: string): boolean =>\n /@\\{[^}]*\\bicon\\s*:/.test(code) ||\n /\\b(?:icon|service|group)\\b[^\\n(]*\\(\\s*[\\w-]+:/.test(code) ||\n /\\bfa[bslr]?:fa-/.test(code);\n\nconst tryFastRender = (\n code: string,\n scheme: ResolvedColorScheme,\n from: Element | null,\n): string | null => {\n if (hasIconSyntax(code)) return null;\n try {\n const svg = stripFontImports(renderMermaidSVG(code, fastRenderOptions(scheme, from)));\n // A zero-sized result is a silent layout failure, not a diagram — take the\n // async fallback rather than caching an empty box. See `hasDrawnContent`.\n return hasDrawnContent(svg) ? svg : null;\n } catch (err) {\n // beautiful-mermaid can't parse every mermaid dialect; the async mermaid\n // renderer is the fallback. Log at debug so regressions are diagnosable\n // without noising up the console on the expected unsupported-syntax path.\n console.debug('[MermaidDiagram] fast render unavailable, using async fallback:', err);\n return null;\n }\n};\n\n/**\n * Whether a mermaid parse error means \"ran out of input\" rather than \"bad syntax\".\n *\n * - Mermaid's jison parsers report the end of input as token `1`, so a source\n * truncated mid-diagram — every intermediate frame of a streaming answer —\n * fails with `hash.token === 1`.\n * - Genuinely invalid syntax fails on a real token (`'ONLY_ONE'`, …) instead.\n * - Only a lower bound: some truncations do land on a real token and read as\n * invalid. Those fall through to the `<pre>` fallback for one frame and clear\n * when the next chunk arrives, which is the pre-existing behaviour.\n */\nconst isTruncatedDiagram = (err: unknown): boolean =>\n typeof err === 'object' && err !== null && 'hash' in err\n ? (err as { hash?: { token?: unknown } }).hash?.token === 1\n : false;\n\nconst RENDER_DEBOUNCE_MS = 300;\n\n// How long a truncated diagram is held as \"still arriving\" before it is shown as\n// source. Comfortably longer than the gap between streamed chunks, short enough\n// that an abandoned stream resolves while the reader is still looking at it.\nconst TRUNCATION_GRACE_MS = 2_000;\n\n// Module-level SVG cache — persists across component remounts (e.g. tab switches\n// that cause React to remount the tree). The colours are baked into the markup,\n// so the key is the code *plus* the theme key (scheme + brand): the same diagram\n// is a different SVG under a different colour scheme or brand.\nconst svgCache = new Map<string, string>();\n\nconst diagramCacheKey = (code: string, themeKey: string): string => `${themeKey}\\n${code}`;\n\n// Resolve an SVG synchronously: cache hit first, otherwise a fast synchronous\n// render. Caches the result and returns it, or null when neither is available\n// (the caller then falls back to the async mermaid render).\nconst resolveSyncSvg = (\n code: string,\n cacheKey: string,\n scheme: ResolvedColorScheme,\n from: Element | null,\n): string | null => {\n const cached = svgCache.get(cacheKey);\n if (cached) return cached;\n const fast = tryFastRender(code, scheme, from);\n if (fast) svgCache.set(cacheKey, fast);\n return fast;\n};\n\ntype Props = {\n /** Mermaid diagram source code. Supports flowchart, sequence, class, state, ER,\n * pie, gantt, and mindmap. Gantt `dateFormat HH:mm` (time-only) is not supported\n * by mermaid's dayjs parser — use `dateFormat YYYY-MM-DD HH:mm` with `axisFormat %H:%M` instead. */\n code: string;\n /** Extra toolbar controls (e.g. an `ExportMenu`), forwarded to `ZoomableSvg`.\n * Receives the sanitized SVG. Omit to keep the default toolbar. */\n renderActions?: (safeSvg: string) => ReactNode;\n};\n\nexport const MermaidDiagram = ({ code, renderActions }: Props) => {\n const id = useId();\n // Re-renders whenever the active colour scheme or brand changes, so the\n // diagram is re-rendered in the new palette instead of staying a light island\n // on a dark page. The scheme comes out of the same read as the key, so the\n // palette can never be resolved under one scheme and cached under the other —\n // see `useThemeAttributes` for why the theme context is a step ahead of the\n // CSS variables it stands for.\n // `scope` is the element the live tokens are read off — the enclosing `ThemeScope`'s own,\n // or `null` for `<html>`. It is part of `themeKey`, so a palette built before the scope\n // answered is never served afterwards.\n const { scheme, cacheKey: themeKey, scope } = useThemeAttributes();\n const cacheKey = diagramCacheKey(code, themeKey);\n\n const [svg, setSvg] = useState<string | null>(() =>\n resolveSyncSvg(code, cacheKey, scheme, scope),\n );\n const [renderFailed, setRenderFailed] = useState(false);\n const [truncated, setTruncated] = useState(false);\n const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const renderIdRef = useRef(0);\n\n // Synchronously reset stale state when the code or the theme changes, to avoid\n // a one-frame flash of the previous diagram.\n const [prevKey, setPrevKey] = useState(cacheKey);\n if (cacheKey !== prevKey) {\n setPrevKey(cacheKey);\n setSvg(resolveSyncSvg(code, cacheKey, scheme, scope));\n setRenderFailed(false);\n setTruncated(false);\n }\n\n useEffect(() => {\n // Synchronous results (cache hit / fast render) are already applied and\n // cached by the useState initializer (mount) and the render-phase reset\n // (code / theme change). Only the async fallback needs an effect.\n if (svgCache.has(cacheKey)) return;\n\n const currentRenderId = ++renderIdRef.current;\n\n if (debounceRef.current) {\n clearTimeout(debounceRef.current);\n }\n\n debounceRef.current = setTimeout(() => {\n getMermaid()\n .then(async (mermaidModule) => {\n if (renderIdRef.current !== currentRenderId) return;\n const rendererId = `mermaid-${id.replaceAll(':', '')}`;\n const container = document.createElement('div');\n container.style.visibility = 'hidden';\n container.style.position = 'absolute';\n container.style.top = '-9999px';\n container.style.width = '900px';\n document.body.appendChild(container);\n // Re-applied per render rather than once at import: `initialize` is the\n // only way to change mermaid's palette, and the palette follows the\n // active scheme/brand.\n mermaidModule.default.initialize(mermaidConfig(scheme, scope));\n try {\n const result = await mermaidModule.default.render(rendererId, code, container);\n if (renderIdRef.current === currentRenderId && result) {\n const svgOutput = flattenForeignObjectLabels(result.svg);\n svgCache.set(cacheKey, svgOutput);\n setSvg(svgOutput);\n setRenderFailed(false);\n setTruncated(false);\n }\n } finally {\n container.remove();\n }\n })\n .catch((err: unknown) => {\n if (renderIdRef.current !== currentRenderId) return;\n setSvg(null);\n // A diagram arriving a chunk at a time is invalid at almost every\n // intermediate length, so a truncation is treated as \"not ready\" and\n // holds the skeleton instead of the raw-code `<pre>`. It is held for a\n // bounded wait, not indefinitely: a stream that dies mid-entity — or a\n // diagram a user simply left unterminated — never gets a next chunk, and\n // a skeleton that stays forever is worse than showing the source. The\n // timer is cleared by the effect teardown, so any further chunk cancels\n // it and re-renders.\n if (isTruncatedDiagram(err)) {\n console.debug('[MermaidDiagram] incomplete diagram, awaiting more input:', err);\n setTruncated(true);\n return;\n }\n console.error('[MermaidDiagram] fallback failed:', err);\n setRenderFailed(true);\n });\n }, RENDER_DEBOUNCE_MS);\n\n const timer = debounceRef.current;\n const renderId = renderIdRef;\n return () => {\n renderId.current++;\n if (timer) {\n clearTimeout(timer);\n }\n };\n }, [cacheKey, code, id, scheme, scope]);\n\n // A truncated diagram is held as \"still arriving\" for a bounded wait, not\n // indefinitely: a stream that dies mid-entity — or a diagram a user left\n // unterminated — never sends another chunk, and a skeleton that stays forever\n // is worse than showing the source. Any further chunk changes `code`, which\n // resets `truncated` and tears this timer down.\n useEffect(() => {\n if (!truncated) return;\n const timer = setTimeout(() => setRenderFailed(true), TRUNCATION_GRACE_MS);\n return () => clearTimeout(timer);\n }, [truncated, cacheKey]);\n\n const processedSvg = svg ? makeResponsive(svg) : null;\n\n if (renderFailed) {\n return <DiagramSource code={code} />;\n }\n\n if (processedSvg) {\n return (\n <ZoomableSvg\n key={code}\n html={processedSvg}\n copyText={`\\`\\`\\`mermaid\\n${code}\\n\\`\\`\\``}\n className=\"tw:my-3\"\n allowForeignObject\n renderActions={renderActions}\n />\n );\n }\n\n return <DiagramSkeleton />;\n};\n"],"mappings":";;;;;;;;;;AAMA,MAAM,eAAe;;;;;;;;;AAUrB,MAAM,oBAAoB;CACxB,MAAM;EAAE,OAAO;EAAe,MAAM;CAAW;CAC/C,mBAAmB;EAAE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AAI;GACtB,CAAC;EACL,GAAG,kBAAkB;EAErB,MAAM,QAAQ,YAAY;EAC1B,MAAM,WAAW;EACjB,aAAa;GACX,SAAS;GACT,IAAI,OACF,aAAa,KAAK;EAEtB;CACF,GAAG;EAAC;EAAU;EAAM;EAAI;EAAQ;CAAK,CAAC;CAOtC,gBAAgB;EACd,IAAI,CAAC,WAAW;EAChB,MAAM,QAAQ,iBAAiB,gBAAgB,IAAI,GAAG,mBAAmB;EACzE,aAAa,aAAa,KAAK;CACjC,GAAG,CAAC,WAAW,QAAQ,CAAC;CAExB,MAAM,eAAe,MAAM,eAAe,GAAG,IAAI;CAEjD,IAAI,cACF,OAAO,oBAAC,eAAD,EAAqB,KAAO,CAAA;CAGrC,IAAI,cACF,OACE,oBAAC,aAAD;EAEE,MAAM;EACN,UAAU,kBAAkB,KAAK;EACjC,WAAU;EACV,oBAAA;EACe;CAChB,GANM,IAMN;CAIL,OAAO,oBAAC,iBAAD,CAAkB,CAAA;AAC3B"}
package/dist/flint.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { DiagramSkeleton } from "./internal/blocks/DiagramShared/DiagramSkeleton.js";
2
+ import { DiagramSource } from "./DiagramSource-C5_d8Gdj.js";
2
3
  import { ZoomableSvg } from "./ZoomableSvg-pooPb1Cu.js";
3
4
  import { useThemeAttributes } from "./themeTokens-qP1-55O7.js";
4
5
  import { SERIES_TOKENS, createVegaColorResolver, vegaRgb, vegaTheme } from "./vegaTheme-CSvFEMBl.js";
5
- import { DiagramSource, makeResponsive } from "./svgTransforms-C9njt92h.js";
6
+ import { makeResponsive } from "./svgTransforms-CJAYPk7o.js";
6
7
  import { useEffect, useState } from "react";
7
8
  import { jsx } from "react/jsx-runtime";
8
9
  //#region src/blocks/FlintChart/flintTheme.ts
package/dist/flint.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"flint.js","names":[],"sources":["../src/blocks/FlintChart/flintTheme.ts","../src/blocks/FlintChart/refuseUnsafeSpec.ts","../src/blocks/FlintChart/renderFlintSvg.ts","../src/blocks/FlintChart/FlintChart.tsx"],"sourcesContent":["import type { ChartAssemblyInput } from 'flint-chart';\n\nimport type { ResolvedColorScheme } from '../../components/ThemeProvider/types';\nimport { createVegaColorResolver, SERIES_TOKENS, vegaRgb } from '../../vega/vegaTokens';\n\n/**\n * How the second palette tier (series 6-10) is derived from the core hues.\n *\n * - Each core hue is pushed *away* from its own surface, so the tier stays\n * in-family but reads as a distinct series: darkened on light, lightened on\n * dark. A single \"multiply the channels\" rule would darken in both, which on\n * a dark surface moves toward the backdrop — measured, that drops contrast\n * from ~6.7:1 to ~3.7:1, while lightening raises it to ~9:1.\n * - `amount` is the fraction of the distance travelled toward black (light) or\n * white (dark).\n */\nconst TIER_TWO_SHIFT = {\n light: { towards: 0, amount: 0.38 },\n dark: { towards: 255, amount: 0.35 },\n} as const;\n\n/**\n * Move an `rgb()` string's channels a fraction of the way toward `towards`\n * (0 = black, 255 = white). Returns the input unchanged if it is not that shape.\n */\nconst shiftChannels = (colour: string, towards: number, amount: number): string => {\n const channels = colour.match(/\\d+/g);\n if (!channels || channels.length < 3) return colour;\n const shifted = channels\n .slice(0, 3)\n .map((c) => Math.round(Number(c) + (towards - Number(c)) * amount));\n return vegaRgb(shifted.join(' '));\n};\n\n/**\n * Put the design system's categorical chart palette on a Flint input.\n *\n * Series colours are resolved by flint itself during assembly (they land in the\n * Vega-Lite `color` scale's `range`), so unlike the chrome in `vegaTheme` they\n * cannot be set through the compile `config` — they ride `theme_spec.ink.series`\n * on the input instead.\n *\n * `--chart-1..5` is the decorative palette the recharts wrappers in\n * `@keboola/design/charts` already use, so a Flint chart now matches the rest of\n * the platform's data-viz, follows the colour scheme, and re-skins with a brand\n * that overrides `colors.chart` / `colorsDark.chart`.\n *\n * An author-supplied `theme_spec` wins: a fence that names a Flint house (or its\n * own spec) asked for that look deliberately, so it is passed through untouched.\n *\n * `null` is not such a spec. The input is `JSON.parse`d model output, where\n * `\"theme_spec\": null` is valid JSON, and flint dereferences the value while\n * assembling (`reading 'extends'`) — so leaving it in place throws and the chart\n * falls back to raw source. It is replaced, exactly like a missing one.\n */\nexport const withFlintSeriesPalette = (\n input: ChartAssemblyInput,\n scheme: ResolvedColorScheme,\n from?: Element | null,\n): ChartAssemblyInput => {\n if (input.theme_spec !== undefined && input.theme_spec !== null) return input;\n\n const token = createVegaColorResolver(scheme, from);\n const categorical = SERIES_TOKENS.map((name) => token(name));\n\n return {\n ...input,\n theme_spec: {\n ink: {\n // `endpointsAgainstSurface` below needs to know what the chart sits on.\n surface: { canvas: token('card') },\n // Flint's own defaults for these assume a light canvas — a title in near-black, axis\n // labels and gridlines just under it. On a dark surface that is a chart with no\n // readable numbers, so both groups come from the tokens like everything else.\n text: {\n primary: token('foreground'),\n secondary: token('muted-foreground'),\n muted: token('muted-foreground'),\n // Ink *on* a filled mark, which is the series colour — the canvas reads against it.\n inverse: token('card'),\n },\n structure: {\n axis: token('border'),\n grid: token('border'),\n frame: token('border'),\n rule: token('border'),\n },\n series: {\n categorical,\n // Past five series flint drops `categorical` wholesale for its own\n // `tableau10` — brand-blind and scheme-blind — so a six-region or\n // seven-month split would silently stop following the theme. The\n // extended set keeps those on our hues: a second tier shifted away\n // from the surface (darker on light, lighter on dark, per\n // `TIER_TWO_SHIFT`), distinct from the core five but the same family.\n categoricalExtended: [\n ...categorical,\n ...categorical.map((colour) =>\n shiftChannels(colour, TIER_TWO_SHIFT[scheme].towards, TIER_TWO_SHIFT[scheme].amount),\n ),\n ],\n // The tail past even the extended set.\n overflow: token('muted-foreground'),\n // A quantitative `color` field takes this ramp instead of the\n // categorical set. Without it flint synthesises `[black, series[0]]`,\n // which puts pure black at the low end in *both* schemes — invisible\n // cells on a dark surface.\n sequential: {\n stops: [token('accent'), token('chart-1')],\n space: 'lab',\n endpointsAgainstSurface: true,\n },\n },\n },\n },\n };\n};\n","/**\n * The boundary in front of the flint renderer: a spec is data, and nothing in it may fetch or run.\n *\n * - Checked on the **input**, before `assembleVegaLite` compiles it. The compiled Vega spec\n * carries `signals` and `expr` of vega's own making, so after compilation the model's keys and\n * the compiler's are no longer tellable apart.\n * - Refused on the **presence of a key**, never on a value looking remote: a relative `data.url`\n * is still a fetch nobody authorised, made by the reader's browser to a host the model chose.\n */\n\n/** Keys whose presence anywhere in a spec is refused: each fetches, evaluates or binds a signal. */\nconst REFUSED_KEYS = new Set(['url', 'expr', 'signal', 'signals', 'params']);\n\n/**\n * Suffix of Vega-Lite's other expression properties — `labelExpr`, `tickCountExpr`, …\n *\n * Matched by shape rather than enumerated, so a property added upstream is refused by default.\n */\nconst EXPRESSION_KEY_SUFFIX = /Expr$/;\n\n/**\n * An own property's value, or `undefined`.\n *\n * - A descriptor, so a prototype's key is not read: an inherited key is not one the model wrote.\n * - And so a getter is not *called* — the payload is model-written, and reading it must not run it.\n */\nconst ownValue = (node: unknown, key: string): unknown => {\n if (typeof node !== 'object' || node === null) return undefined;\n\n return Object.getOwnPropertyDescriptor(node, key)?.value;\n};\n\n/**\n * The chart's own rows, which the walk does not descend into — `spec.data.values`, and nowhere else.\n *\n * - Rows are data, never spec: vega reads a row's fields as datum values and evaluates none of\n * them, so a column named `url` is a column. Without this the guard refuses a chart of URLs.\n * - Flint takes exactly one dataset, at the top level (`ChartAssemblyInput['data']`), and an\n * array is what a dataset is (`data: { values: any[] }`). So this is the whole of a payload\n * that is data, and every other node is spec.\n * - The walk then skips it by **identity**. Skipping on the key name would leave `values` the\n * one word in the payload that hides a refused key, at any depth and under any parent —\n * including a nested object merely named `data`.\n */\nconst inlineRows = (spec: unknown): unknown[] | null => {\n const values = ownValue(ownValue(spec, 'data'), 'values');\n\n return Array.isArray(values) ? values : null;\n};\n\n/**\n * The top-level maps flint keys by **column name**, whose keys are therefore the model's data.\n *\n * - `semantic_types` and `field_display_names` are `Record<columnName, …>`\n * (`ChartAssemblyInput`), so a column named `url` puts `url` in a key position. Checking those\n * keys refuses \"Top landing pages by sessions\" — a chart with nothing remote in it.\n * - Only the keys are the column's. Each value is spec, and is walked like any other node.\n * - Matched by identity, for the reason `inlineRows` is: a nested object merely *named*\n * `semantic_types` is one flint never reads, so it buys no exemption.\n */\nconst COLUMN_KEYED_MAPS = ['semantic_types', 'field_display_names'];\n\nconst columnKeyedMaps = (spec: unknown): unknown[] =>\n COLUMN_KEYED_MAPS.map((key) => ownValue(spec, key)).filter(\n (map) => typeof map === 'object' && map !== null,\n );\n\n/**\n * Ceiling on the nodes the walk will visit.\n *\n * The payload is model-written, so its shape is not ours to assume. Exceeding this refuses rather\n * than passes: a spec the guard could not finish checking has not been checked.\n */\nconst MAX_SPEC_NODES = 10_000;\n\nconst TOO_LARGE = 'is too large to check';\n\n/**\n * Why this spec may not be rendered, or `null` if it may.\n *\n * - The reason reaches a console line, not a reader — the refusal itself surfaces as the source\n * fence `DiagramSource` already draws for a chart that would not render.\n * - Iterative, not recursive: a deeply nested payload must not land as a stack overflow.\n * - Nodes are charged on entering the stack, so the ceiling bounds the work, not the result.\n * - An accessor property is refused, not skipped: JSON carries none, so it is not a spec the\n * model wrote, and its value cannot be read without running it — leaving that subtree unchecked.\n */\nexport const findUnsafeSpecKey = (spec: unknown): string | null => {\n const rows = inlineRows(spec);\n const columnKeyed = columnKeyedMaps(spec);\n const stack: unknown[] = [spec];\n let visited = 1;\n\n while (stack.length > 0) {\n const node = stack.pop();\n\n if (Array.isArray(node)) {\n visited += node.length;\n if (visited > MAX_SPEC_NODES) return TOO_LARGE;\n stack.push(...node);\n continue;\n }\n\n if (typeof node !== 'object' || node === null) continue;\n\n const keysAreColumnNames = columnKeyed.includes(node);\n\n // Descriptors, not `Object.entries` or `for…in`: an inherited key is not one the model wrote,\n // and reading an own one must not *call* anything.\n for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(node))) {\n if (!keysAreColumnNames && (REFUSED_KEYS.has(key) || EXPRESSION_KEY_SUFFIX.test(key))) {\n return `carries \\`${key}\\``;\n }\n if (!('value' in descriptor)) return `carries an accessor at \\`${key}\\``;\n\n const { value } = descriptor;\n if (rows !== null && value === rows) continue;\n\n visited += 1;\n if (visited > MAX_SPEC_NODES) return TOO_LARGE;\n stack.push(value);\n }\n }\n\n return null;\n};\n","import type { ChartAssemblyInput } from 'flint-chart';\nimport type { assembleVegaLite } from 'flint-chart/vegalite';\nimport type * as vega from 'vega';\nimport type * as vegaLite from 'vega-lite';\nimport type { Config, TopLevelSpec } from 'vega-lite';\n\nimport { findUnsafeSpecKey } from './refuseUnsafeSpec';\n\n// The subset of the lazily imported modules the render pipeline needs. Kept as\n// a parameter (not module state) so the pipeline is unit-testable with a fake\n// runtime, without mocking dynamic imports.\nexport type FlintRuntime = {\n assembleVegaLite: typeof assembleVegaLite;\n vega: Pick<typeof vega, 'View' | 'parse'>;\n vegaLite: Pick<typeof vegaLite, 'compile'>;\n};\n\n/**\n * Compile a Flint `ChartAssemblyInput` to a static SVG string.\n *\n * - The input is refused before anything compiles it if it carries a key that would fetch or\n * evaluate — see `refuseUnsafeSpec.ts`. Every path to the renderer goes through here, so this\n * is the one place that check has to be.\n * - `assembleVegaLite` returns a Vega-Lite spec carrying `_`-prefixed internal\n * hint keys (`_width`, `_options`, `_transform`, …) that are not part of the\n * Vega-Lite schema — they are stripped before compiling.\n * - `config` (the scheme-following theme) rides the compile options; flint's\n * spec-side config sets no colours, so the two cannot conflict on merge.\n * - The Vega view renders headless (`renderer: 'none'`); nothing mounts to the\n * DOM, `toSVG()` is the only output.\n */\nexport const renderFlintSvg = async (\n runtime: FlintRuntime,\n input: ChartAssemblyInput,\n config: Config,\n): Promise<string> => {\n const unsafe = findUnsafeSpecKey(input);\n if (unsafe !== null) {\n throw new Error(`Refusing to render a flint spec that ${unsafe}`);\n }\n\n const assembled: Record<string, unknown> = runtime.assembleVegaLite(input);\n // `assembleVegaLite` is typed loosely upstream; once the hint keys are gone\n // the remainder is the Vega-Lite spec `compile` expects, which TypeScript\n // cannot see through the untyped boundary — hence the assertion.\n const vlSpec = Object.fromEntries(\n Object.entries(assembled).filter(([key]) => !key.startsWith('_')),\n ) as unknown as TopLevelSpec;\n const { spec } = runtime.vegaLite.compile(vlSpec, { config });\n const view = new runtime.vega.View(runtime.vega.parse(spec), { renderer: 'none' });\n try {\n await view.runAsync();\n return await view.toSVG();\n } finally {\n view.finalize();\n }\n};\n","import { useEffect, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport type { ChartAssemblyInput } from 'flint-chart';\n\nimport { useThemeAttributes } from '../../components/ThemeProvider/useThemeAttributes';\nimport { ZoomableSvg } from '../../components/ZoomableSvg';\nimport { vegaTheme } from '../../vega/vegaTheme';\nimport { DiagramSkeleton } from '../DiagramShared/DiagramSkeleton';\nimport { DiagramSource } from '../DiagramShared/DiagramSource';\nimport { makeResponsive } from '../DiagramShared/svgTransforms';\n\nimport { withFlintSeriesPalette } from './flintTheme';\nimport type { FlintRuntime } from './renderFlintSvg';\nimport { renderFlintSvg } from './renderFlintSvg';\n\nlet runtimePromise: Promise<FlintRuntime> | null = null;\n\n// One memoized promise for the heavy chart stack (flint-chart + vega +\n// vega-lite), reset on failure so a transient chunk-load error can retry on the\n// next render — mirrors `getMermaid()` in `MermaidDiagram`.\nconst getFlintRuntime = (): Promise<FlintRuntime> => {\n if (!runtimePromise) {\n runtimePromise = Promise.all([\n import('flint-chart/vegalite'),\n import('vega'),\n import('vega-lite'),\n ])\n .then(([flint, vega, vegaLite]) => ({\n assembleVegaLite: flint.assembleVegaLite,\n vega,\n vegaLite,\n }))\n .catch((err) => {\n runtimePromise = null;\n throw err;\n });\n }\n return runtimePromise;\n};\n\nconst RENDER_DEBOUNCE_MS = 300;\n\n// No prefix of a JSON document parses, so while a ```flint fence streams in the\n// source is unparseable in exactly the same way a broken one is. Unparseable\n// source is treated as still-streaming (skeleton stays up) until it has been\n// unchanged this long — only then is it shown as raw source.\nconst PARSE_GRACE_MS = 1500;\n\n// Ceiling on the fence source, in characters. `JSON.parse` plus vega's compile\n// and layout are synchronous, so an oversized payload — a model dumping a raw\n// table into the block — would block the main thread and freeze the chat. The\n// prompt caps inline data at ~50 rows; this sits far above a legitimate spec of\n// that size while still refusing anything pathological.\nconst MAX_SOURCE_CHARS = 200_000;\n\n// Module-level SVG cache — persists across component remounts (e.g. tab switches\n// that cause React to remount the tree). The chart chrome colours are baked into\n// the markup, so the key is the code *plus* the theme key (scheme + brand): the\n// same spec is a different SVG under a different colour scheme or brand.\n// Values are stored already `makeResponsive`d, so the string identity is stable\n// and ZoomableSvg's sanitize memo never re-runs for an unchanged chart.\n//\n// Bounded, and evicted oldest-first: a vega SVG is mark-per-datum, so entries run\n// to hundreds of KB, and a long chat visits many distinct charts. `Map` iterates\n// in insertion order, so the first key is the oldest.\nconst MAX_CACHED_CHARTS = 24;\nconst svgCache = new Map<string, string>();\n\nconst cacheSvg = (key: string, svg: string): void => {\n // Overwriting an existing key adds no entry, so it must not evict one — two\n // instances of the same chart both missing the cache and both writing would\n // otherwise cost an unrelated chart its slot.\n if (!svgCache.has(key) && svgCache.size >= MAX_CACHED_CHARTS) {\n const oldest = svgCache.keys().next();\n if (!oldest.done) svgCache.delete(oldest.value);\n }\n svgCache.set(key, svg);\n};\n\nconst chartCacheKey = (code: string, themeKey: string): string => `${themeKey}\\n${code}`;\n\n// The theme half of a cache key — used to tell \"same theme, more source\" (a spec\n// still streaming) from a theme/brand switch, which must not keep a stale chart.\nconst prevThemeKeyOf = (key: string): string => key.slice(0, key.indexOf('\\n'));\n\ntype Props = {\n /** Raw source of a ```flint fence — a flint-chart `ChartAssemblyInput` as pure JSON\n * (`data.values` rows, optional `semantic_types`, and a `chart_spec` naming the\n * chartType and encodings). Rendered through the Vega-Lite backend. */\n code: string;\n /** Extra toolbar controls (e.g. an `ExportMenu`), forwarded to `ZoomableSvg`.\n * Receives the sanitized SVG. Omit to keep the default toolbar. */\n renderActions?: (safeSvg: string) => ReactNode;\n};\n\nexport const FlintChart = ({ code, renderActions }: Props) => {\n // Re-renders whenever the active colour scheme or brand changes, so the chart\n // chrome is re-rendered in the new palette instead of staying a light island\n // on a dark page — same contract as MermaidDiagram.\n // `scope` is the element the live tokens are read off — the enclosing `ThemeScope`'s own,\n // or `null` for `<html>`. It is part of `themeKey`, so a palette built before the scope\n // answered is never served afterwards.\n const { scheme, cacheKey: themeKey, scope } = useThemeAttributes();\n const cacheKey = chartCacheKey(code, themeKey);\n\n const [svg, setSvg] = useState<string | null>(() => svgCache.get(cacheKey) ?? null);\n const [renderFailed, setRenderFailed] = useState(false);\n\n // Synchronously reset stale state when the code or the theme changes, to avoid\n // a one-frame flash.\n //\n // A cache hit is applied immediately. On a miss the previous SVG is dropped\n // unless *only* the tail of the source grew — i.e. the same spec still\n // streaming in, where holding the last good chart avoids a skeleton flicker\n // between chunks. Anything else (a different spec, or a new theme/brand) must\n // clear: the colours are baked into the markup, so keeping it would show a\n // light chart on a dark page, and keeping a chart for a spec that is no longer\n // on screen is simply wrong.\n const [prevKey, setPrevKey] = useState(cacheKey);\n const [prevCode, setPrevCode] = useState(code);\n if (cacheKey !== prevKey) {\n const cached = svgCache.get(cacheKey);\n const sameThemeStillStreaming =\n themeKey === prevThemeKeyOf(prevKey) && code.startsWith(prevCode);\n setPrevKey(cacheKey);\n setPrevCode(code);\n if (cached) setSvg(cached);\n else if (!sameThemeStillStreaming) setSvg(null);\n setRenderFailed(false);\n }\n\n useEffect(() => {\n if (svgCache.has(cacheKey)) return;\n\n let cancelled = false;\n let graceTimer: ReturnType<typeof setTimeout> | undefined;\n\n const debounceTimer = setTimeout(() => {\n if (code.length > MAX_SOURCE_CHARS) {\n // Not a streaming artifact — a fence this size never becomes renderable,\n // so fail straight to the source instead of waiting out the grace period.\n console.error(\n `[FlintChart] source exceeds ${MAX_SOURCE_CHARS} characters (${code.length}); not rendering`,\n );\n setSvg(null);\n setRenderFailed(true);\n return;\n }\n\n let input: ChartAssemblyInput;\n try {\n input = JSON.parse(code);\n } catch (err) {\n // Likely a fence still streaming — declare failure (and log the parse\n // error) only if the code is still unchanged when the grace period ends.\n graceTimer = setTimeout(() => {\n console.debug('[FlintChart] source never became parseable JSON:', err);\n setSvg(null);\n setRenderFailed(true);\n }, PARSE_GRACE_MS - RENDER_DEBOUNCE_MS);\n return;\n }\n\n getFlintRuntime()\n .then(async (runtime) => {\n if (cancelled) return;\n // Theme resolved at render time, off the live CSS variables — the\n // scheme comes out of the same read as the cache key, so the palette\n // can never be resolved under one scheme and cached under the other.\n const svgOutput = makeResponsive(\n await renderFlintSvg(\n runtime,\n withFlintSeriesPalette(input, scheme, scope),\n vegaTheme(scheme, scope),\n ),\n );\n if (cancelled) return;\n cacheSvg(cacheKey, svgOutput);\n setSvg(svgOutput);\n setRenderFailed(false);\n })\n .catch((err) => {\n if (cancelled) return;\n console.error('[FlintChart] render failed:', err);\n setSvg(null);\n setRenderFailed(true);\n });\n }, RENDER_DEBOUNCE_MS);\n\n return () => {\n cancelled = true;\n clearTimeout(debounceTimer);\n if (graceTimer) clearTimeout(graceTimer);\n };\n }, [cacheKey, code, scheme, scope]);\n\n if (renderFailed) {\n return <DiagramSource code={code} />;\n }\n\n if (svg) {\n return (\n <ZoomableSvg\n // Keyed by the rendered SVG, not the source: while the same fence is\n // still streaming the chart is deliberately held (see above), and keying\n // on `code` would remount it on every chunk — dropping the reader's\n // zoom/pan and re-running the DOMPurify pass over an identical chart.\n key={svg}\n html={svg}\n copyText={`\\`\\`\\`flint\\n${code}\\n\\`\\`\\``}\n className=\"tw:my-3\"\n renderActions={renderActions}\n />\n );\n }\n\n return <DiagramSkeleton />;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgBA,MAAM,iBAAiB;CACrB,OAAO;EAAE,SAAS;EAAG,QAAQ;CAAK;CAClC,MAAM;EAAE,SAAS;EAAK,QAAQ;CAAK;AACrC;;;;;AAMA,MAAM,iBAAiB,QAAgB,SAAiB,WAA2B;CACjF,MAAM,WAAW,OAAO,MAAM,MAAM;CACpC,IAAI,CAAC,YAAY,SAAS,SAAS,GAAG,OAAO;CAC7C,MAAM,UAAU,SACb,MAAM,GAAG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,eACJ,SACA,uBAAuB,OAAO,QAAQ,KAAK,GAC3C,UAAU,QAAQ,KAAK,CACzB,CACF;IACA,IAAI,WAAW;IACf,SAAS,UAAU,SAAS;IAC5B,OAAO,SAAS;IAChB,gBAAgB,KAAK;GACvB,CAAC,CAAC,CACD,OAAO,QAAQ;IACd,IAAI,WAAW;IACf,QAAQ,MAAM,+BAA+B,GAAG;IAChD,OAAO,IAAI;IACX,gBAAgB,IAAI;GACtB,CAAC;EACL,GAAG,kBAAkB;EAErB,aAAa;GACX,YAAY;GACZ,aAAa,aAAa;GAC1B,IAAI,YAAY,aAAa,UAAU;EACzC;CACF,GAAG;EAAC;EAAU;EAAM;EAAQ;CAAK,CAAC;CAElC,IAAI,cACF,OAAO,oBAAC,eAAD,EAAqB,KAAO,CAAA;CAGrC,IAAI,KACF,OACE,oBAAC,aAAD;EAME,MAAM;EACN,UAAU,gBAAgB,KAAK;EAC/B,WAAU;EACK;CAChB,GALM,GAKN;CAIL,OAAO,oBAAC,iBAAD,CAAkB,CAAA;AAC3B"}
1
+ {"version":3,"file":"flint.js","names":[],"sources":["../src/blocks/FlintChart/flintTheme.ts","../src/blocks/FlintChart/refuseUnsafeSpec.ts","../src/blocks/FlintChart/renderFlintSvg.ts","../src/blocks/FlintChart/FlintChart.tsx"],"sourcesContent":["import type { ChartAssemblyInput } from 'flint-chart';\n\nimport type { ResolvedColorScheme } from '../../components/ThemeProvider/types';\nimport { createVegaColorResolver, SERIES_TOKENS, vegaRgb } from '../../vega/vegaTokens';\n\n/**\n * How the second palette tier (series 6-10) is derived from the core hues.\n *\n * - Each core hue is pushed *away* from its own surface, so the tier stays\n * in-family but reads as a distinct series: darkened on light, lightened on\n * dark. A single \"multiply the channels\" rule would darken in both, which on\n * a dark surface moves toward the backdrop — measured, that drops contrast\n * from ~6.7:1 to ~3.7:1, while lightening raises it to ~9:1.\n * - `amount` is the fraction of the distance travelled toward black (light) or\n * white (dark).\n */\nconst TIER_TWO_SHIFT = {\n light: { towards: 0, amount: 0.38 },\n dark: { towards: 255, amount: 0.35 },\n} as const;\n\n/**\n * Move an `rgb()` string's channels a fraction of the way toward `towards`\n * (0 = black, 255 = white). Returns the input unchanged if it is not that shape.\n */\nconst shiftChannels = (colour: string, towards: number, amount: number): string => {\n const channels = colour.match(/\\d+/g);\n if (!channels || channels.length < 3) return colour;\n const shifted = channels\n .slice(0, 3)\n .map((c) => Math.round(Number(c) + (towards - Number(c)) * amount));\n return vegaRgb(shifted.join(' '));\n};\n\n/**\n * Put the design system's categorical chart palette on a Flint input.\n *\n * Series colours are resolved by flint itself during assembly (they land in the\n * Vega-Lite `color` scale's `range`), so unlike the chrome in `vegaTheme` they\n * cannot be set through the compile `config` — they ride `theme_spec.ink.series`\n * on the input instead.\n *\n * `--chart-1..5` is the decorative palette the recharts wrappers in\n * `@keboola/design/charts` already use, so a Flint chart now matches the rest of\n * the platform's data-viz, follows the colour scheme, and re-skins with a brand\n * that overrides `colors.chart` / `colorsDark.chart`.\n *\n * An author-supplied `theme_spec` wins: a fence that names a Flint house (or its\n * own spec) asked for that look deliberately, so it is passed through untouched.\n *\n * `null` is not such a spec. The input is `JSON.parse`d model output, where\n * `\"theme_spec\": null` is valid JSON, and flint dereferences the value while\n * assembling (`reading 'extends'`) — so leaving it in place throws and the chart\n * falls back to raw source. It is replaced, exactly like a missing one.\n */\nexport const withFlintSeriesPalette = (\n input: ChartAssemblyInput,\n scheme: ResolvedColorScheme,\n from?: Element | null,\n): ChartAssemblyInput => {\n if (input.theme_spec !== undefined && input.theme_spec !== null) return input;\n\n const token = createVegaColorResolver(scheme, from);\n const categorical = SERIES_TOKENS.map((name) => token(name));\n\n return {\n ...input,\n theme_spec: {\n ink: {\n // `endpointsAgainstSurface` below needs to know what the chart sits on.\n surface: { canvas: token('card') },\n // Flint's own defaults for these assume a light canvas — a title in near-black, axis\n // labels and gridlines just under it. On a dark surface that is a chart with no\n // readable numbers, so both groups come from the tokens like everything else.\n text: {\n primary: token('foreground'),\n secondary: token('muted-foreground'),\n muted: token('muted-foreground'),\n // Ink *on* a filled mark, which is the series colour — the canvas reads against it.\n inverse: token('card'),\n },\n structure: {\n axis: token('border'),\n grid: token('border'),\n frame: token('border'),\n rule: token('border'),\n },\n series: {\n categorical,\n // Past five series flint drops `categorical` wholesale for its own\n // `tableau10` — brand-blind and scheme-blind — so a six-region or\n // seven-month split would silently stop following the theme. The\n // extended set keeps those on our hues: a second tier shifted away\n // from the surface (darker on light, lighter on dark, per\n // `TIER_TWO_SHIFT`), distinct from the core five but the same family.\n categoricalExtended: [\n ...categorical,\n ...categorical.map((colour) =>\n shiftChannels(colour, TIER_TWO_SHIFT[scheme].towards, TIER_TWO_SHIFT[scheme].amount),\n ),\n ],\n // The tail past even the extended set.\n overflow: token('muted-foreground'),\n // A quantitative `color` field takes this ramp instead of the\n // categorical set. Without it flint synthesises `[black, series[0]]`,\n // which puts pure black at the low end in *both* schemes — invisible\n // cells on a dark surface.\n sequential: {\n stops: [token('accent'), token('chart-1')],\n space: 'lab',\n endpointsAgainstSurface: true,\n },\n },\n },\n },\n };\n};\n","/**\n * The boundary in front of the flint renderer: a spec is data, and nothing in it may fetch or run.\n *\n * - Checked on the **input**, before `assembleVegaLite` compiles it. The compiled Vega spec\n * carries `signals` and `expr` of vega's own making, so after compilation the model's keys and\n * the compiler's are no longer tellable apart.\n * - Refused on the **presence of a key**, never on a value looking remote: a relative `data.url`\n * is still a fetch nobody authorised, made by the reader's browser to a host the model chose.\n */\n\n/** Keys whose presence anywhere in a spec is refused: each fetches, evaluates or binds a signal. */\nconst REFUSED_KEYS = new Set(['url', 'expr', 'signal', 'signals', 'params']);\n\n/**\n * Suffix of Vega-Lite's other expression properties — `labelExpr`, `tickCountExpr`, …\n *\n * Matched by shape rather than enumerated, so a property added upstream is refused by default.\n */\nconst EXPRESSION_KEY_SUFFIX = /Expr$/;\n\n/**\n * An own property's value, or `undefined`.\n *\n * - A descriptor, so a prototype's key is not read: an inherited key is not one the model wrote.\n * - And so a getter is not *called* — the payload is model-written, and reading it must not run it.\n */\nconst ownValue = (node: unknown, key: string): unknown => {\n if (typeof node !== 'object' || node === null) return undefined;\n\n return Object.getOwnPropertyDescriptor(node, key)?.value;\n};\n\n/**\n * The chart's own rows, which the walk does not descend into — `spec.data.values`, and nowhere else.\n *\n * - Rows are data, never spec: vega reads a row's fields as datum values and evaluates none of\n * them, so a column named `url` is a column. Without this the guard refuses a chart of URLs.\n * - Flint takes exactly one dataset, at the top level (`ChartAssemblyInput['data']`), and an\n * array is what a dataset is (`data: { values: any[] }`). So this is the whole of a payload\n * that is data, and every other node is spec.\n * - The walk then skips it by **identity**. Skipping on the key name would leave `values` the\n * one word in the payload that hides a refused key, at any depth and under any parent —\n * including a nested object merely named `data`.\n */\nconst inlineRows = (spec: unknown): unknown[] | null => {\n const values = ownValue(ownValue(spec, 'data'), 'values');\n\n return Array.isArray(values) ? values : null;\n};\n\n/**\n * The top-level maps flint keys by **column name**, whose keys are therefore the model's data.\n *\n * - `semantic_types` and `field_display_names` are `Record<columnName, …>`\n * (`ChartAssemblyInput`), so a column named `url` puts `url` in a key position. Checking those\n * keys refuses \"Top landing pages by sessions\" — a chart with nothing remote in it.\n * - Only the keys are the column's. Each value is spec, and is walked like any other node.\n * - Matched by identity, for the reason `inlineRows` is: a nested object merely *named*\n * `semantic_types` is one flint never reads, so it buys no exemption.\n */\nconst COLUMN_KEYED_MAPS = ['semantic_types', 'field_display_names'];\n\nconst columnKeyedMaps = (spec: unknown): unknown[] =>\n COLUMN_KEYED_MAPS.map((key) => ownValue(spec, key)).filter(\n (map) => typeof map === 'object' && map !== null,\n );\n\n/**\n * Ceiling on the nodes the walk will visit.\n *\n * The payload is model-written, so its shape is not ours to assume. Exceeding this refuses rather\n * than passes: a spec the guard could not finish checking has not been checked.\n */\nconst MAX_SPEC_NODES = 10_000;\n\nconst TOO_LARGE = 'is too large to check';\n\n/**\n * Why this spec may not be rendered, or `null` if it may.\n *\n * - The reason reaches a console line, not a reader — the refusal itself surfaces as the source\n * fence `DiagramSource` already draws for a chart that would not render.\n * - Iterative, not recursive: a deeply nested payload must not land as a stack overflow.\n * - Nodes are charged on entering the stack, so the ceiling bounds the work, not the result.\n * - An accessor property is refused, not skipped: JSON carries none, so it is not a spec the\n * model wrote, and its value cannot be read without running it — leaving that subtree unchecked.\n */\nexport const findUnsafeSpecKey = (spec: unknown): string | null => {\n const rows = inlineRows(spec);\n const columnKeyed = columnKeyedMaps(spec);\n const stack: unknown[] = [spec];\n let visited = 1;\n\n while (stack.length > 0) {\n const node = stack.pop();\n\n if (Array.isArray(node)) {\n visited += node.length;\n if (visited > MAX_SPEC_NODES) return TOO_LARGE;\n stack.push(...node);\n continue;\n }\n\n if (typeof node !== 'object' || node === null) continue;\n\n const keysAreColumnNames = columnKeyed.includes(node);\n\n // Descriptors, not `Object.entries` or `for…in`: an inherited key is not one the model wrote,\n // and reading an own one must not *call* anything.\n for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(node))) {\n if (!keysAreColumnNames && (REFUSED_KEYS.has(key) || EXPRESSION_KEY_SUFFIX.test(key))) {\n return `carries \\`${key}\\``;\n }\n if (!('value' in descriptor)) return `carries an accessor at \\`${key}\\``;\n\n const { value } = descriptor;\n if (rows !== null && value === rows) continue;\n\n visited += 1;\n if (visited > MAX_SPEC_NODES) return TOO_LARGE;\n stack.push(value);\n }\n }\n\n return null;\n};\n","import type { ChartAssemblyInput } from 'flint-chart';\nimport type { assembleVegaLite } from 'flint-chart/vegalite';\nimport type * as vega from 'vega';\nimport type * as vegaLite from 'vega-lite';\nimport type { Config, TopLevelSpec } from 'vega-lite';\n\nimport { findUnsafeSpecKey } from './refuseUnsafeSpec';\n\n// The subset of the lazily imported modules the render pipeline needs. Kept as\n// a parameter (not module state) so the pipeline is unit-testable with a fake\n// runtime, without mocking dynamic imports.\nexport type FlintRuntime = {\n assembleVegaLite: typeof assembleVegaLite;\n vega: Pick<typeof vega, 'View' | 'parse'>;\n vegaLite: Pick<typeof vegaLite, 'compile'>;\n};\n\n/**\n * Compile a Flint `ChartAssemblyInput` to a static SVG string.\n *\n * - The input is refused before anything compiles it if it carries a key that would fetch or\n * evaluate — see `refuseUnsafeSpec.ts`. Every path to the renderer goes through here, so this\n * is the one place that check has to be.\n * - `assembleVegaLite` returns a Vega-Lite spec carrying `_`-prefixed internal\n * hint keys (`_width`, `_options`, `_transform`, …) that are not part of the\n * Vega-Lite schema — they are stripped before compiling.\n * - `config` (the scheme-following theme) rides the compile options; flint's\n * spec-side config sets no colours, so the two cannot conflict on merge.\n * - The Vega view renders headless (`renderer: 'none'`); nothing mounts to the\n * DOM, `toSVG()` is the only output.\n */\nexport const renderFlintSvg = async (\n runtime: FlintRuntime,\n input: ChartAssemblyInput,\n config: Config,\n): Promise<string> => {\n const unsafe = findUnsafeSpecKey(input);\n if (unsafe !== null) {\n throw new Error(`Refusing to render a flint spec that ${unsafe}`);\n }\n\n const assembled: Record<string, unknown> = runtime.assembleVegaLite(input);\n // `assembleVegaLite` is typed loosely upstream; once the hint keys are gone\n // the remainder is the Vega-Lite spec `compile` expects, which TypeScript\n // cannot see through the untyped boundary — hence the assertion.\n const vlSpec = Object.fromEntries(\n Object.entries(assembled).filter(([key]) => !key.startsWith('_')),\n ) as unknown as TopLevelSpec;\n const { spec } = runtime.vegaLite.compile(vlSpec, { config });\n const view = new runtime.vega.View(runtime.vega.parse(spec), { renderer: 'none' });\n try {\n await view.runAsync();\n return await view.toSVG();\n } finally {\n view.finalize();\n }\n};\n","import { useEffect, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport type { ChartAssemblyInput } from 'flint-chart';\n\nimport { useThemeAttributes } from '../../components/ThemeProvider/useThemeAttributes';\nimport { ZoomableSvg } from '../../components/ZoomableSvg';\nimport { vegaTheme } from '../../vega/vegaTheme';\nimport { DiagramSkeleton } from '../DiagramShared/DiagramSkeleton';\nimport { DiagramSource } from '../DiagramShared/DiagramSource';\nimport { makeResponsive } from '../DiagramShared/svgTransforms';\n\nimport { withFlintSeriesPalette } from './flintTheme';\nimport type { FlintRuntime } from './renderFlintSvg';\nimport { renderFlintSvg } from './renderFlintSvg';\n\nlet runtimePromise: Promise<FlintRuntime> | null = null;\n\n// One memoized promise for the heavy chart stack (flint-chart + vega +\n// vega-lite), reset on failure so a transient chunk-load error can retry on the\n// next render — mirrors `getMermaid()` in `MermaidDiagram`.\nconst getFlintRuntime = (): Promise<FlintRuntime> => {\n if (!runtimePromise) {\n runtimePromise = Promise.all([\n import('flint-chart/vegalite'),\n import('vega'),\n import('vega-lite'),\n ])\n .then(([flint, vega, vegaLite]) => ({\n assembleVegaLite: flint.assembleVegaLite,\n vega,\n vegaLite,\n }))\n .catch((err) => {\n runtimePromise = null;\n throw err;\n });\n }\n return runtimePromise;\n};\n\nconst RENDER_DEBOUNCE_MS = 300;\n\n// No prefix of a JSON document parses, so while a ```flint fence streams in the\n// source is unparseable in exactly the same way a broken one is. Unparseable\n// source is treated as still-streaming (skeleton stays up) until it has been\n// unchanged this long — only then is it shown as raw source.\nconst PARSE_GRACE_MS = 1500;\n\n// Ceiling on the fence source, in characters. `JSON.parse` plus vega's compile\n// and layout are synchronous, so an oversized payload — a model dumping a raw\n// table into the block — would block the main thread and freeze the chat. The\n// prompt caps inline data at ~50 rows; this sits far above a legitimate spec of\n// that size while still refusing anything pathological.\nconst MAX_SOURCE_CHARS = 200_000;\n\n// Module-level SVG cache — persists across component remounts (e.g. tab switches\n// that cause React to remount the tree). The chart chrome colours are baked into\n// the markup, so the key is the code *plus* the theme key (scheme + brand): the\n// same spec is a different SVG under a different colour scheme or brand.\n// Values are stored already `makeResponsive`d, so the string identity is stable\n// and ZoomableSvg's sanitize memo never re-runs for an unchanged chart.\n//\n// Bounded, and evicted oldest-first: a vega SVG is mark-per-datum, so entries run\n// to hundreds of KB, and a long chat visits many distinct charts. `Map` iterates\n// in insertion order, so the first key is the oldest.\nconst MAX_CACHED_CHARTS = 24;\nconst svgCache = new Map<string, string>();\n\nconst cacheSvg = (key: string, svg: string): void => {\n // Overwriting an existing key adds no entry, so it must not evict one — two\n // instances of the same chart both missing the cache and both writing would\n // otherwise cost an unrelated chart its slot.\n if (!svgCache.has(key) && svgCache.size >= MAX_CACHED_CHARTS) {\n const oldest = svgCache.keys().next();\n if (!oldest.done) svgCache.delete(oldest.value);\n }\n svgCache.set(key, svg);\n};\n\nconst chartCacheKey = (code: string, themeKey: string): string => `${themeKey}\\n${code}`;\n\n// The theme half of a cache key — used to tell \"same theme, more source\" (a spec\n// still streaming) from a theme/brand switch, which must not keep a stale chart.\nconst prevThemeKeyOf = (key: string): string => key.slice(0, key.indexOf('\\n'));\n\ntype Props = {\n /** Raw source of a ```flint fence — a flint-chart `ChartAssemblyInput` as pure JSON\n * (`data.values` rows, optional `semantic_types`, and a `chart_spec` naming the\n * chartType and encodings). Rendered through the Vega-Lite backend. */\n code: string;\n /** Extra toolbar controls (e.g. an `ExportMenu`), forwarded to `ZoomableSvg`.\n * Receives the sanitized SVG. Omit to keep the default toolbar. */\n renderActions?: (safeSvg: string) => ReactNode;\n};\n\nexport const FlintChart = ({ code, renderActions }: Props) => {\n // Re-renders whenever the active colour scheme or brand changes, so the chart\n // chrome is re-rendered in the new palette instead of staying a light island\n // on a dark page — same contract as MermaidDiagram.\n // `scope` is the element the live tokens are read off — the enclosing `ThemeScope`'s own,\n // or `null` for `<html>`. It is part of `themeKey`, so a palette built before the scope\n // answered is never served afterwards.\n const { scheme, cacheKey: themeKey, scope } = useThemeAttributes();\n const cacheKey = chartCacheKey(code, themeKey);\n\n const [svg, setSvg] = useState<string | null>(() => svgCache.get(cacheKey) ?? null);\n const [renderFailed, setRenderFailed] = useState(false);\n\n // Synchronously reset stale state when the code or the theme changes, to avoid\n // a one-frame flash.\n //\n // A cache hit is applied immediately. On a miss the previous SVG is dropped\n // unless *only* the tail of the source grew — i.e. the same spec still\n // streaming in, where holding the last good chart avoids a skeleton flicker\n // between chunks. Anything else (a different spec, or a new theme/brand) must\n // clear: the colours are baked into the markup, so keeping it would show a\n // light chart on a dark page, and keeping a chart for a spec that is no longer\n // on screen is simply wrong.\n const [prevKey, setPrevKey] = useState(cacheKey);\n const [prevCode, setPrevCode] = useState(code);\n if (cacheKey !== prevKey) {\n const cached = svgCache.get(cacheKey);\n const sameThemeStillStreaming =\n themeKey === prevThemeKeyOf(prevKey) && code.startsWith(prevCode);\n setPrevKey(cacheKey);\n setPrevCode(code);\n if (cached) setSvg(cached);\n else if (!sameThemeStillStreaming) setSvg(null);\n setRenderFailed(false);\n }\n\n useEffect(() => {\n if (svgCache.has(cacheKey)) return;\n\n let cancelled = false;\n let graceTimer: ReturnType<typeof setTimeout> | undefined;\n\n const debounceTimer = setTimeout(() => {\n if (code.length > MAX_SOURCE_CHARS) {\n // Not a streaming artifact — a fence this size never becomes renderable,\n // so fail straight to the source instead of waiting out the grace period.\n console.error(\n `[FlintChart] source exceeds ${MAX_SOURCE_CHARS} characters (${code.length}); not rendering`,\n );\n setSvg(null);\n setRenderFailed(true);\n return;\n }\n\n let input: ChartAssemblyInput;\n try {\n input = JSON.parse(code);\n } catch (err) {\n // Likely a fence still streaming — declare failure (and log the parse\n // error) only if the code is still unchanged when the grace period ends.\n graceTimer = setTimeout(() => {\n console.debug('[FlintChart] source never became parseable JSON:', err);\n setSvg(null);\n setRenderFailed(true);\n }, PARSE_GRACE_MS - RENDER_DEBOUNCE_MS);\n return;\n }\n\n getFlintRuntime()\n .then(async (runtime) => {\n if (cancelled) return;\n // Theme resolved at render time, off the live CSS variables — the\n // scheme comes out of the same read as the cache key, so the palette\n // can never be resolved under one scheme and cached under the other.\n const svgOutput = makeResponsive(\n await renderFlintSvg(\n runtime,\n withFlintSeriesPalette(input, scheme, scope),\n vegaTheme(scheme, scope),\n ),\n );\n if (cancelled) return;\n cacheSvg(cacheKey, svgOutput);\n setSvg(svgOutput);\n setRenderFailed(false);\n })\n .catch((err) => {\n if (cancelled) return;\n console.error('[FlintChart] render failed:', err);\n setSvg(null);\n setRenderFailed(true);\n });\n }, RENDER_DEBOUNCE_MS);\n\n return () => {\n cancelled = true;\n clearTimeout(debounceTimer);\n if (graceTimer) clearTimeout(graceTimer);\n };\n }, [cacheKey, code, scheme, scope]);\n\n if (renderFailed) {\n return <DiagramSource code={code} />;\n }\n\n if (svg) {\n return (\n <ZoomableSvg\n // Keyed by the rendered SVG, not the source: while the same fence is\n // still streaming the chart is deliberately held (see above), and keying\n // on `code` would remount it on every chunk — dropping the reader's\n // zoom/pan and re-running the DOMPurify pass over an identical chart.\n key={svg}\n html={svg}\n copyText={`\\`\\`\\`flint\\n${code}\\n\\`\\`\\``}\n className=\"tw:my-3\"\n renderActions={renderActions}\n />\n );\n }\n\n return <DiagramSkeleton />;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgBA,MAAM,iBAAiB;CACrB,OAAO;EAAE,SAAS;EAAG,QAAQ;CAAK;CAClC,MAAM;EAAE,SAAS;EAAK,QAAQ;CAAK;AACrC;;;;;AAMA,MAAM,iBAAiB,QAAgB,SAAiB,WAA2B;CACjF,MAAM,WAAW,OAAO,MAAM,MAAM;CACpC,IAAI,CAAC,YAAY,SAAS,SAAS,GAAG,OAAO;CAC7C,MAAM,UAAU,SACb,MAAM,GAAG,CAAC,CAAC,CACX,KAAK,MAAM,KAAK,MAAM,OAAO,CAAC,KAAK,UAAU,OAAO,CAAC,KAAK,MAAM,CAAC;CACpE,OAAO,QAAQ,QAAQ,KAAK,GAAG,CAAC;AAClC;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,0BACX,OACA,QACA,SACuB;CACvB,IAAI,MAAM,eAAe,KAAA,KAAa,MAAM,eAAe,MAAM,OAAO;CAExE,MAAM,QAAQ,wBAAwB,QAAQ,IAAI;CAClD,MAAM,cAAc,cAAc,KAAK,SAAS,MAAM,IAAI,CAAC;CAE3D,OAAO;EACL,GAAG;EACH,YAAY,EACV,KAAK;GAEH,SAAS,EAAE,QAAQ,MAAM,MAAM,EAAE;GAIjC,MAAM;IACJ,SAAS,MAAM,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