:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(notebooks): prepare markdown notebook rollout (#66675)
Marius Andrab4c4bc883c34
diff --git a/frontend/src/models/notebooksModel.test.ts b/frontend/src/models/notebooksModel.test.tsnew file mode 100644index 000000000000..17521f1607f6--- /dev/null+++ b/frontend/src/models/notebooksModel.test.ts@@ -0,0 +1,100 @@+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { buildMarkdownNotebookContent, getMarkdownNotebookMarkdown } from 'scenes/notebooks/Notebook/markdownNotebookV2'+import { NotebookNodeType, NotebookTarget, NotebookType } from 'scenes/notebooks/types'++import { NodeKind } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import { AccessControlLevel } from '~/types'++import { notebooksModel } from './notebooksModel'++jest.mock('lib/utils/product-intents', () => ({+ addProductIntent: jest.fn().mockResolvedValue(null),+}))++describe('notebooksModel', () => {+ let logic: ReturnType<typeof notebooksModel.build>++ beforeEach(() => {+ initKeaTests()+ logic = notebooksModel()+ logic.mount()+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ it('creates rich notebooks when markdown notebooks are not enabled', async () => {+ const createNotebookSpy = mockCreateNotebook()++ await expectLogic(logic, () => {+ logic.actions.createNotebook(NotebookTarget.Scene, 'Activation')+ }).toDispatchActions(['createNotebookSuccess'])++ expect(createNotebookSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ title: 'Activation',+ content: {+ type: 'doc',+ content: [+ {+ type: 'heading',+ attrs: { level: 1 },+ content: [{ type: 'text', text: 'Activation' }],+ },+ ],+ },+ })+ )+ })++ it('creates markdown notebooks when markdown notebooks are enabled', async () => {+ const createNotebookSpy = mockCreateNotebook()+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.MARKDOWN_NOTEBOOKS], {+ [FEATURE_FLAGS.MARKDOWN_NOTEBOOKS]: true,+ })++ await expectLogic(logic, () => {+ logic.actions.createNotebook(NotebookTarget.Scene, 'Activation', [+ {+ type: NotebookNodeType.Query,+ attrs: {+ title: 'Signup',+ query: { kind: NodeKind.HogQLQuery, query: 'select 1' },+ },+ },+ ])+ }).toDispatchActions(['createNotebookSuccess'])++ const content = createNotebookSpy.mock.calls[0][0]?.content+ expect(content).toEqual(buildMarkdownNotebookContent(getMarkdownNotebookMarkdown(content)))+ expect(getMarkdownNotebookMarkdown(content)).toContain('# Activation')+ expect(getMarkdownNotebookMarkdown(content)).toContain('<Query')+ expect(getMarkdownNotebookMarkdown(content)).toContain('"kind":"HogQLQuery"')+ })+})++function mockCreateNotebook(): jest.SpyInstance<+ ReturnType<typeof api.notebooks.create>,+ Parameters<typeof api.notebooks.create>+> {+ return jest.spyOn(api.notebooks, 'create').mockImplementation(async (data) => {+ const notebook: NotebookType = {+ id: 'created-notebook',+ short_id: 'created-notebook',+ created_at: '2026-06-29T00:00:00Z',+ created_by: null,+ version: 1,+ content: data?.content ?? null,+ title: data?.title,+ user_access_level: AccessControlLevel.Editor,+ }++ return notebook+ })+}diff --git a/frontend/src/models/notebooksModel.ts b/frontend/src/models/notebooksModel.tsindex 5836296d4475..a1aaa411923e 100644--- a/frontend/src/models/notebooksModel.ts+++ b/frontend/src/models/notebooksModel.ts@@ -5,6 +5,8 @@ import posthog from 'posthog-js'import api from 'lib/api'import { EditorFocusPosition, JSONContent } from 'lib/components/RichContentEditor/types'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { addProductIntent } from 'lib/utils/product-intents'import { notebookLogic } from 'scenes/notebooks/Notebook/notebookLogic'@@ -100,7 +102,7 @@ export const notebooksModel = kea<notebooksModelType>([createNotebookFromDashboard: (dashboard: DashboardType<QueryBasedInsightModel>) => ({ dashboard }),}),connect(() => ({- values: [projectLogic, ['currentProjectId']],+ values: [projectLogic, ['currentProjectId'], featureFlagLogic, ['featureFlags']],})),reducers({@@ -112,9 +114,10 @@ export const notebooksModel = kea<notebooksModelType>([[] as NotebookListItemType[],{createNotebook: async ({ title, location, content, onCreate, shortId }) => {+ const useMarkdownNotebook = !!values.featureFlags[FEATURE_FLAGS.MARKDOWN_NOTEBOOKS]const notebook = await api.notebooks.create({title,- content: defaultNotebookContent(title, content),+ content: defaultNotebookContent(title, content, { markdown: useMarkdownNotebook }),_create_in_folder: getLastNewFolder(),...(shortId ? { short_id: shortId } : {}),})diff --git a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx b/frontend/src/scenes/notebooks/Notebook/Notebook.tsxindex 328ae24baaba..676a24de14f2 100644--- a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx+++ b/frontend/src/scenes/notebooks/Notebook/Notebook.tsx@@ -181,7 +181,7 @@ export function Notebook({) : null}<div className="Notebook_content">- {isMarkdownNotebook ? null : <NotebookColumnLeft />}+ <NotebookColumnLeft /><ErrorBoundary>{isMarkdownNotebook ? (<MarkdownNotebookV2diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookColumnLeft.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookColumnLeft.tsxindex f9053809700c..49df17443e42 100644--- a/frontend/src/scenes/notebooks/Notebook/NotebookColumnLeft.tsx+++ b/frontend/src/scenes/notebooks/Notebook/NotebookColumnLeft.tsx@@ -22,14 +22,12 @@ export const NotebookColumnLeft = (): JSX.Element | null => {useValues(notebookLogic)const isMarkdownNotebook = isMarkdownNotebookContent(content)- if (isMarkdownNotebook) {- return null- }-const shouldShowTableOfContents = showTableOfContents && !isMarkdownNotebook+ const shouldShowNodeSettings = editingNodeLogicsForLeft.length > 0 && !isMarkdownNotebook+ const shouldShowKernelInfo = showKernelInfo && !isMarkdownNotebookconst isShowingEffectiveLeftColumn =isShowingLeftColumn &&- (editingNodeLogicsForLeft.length > 0 || showHistory || shouldShowTableOfContents || showKernelInfo)+ (shouldShowNodeSettings || showHistory || shouldShowTableOfContents || shouldShowKernelInfo)return (<div@@ -40,15 +38,17 @@ export const NotebookColumnLeft = (): JSX.Element | null => {<div className="NotebookColumn__content">{isShowingEffectiveLeftColumn ? (<>- {editingNodeLogicsForLeft.map((logic) => (- <div key={logic.values.nodeId}>- <NotebookNodeSettingsOffset logic={logic} />- <NotebookNodeSettingsWidget logic={logic} />- </div>- ))}+ {shouldShowNodeSettings+ ? editingNodeLogicsForLeft.map((logic) => (+ <div key={logic.values.nodeId}>+ <NotebookNodeSettingsOffset logic={logic} />+ <NotebookNodeSettingsWidget logic={logic} />+ </div>+ ))+ : null}{showHistory ? <NotebookHistory /> : null}{shouldShowTableOfContents ? <NotebookTableOfContents /> : null}- {showKernelInfo ? <NotebookKernelInfo /> : null}+ {shouldShowKernelInfo ? <NotebookKernelInfo /> : null}</>) : null}</div>diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.tsindex 0192f527a537..7a8a2a46b146 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts@@ -248,7 +248,7 @@ Thinking...`)expect(logic.values.notebook?.content).toEqual(latestNotebook.content)})- it('does not surface legacy left-column state for markdown notebooks', () => {+ it('only surfaces the left column for markdown notebooks when history is open', () => {logic.unmount()logic = notebookLogic({ shortId: SHORT_ID, mode: 'notebook' })logic.mount()@@ -275,5 +275,9 @@ Thinking...`)expect(logic.values.editingNodeLogics).toEqual([nodeLogic])expect(logic.values.editingNodeLogicsForLeft).toEqual([])expect(logic.values.isShowingLeftColumn).toBe(false)++ logic.actions.setShowHistory(true)++ expect(logic.values.isShowingLeftColumn).toBe(true)})})diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.tsindex 2650aeedcfb6..0220e1fcdd72 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts@@ -105,6 +105,90 @@ A **bold** paragraph.`)})+ it('converts raw legacy content arrays without dropping top-level text nodes', () => {+ const content: JSONContent[] = [+ {+ type: 'heading',+ attrs: { level: 1 },+ content: [{ type: 'text', text: 'Array notebook' }],+ },+ { type: 'text', text: 'Loose top-level text', marks: [{ type: 'italic' }] },+ { type: 'paragraph', content: [{ type: 'text', text: 'Wrapped paragraph' }] },+ ]++ expect(convertNotebookContentToMarkdown(content)).toEqual(`# Array notebook++*Loose top-level text*++Wrapped paragraph`)+ })++ it('converts string content without dropping data', () => {+ const legacyDocString = JSON.stringify({+ type: 'doc',+ content: [+ {+ type: 'heading',+ attrs: { level: 1 },+ content: [{ type: 'text', text: 'JSON string notebook' }],+ },+ ],+ })++ expect(convertNotebookContentToMarkdown(legacyDocString)).toEqual('# JSON string notebook')+ expect(convertNotebookContentToMarkdown('# Already Markdown\n\nPlain body')).toEqual(+ '# Already Markdown\n\nPlain body'+ )+ expect(convertNotebookContentToMarkdown('Plain text body')).toEqual('Plain text body')+ })++ it('converts legacy ph-insight nodes to saved insight query tags', () => {+ const content: JSONContent = {+ type: 'doc',+ content: [+ { type: 'ph-insight', attrs: { id: 'abc123' } },+ { type: 'ph-insight', attrs: { id: 123, short_id: 'def456' } },+ ],+ }++ expect(convertNotebookContentToMarkdown(content))+ .toEqual(`<Query query={{"kind":"SavedInsightNode","shortId":"abc123"}} />++<Query query={{"kind":"SavedInsightNode","shortId":"def456"}} />`)+ })++ it('converts remaining legacy production node shapes without unknown nodes', () => {+ const content: JSONContent = {+ type: 'doc',+ content: [+ { type: 'ph-text', attrs: { body: '# Markdown body' } },+ { type: 'ph-dashboard', attrs: { id: 123 } },+ {+ type: 'query',+ attrs: {+ query: {+ kind: 'HogQLQuery',+ query: 'select event from events limit 1',+ },+ },+ },+ ],+ }++ expect(convertNotebookContentToMarkdown(content)).toEqual(`# Markdown body++Dashboard 123++<Query query={{"kind":"DataVisualizationNode","source":{"kind":"HogQLQuery","query":"select event from events limit 1"}}} />`)+ })++ it('keeps the stable id vector for markdown query blocks without nodeId props', () => {+ const markdown =+ '<Query query={{"kind":"DataTableNode","source":{"kind":"EventsQuery","select":["event"],"after":"-24h","limit":1}}} />'++ expect(parseMarkdownNotebook(markdown).nodes[0]?.id).toEqual('mdn-197jp5a-0')+ })+it('keeps a query attr whose object carries nested undefined optional fields', () => {const content: JSONContent = {type: 'doc',diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.tsindex b698ace7067e..b322507366d7 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts@@ -31,6 +31,8 @@ export type MarkdownNotebookV2Node = {}}+export type NotebookContentForMarkdownConversion = JSONContent | JSONContent[] | string | null | undefined+const MARKDOWN_NOTEBOOK_NODE_ID = 'markdown-notebook-v2'export const NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG: Partial<Record<NotebookNodeType, string>> = {@@ -67,15 +69,15 @@ export const NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG: Partial<Record<NotebookNodeType[NotebookNodeType.SupportTickets]: 'SupportTickets',}-export function isMarkdownNotebookContent(content: JSONContent | null | undefined): boolean {+export function isMarkdownNotebookContent(content: NotebookContentForMarkdownConversion): boolean {return !!getMarkdownNotebookNode(content)}-export function getMarkdownNotebookMarkdown(content: JSONContent | null | undefined): string {+export function getMarkdownNotebookMarkdown(content: NotebookContentForMarkdownConversion): string {return getMarkdownNotebookNode(content)?.attrs?.markdown ?? ''}-export function getMarkdownNotebookNodeId(content: JSONContent | null | undefined): string {+export function getMarkdownNotebookNodeId(content: NotebookContentForMarkdownConversion): string {return getMarkdownNotebookNode(content)?.attrs?.nodeId ?? MARKDOWN_NOTEBOOK_NODE_ID}@@ -169,16 +171,22 @@ export type NotebookMarkdownConversionOptions = {}export function convertNotebookContentToMarkdown(- content: JSONContent | null | undefined,+ content: NotebookContentForMarkdownConversion,options: NotebookMarkdownConversionOptions = {}): string {- if (isMarkdownNotebookContent(content)) {- return getMarkdownNotebookMarkdown(content)+ const normalizedContent = normalizeNotebookContentForMarkdownConversion(content)++ if (typeof normalizedContent === 'string') {+ return normalizedContent+ }++ if (isMarkdownNotebookContent(normalizedContent)) {+ return getMarkdownNotebookMarkdown(normalizedContent)}const blocks: string[] = []const emittedCommentMarkIds = new Set<string>()- for (const node of content?.content ?? []) {+ for (const node of normalizedContent?.content ?? []) {// Each comment-marked range gets its thread right above the block holding the// highlight, so the margin-anchored thread aligns with the text it is about.for (const markId of collectCommentMarkIds(node)) {@@ -205,6 +213,48 @@ export function convertNotebookContentToMarkdown(return blocks.join('\n\n')}+function normalizeNotebookContentForMarkdownConversion(+ content: NotebookContentForMarkdownConversion+): JSONContent | string | null | undefined {+ if (typeof content === 'string') {+ const parsedContent = parseJsonEncodedNotebookContent(content)+ return parsedContent ?? content+ }++ if (Array.isArray(content)) {+ return { type: 'doc', content }+ }++ return content+}++function parseJsonEncodedNotebookContent(content: string): JSONContent | string | null {+ const trimmedContent = content.trim()+ if (+ !trimmedContent ||+ (!trimmedContent.startsWith('{') && !trimmedContent.startsWith('[') && !trimmedContent.startsWith('"'))+ ) {+ return null+ }++ try {+ const parsedContent = JSON.parse(trimmedContent) as unknown+ if (typeof parsedContent === 'string') {+ return parseJsonEncodedNotebookContent(parsedContent) ?? parsedContent+ }+ if (Array.isArray(parsedContent)) {+ return { type: 'doc', content: parsedContent as JSONContent[] }+ }+ if (parsedContent && typeof parsedContent === 'object') {+ return parsedContent as JSONContent+ }+ } catch {+ return null+ }++ return null+}+function collectCommentMarkIds(node: JSONContent): string[] {const markIds: string[] = []const visit = (current: JSONContent): void => {@@ -246,7 +296,10 @@ export function getMarkdownNotebookTitle(content: JSONContent | null | undefinedreturn getInlineText(firstHeading.children).trim() || null}-function getMarkdownNotebookNode(content: JSONContent | null | undefined): MarkdownNotebookV2Node | null {+function getMarkdownNotebookNode(content: NotebookContentForMarkdownConversion): MarkdownNotebookV2Node | null {+ if (!content || typeof content !== 'object' || Array.isArray(content)) {+ return null+ }const nodes = content?.content ?? []if (nodes.length !== 1 || nodes[0]?.type !== NotebookNodeType.MarkdownNotebook) {return null@@ -347,6 +400,10 @@ function serializeRichContentNode(listDepth = 0,options: NotebookMarkdownConversionOptions = {}): string {+ if (node.type === 'text') {+ return escapeMarkdownBlockLines(serializeInlineNode(node, options))+ }+if (node.type === 'heading') {const level = typeof node.attrs?.level === 'number' ? Math.min(Math.max(node.attrs.level, 1), 6) : 1return `${'#'.repeat(level)} ${serializeInlineContent(node.content, options)}`@@ -387,6 +444,22 @@ function serializeRichContentNode(return serializeTable(node, options)}+ if (node.type === 'ph-text') {+ return serializeLegacyTextNode(node)+ }++ if (node.type === 'ph-insight') {+ return serializeLegacyInsightNode(node)+ }++ if (node.type === 'ph-dashboard') {+ return serializeLegacyDashboardNode(node)+ }++ if (node.type === 'query') {+ return serializeLegacyQueryNode(node)+ }+const markdownTagName = NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG[node.type as NotebookNodeType]if (markdownTagName) {return serializeNode({@@ -405,13 +478,72 @@ function serializeRichContentNode(return childMarkdown}+ return serializeUnknownRichContentNode(node)+}++function serializeLegacyTextNode(node: JSONContent): string {+ const body = node.attrs?.body+ return typeof body === 'string' ? body : serializeUnknownRichContentNode(node)+}++function serializeLegacyInsightNode(node: JSONContent): string {+ const insightShortId = typeof node.attrs?.short_id === 'string' ? node.attrs.short_id : node.attrs?.id+ if (typeof insightShortId !== 'string' || !insightShortId) {+ return serializeUnknownRichContentNode(node)+ }++ return serializeNode({+ id: '',+ type: 'component',+ tagName: 'Query',+ props: {+ query: { kind: NodeKind.SavedInsightNode, shortId: insightShortId },+ },+ })+}++function serializeLegacyDashboardNode(node: JSONContent): string {+ const dashboardId = node.attrs?.id+ if (typeof dashboardId !== 'string' && typeof dashboardId !== 'number') {+ return serializeUnknownRichContentNode(node)+ }++ return escapeMarkdownBlockLines(escapeInlineMarkdownText(`Dashboard ${String(dashboardId)}`))+}++function serializeLegacyQueryNode(node: JSONContent): string {+ const props = getSerializableAttrs(node.attrs)+ const query = props.query+ if (isNotebookObjectProp(query) && query.kind === NodeKind.HogQLQuery) {+ props.query = { kind: NodeKind.DataVisualizationNode, source: query }+ }++ return serializeNode({+ id: '',+ type: 'component',+ tagName: 'Query',+ props,+ })+}++function isNotebookObjectProp(value: NotebookPropValue | undefined): value is Record<string, NotebookPropValue> {+ return !!value && typeof value === 'object' && !Array.isArray(value)+}++function serializeUnknownRichContentNode(node: JSONContent): string {// An unmapped leaf node must not vanish on upgrade — preserve it as a component the// editor renders with its unknown-tag fallback+ const attrs = getSerializableAttrs(node.attrs)+ const props: NotebookComponentProps = node.type ? { nodeType: node.type, ...attrs } : attrs+ if (node.type) {+ props.nodeType = node.type+ }+return serializeNode({id: '',type: 'component',tagName: 'UnknownNode',- props: { nodeType: node.type, ...getSerializableAttrs(node.attrs) },+ props,})}diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.tsindex a5980b8cf7bc..2e1d894057a6 100644--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts@@ -1168,13 +1168,13 @@ export const notebookLogic = kea<notebookLogicType>([containerSize: 'small' | 'medium',content: JSONContent) => {- if (isMarkdownNotebookContent(content)) {- return false- }-- const shouldShowSettings = editingNodeLogicsForLeft.length > 0 && containerSize !== 'small'+ const isMarkdownNotebook = isMarkdownNotebookContent(content)+ const shouldShowSettings =+ !isMarkdownNotebook && editingNodeLogicsForLeft.length > 0 && containerSize !== 'small'+ const shouldShowTableOfContents = !isMarkdownNotebook && showTableOfContents+ const shouldShowKernelInfo = !isMarkdownNotebook && showKernelInfo- return showHistory || showTableOfContents || showKernelInfo || shouldShowSettings+ return showHistory || shouldShowTableOfContents || shouldShowKernelInfo || shouldShowSettings},],diff --git a/frontend/src/scenes/notebooks/utils.ts b/frontend/src/scenes/notebooks/utils.tsindex c765af8e2b7c..abe2b5019d8f 100644--- a/frontend/src/scenes/notebooks/utils.ts+++ b/frontend/src/scenes/notebooks/utils.ts@@ -3,6 +3,7 @@ import { TextSerializer, getText } from '@tiptap/core'import { JSONContent, RichContentNode, TTEditor } from 'lib/components/RichContentEditor/types'+import { buildMarkdownNotebookContent, convertNotebookContentToMarkdown } from './Notebook/markdownNotebookV2'import { CreatePostHogWidgetNodeOptions, NotebookNodeType } from './types'export const KNOWN_NODES: Record<string, CreatePostHogWidgetNodeOptions<any>> = {}@@ -80,7 +81,15 @@ export const textContent = (node: RichContentNode): string => {})}-export function defaultNotebookContent(title?: string, content?: JSONContent[]): JSONContent {+type DefaultNotebookContentOptions = {+ markdown?: boolean+}++export function defaultNotebookContent(+ title?: string,+ content?: JSONContent[],+ options: DefaultNotebookContentOptions = {}+): JSONContent {const initialContent = [{type: 'heading',@@ -93,7 +102,13 @@ export function defaultNotebookContent(title?: string, content?: JSONContent[]):initialContent.push(...content)}- return { type: 'doc', content: initialContent }+ const richContent: JSONContent = { type: 'doc', content: initialContent }++ if (options.markdown) {+ return buildMarkdownNotebookContent(convertNotebookContentToMarkdown(richContent))+ }++ return richContent}export function updateContentHeading(content: JSONContent, newTitle: string): JSONContent {diff --git a/products/notebooks/backend/test/test_sharing.py b/products/notebooks/backend/test/test_sharing.pyindex f469d9a6aad4..5647519f8eb4 100644--- a/products/notebooks/backend/test/test_sharing.py+++ b/products/notebooks/backend/test/test_sharing.py@@ -1,6 +1,8 @@+import jsonfrom typing import Anyfrom posthog.test.base import APIBaseTest+from unittest import TestCasefrom parameterized import parameterizedfrom rest_framework import status@@ -38,7 +40,19 @@ def _doc(*nodes: dict[str, Any]) -> dict[str, Any]:return {"type": "doc", "content": list(nodes)}-class TestExtractReferencedInsightShortIds(APIBaseTest):+def _markdown_doc(markdown: str) -> dict[str, Any]:+ return {+ "type": "doc",+ "content": [+ {+ "type": "ph-markdown-notebook",+ "attrs": {"nodeId": "markdown-notebook-v2", "markdown": markdown},+ }+ ],+ }+++class TestExtractReferencedInsightShortIds(TestCase):@parameterized.expand([("none", None, set()),@@ -110,6 +124,26 @@ class TestExtractReferencedInsightShortIds(APIBaseTest):),set(),),+ (+ "markdown_saved_insight",+ _markdown_doc('<Query hideFilters query={{"kind":"SavedInsightNode","shortId":"abc123"}} />'),+ {"abc123"},+ ),+ (+ "markdown_saved_insight_with_string_query",+ _markdown_doc('<Query query="{\\"kind\\":\\"SavedInsightNode\\",\\"shortId\\":\\"abc123\\"}" />'),+ {"abc123"},+ ),+ (+ "markdown_saved_insight_with_even_backslashes_before_quote",+ _markdown_doc(r'<Query query={{"kind":"SavedInsightNode","shortId":"abc123","path":"C:\\\\"}} />'),+ {"abc123"},+ ),+ (+ "markdown_query_inside_code_block_ignored",+ _markdown_doc('```md\n<Query query={{"kind":"SavedInsightNode","shortId":"abc123"}} />\n```'),+ set(),+ ),])def test_extract(self, _name: str, content: Any, expected: set[str]) -> None:@@ -120,10 +154,6 @@ class TestExtractReferencedInsightShortIds(APIBaseTest):self.assertEqual(list(iter_prosemirror_nodes(doc)), [doc])def test_extract_handles_stringified_query_attr(self) -> None:- """Tiptap's jsonAttr wrapper can serialize complex attrs as JSON strings; the extractor- accepts either form so legacy / serialized notebooks still surface their saved insight."""- import json-doc = _doc({"type": "ph-query",@@ -133,7 +163,7 @@ class TestExtractReferencedInsightShortIds(APIBaseTest):self.assertEqual(extract_referenced_insight_short_ids(doc), {"abc123"})-class TestExtractInlineQueryNodes(APIBaseTest):+class TestExtractInlineQueryNodes(TestCase):@parameterized.expand([("none", None, []),@@ -186,14 +216,49 @@ class TestExtractInlineQueryNodes(APIBaseTest):),[("deep-node", {"kind": "DataTableNode", "source": {"kind": "EventsQuery", "select": ["*"]}})],),+ (+ "markdown_inline_query_with_explicit_node_id",+ _markdown_doc(+ '<Query nodeId="inline-node-1" query={{"kind":"DataTableNode","source":{"kind":"EventsQuery","select":["event"]}}} />'+ ),+ [("inline-node-1", {"kind": "DataTableNode", "source": {"kind": "EventsQuery", "select": ["event"]}})],+ ),+ (+ "markdown_inline_query_with_derived_node_id",+ _markdown_doc(+ '<Query query={{"kind":"DataTableNode","source":{"kind":"EventsQuery","select":["event"],"after":"-24h","limit":1}}} />'+ ),+ [+ (+ "mdn-197jp5a-0",+ {+ "kind": "DataTableNode",+ "source": {"kind": "EventsQuery", "select": ["event"], "after": "-24h", "limit": 1},+ },+ )+ ],+ ),+ (+ "markdown_inline_query_with_even_backslashes_before_quote",+ _markdown_doc(+ r'<Query nodeId="inline-node-1" query={{"kind":"DataTableNode","source":{"kind":"EventsQuery","select":["event"],"path":"C:\\\\"}}} />'+ ),+ [+ (+ "inline-node-1",+ {+ "kind": "DataTableNode",+ "source": {"kind": "EventsQuery", "select": ["event"], "path": "C:\\\\"},+ },+ )+ ],+ ),])- def test_extract(self, _name: str, content: Any, expected: list[tuple[str, dict]]) -> None:+ def test_extract(self, _name: str, content: Any, expected: list[tuple[str, dict[str, Any]]]) -> None:self.assertEqual(extract_inline_query_nodes(content), expected)def test_extract_handles_stringified_query_attr(self) -> None:- import json-doc = _doc({"type": "ph-query",@@ -209,7 +274,7 @@ class TestExtractInlineQueryNodes(APIBaseTest):)-class TestFilterNotebookContentForSharing(APIBaseTest):+class TestFilterNotebookContentForSharing(TestCase):@parameterized.expand([("none", None, None),@@ -289,6 +354,29 @@ class TestFilterNotebookContentForSharing(APIBaseTest):}),),+ (+ "markdown_notebook_keeps_safe_components_and_strips_unsupported_props",+ _markdown_doc(+ "\n\n".join(+ [+ '<Query query={{"kind":"SavedInsightNode","shortId":"abc123"}} />',+ '<Embed src="https://posthog.com" />',+ '<Python code="SECRET = true" />',+ '<Chat messages={{["secret"]}} />',+ ]+ )+ ),+ _markdown_doc(+ "\n\n".join(+ [+ '<Query query={{"kind":"SavedInsightNode","shortId":"abc123"}} />',+ '<Embed src="https://posthog.com" />',+ "<Python />",+ "<Chat />",+ ]+ )+ ),+ ),])def test_filter(self, _name: str, content: Any, expected: Any) -> None:@@ -391,6 +479,112 @@ class TestNotebookSharingConfiguration(APIBaseTest):self.assertNotIn("01893f8c-some-recording", raw)self.assertIsNone(body["notebook"]["text_content"])+ def test_shared_notebook_strips_unsupported_markdown_component_props(self) -> None:+ markdown = "\n\n".join(+ [+ "hello",+ '<Query query={{"kind":"SavedInsightNode","shortId":"abc123"}} />',+ '<Python code="SECRET = true" />',+ '<Chat messages={{["SECRET_CHAT"]}} />',+ ]+ )+ self.notebook.content = _doc(+ {"type": "paragraph", "content": [{"type": "text", "text": "hi"}]},+ {+ "type": "blockquote",+ "content": [+ {+ "type": "ph-markdown-notebook",+ "attrs": {+ "nodeId": "markdown-notebook-v2",+ "markdown": markdown,+ "runtimeState": {"secret": "SECRET_RUNTIME"},+ },+ }+ ],+ },+ )+ self.notebook.text_content = "hi SECRET = true SECRET_CHAT SECRET_RUNTIME"+ self.notebook.save()+ self.client.patch(self._sharing_url(), {"enabled": True}, format="json")+ config = SharingConfiguration.objects.get(notebook=self.notebook, expires_at__isnull=True)++ self.client.logout()+ response = self.client.get(f"/shared/{config.access_token}.json")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ body = response.json()++ markdown_node = body["notebook"]["content"]["content"][1]["content"][0]+ self.assertEqual(+ markdown_node,+ {+ "type": "ph-markdown-notebook",+ "attrs": {+ "nodeId": "markdown-notebook-v2",+ "markdown": "\n\n".join(+ [+ "hello",+ '<Query query={{"kind":"SavedInsightNode","shortId":"abc123"}} />',+ "<Python />",+ "<Chat />",+ ]+ ),+ },+ },+ )++ raw = response.content.decode()+ self.assertNotIn("SECRET", raw)+ self.assertNotIn("SECRET_CHAT", raw)+ self.assertNotIn("SECRET_RUNTIME", raw)+ self.assertIsNone(body["notebook"]["text_content"])++ def test_shared_notebook_reserializes_allowlisted_markdown_component_props(self) -> None:+ markdown = "\n\n".join(+ [+ "hello",+ (+ '<Embed src="https://posthog.com" title="Public docs" height={320} '+ 'unsafe="<Python code="SECRET_EMBED" />" '+ 'cachedResults={{"rows":["SECRET_CACHE"]}} />'+ ),+ ]+ )+ self.notebook.content = _markdown_doc(markdown)+ self.notebook.text_content = "hello SECRET_EMBED SECRET_CACHE"+ self.notebook.save()+ self.client.patch(self._sharing_url(), {"enabled": True}, format="json")+ config = SharingConfiguration.objects.get(notebook=self.notebook, expires_at__isnull=True)++ self.client.logout()+ response = self.client.get(f"/shared/{config.access_token}.json")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ body = response.json()++ markdown_node = body["notebook"]["content"]["content"][0]+ self.assertEqual(+ markdown_node,+ {+ "type": "ph-markdown-notebook",+ "attrs": {+ "nodeId": "markdown-notebook-v2",+ "markdown": "\n\n".join(+ [+ "hello",+ '<Embed height={320} src="https://posthog.com" title="Public docs" />',+ ]+ ),+ },+ },+ )++ raw = response.content.decode()+ self.assertNotIn("SECRET_EMBED", raw)+ self.assertNotIn("SECRET_CACHE", raw)+ self.assertNotIn("unsafe", raw)+ self.assertNotIn("cachedResults", raw)+ self.assertIsNone(body["notebook"]["text_content"])+def test_deleted_notebook_404s_on_shared_endpoint(self) -> None:self.client.patch(self._sharing_url(), {"enabled": True}, format="json")config = SharingConfiguration.objects.get(notebook=self.notebook, expires_at__isnull=True)@@ -546,6 +740,39 @@ class TestNotebookSharingGrantsInsightAccess(APIBaseTest):# — if it's missing, dataNodeLogic would try to POST /query/ at render time.self.assertIn("result", body["insights"]["ref0001"])+ def test_shared_markdown_notebook_payload_inlines_referenced_insights(self) -> None:+ self.notebook.content = _markdown_doc(+ '<Query hideFilters query={{"kind":"SavedInsightNode","shortId":"ref0001"}} />'+ )+ self.notebook.save()++ self.client.logout()+ response = self.client.get(f"/shared/{self.config.access_token}.json")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ body = response.json()+ self.assertIn("insights", body)+ self.assertIn("ref0001", body["insights"])+ self.assertNotIn("unr0001", body["insights"])+ self.assertIn("result", body["insights"]["ref0001"])+ self.assertIn("ph-markdown-notebook", response.content.decode())++ def test_shared_markdown_notebook_payload_inlines_inline_query_results(self) -> None:+ self.notebook.content = _markdown_doc(+ '<Query query={{"kind":"DataTableNode","source":{"kind":"EventsQuery","select":["event"],"after":"-24h","limit":1}}} />'+ )+ self.notebook.save()++ self.client.logout()+ response = self.client.get(f"/shared/{self.config.access_token}.json")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ body = response.json()+ self.assertIn("inline_query_results", body)+ self.assertIn("mdn-197jp5a-0", body["inline_query_results"])+ inline_result = body["inline_query_results"]["mdn-197jp5a-0"]+ self.assertIsInstance(inline_result, dict)+ self.assertIn("results", inline_result)+ self.assertFalse(inline_result.get("error"))+def test_anonymous_request_with_share_token_cannot_load_unreferenced_insight(self) -> None:self.client.logout()response = self.client.get(diff --git a/products/notebooks/backend/util.py b/products/notebooks/backend/util.pyindex 18bc2a8b720c..83dc2571f8ad 100644--- a/products/notebooks/backend/util.py+++ b/products/notebooks/backend/util.py@@ -1,3 +1,5 @@+import re+import htmlimport jsonimport uuidfrom collections.abc import Iterator@@ -7,11 +9,15 @@ from typing import AnyTipTapNode = dict[str, Any]TipTapContent = list[TipTapNode]+# ProseMirror node type used by Markdown notebooks.+# Keep in sync with `NotebookNodeType.MarkdownNotebook` in frontend/src/scenes/notebooks/types.ts.+MARKDOWN_NOTEBOOK_NODE_TYPE = "ph-markdown-notebook"# ProseMirror node type used by NotebookNodeQuery on the frontend.# Keep in sync with `NotebookNodeType.Query` in frontend/src/scenes/notebooks/types.ts.QUERY_NODE_TYPE = "ph-query"# QuerySchema kind that points at a saved insight by its short_id.SAVED_INSIGHT_NODE_KIND = "SavedInsightNode"+MARKDOWN_QUERY_TAG = "Query"# Keep in sync with `SHARED_NOTEBOOK_SUPPORTED_NODE_TYPES` in# `frontend/src/scenes/notebooks/Nodes/sharedNodeSupport.tsx`.@@ -24,6 +30,42 @@ SHARED_NOTEBOOK_SUPPORTED_NODE_TYPES: frozenset[str] = frozenset(})+SHARED_NOTEBOOK_SUPPORTED_MARKDOWN_COMPONENT_TAGS: frozenset[str] = frozenset(+ {+ "Comment",+ "Divider",+ "Embed",+ "Image",+ "Latex",+ "Query",+ }+)++_SHARED_NOTEBOOK_MARKDOWN_COMPONENT_PROP_TYPES: dict[str, dict[str, type | tuple[type, ...]]] = {+ "Comment": {"ref": str, "replies": list, "text": str},+ "Divider": {},+ "Embed": {"height": (int, float), "src": str, "title": str, "width": (int, float)},+ "Image": {"alt": str, "height": (int, float), "src": str, "title": str, "width": (int, float)},+ "Latex": {"content": str, "editing": bool, "title": str},+ "Query": {+ "hideFilters": bool,+ "hideResults": bool,+ "height": (int, float),+ "isDefaultFilterApplied": bool,+ "nodeId": str,+ "outputTab": str,+ "query": dict,+ "showSettings": bool,+ "title": str,+ },+}++_MARKDOWN_COMPONENT_START_REGEX = re.compile(r"^<[A-Z][A-Za-z0-9]*(\s|>|/)")+_MARKDOWN_COMPONENT_TAG_REGEX = re.compile(r"^<([A-Z][A-Za-z0-9]*)([\s\S]*?)(?:/>|>[\s\S]*</\1>)$")+_MARKDOWN_COMPONENT_PROP_NAME_REGEX = re.compile(r"^([A-Za-z_][A-Za-z0-9_-]*)")+_MARKDOWN_COMPONENT_RAW_PROP_VALUE_REGEX = re.compile(r"^([^\s/>]+)")+_MARKDOWN_COMPONENT_NUMBER_REGEX = re.compile(r"^-?\d+(\.\d+)?$")+def filter_notebook_content_for_sharing(content: Any) -> Any:"""Return a copy of a notebook's ProseMirror document with unsupported widget nodes redacted.@@ -37,6 +79,9 @@ def filter_notebook_content_for_sharing(content: Any) -> Any:return contentnode_type = content.get("type")+ if node_type == MARKDOWN_NOTEBOOK_NODE_TYPE:+ return _filter_markdown_notebook_content_for_sharing(content)+if (isinstance(node_type, str)and node_type.startswith("ph-")@@ -47,13 +92,102 @@ def filter_notebook_content_for_sharing(content: Any) -> Any:filtered: dict[str, Any] = {k: v for k, v in content.items() if k != "content"}children = content.get("content")if isinstance(children, list):- filtered["content"] = [filter_notebook_content_for_sharing(child) for child in children]+ filtered["content"] = [_filter_notebook_child_content_for_sharing(child) for child in children]elif "content" in content:filtered["content"] = childrenreturn filtered-def _coerce_query_attr(raw: Any) -> dict | None:+def _filter_notebook_child_content_for_sharing(child: Any) -> Any:+ if isinstance(child, dict) and child.get("type") == MARKDOWN_NOTEBOOK_NODE_TYPE:+ return _filter_markdown_notebook_content_for_sharing(child)+ return filter_notebook_content_for_sharing(child)+++def _filter_markdown_notebook_content_for_sharing(content: TipTapNode) -> TipTapNode:+ attrs = content.get("attrs")+ if not isinstance(attrs, dict):+ return {"type": MARKDOWN_NOTEBOOK_NODE_TYPE}++ filtered_attrs: dict[str, Any] = {}+ node_id = attrs.get("nodeId")+ if isinstance(node_id, str):+ filtered_attrs["nodeId"] = node_id++ markdown = attrs.get("markdown")+ if isinstance(markdown, str):+ filtered_attrs["markdown"] = _filter_markdown_components_for_sharing(markdown)++ return {"type": MARKDOWN_NOTEBOOK_NODE_TYPE, "attrs": filtered_attrs}+++def _filter_markdown_components_for_sharing(markdown: str) -> str:+ lines = markdown.replace("\r\n", "\n").replace("\r", "\n").split("\n")+ filtered_lines: list[str] = []+ line_index = 0++ while line_index < len(lines):+ if lines[line_index].strip().startswith("```"):+ code_block_end = _get_markdown_code_block_end(lines, line_index)+ filtered_lines.extend(lines[line_index:code_block_end])+ line_index = code_block_end+ continue++ component = _read_markdown_component_block(lines, line_index)+ if component is None:+ filtered_lines.append(lines[line_index])+ line_index += 1+ continue++ tag_name, _raw, next_line_index = component+ if tag_name in SHARED_NOTEBOOK_SUPPORTED_MARKDOWN_COMPONENT_TAGS:+ filtered_lines.append(_filter_supported_markdown_component_for_sharing(tag_name, _raw))+ else:+ filtered_lines.append(f"<{tag_name} />")+ line_index = next_line_index++ return "\n".join(filtered_lines)+++def _filter_supported_markdown_component_for_sharing(tag_name: str, raw: str) -> str:+ supported_props = _SHARED_NOTEBOOK_MARKDOWN_COMPONENT_PROP_TYPES[tag_name]+ props = _parse_markdown_component_props(raw)+ filtered_props: dict[str, Any] = {}++ for prop_name, expected_type in supported_props.items():+ value = props.get(prop_name)+ if _is_markdown_component_prop_type(value, expected_type):+ filtered_props[prop_name] = value++ return _serialize_markdown_component(tag_name, filtered_props)+++def _is_markdown_component_prop_type(value: Any, expected_type: type | tuple[type, ...]) -> bool:+ if isinstance(value, bool):+ return expected_type is bool or (isinstance(expected_type, tuple) and bool in expected_type)+ if isinstance(value, expected_type):+ return True+ return False+++def _serialize_markdown_component(tag_name: str, props: dict[str, Any]) -> str:+ prop_source = "".join(+ _serialize_markdown_component_prop(name, props[name])+ for name in _SHARED_NOTEBOOK_MARKDOWN_COMPONENT_PROP_TYPES[tag_name]+ if name in props+ )+ return f"<{tag_name}{prop_source} />"+++def _serialize_markdown_component_prop(name: str, value: Any) -> str:+ if value is True:+ return f" {name}"+ if isinstance(value, str):+ return f" {name}={json.dumps(value, ensure_ascii=False)}"+ return f" {name}={{{json.dumps(value, ensure_ascii=False, separators=(',', ':'))}}}"+++def _coerce_query_attr(raw: Any) -> dict[str, Any] | None:"""Resolve a notebook ph-query node's `query` attribute to a dict.Notebooks save attrs through tiptap, which can serialize complex attrs as JSON strings@@ -109,10 +243,16 @@ def extract_referenced_insight_short_ids(content: Any) -> set[str]:short_id = query.get("shortId")if isinstance(short_id, str) and short_id:short_ids.add(short_id)+ for _node_id, query in iter_markdown_query_nodes(content):+ if query.get("kind") != SAVED_INSIGHT_NODE_KIND:+ continue+ short_id = query.get("shortId")+ if isinstance(short_id, str) and short_id:+ short_ids.add(short_id)return short_ids-def extract_inline_query_nodes(content: Any) -> list[tuple[str, dict]]:+def extract_inline_query_nodes(content: Any) -> list[tuple[str, dict[str, Any]]]:"""Walk a notebook's ProseMirror document and collect every inline (non-saved-insight) query.Returns a list of ``(nodeId, query_dict)`` pairs. Used by the shared-notebook payload@@ -124,10 +264,12 @@ def extract_inline_query_nodes(content: Any) -> list[tuple[str, dict]]::func:`extract_referenced_insight_short_ids` and the existing``InsightSerializer`` shared-mode path.- Nodes whose ``nodeId`` is missing are skipped; without it the frontend has no key to look- the cached result up by, so we'd risk attaching the wrong result to the wrong node.+ Legacy ProseMirror ``ph-query`` nodes whose ``nodeId`` is missing are skipped; without it+ the frontend has no key to look the cached result up by. Markdown ``<Query>`` components+ without an explicit ``nodeId`` instead receive a content-derived stable ID (see+ :func:`iter_markdown_query_nodes`)."""- inline_nodes: list[tuple[str, dict]] = []+ inline_nodes: list[tuple[str, dict[str, Any]]] = []for node in iter_prosemirror_nodes(content):if node.get("type") != QUERY_NODE_TYPE:continue@@ -143,9 +285,299 @@ def extract_inline_query_nodes(content: Any) -> list[tuple[str, dict]]:if not isinstance(node_id, str) or not node_id:continueinline_nodes.append((node_id, query))+ for node_id, query in iter_markdown_query_nodes(content):+ if query.get("kind") == SAVED_INSIGHT_NODE_KIND:+ continue+ inline_nodes.append((node_id, query))return inline_nodes+def iter_markdown_query_nodes(content: Any) -> Iterator[tuple[str, dict[str, Any]]]:+ markdown = _get_markdown_notebook_markdown(content)+ if markdown is None:+ return++ occurrences: dict[str, int] = {}+ for tag_name, raw, _next_line_index in _iter_markdown_component_blocks(markdown):+ if tag_name != MARKDOWN_QUERY_TAG:+ continue++ props = _parse_markdown_component_props(raw)+ fingerprint = _get_markdown_component_fingerprint(tag_name, props)+ occurrence = occurrences.get(fingerprint, 0)+ occurrences[fingerprint] = occurrence + 1++ query = _coerce_query_attr(props.get("query"))+ if query is None:+ continue++ explicit_node_id = props.get("nodeId")+ node_id = (+ explicit_node_id+ if isinstance(explicit_node_id, str) and explicit_node_id+ else _create_stable_markdown_node_id(fingerprint, occurrence)+ )+ yield node_id, query+++def _get_markdown_notebook_markdown(content: Any) -> str | None:+ if not isinstance(content, dict):+ return None++ nodes = content.get("content")+ if not isinstance(nodes, list) or len(nodes) != 1:+ return None++ node = nodes[0]+ if not isinstance(node, dict) or node.get("type") != MARKDOWN_NOTEBOOK_NODE_TYPE:+ return None++ attrs = node.get("attrs")+ markdown = attrs.get("markdown") if isinstance(attrs, dict) else None+ return markdown if isinstance(markdown, str) else None+++def _iter_markdown_component_blocks(markdown: str) -> Iterator[tuple[str, str, int]]:+ lines = markdown.replace("\r\n", "\n").replace("\r", "\n").split("\n")+ line_index = 0++ while line_index < len(lines):+ if lines[line_index].strip().startswith("```"):+ line_index = _get_markdown_code_block_end(lines, line_index)+ continue++ component = _read_markdown_component_block(lines, line_index)+ if component is None:+ line_index += 1+ continue++ yield component+ line_index = component[2]+++def _get_markdown_code_block_end(lines: list[str], line_index: int) -> int:+ next_line_index = line_index + 1+ while next_line_index < len(lines):+ if lines[next_line_index].strip().startswith("```"):+ return next_line_index + 1+ next_line_index += 1+ return next_line_index+++def _read_markdown_component_block(lines: list[str], line_index: int) -> tuple[str, str, int] | None:+ first_line = lines[line_index].strip()+ if not _MARKDOWN_COMPONENT_START_REGEX.match(first_line):+ return None++ tag_match = re.match(r"^<([A-Z][A-Za-z0-9]*)", first_line)+ tag_name = tag_match.group(1) if tag_match else None+ if not tag_name:+ return None++ raw_lines: list[str] = []+ next_line_index = line_index+ found_terminator = False+ while next_line_index < len(lines) and (next_line_index == line_index or lines[next_line_index].strip()):+ raw_lines.append(lines[next_line_index])+ raw = "\n".join(raw_lines).strip()+ if raw.endswith("/>") or f"</{tag_name}>" in raw:+ found_terminator = True+ break+ next_line_index += 1++ if not found_terminator:+ return None++ return tag_name, "\n".join(raw_lines).strip(), next_line_index + 1+++def _parse_markdown_component_props(raw: str) -> dict[str, Any]:+ match = _MARKDOWN_COMPONENT_TAG_REGEX.match(raw)+ if not match:+ return {}++ props: dict[str, Any] = {}+ source = match.group(2) or ""+ index = 0+ while index < len(source):+ while index < len(source) and source[index].isspace():+ index += 1+ if index >= len(source):+ break++ name_match = _MARKDOWN_COMPONENT_PROP_NAME_REGEX.match(source[index:])+ if not name_match:+ break++ name = name_match.group(1)+ index += len(name)+ while index < len(source) and source[index].isspace():+ index += 1++ if index >= len(source) or source[index] != "=":+ props[name] = True+ continue++ index += 1+ while index < len(source) and source[index].isspace():+ index += 1++ value, index = _read_markdown_component_prop_value(source, index)+ if _is_markdown_notebook_prop_value(value):+ props[name] = value++ return props+++def _read_markdown_component_prop_value(source: str, index: int) -> tuple[Any, int]:+ first_char = source[index] if index < len(source) else ""++ if first_char in {"'", '"'}:+ quote = first_char+ next_index = index + 1+ value = ""+ while next_index < len(source):+ character = source[next_index]+ if character == "\\" and next_index + 1 < len(source):+ value += source[next_index + 1]+ next_index += 2+ continue+ if character == quote:+ if quote == '"':+ try:+ parsed_value = json.loads(source[index : next_index + 1])+ if isinstance(parsed_value, str):+ return html.unescape(parsed_value), next_index + 1+ except (TypeError, ValueError):+ pass+ return html.unescape(value), next_index + 1+ value += character+ next_index += 1+ return None, next_index++ if first_char == "{":+ balanced = _read_balanced_markdown_expression(source, index)+ if balanced is None:+ return None, len(source)+ value, next_index = balanced+ return _parse_markdown_expression_value(value), next_index++ raw_match = _MARKDOWN_COMPONENT_RAW_PROP_VALUE_REGEX.match(source[index:])+ raw = raw_match.group(1) if raw_match else ""+ return _parse_markdown_expression_value(raw), index + len(raw)+++def _read_balanced_markdown_expression(source: str, index: int) -> tuple[str, int] | None:+ depth = 0+ next_index = index+ quote: str | None = None++ while next_index < len(source):+ character = source[next_index]+ if quote:+ if character == quote and not _is_escaped_markdown_expression_quote(source, next_index):+ quote = None+ next_index += 1+ continue++ if character in {"'", '"'}:+ quote = character+ next_index += 1+ continue++ if character == "{":+ depth += 1+ if character == "}":+ depth -= 1+ if depth == 0:+ return source[index : next_index + 1], next_index + 1+ next_index += 1++ return None+++def _is_escaped_markdown_expression_quote(source: str, quote_index: int) -> bool:+ backslash_count = 0+ index = quote_index - 1+ while index >= 0 and source[index] == "\\":+ backslash_count += 1+ index -= 1+ return backslash_count % 2 == 1+++def _parse_markdown_expression_value(raw: str) -> Any:+ trimmed = raw.strip()+ unwrapped = trimmed[1:-1].strip() if trimmed.startswith("{") and trimmed.endswith("}") else trimmed++ if unwrapped == "true":+ return True+ if unwrapped == "false":+ return False+ if unwrapped == "null":+ return None+ if _MARKDOWN_COMPONENT_NUMBER_REGEX.match(unwrapped):+ return float(unwrapped) if "." in unwrapped else int(unwrapped)++ try:+ return json.loads(unwrapped)+ except (TypeError, ValueError):+ return trimmed+++def _is_markdown_notebook_prop_value(value: Any) -> bool:+ if value is None or isinstance(value, str | int | float | bool):+ return True+ if isinstance(value, list):+ return all(_is_markdown_notebook_prop_value(item) for item in value)+ if isinstance(value, dict):+ return all(isinstance(key, str) and _is_markdown_notebook_prop_value(item) for key, item in value.items())+ return False+++def _get_markdown_component_fingerprint(tag_name: str, props: dict[str, Any]) -> str:+ return json.dumps(+ {"type": "component", "tagName": tag_name, "props": _sort_markdown_component_props(props)},+ ensure_ascii=False,+ separators=(",", ":"),+ )+++def _sort_markdown_component_props(props: dict[str, Any]) -> dict[str, Any]:+ return {key: _sort_markdown_component_prop_value(props[key]) for key in sorted(props)}+++def _sort_markdown_component_prop_value(value: Any) -> Any:+ if isinstance(value, list):+ return [_sort_markdown_component_prop_value(item) for item in value]+ if isinstance(value, dict):+ return _sort_markdown_component_props(value)+ return value+++def _create_stable_markdown_node_id(fingerprint: str, occurrence: int) -> str:+ return f"mdn-{_hash_markdown_node_id_seed(fingerprint)}-{occurrence}"+++def _hash_markdown_node_id_seed(value: str) -> str:+ hash_value = 5381+ encoded = value.encode("utf-16-le", "surrogatepass")+ for index in range(0, len(encoded), 2):+ code_unit = encoded[index] | (encoded[index + 1] << 8)+ hash_value = ((hash_value * 33) ^ code_unit) & 0xFFFFFFFF+ return _to_base36(hash_value)+++def _to_base36(value: int) -> str:+ digits = "0123456789abcdefghijklmnopqrstuvwxyz"+ if value == 0:+ return "0"+ result = ""+ while value:+ value, remainder = divmod(value, 36)+ result = digits[remainder] + result+ return result++def create_bullet_list(items: list[str] | list[TipTapContent] | TipTapContent) -> TipTapNode:"""Create a bullet list with list items. Items can be strings or content arrays."""list_items = []