cms-renderer 0.2.6 → 0.3.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,5 +1,5 @@
1
1
  import React__default from 'react';
2
- import { BlockData, BlockComponentRegistry } from './types.js';
2
+ import { BlockData, BlockComponentRegistry, ResolvedRouteParams } from './types.js';
3
3
  import '@repo/cms-schema/blocks';
4
4
 
5
5
  /**
@@ -55,6 +55,11 @@ interface BlockRendererProps {
55
55
  * If true, renders the component without any tree walking or editable wrappers.
56
56
  */
57
57
  disableEditable?: boolean;
58
+ /**
59
+ * Resolved route parameters from parametric routes.
60
+ * Each key is a param name (e.g., "country") with its value, schema name, and full document.
61
+ */
62
+ routeParams?: ResolvedRouteParams;
58
63
  }
59
64
  /**
60
65
  * Renders a single block by dispatching to the appropriate component.
@@ -67,6 +72,6 @@ interface BlockRendererProps {
67
72
  * 2. Extracts all string values from block.content
68
73
  * 3. Walks the rendered tree and wraps matching text nodes with spans
69
74
  */
70
- declare function BlockRenderer({ block, registry, disableEditable }: BlockRendererProps): React__default.JSX.Element | null;
75
+ declare function BlockRenderer({ block, registry, disableEditable, routeParams, }: BlockRendererProps): React__default.JSX.Element | null;
71
76
 
72
77
  export { BlockRenderer, walkReactNode };
@@ -97,7 +97,12 @@ function renderToWalkableTree(node, keyPrefix = "") {
97
97
  }
98
98
  return node;
99
99
  }
100
- function BlockRenderer({ block, registry, disableEditable }) {
100
+ function BlockRenderer({
101
+ block,
102
+ registry,
103
+ disableEditable,
104
+ routeParams
105
+ }) {
101
106
  const Component = registry[block.type];
102
107
  if (!Component) {
103
108
  if (process.env.NODE_ENV === "development") {
@@ -105,7 +110,7 @@ function BlockRenderer({ block, registry, disableEditable }) {
105
110
  }
106
111
  return null;
107
112
  }
108
- const component = /* @__PURE__ */ jsx(Component, { content: block.content });
113
+ const component = /* @__PURE__ */ jsx(Component, { content: block.content, routeParams });
109
114
  if (disableEditable) {
110
115
  return component;
111
116
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../lib/block-renderer.tsx"],"sourcesContent":["/**\n * Block Renderer Component\n *\n * Dispatches block data to the appropriate component using the ComponentMap pattern.\n * This is the main entry point for rendering blocks from the CMS.\n */\n\nimport React from 'react';\nimport { BlockToolbar } from './block-toolbar';\nimport type { BlockComponentRegistry, BlockData } from './types';\n\ntype TextInfo = {\n value: string;\n path: Array<string | number>;\n parentType?: React.ElementType;\n key?: React.Key | null;\n};\n\ntype ElementInfo = {\n element: React.ReactElement;\n path: Array<string | number>;\n};\n\ntype WalkVisitors = {\n /**\n * Called for every string/number child encountered.\n * Return:\n * - same string (or modified)\n * - a ReactNode (e.g. wrap in <span/>)\n */\n onText?: (info: TextInfo) => React.ReactNode;\n\n /**\n * Called for every ReactElement encountered (after children are processed).\n * Return:\n * - same element\n * - a cloned/modified element\n */\n onElement?: (info: ElementInfo) => React.ReactElement;\n};\n\n/**\n * Recursively maps a ReactNode tree, allowing transformations of text nodes and/or elements.\n * SSR-safe: does not touch DOM APIs.\n */\nexport function walkReactNode(\n node: React.ReactNode,\n visitors: WalkVisitors,\n ctx: {\n path?: Array<string | number>;\n parentType?: React.ElementType;\n key?: React.Key | null;\n } = {}\n): React.ReactNode {\n const path = ctx.path ?? [];\n\n // Fast-path primitives\n if (node == null || typeof node === 'boolean') return node;\n\n if (typeof node === 'string' || typeof node === 'number') {\n const value = String(node);\n return visitors.onText\n ? visitors.onText({ value, path, parentType: ctx.parentType, key: ctx.key })\n : node;\n }\n\n // Arrays\n if (Array.isArray(node)) {\n return node.map((child, i) => {\n // biome-ignore lint/suspicious/noExplicitAny: React child key access\n const childKey = (child as any)?.key ?? null;\n const result = walkReactNode(child, visitors, {\n path: [...path, i],\n parentType: ctx.parentType,\n key: childKey,\n });\n // Ensure array children have keys\n if (React.isValidElement(result) && result.key == null) {\n return React.cloneElement(result, { key: childKey ?? `arr-${path.join('-')}-${i}` });\n }\n return result;\n });\n }\n\n // ReactElement (including Fragment)\n if (React.isValidElement(node)) {\n // biome-ignore lint/suspicious/noExplicitAny: React element props access\n const el = node as React.ReactElement<any>;\n const elProps = el.props as Record<string, unknown> | null;\n\n // Recurse into children (if any)\n const hasChildren = elProps && 'children' in elProps;\n const nextChildren = hasChildren\n ? React.Children.map(elProps.children as React.ReactNode, (child, i) => {\n // biome-ignore lint/suspicious/noExplicitAny: React child key access\n const childKey = (child as any)?.key ?? null;\n const result = walkReactNode(child, visitors, {\n path: [...path, 'children', i],\n parentType: el.type as React.ElementType,\n key: childKey,\n });\n // Ensure children have keys\n if (React.isValidElement(result) && result.key == null) {\n return React.cloneElement(result, { key: childKey ?? `child-${path.join('-')}-${i}` });\n }\n return result;\n })\n : (elProps?.children as React.ReactNode);\n\n // Only clone if children changed (or if you want to force a clone)\n const cloned = hasChildren\n ? React.cloneElement(el, undefined, nextChildren as React.ReactNode)\n : el;\n\n return visitors.onElement ? visitors.onElement({ element: cloned, path }) : cloned;\n }\n\n // Functions, symbols, portals, etc. are rare here; return as-is\n return node;\n}\n\n// -----------------------------------------------------------------------------\n// Content Value Extraction\n// -----------------------------------------------------------------------------\n\ntype ContentMatch = {\n contentPath: string;\n value: string;\n};\n\n/**\n * Extracts all string values from a content object with their paths.\n * Returns a Map where keys are string values and values are arrays of content paths.\n */\nfunction extractContentValues(\n content: Record<string, unknown>,\n basePath: string[] = []\n): Map<string, ContentMatch[]> {\n const map = new Map<string, ContentMatch[]>();\n\n function walk(obj: unknown, path: string[]) {\n if (typeof obj === 'string' && obj.trim() !== '') {\n const contentPath = path.join('.');\n const existing = map.get(obj) || [];\n existing.push({ contentPath, value: obj });\n map.set(obj, existing);\n } else if (Array.isArray(obj)) {\n for (let index = 0; index < obj.length; index++) {\n walk(obj[index], [...path, String(index)]);\n }\n } else if (obj && typeof obj === 'object') {\n for (const [key, value] of Object.entries(obj)) {\n walk(value, [...path, key]);\n }\n }\n }\n\n walk(content, basePath);\n return map;\n}\n\n// -----------------------------------------------------------------------------\n// Props\n// -----------------------------------------------------------------------------\n\ninterface BlockRendererProps {\n /**\n * The block data to render.\n * Must have a `type` field that maps to a registered component.\n */\n block: BlockData;\n registry: Partial<BlockComponentRegistry>;\n /**\n * If true, renders the component without any tree walking or editable wrappers.\n */\n disableEditable?: boolean;\n}\n\n// -----------------------------------------------------------------------------\n// Component\n// -----------------------------------------------------------------------------\n\n/**\n * Recursively renders a React node, invoking function components to get their output.\n * This allows us to walk the full rendered tree, not just the element wrappers.\n */\nfunction renderToWalkableTree(node: React.ReactNode, keyPrefix = ''): React.ReactNode {\n if (node == null || typeof node === 'boolean') return node;\n if (typeof node === 'string' || typeof node === 'number') return node;\n\n if (Array.isArray(node)) {\n return node.map((child, i) => {\n const result = renderToWalkableTree(child, `${keyPrefix}${i}-`);\n // Ensure array children have keys\n if (React.isValidElement(result) && result.key == null) {\n // biome-ignore lint/suspicious/noExplicitAny: Adding key to element\n const existingKey = (child as any)?.key;\n return React.cloneElement(result, { key: existingKey ?? `${keyPrefix}${i}` });\n }\n return result;\n });\n }\n\n if (React.isValidElement(node)) {\n // biome-ignore lint/suspicious/noExplicitAny: React element props access\n const el = node as React.ReactElement<any>;\n const elProps = el.props as Record<string, unknown> | null;\n\n // If it's a function component, invoke it to get the rendered output\n if (typeof el.type === 'function') {\n try {\n // biome-ignore lint/complexity/noBannedTypes: Need to invoke React function component\n const rendered = (el.type as Function)(el.props);\n return renderToWalkableTree(rendered, keyPrefix);\n } catch {\n // If component throws (e.g., uses hooks), return as-is\n return node;\n }\n }\n\n // For host elements (div, span, etc.), recurse into children\n if (elProps && 'children' in elProps) {\n const newChildren = renderToWalkableTree(elProps.children as React.ReactNode, keyPrefix);\n return React.cloneElement(el, undefined, newChildren);\n }\n\n return node;\n }\n\n return node;\n}\n\n/**\n * Renders a single block by dispatching to the appropriate component.\n *\n * Uses the ComponentMap pattern: the block's `type` field determines which\n * component renders the block's `content`.\n *\n * Internally, it:\n * 1. Renders the component tree by invoking function components\n * 2. Extracts all string values from block.content\n * 3. Walks the rendered tree and wraps matching text nodes with spans\n */\nexport function BlockRenderer({ block, registry, disableEditable }: BlockRendererProps) {\n const Component = registry[block.type];\n\n if (!Component) {\n // Log warning in development, render nothing in production\n if (process.env.NODE_ENV === 'development') {\n console.warn(`[BlockRenderer] Unknown block type: ${block.type}`);\n }\n return null;\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Type safety ensured by BlockData discriminated union\n const component = <Component content={block.content as any} />;\n\n if (disableEditable) {\n return component;\n }\n\n // Extract all string values from content with their paths\n const contentValueMap = extractContentValues(block.content as Record<string, unknown>);\n\n // Try server-side tree walking for text span injection (best-effort).\n // This works for sync server components but fails for client components,\n // async components, and components using hooks.\n let renderedComponent: React.ReactNode = component;\n let needsClientSideSpans = true;\n\n try {\n const renderedTree = renderToWalkableTree(component);\n\n // Check if tree walking produced host elements (div, section, etc.)\n // vs the original component reference (function type = couldn't be invoked)\n const isWalkable =\n React.isValidElement(renderedTree) &&\n typeof (renderedTree as React.ReactElement<Record<string, unknown>>).type === 'string';\n\n if (isWalkable) {\n const usedPaths = new Set<string>();\n\n renderedComponent = walkReactNode(renderedTree, {\n onText: ({ value, key, path }) => {\n const matches = contentValueMap.get(value);\n if (!matches || matches.length === 0) return value;\n\n const match = matches.find((m) => !usedPaths.has(m.contentPath)) ?? matches[0];\n if (!match) return value;\n\n usedPaths.add(match.contentPath);\n const spanKey = key ?? `${block.id}-${match.contentPath}-${path.join('-')}`;\n\n return (\n <span\n key={spanKey}\n data-cms-editable\n data-block-id={block.id}\n data-block-type={block.type}\n data-content-path={match.contentPath}\n >\n {value}\n </span>\n );\n },\n });\n\n needsClientSideSpans = false;\n }\n } catch {\n // Tree walking failed entirely, fall back to client-side injection\n }\n\n // Build content entries for client-side text matching when server-side fails\n const contentEntries = needsClientSideSpans\n ? Array.from(contentValueMap.entries())\n .map(([value, matches]) => ({ v: value, p: matches[0]?.contentPath }))\n .filter((e): e is { v: string; p: string } => !!e.p)\n : [];\n\n return (\n <div\n key={block.id}\n data-cms-block\n data-block-id={block.id}\n data-block-type={block.type}\n style={{ position: 'relative' }}\n >\n <style>{`\n [data-cms-block] {\n position: relative;\n }\n [data-cms-block]:hover {\n outline: 2px solid #3b82f6;\n outline-offset: 4px;\n }\n [data-cms-editable] {\n cursor: pointer;\n border-radius: 2px;\n }\n [data-cms-editable]:hover {\n outline: 2px solid #3b82f6;\n outline-offset: 2px;\n }\n .cms-block-toolbar {\n position: absolute;\n bottom: 8px;\n left: 50%;\n transform: translateX(-50%);\n display: flex;\n gap: 4px;\n background: #1f2937;\n border-radius: 6px;\n padding: 4px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);\n opacity: 0;\n pointer-events: none;\n transition: opacity 0.15s ease;\n z-index: 1000;\n }\n [data-cms-block]:hover .cms-block-toolbar {\n opacity: 1;\n pointer-events: auto;\n }\n .cms-block-toolbar button {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: none;\n background: transparent;\n color: #9ca3af;\n border-radius: 4px;\n cursor: pointer;\n transition: background 0.15s ease, color 0.15s ease;\n }\n .cms-block-toolbar button:hover {\n background: #374151;\n color: #fff;\n }\n .cms-block-toolbar button.delete:hover {\n background: #dc2626;\n color: #fff;\n }\n .cms-block-toolbar button:disabled {\n opacity: 0.4;\n cursor: not-allowed;\n }\n .cms-block-toolbar button:disabled:hover {\n background: transparent;\n color: #9ca3af;\n }\n .cms-block-toolbar svg {\n width: 16px;\n height: 16px;\n }\n `}</style>\n <script\n // biome-ignore lint/security/noDangerouslySetInnerHtml: Inline script for iframe postMessage and client-side text matching\n dangerouslySetInnerHTML={{\n __html: `\n (function() {\n if (!window.__cmsEditableInitialized) {\n window.__cmsEditableInitialized = true;\n\n document.addEventListener('click', function(e) {\n if (e.target.closest('.cms-block-toolbar')) return;\n\n var editableTarget = e.target.closest('[data-cms-editable]');\n if (editableTarget) {\n var message = {\n type: 'cms-editable-click',\n blockId: editableTarget.getAttribute('data-block-id'),\n blockType: editableTarget.getAttribute('data-block-type'),\n contentPath: editableTarget.getAttribute('data-content-path')\n };\n if (window.parent && window.parent !== window) {\n window.parent.postMessage(message, '*');\n }\n return;\n }\n\n var blockTarget = e.target.closest('[data-cms-block]');\n if (blockTarget) {\n var message = {\n type: 'cms-editable-click',\n blockId: blockTarget.getAttribute('data-block-id'),\n blockType: blockTarget.getAttribute('data-block-type'),\n contentPath: null\n };\n if (window.parent && window.parent !== window) {\n window.parent.postMessage(message, '*');\n }\n }\n });\n }\n })();\n ${\n contentEntries.length > 0\n ? `\n (function() {\n var blockId = ${JSON.stringify(block.id)};\n var blockType = ${JSON.stringify(block.type)};\n var entries = ${JSON.stringify(contentEntries)};\n\n function injectSpans() {\n var block = document.querySelector('[data-block-id=\"' + blockId + '\"]');\n if (!block || block.getAttribute('data-cms-spans-injected')) return;\n block.setAttribute('data-cms-spans-injected', 'true');\n\n var used = {};\n var walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT, null);\n var textNodes = [];\n var n;\n while (n = walker.nextNode()) {\n if (n.parentNode && n.parentNode.closest && n.parentNode.closest('.cms-block-toolbar')) continue;\n if (n.nodeValue && n.nodeValue.trim()) textNodes.push(n);\n }\n\n for (var i = 0; i < textNodes.length; i++) {\n var node = textNodes[i];\n var text = node.nodeValue;\n if (!text) continue;\n\n for (var j = 0; j < entries.length; j++) {\n var e = entries[j];\n if (used[e.p]) continue;\n if (text.indexOf(e.v) !== -1 && text.trim() === e.v.trim()) {\n used[e.p] = true;\n var span = document.createElement('span');\n span.setAttribute('data-cms-editable', '');\n span.setAttribute('data-block-id', blockId);\n span.setAttribute('data-block-type', blockType);\n span.setAttribute('data-content-path', e.p);\n node.parentNode.insertBefore(span, node);\n span.appendChild(node);\n break;\n }\n }\n }\n }\n\n if (document.readyState === 'complete') {\n requestAnimationFrame(injectSpans);\n } else {\n window.addEventListener('load', function() {\n requestAnimationFrame(injectSpans);\n });\n }\n })();\n `\n : ''\n }\n `,\n }}\n />\n {renderedComponent}\n <BlockToolbar key=\"c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,QACD,oBAAC,gBAA+B,SAAS,MAAM,MAA7B,aAAiC;AAAA;AAAA;AAAA,IAhL9C,MAAM;AAAA,EAiLb;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../../lib/block-renderer.tsx"],"sourcesContent":["/**\n * Block Renderer Component\n *\n * Dispatches block data to the appropriate component using the ComponentMap pattern.\n * This is the main entry point for rendering blocks from the CMS.\n */\n\nimport React from 'react';\nimport { BlockToolbar } from './block-toolbar';\nimport type { BlockComponentRegistry, BlockData, ResolvedRouteParams } from './types';\n\ntype TextInfo = {\n value: string;\n path: Array<string | number>;\n parentType?: React.ElementType;\n key?: React.Key | null;\n};\n\ntype ElementInfo = {\n element: React.ReactElement;\n path: Array<string | number>;\n};\n\ntype WalkVisitors = {\n /**\n * Called for every string/number child encountered.\n * Return:\n * - same string (or modified)\n * - a ReactNode (e.g. wrap in <span/>)\n */\n onText?: (info: TextInfo) => React.ReactNode;\n\n /**\n * Called for every ReactElement encountered (after children are processed).\n * Return:\n * - same element\n * - a cloned/modified element\n */\n onElement?: (info: ElementInfo) => React.ReactElement;\n};\n\n/**\n * Recursively maps a ReactNode tree, allowing transformations of text nodes and/or elements.\n * SSR-safe: does not touch DOM APIs.\n */\nexport function walkReactNode(\n node: React.ReactNode,\n visitors: WalkVisitors,\n ctx: {\n path?: Array<string | number>;\n parentType?: React.ElementType;\n key?: React.Key | null;\n } = {}\n): React.ReactNode {\n const path = ctx.path ?? [];\n\n // Fast-path primitives\n if (node == null || typeof node === 'boolean') return node;\n\n if (typeof node === 'string' || typeof node === 'number') {\n const value = String(node);\n return visitors.onText\n ? visitors.onText({ value, path, parentType: ctx.parentType, key: ctx.key })\n : node;\n }\n\n // Arrays\n if (Array.isArray(node)) {\n return node.map((child, i) => {\n // biome-ignore lint/suspicious/noExplicitAny: React child key access\n const childKey = (child as any)?.key ?? null;\n const result = walkReactNode(child, visitors, {\n path: [...path, i],\n parentType: ctx.parentType,\n key: childKey,\n });\n // Ensure array children have keys\n if (React.isValidElement(result) && result.key == null) {\n return React.cloneElement(result, { key: childKey ?? `arr-${path.join('-')}-${i}` });\n }\n return result;\n });\n }\n\n // ReactElement (including Fragment)\n if (React.isValidElement(node)) {\n // biome-ignore lint/suspicious/noExplicitAny: React element props access\n const el = node as React.ReactElement<any>;\n const elProps = el.props as Record<string, unknown> | null;\n\n // Recurse into children (if any)\n const hasChildren = elProps && 'children' in elProps;\n const nextChildren = hasChildren\n ? React.Children.map(elProps.children as React.ReactNode, (child, i) => {\n // biome-ignore lint/suspicious/noExplicitAny: React child key access\n const childKey = (child as any)?.key ?? null;\n const result = walkReactNode(child, visitors, {\n path: [...path, 'children', i],\n parentType: el.type as React.ElementType,\n key: childKey,\n });\n // Ensure children have keys\n if (React.isValidElement(result) && result.key == null) {\n return React.cloneElement(result, { key: childKey ?? `child-${path.join('-')}-${i}` });\n }\n return result;\n })\n : (elProps?.children as React.ReactNode);\n\n // Only clone if children changed (or if you want to force a clone)\n const cloned = hasChildren\n ? React.cloneElement(el, undefined, nextChildren as React.ReactNode)\n : el;\n\n return visitors.onElement ? visitors.onElement({ element: cloned, path }) : cloned;\n }\n\n // Functions, symbols, portals, etc. are rare here; return as-is\n return node;\n}\n\n// -----------------------------------------------------------------------------\n// Content Value Extraction\n// -----------------------------------------------------------------------------\n\ntype ContentMatch = {\n contentPath: string;\n value: string;\n};\n\n/**\n * Extracts all string values from a content object with their paths.\n * Returns a Map where keys are string values and values are arrays of content paths.\n */\nfunction extractContentValues(\n content: Record<string, unknown>,\n basePath: string[] = []\n): Map<string, ContentMatch[]> {\n const map = new Map<string, ContentMatch[]>();\n\n function walk(obj: unknown, path: string[]) {\n if (typeof obj === 'string' && obj.trim() !== '') {\n const contentPath = path.join('.');\n const existing = map.get(obj) || [];\n existing.push({ contentPath, value: obj });\n map.set(obj, existing);\n } else if (Array.isArray(obj)) {\n for (let index = 0; index < obj.length; index++) {\n walk(obj[index], [...path, String(index)]);\n }\n } else if (obj && typeof obj === 'object') {\n for (const [key, value] of Object.entries(obj)) {\n walk(value, [...path, key]);\n }\n }\n }\n\n walk(content, basePath);\n return map;\n}\n\n// -----------------------------------------------------------------------------\n// Props\n// -----------------------------------------------------------------------------\n\ninterface BlockRendererProps {\n /**\n * The block data to render.\n * Must have a `type` field that maps to a registered component.\n */\n block: BlockData;\n registry: Partial<BlockComponentRegistry>;\n /**\n * If true, renders the component without any tree walking or editable wrappers.\n */\n disableEditable?: boolean;\n /**\n * Resolved route parameters from parametric routes.\n * Each key is a param name (e.g., \"country\") with its value, schema name, and full document.\n */\n routeParams?: ResolvedRouteParams;\n}\n\n// -----------------------------------------------------------------------------\n// Component\n// -----------------------------------------------------------------------------\n\n/**\n * Recursively renders a React node, invoking function components to get their output.\n * This allows us to walk the full rendered tree, not just the element wrappers.\n */\nfunction renderToWalkableTree(node: React.ReactNode, keyPrefix = ''): React.ReactNode {\n if (node == null || typeof node === 'boolean') return node;\n if (typeof node === 'string' || typeof node === 'number') return node;\n\n if (Array.isArray(node)) {\n return node.map((child, i) => {\n const result = renderToWalkableTree(child, `${keyPrefix}${i}-`);\n // Ensure array children have keys\n if (React.isValidElement(result) && result.key == null) {\n // biome-ignore lint/suspicious/noExplicitAny: Adding key to element\n const existingKey = (child as any)?.key;\n return React.cloneElement(result, { key: existingKey ?? `${keyPrefix}${i}` });\n }\n return result;\n });\n }\n\n if (React.isValidElement(node)) {\n // biome-ignore lint/suspicious/noExplicitAny: React element props access\n const el = node as React.ReactElement<any>;\n const elProps = el.props as Record<string, unknown> | null;\n\n // If it's a function component, invoke it to get the rendered output\n if (typeof el.type === 'function') {\n try {\n // biome-ignore lint/complexity/noBannedTypes: Need to invoke React function component\n const rendered = (el.type as Function)(el.props);\n return renderToWalkableTree(rendered, keyPrefix);\n } catch {\n // If component throws (e.g., uses hooks), return as-is\n return node;\n }\n }\n\n // For host elements (div, span, etc.), recurse into children\n if (elProps && 'children' in elProps) {\n const newChildren = renderToWalkableTree(elProps.children as React.ReactNode, keyPrefix);\n return React.cloneElement(el, undefined, newChildren);\n }\n\n return node;\n }\n\n return node;\n}\n\n/**\n * Renders a single block by dispatching to the appropriate component.\n *\n * Uses the ComponentMap pattern: the block's `type` field determines which\n * component renders the block's `content`.\n *\n * Internally, it:\n * 1. Renders the component tree by invoking function components\n * 2. Extracts all string values from block.content\n * 3. Walks the rendered tree and wraps matching text nodes with spans\n */\nexport function BlockRenderer({\n block,\n registry,\n disableEditable,\n routeParams,\n}: BlockRendererProps) {\n const Component = registry[block.type];\n\n if (!Component) {\n // Log warning in development, render nothing in production\n if (process.env.NODE_ENV === 'development') {\n console.warn(`[BlockRenderer] Unknown block type: ${block.type}`);\n }\n return null;\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Type safety ensured by BlockData discriminated union\n const component = <Component content={block.content as any} routeParams={routeParams} />;\n\n if (disableEditable) {\n return component;\n }\n\n // Extract all string values from content with their paths\n const contentValueMap = extractContentValues(block.content as Record<string, unknown>);\n\n // Try server-side tree walking for text span injection (best-effort).\n // This works for sync server components but fails for client components,\n // async components, and components using hooks.\n let renderedComponent: React.ReactNode = component;\n let needsClientSideSpans = true;\n\n try {\n const renderedTree = renderToWalkableTree(component);\n\n // Check if tree walking produced host elements (div, section, etc.)\n // vs the original component reference (function type = couldn't be invoked)\n const isWalkable =\n React.isValidElement(renderedTree) &&\n typeof (renderedTree as React.ReactElement<Record<string, unknown>>).type === 'string';\n\n if (isWalkable) {\n const usedPaths = new Set<string>();\n\n renderedComponent = walkReactNode(renderedTree, {\n onText: ({ value, key, path }) => {\n const matches = contentValueMap.get(value);\n if (!matches || matches.length === 0) return value;\n\n const match = matches.find((m) => !usedPaths.has(m.contentPath)) ?? matches[0];\n if (!match) return value;\n\n usedPaths.add(match.contentPath);\n const spanKey = key ?? `${block.id}-${match.contentPath}-${path.join('-')}`;\n\n return (\n <span\n key={spanKey}\n data-cms-editable\n data-block-id={block.id}\n data-block-type={block.type}\n data-content-path={match.contentPath}\n >\n {value}\n </span>\n );\n },\n });\n\n needsClientSideSpans = false;\n }\n } catch {\n // Tree walking failed entirely, fall back to client-side injection\n }\n\n // Build content entries for client-side text matching when server-side fails\n const contentEntries = needsClientSideSpans\n ? Array.from(contentValueMap.entries())\n .map(([value, matches]) => ({ v: value, p: matches[0]?.contentPath }))\n .filter((e): e is { v: string; p: string } => !!e.p)\n : [];\n\n return (\n <div\n key={block.id}\n data-cms-block\n data-block-id={block.id}\n data-block-type={block.type}\n style={{ position: 'relative' }}\n >\n <style>{`\n [data-cms-block] {\n position: relative;\n }\n [data-cms-block]:hover {\n outline: 2px solid #3b82f6;\n outline-offset: 4px;\n }\n [data-cms-editable] {\n cursor: pointer;\n border-radius: 2px;\n }\n [data-cms-editable]:hover {\n outline: 2px solid #3b82f6;\n outline-offset: 2px;\n }\n .cms-block-toolbar {\n position: absolute;\n bottom: 8px;\n left: 50%;\n transform: translateX(-50%);\n display: flex;\n gap: 4px;\n background: #1f2937;\n border-radius: 6px;\n padding: 4px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);\n opacity: 0;\n pointer-events: none;\n transition: opacity 0.15s ease;\n z-index: 1000;\n }\n [data-cms-block]:hover .cms-block-toolbar {\n opacity: 1;\n pointer-events: auto;\n }\n .cms-block-toolbar button {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: none;\n background: transparent;\n color: #9ca3af;\n border-radius: 4px;\n cursor: pointer;\n transition: background 0.15s ease, color 0.15s ease;\n }\n .cms-block-toolbar button:hover {\n background: #374151;\n color: #fff;\n }\n .cms-block-toolbar button.delete:hover {\n background: #dc2626;\n color: #fff;\n }\n .cms-block-toolbar button:disabled {\n opacity: 0.4;\n cursor: not-allowed;\n }\n .cms-block-toolbar button:disabled:hover {\n background: transparent;\n color: #9ca3af;\n }\n .cms-block-toolbar svg {\n width: 16px;\n height: 16px;\n }\n `}</style>\n <script\n // biome-ignore lint/security/noDangerouslySetInnerHtml: Inline script for iframe postMessage and client-side text matching\n dangerouslySetInnerHTML={{\n __html: `\n (function() {\n if (!window.__cmsEditableInitialized) {\n window.__cmsEditableInitialized = true;\n\n document.addEventListener('click', function(e) {\n if (e.target.closest('.cms-block-toolbar')) return;\n\n var editableTarget = e.target.closest('[data-cms-editable]');\n if (editableTarget) {\n var message = {\n type: 'cms-editable-click',\n blockId: editableTarget.getAttribute('data-block-id'),\n blockType: editableTarget.getAttribute('data-block-type'),\n contentPath: editableTarget.getAttribute('data-content-path')\n };\n if (window.parent && window.parent !== window) {\n window.parent.postMessage(message, '*');\n }\n return;\n }\n\n var blockTarget = e.target.closest('[data-cms-block]');\n if (blockTarget) {\n var message = {\n type: 'cms-editable-click',\n blockId: blockTarget.getAttribute('data-block-id'),\n blockType: blockTarget.getAttribute('data-block-type'),\n contentPath: null\n };\n if (window.parent && window.parent !== window) {\n window.parent.postMessage(message, '*');\n }\n }\n });\n }\n })();\n ${\n contentEntries.length > 0\n ? `\n (function() {\n var blockId = ${JSON.stringify(block.id)};\n var blockType = ${JSON.stringify(block.type)};\n var entries = ${JSON.stringify(contentEntries)};\n\n function injectSpans() {\n var block = document.querySelector('[data-block-id=\"' + blockId + '\"]');\n if (!block || block.getAttribute('data-cms-spans-injected')) return;\n block.setAttribute('data-cms-spans-injected', 'true');\n\n var used = {};\n var walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT, null);\n var textNodes = [];\n var n;\n while (n = walker.nextNode()) {\n if (n.parentNode && n.parentNode.closest && n.parentNode.closest('.cms-block-toolbar')) continue;\n if (n.nodeValue && n.nodeValue.trim()) textNodes.push(n);\n }\n\n for (var i = 0; i < textNodes.length; i++) {\n var node = textNodes[i];\n var text = node.nodeValue;\n if (!text) continue;\n\n for (var j = 0; j < entries.length; j++) {\n var e = entries[j];\n if (used[e.p]) continue;\n if (text.indexOf(e.v) !== -1 && text.trim() === e.v.trim()) {\n used[e.p] = true;\n var span = document.createElement('span');\n span.setAttribute('data-cms-editable', '');\n span.setAttribute('data-block-id', blockId);\n span.setAttribute('data-block-type', blockType);\n span.setAttribute('data-content-path', e.p);\n node.parentNode.insertBefore(span, node);\n span.appendChild(node);\n break;\n }\n }\n }\n }\n\n if (document.readyState === 'complete') {\n requestAnimationFrame(injectSpans);\n } else {\n window.addEventListener('load', function() {\n requestAnimationFrame(injectSpans);\n });\n }\n })();\n `\n : ''\n }\n `,\n }}\n />\n {renderedComponent}\n <BlockToolbar key=\"cms-toolbar\" blockId={block.id} />\n </div>\n );\n}\n"],"mappings":";AAOA,OAAO,WAAW;AAClB,SAAS,oBAAoB;AAiQT,cAkEhB,YAlEgB;AA5Nb,SAAS,cACd,MACA,UACA,MAII,CAAC,GACY;AACjB,QAAM,OAAO,IAAI,QAAQ,CAAC;AAG1B,MAAI,QAAQ,QAAQ,OAAO,SAAS,UAAW,QAAO;AAEtD,MAAI,OAAO,SAAS,YAAY,OAAO,SAAS,UAAU;AACxD,UAAM,QAAQ,OAAO,IAAI;AACzB,WAAO,SAAS,SACZ,SAAS,OAAO,EAAE,OAAO,MAAM,YAAY,IAAI,YAAY,KAAK,IAAI,IAAI,CAAC,IACzE;AAAA,EACN;AAGA,MAAI,MAAM,QAAQ,IAAI,GAAG;AACvB,WAAO,KAAK,IAAI,CAAC,OAAO,MAAM;AAE5B,YAAM,WAAY,OAAe,OAAO;AACxC,YAAM,SAAS,cAAc,OAAO,UAAU;AAAA,QAC5C,MAAM,CAAC,GAAG,MAAM,CAAC;AAAA,QACjB,YAAY,IAAI;AAAA,QAChB,KAAK;AAAA,MACP,CAAC;AAED,UAAI,MAAM,eAAe,MAAM,KAAK,OAAO,OAAO,MAAM;AACtD,eAAO,MAAM,aAAa,QAAQ,EAAE,KAAK,YAAY,OAAO,KAAK,KAAK,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC;AAAA,MACrF;AACA,aAAO;AAAA,IACT,CAAC;AAAA,EACH;AAGA,MAAI,MAAM,eAAe,IAAI,GAAG;AAE9B,UAAM,KAAK;AACX,UAAM,UAAU,GAAG;AAGnB,UAAM,cAAc,WAAW,cAAc;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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAgD1C,EACN;AAAA;AAAA,YAEJ;AAAA;AAAA,QACF;AAAA,QACC;AAAA,QACD,oBAAC,gBAA+B,SAAS,MAAM,MAA7B,aAAiC;AAAA;AAAA;AAAA,IAhL9C,MAAM;AAAA,EAiLb;AAEJ;","names":[]}
@@ -2,6 +2,7 @@
2
2
  "use client";
3
3
 
4
4
  // lib/block-toolbar.tsx
5
+ import { ChevronDown, ChevronUp, Plus, Trash2 } from "lucide-react";
5
6
  import { jsx, jsxs } from "react/jsx-runtime";
6
7
  function BlockToolbar({ blockId }) {
7
8
  const handleAction = (action) => {
@@ -21,24 +22,13 @@ function BlockToolbar({ blockId }) {
21
22
  {
22
23
  type: "button",
23
24
  title: "Move up",
25
+ "aria-label": "Move up",
24
26
  "data-action": "move-up",
25
27
  onClick: (e) => {
26
28
  e.stopPropagation();
27
29
  handleAction("move-up");
28
30
  },
29
- children: /* @__PURE__ */ jsx(
30
- "svg",
31
- {
32
- xmlns: "http://www.w3.org/2000/svg",
33
- viewBox: "0 0 24 24",
34
- fill: "none",
35
- stroke: "currentColor",
36
- strokeWidth: "2",
37
- strokeLinecap: "round",
38
- strokeLinejoin: "round",
39
- children: /* @__PURE__ */ jsx("path", { d: "m18 15-6-6-6 6" })
40
- }
41
- )
31
+ children: /* @__PURE__ */ jsx(ChevronUp, {})
42
32
  }
43
33
  ),
44
34
  /* @__PURE__ */ jsx(
@@ -46,24 +36,13 @@ function BlockToolbar({ blockId }) {
46
36
  {
47
37
  type: "button",
48
38
  title: "Move down",
39
+ "aria-label": "Move down",
49
40
  "data-action": "move-down",
50
41
  onClick: (e) => {
51
42
  e.stopPropagation();
52
43
  handleAction("move-down");
53
44
  },
54
- children: /* @__PURE__ */ jsx(
55
- "svg",
56
- {
57
- xmlns: "http://www.w3.org/2000/svg",
58
- viewBox: "0 0 24 24",
59
- fill: "none",
60
- stroke: "currentColor",
61
- strokeWidth: "2",
62
- strokeLinecap: "round",
63
- strokeLinejoin: "round",
64
- children: /* @__PURE__ */ jsx("path", { d: "m6 9 6 6 6-6" })
65
- }
66
- )
45
+ children: /* @__PURE__ */ jsx(ChevronDown, {})
67
46
  }
68
47
  ),
69
48
  /* @__PURE__ */ jsx(
@@ -71,27 +50,13 @@ function BlockToolbar({ blockId }) {
71
50
  {
72
51
  type: "button",
73
52
  title: "Add block",
53
+ "aria-label": "Add block",
74
54
  "data-action": "add-block",
75
55
  onClick: (e) => {
76
56
  e.stopPropagation();
77
57
  handleAction("add-block");
78
58
  },
79
- children: /* @__PURE__ */ jsxs(
80
- "svg",
81
- {
82
- xmlns: "http://www.w3.org/2000/svg",
83
- viewBox: "0 0 24 24",
84
- fill: "none",
85
- stroke: "currentColor",
86
- strokeWidth: "2",
87
- strokeLinecap: "round",
88
- strokeLinejoin: "round",
89
- children: [
90
- /* @__PURE__ */ jsx("line", { x1: "12", x2: "12", y1: "5", y2: "19" }),
91
- /* @__PURE__ */ jsx("line", { x1: "5", x2: "19", y1: "12", y2: "12" })
92
- ]
93
- }
94
- )
59
+ children: /* @__PURE__ */ jsx(Plus, {})
95
60
  }
96
61
  ),
97
62
  /* @__PURE__ */ jsx(
@@ -100,30 +65,13 @@ function BlockToolbar({ blockId }) {
100
65
  type: "button",
101
66
  className: "delete",
102
67
  title: "Delete block",
68
+ "aria-label": "Delete block",
103
69
  "data-action": "delete",
104
70
  onClick: (e) => {
105
71
  e.stopPropagation();
106
72
  handleAction("delete");
107
73
  },
108
- children: /* @__PURE__ */ jsxs(
109
- "svg",
110
- {
111
- xmlns: "http://www.w3.org/2000/svg",
112
- viewBox: "0 0 24 24",
113
- fill: "none",
114
- stroke: "currentColor",
115
- strokeWidth: "2",
116
- strokeLinecap: "round",
117
- strokeLinejoin: "round",
118
- children: [
119
- /* @__PURE__ */ jsx("path", { d: "M3 6h18" }),
120
- /* @__PURE__ */ jsx("path", { d: "M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6" }),
121
- /* @__PURE__ */ jsx("path", { d: "M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2" }),
122
- /* @__PURE__ */ jsx("line", { x1: "10", x2: "10", y1: "11", y2: "17" }),
123
- /* @__PURE__ */ jsx("line", { x1: "14", x2: "14", y1: "11", y2: "17" })
124
- ]
125
- }
126
- )
74
+ children: /* @__PURE__ */ jsx(Trash2, {})
127
75
  }
128
76
  )
129
77
  ]
@@ -1 +1 @@
1
- {"version":3,"sources":["../../lib/block-toolbar.tsx"],"sourcesContent":["'use client';\n\n/**\n * Block Toolbar Component\n *\n * Provides move up/down and delete controls for blocks in edit mode.\n * This is a Client Component because it requires onClick handlers.\n */\n\nexport function BlockToolbar({ blockId }: { blockId: string }) {\n const handleAction = (action: string) => {\n if (typeof window !== 'undefined' && window.parent && window.parent !== window) {\n window.parent.postMessage({ type: 'cms-block-action', action, blockId }, '*');\n }\n };\n\n return (\n <div\n className=\"cms-block-toolbar\"\n data-cms-toolbar=\"true\"\n style={{ position: 'absolute', zIndex: 9999 }}\n >\n <button\n type=\"button\"\n title=\"Move up\"\n data-action=\"move-up\"\n onClick={(e) => {\n e.stopPropagation();\n handleAction('move-up');\n }}\n >\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"m18 15-6-6-6 6\" />\n </svg>\n </button>\n <button\n type=\"button\"\n title=\"Move down\"\n data-action=\"move-down\"\n onClick={(e) => {\n e.stopPropagation();\n handleAction('move-down');\n }}\n >\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"m6 9 6 6 6-6\" />\n </svg>\n </button>\n <button\n type=\"button\"\n title=\"Add block\"\n data-action=\"add-block\"\n onClick={(e) => {\n e.stopPropagation();\n handleAction('add-block');\n }}\n >\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <line x1=\"12\" x2=\"12\" y1=\"5\" y2=\"19\" />\n <line x1=\"5\" x2=\"19\" y1=\"12\" y2=\"12\" />\n </svg>\n </button>\n <button\n type=\"button\"\n className=\"delete\"\n title=\"Delete block\"\n data-action=\"delete\"\n onClick={(e) => {\n e.stopPropagation();\n handleAction('delete');\n }}\n >\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"M3 6h18\" />\n <path d=\"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6\" />\n <path d=\"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2\" />\n <line x1=\"10\" x2=\"10\" y1=\"11\" y2=\"17\" />\n <line x1=\"14\" x2=\"14\" y1=\"11\" y2=\"17\" />\n </svg>\n </button>\n </div>\n );\n}\n"],"mappings":";;;;AAwCU,cAiCF,YAjCE;AA/BH,SAAS,aAAa,EAAE,QAAQ,GAAwB;AAC7D,QAAM,eAAe,CAAC,WAAmB;AACvC,QAAI,OAAO,WAAW,eAAe,OAAO,UAAU,OAAO,WAAW,QAAQ;AAC9E,aAAO,OAAO,YAAY,EAAE,MAAM,oBAAoB,QAAQ,QAAQ,GAAG,GAAG;AAAA,IAC9E;AAAA,EACF;AAEA,SACE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AAA,gBAEf;AAAA,sCAAC,UAAK,IAAG,MAAK,IAAG,MAAK,IAAG,KAAI,IAAG,MAAK;AAAA,kBACrC,oBAAC,UAAK,IAAG,KAAI,IAAG,MAAK,IAAG,MAAK,IAAG,MAAK;AAAA;AAAA;AAAA,YACvC;AAAA;AAAA,QACF;AAAA,QACA;AAAA,UAAC;AAAA;AAAA,YACC,MAAK;AAAA,YACL,WAAU;AAAA,YACV,OAAM;AAAA,YACN,eAAY;AAAA,YACZ,SAAS,CAAC,MAAM;AACd,gBAAE,gBAAgB;AAClB,2BAAa,QAAQ;AAAA,YACvB;AAAA,YAEA;AAAA,cAAC;AAAA;AAAA,gBACC,OAAM;AAAA,gBACN,SAAQ;AAAA,gBACR,MAAK;AAAA,gBACL,QAAO;AAAA,gBACP,aAAY;AAAA,gBACZ,eAAc;AAAA,gBACd,gBAAe;AAAA,gBAEf;AAAA,sCAAC,UAAK,GAAE,WAAU;AAAA,kBAClB,oBAAC,UAAK,GAAE,yCAAwC;AAAA,kBAChD,oBAAC,UAAK,GAAE,sCAAqC;AAAA,kBAC7C,oBAAC,UAAK,IAAG,MAAK,IAAG,MAAK,IAAG,MAAK,IAAG,MAAK;AAAA,kBACtC,oBAAC,UAAK,IAAG,MAAK,IAAG,MAAK,IAAG,MAAK,IAAG,MAAK;AAAA;AAAA;AAAA,YACxC;AAAA;AAAA,QACF;AAAA;AAAA;AAAA,EACF;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../../lib/block-toolbar.tsx"],"sourcesContent":["'use client';\n\nimport { ChevronDown, ChevronUp, Plus, Trash2 } from 'lucide-react';\n\n/**\n * Block Toolbar Component\n *\n * Provides move up/down and delete controls for blocks in edit mode.\n * This is a Client Component because it requires onClick handlers.\n */\n\nexport function BlockToolbar({ blockId }: { blockId: string }) {\n const handleAction = (action: string) => {\n if (typeof window !== 'undefined' && window.parent && window.parent !== window) {\n window.parent.postMessage({ type: 'cms-block-action', action, blockId }, '*');\n }\n };\n\n return (\n <div\n className=\"cms-block-toolbar\"\n data-cms-toolbar=\"true\"\n style={{ position: 'absolute', zIndex: 9999 }}\n >\n <button\n type=\"button\"\n title=\"Move up\"\n aria-label=\"Move up\"\n data-action=\"move-up\"\n onClick={(e) => {\n e.stopPropagation();\n handleAction('move-up');\n }}\n >\n <ChevronUp />\n </button>\n <button\n type=\"button\"\n title=\"Move down\"\n aria-label=\"Move down\"\n data-action=\"move-down\"\n onClick={(e) => {\n e.stopPropagation();\n handleAction('move-down');\n }}\n >\n <ChevronDown />\n </button>\n <button\n type=\"button\"\n title=\"Add block\"\n aria-label=\"Add block\"\n data-action=\"add-block\"\n onClick={(e) => {\n e.stopPropagation();\n handleAction('add-block');\n }}\n >\n <Plus />\n </button>\n <button\n type=\"button\"\n className=\"delete\"\n title=\"Delete block\"\n aria-label=\"Delete block\"\n data-action=\"delete\"\n onClick={(e) => {\n e.stopPropagation();\n handleAction('delete');\n }}\n >\n <Trash2 />\n </button>\n </div>\n );\n}\n"],"mappings":";;;;AAEA,SAAS,aAAa,WAAW,MAAM,cAAc;AAiBjD,SAeI,KAfJ;AARG,SAAS,aAAa,EAAE,QAAQ,GAAwB;AAC7D,QAAM,eAAe,CAAC,WAAmB;AACvC,QAAI,OAAO,WAAW,eAAe,OAAO,UAAU,OAAO,WAAW,QAAQ;AAC9E,aAAO,OAAO,YAAY,EAAE,MAAM,oBAAoB,QAAQ,QAAQ,GAAG,GAAG;AAAA,IAC9E;AAAA,EACF;AAEA,SACE;AAAA,IAAC;AAAA;AAAA,MACC,WAAU;AAAA,MACV,oBAAiB;AAAA,MACjB,OAAO,EAAE,UAAU,YAAY,QAAQ,KAAK;AAAA,MAE5C;AAAA;AAAA,UAAC;AAAA;AAAA,YACC,MAAK;AAAA,YACL,OAAM;AAAA,YACN,cAAW;AAAA,YACX,eAAY;AAAA,YACZ,SAAS,CAAC,MAAM;AACd,gBAAE,gBAAgB;AAClB,2BAAa,SAAS;AAAA,YACxB;AAAA,YAEA,8BAAC,aAAU;AAAA;AAAA,QACb;AAAA,QACA;AAAA,UAAC;AAAA;AAAA,YACC,MAAK;AAAA,YACL,OAAM;AAAA,YACN,cAAW;AAAA,YACX,eAAY;AAAA,YACZ,SAAS,CAAC,MAAM;AACd,gBAAE,gBAAgB;AAClB,2BAAa,WAAW;AAAA,YAC1B;AAAA,YAEA,8BAAC,eAAY;AAAA;AAAA,QACf;AAAA,QACA;AAAA,UAAC;AAAA;AAAA,YACC,MAAK;AAAA,YACL,OAAM;AAAA,YACN,cAAW;AAAA,YACX,eAAY;AAAA,YACZ,SAAS,CAAC,MAAM;AACd,gBAAE,gBAAgB;AAClB,2BAAa,WAAW;AAAA,YAC1B;AAAA,YAEA,8BAAC,QAAK;AAAA;AAAA,QACR;AAAA,QACA;AAAA,UAAC;AAAA;AAAA,YACC,MAAK;AAAA,YACL,WAAU;AAAA,YACV,OAAM;AAAA,YACN,cAAW;AAAA,YACX,eAAY;AAAA,YACZ,SAAS,CAAC,MAAM;AACd,gBAAE,gBAAgB;AAClB,2BAAa,QAAQ;AAAA,YACvB;AAAA,YAEA,8BAAC,UAAO;AAAA;AAAA,QACV;AAAA;AAAA;AAAA,EACF;AAEJ;","names":[]}
@@ -10,16 +10,18 @@ import { CreateTRPCClient } from '@trpc/client';
10
10
 
11
11
  /** Type alias for the CMS API client */
12
12
  type CmsClient = CreateTRPCClient<AppRouter>;
13
- /** Options for creating a CMS client */
14
- interface CmsClientOptions {
13
+ /** Unified configuration for all CMS API access */
14
+ interface CmsConfig {
15
15
  /** CMS API base URL (e.g., 'http://localhost:3000') */
16
16
  cmsUrl: string;
17
- /** API key for authentication (passed as query parameter) */
17
+ /** API key for authentication */
18
18
  apiKey?: string;
19
+ /** Website ID to scope API requests */
20
+ websiteId?: string;
19
21
  }
20
22
  /**
21
23
  * Get a CMS client for the specified CMS URL.
22
24
  */
23
- declare function getCmsClient(options: CmsClientOptions): CmsClient;
25
+ declare function getCmsClient(options: CmsConfig): CmsClient;
24
26
 
25
- export { type CmsClientOptions, getCmsClient };
27
+ export { type CmsConfig, getCmsClient };
@@ -2,14 +2,19 @@
2
2
  import { createTRPCClient, httpBatchLink } from "@trpc/client";
3
3
  import superjson from "superjson";
4
4
  function getCmsApiUrl(cmsUrl) {
5
- return `${cmsUrl}/api/trpc`;
5
+ return new URL("/api/trpc", cmsUrl).toString();
6
6
  }
7
- function createFetchWithApiKey(apiKey) {
7
+ function createFetchWithApiKey(apiKey, websiteId) {
8
8
  return async (url, options) => {
9
9
  let finalUrl = url;
10
+ const urlObj = new URL(url.toString());
10
11
  if (apiKey) {
11
- const urlObj = new URL(url.toString());
12
12
  urlObj.searchParams.set("api_key", apiKey);
13
+ }
14
+ if (websiteId) {
15
+ urlObj.searchParams.set("website_id", websiteId);
16
+ }
17
+ if (apiKey || websiteId) {
13
18
  finalUrl = urlObj.toString();
14
19
  }
15
20
  const response = await fetch(finalUrl, options);
@@ -18,13 +23,12 @@ function createFetchWithApiKey(apiKey) {
18
23
  }
19
24
  function createCmsClient(options) {
20
25
  const url = getCmsApiUrl(options.cmsUrl);
21
- console.log("[CMS API] Creating client with URL:", url);
22
26
  return createTRPCClient({
23
27
  links: [
24
28
  httpBatchLink({
25
29
  url,
26
30
  transformer: superjson,
27
- fetch: createFetchWithApiKey(options.apiKey)
31
+ fetch: createFetchWithApiKey(options.apiKey, options.websiteId)
28
32
  })
29
33
  ]
30
34
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../lib/cms-api.ts"],"sourcesContent":["/**\n * CMS API Client\n *\n * Creates an HTTP-based tRPC client for calling the CMS API.\n * Used in Server Components to fetch routes and blocks from the CMS.\n */\n\nimport type { AppRouter } from '@repo/cms-schema/trpc';\nimport { type CreateTRPCClient, createTRPCClient, httpBatchLink } from '@trpc/client';\nimport superjson from 'superjson';\n\n/** Type alias for the CMS API client */\ntype CmsClient = CreateTRPCClient<AppRouter>;\n\n/**\n * Get the CMS API URL from the provided base URL.\n */\nfunction getCmsApiUrl(cmsUrl: string): string {\n return `${cmsUrl}/api/trpc`;\n}\n\n/** Options for creating a CMS client */\nexport interface CmsClientOptions {\n /** CMS API base URL (e.g., 'http://localhost:3000') */\n cmsUrl: string;\n /** API key for authentication (passed as query parameter) */\n apiKey?: string;\n}\n\n/**\n * Create a custom fetch function that appends API key as query parameter.\n */\nfunction createFetchWithApiKey(apiKey?: string) {\n return async (url: URL | RequestInfo, options?: RequestInit): Promise<Response> => {\n let finalUrl = url;\n\n // Append api_key to URL if provided\n if (apiKey) {\n const urlObj = new URL(url.toString());\n urlObj.searchParams.set('api_key', apiKey);\n finalUrl = urlObj.toString();\n }\n\n const response = await fetch(finalUrl, options);\n\n return response;\n };\n}\n\n/**\n * Create a tRPC client for the CMS API.\n */\nfunction createCmsClient(options: CmsClientOptions): CmsClient {\n const url = getCmsApiUrl(options.cmsUrl);\n console.log('[CMS API] Creating client with URL:', url);\n\n return createTRPCClient<AppRouter>({\n links: [\n httpBatchLink({\n url,\n transformer: superjson,\n fetch: createFetchWithApiKey(options.apiKey),\n }),\n ],\n });\n}\n\n/**\n * Get a CMS client for the specified CMS URL.\n */\nexport function getCmsClient(options: CmsClientOptions): CmsClient {\n return createCmsClient(options);\n}\n"],"mappings":";AAQA,SAAgC,kBAAkB,qBAAqB;AACvE,OAAO,eAAe;AAQtB,SAAS,aAAa,QAAwB;AAC5C,SAAO,GAAG,MAAM;AAClB;AAaA,SAAS,sBAAsB,QAAiB;AAC9C,SAAO,OAAO,KAAwB,YAA6C;AACjF,QAAI,WAAW;AAGf,QAAI,QAAQ;AACV,YAAM,SAAS,IAAI,IAAI,IAAI,SAAS,CAAC;AACrC,aAAO,aAAa,IAAI,WAAW,MAAM;AACzC,iBAAW,OAAO,SAAS;AAAA,IAC7B;AAEA,UAAM,WAAW,MAAM,MAAM,UAAU,OAAO;AAE9C,WAAO;AAAA,EACT;AACF;AAKA,SAAS,gBAAgB,SAAsC;AAC7D,QAAM,MAAM,aAAa,QAAQ,MAAM;AACvC,UAAQ,IAAI,uCAAuC,GAAG;AAEtD,SAAO,iBAA4B;AAAA,IACjC,OAAO;AAAA,MACL,cAAc;AAAA,QACZ;AAAA,QACA,aAAa;AAAA,QACb,OAAO,sBAAsB,QAAQ,MAAM;AAAA,MAC7C,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;AAKO,SAAS,aAAa,SAAsC;AACjE,SAAO,gBAAgB,OAAO;AAChC;","names":[]}
1
+ {"version":3,"sources":["../../lib/cms-api.ts"],"sourcesContent":["/**\n * CMS API Client\n *\n * Creates an HTTP-based tRPC client for calling the CMS API.\n * Used in Server Components to fetch routes and blocks from the CMS.\n */\n\nimport type { AppRouter } from '@repo/cms-schema/trpc';\nimport { type CreateTRPCClient, createTRPCClient, httpBatchLink } from '@trpc/client';\nimport superjson from 'superjson';\n\n/** Type alias for the CMS API client */\ntype CmsClient = CreateTRPCClient<AppRouter>;\n\n/**\n * Get the CMS API URL from the provided base URL.\n */\nfunction getCmsApiUrl(cmsUrl: string): string {\n return new URL('/api/trpc', cmsUrl).toString();\n}\n\n/** Unified configuration for all CMS API access */\nexport interface CmsConfig {\n /** CMS API base URL (e.g., 'http://localhost:3000') */\n cmsUrl: string;\n /** API key for authentication */\n apiKey?: string;\n /** Website ID to scope API requests */\n websiteId?: string;\n}\n\n/**\n * Create a custom fetch function that appends API key as query parameter.\n */\nfunction createFetchWithApiKey(apiKey?: string, websiteId?: string) {\n return async (url: URL | RequestInfo, options?: RequestInit): Promise<Response> => {\n let finalUrl = url;\n\n const urlObj = new URL(url.toString());\n if (apiKey) {\n urlObj.searchParams.set('api_key', apiKey);\n }\n if (websiteId) {\n urlObj.searchParams.set('website_id', websiteId);\n }\n if (apiKey || websiteId) {\n finalUrl = urlObj.toString();\n }\n\n\n\n const response = await fetch(finalUrl, options);\n\n return response;\n };\n}\n\n/**\n * Create a tRPC client for the CMS API.\n */\nfunction createCmsClient(options: CmsConfig): CmsClient {\n const url = getCmsApiUrl(options.cmsUrl);\n\n return createTRPCClient<AppRouter>({\n links: [\n httpBatchLink({\n url,\n transformer: superjson,\n fetch: createFetchWithApiKey(options.apiKey, options.websiteId),\n }),\n ],\n });\n}\n\n/**\n * Get a CMS client for the specified CMS URL.\n */\nexport function getCmsClient(options: CmsConfig): CmsClient {\n return createCmsClient(options);\n}\n"],"mappings":";AAQA,SAAgC,kBAAkB,qBAAqB;AACvE,OAAO,eAAe;AAQtB,SAAS,aAAa,QAAwB;AAC5C,SAAO,IAAI,IAAI,aAAa,MAAM,EAAE,SAAS;AAC/C;AAeA,SAAS,sBAAsB,QAAiB,WAAoB;AAClE,SAAO,OAAO,KAAwB,YAA6C;AACjF,QAAI,WAAW;AAEf,UAAM,SAAS,IAAI,IAAI,IAAI,SAAS,CAAC;AACrC,QAAI,QAAQ;AACV,aAAO,aAAa,IAAI,WAAW,MAAM;AAAA,IAC3C;AACA,QAAI,WAAW;AACb,aAAO,aAAa,IAAI,cAAc,SAAS;AAAA,IACjD;AACA,QAAI,UAAU,WAAW;AACvB,iBAAW,OAAO,SAAS;AAAA,IAC7B;AAIA,UAAM,WAAW,MAAM,MAAM,UAAU,OAAO;AAE9C,WAAO;AAAA,EACT;AACF;AAKA,SAAS,gBAAgB,SAA+B;AACtD,QAAM,MAAM,aAAa,QAAQ,MAAM;AAEvC,SAAO,iBAA4B;AAAA,IACjC,OAAO;AAAA,MACL,cAAc;AAAA,QACZ;AAAA,QACA,aAAa;AAAA,QACb,OAAO,sBAAsB,QAAQ,QAAQ,QAAQ,SAAS;AAAA,MAChE,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;AAKO,SAAS,aAAa,SAA+B;AAC1D,SAAO,gBAAgB,OAAO;AAChC;","names":[]}
@@ -0,0 +1,94 @@
1
+ import { FieldDefinition } from '@repo/cms-schema/documents';
2
+ import { ZodObject, ZodRawShape } from 'zod';
3
+ import { CmsConfig } from './cms-api.js';
4
+ import '@repo/cms-schema/trpc';
5
+ import '@trpc/client';
6
+
7
+ /**
8
+ * Custom Schema Fetcher
9
+ *
10
+ * Fetches custom schema definitions (field metadata as JSON) from the CMS API
11
+ * for a given website. Uses the tRPC client to call the customSchema router.
12
+ */
13
+
14
+ interface CustomSchemaFields {
15
+ name: string;
16
+ displayName: string;
17
+ description: string | null;
18
+ fields: FieldDefinition[];
19
+ routeSlugField: string | null;
20
+ version: number;
21
+ }
22
+ type FetchCustomSchemasOptions = CmsConfig & {
23
+ websiteId: string;
24
+ };
25
+ /**
26
+ * Fetches all custom schemas with their field definitions for a website.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * const schemas = await fetchAllCustomSchemaFields({
31
+ * cmsUrl: 'http://localhost:3000',
32
+ * apiKey: 'my-api-key',
33
+ * websiteId: 'uuid-here',
34
+ * });
35
+ *
36
+ * for (const schema of schemas) {
37
+ * console.log(schema.name, schema.fields);
38
+ * }
39
+ * ```
40
+ */
41
+ declare function fetchAllCustomSchemaFields(options: FetchCustomSchemasOptions): Promise<CustomSchemaFields[]>;
42
+ /**
43
+ * Fetches a single custom schema's field definitions by name.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * const schema = await fetchCustomSchemaFields({
48
+ * cmsUrl: 'http://localhost:3000',
49
+ * apiKey: 'my-api-key',
50
+ * websiteId: 'uuid-here',
51
+ * }, 'blog_post');
52
+ *
53
+ * console.log(schema.fields);
54
+ * ```
55
+ */
56
+ declare function fetchCustomSchemaFields(options: FetchCustomSchemasOptions, schemaName: string): Promise<CustomSchemaFields>;
57
+ /**
58
+ * Converts an array of custom schema definitions into a record of Zod schemas,
59
+ * keyed by schema name.
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * const schemas = await fetchAllCustomSchemaFields(options);
64
+ * const zodSchemas = buildZodSchemas(schemas);
65
+ *
66
+ * // Validate a blog post document
67
+ * const result = zodSchemas['blog_post'].safeParse(data);
68
+ * ```
69
+ */
70
+ declare function buildZodSchemas(schemas: CustomSchemaFields[]): Record<string, ZodObject<ZodRawShape>>;
71
+ /**
72
+ * Converts an array of custom schema definitions into a record of Zod source
73
+ * code strings, keyed by schema name.
74
+ *
75
+ * @example
76
+ * ```ts
77
+ * const schemas = await fetchAllCustomSchemaFields(options);
78
+ * const codeMap = buildZodSchemaCode(schemas);
79
+ *
80
+ * // Write blog_post schema to a file
81
+ * fs.writeFileSync('blog-post.ts', codeMap['blog_post']);
82
+ * ```
83
+ */
84
+ declare function buildZodSchemaCode(schemas: CustomSchemaFields[]): Record<string, string>;
85
+ /**
86
+ * Generates combined Zod schema code from all custom schemas and writes it
87
+ * to the specified file path.
88
+ *
89
+ * @param schemas - Array of custom schema definitions
90
+ * @param filePath - Absolute or relative path to write the generated file
91
+ */
92
+ declare function saveZodSchemaCode(schemas: CustomSchemaFields[], filePath: string): Promise<void>;
93
+
94
+ export { type CustomSchemaFields, type FetchCustomSchemasOptions, buildZodSchemaCode, buildZodSchemas, fetchAllCustomSchemaFields, fetchCustomSchemaFields, saveZodSchemaCode };